#include "ADS1231.h"

extern float Temperature; 


void ADS1231_Open(void)
{
	PDWN1_SET();
	PDWN2_SET();
	PDWN3_SET();
	PDWN4_SET();
}

void ADS1231_HighSpeedSet(void)
{
	SPEED1_SET();
	SPEED2_SET();
	SPEED3_SET();
	SPEED4_SET();
}

void ADS1231_LowSpeedSet(void)
{
	SPEED1_RESET();
	SPEED2_RESET();
	SPEED3_RESET();
	SPEED4_RESET();
}

uint32_t GpioAGetDout(en_pin_t enPin)
{
	return *(uint32_t *)((uint32_t)(&M4_PORT->PIDRA)) & (enPin);
}

uint32_t GpioBGetDout(en_pin_t enPin)
{
	return *(uint32_t *)((uint32_t)(&M4_PORT->PIDRB)) & (enPin);
}

bool ADS1231_Read(uint32_t *r_data, uint8_t channel) {
	uint8_t i;
	uint32_t data = 0;
	
	switch(channel) {
		case 0:
			if(GpioAGetDout(DRDY_DOUT1_PIN) != 0)
				return false;
			
			for(i = 0; i < 24; i++) {
				SCLK1_SET();
				data <<= 0x01;
				__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
				SCLK1_RESET();
				
				if(GpioAGetDout(DRDY_DOUT1_PIN) != 0)
					data |= 0x01;
			}
			SCLK1_SET();
			__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
			SCLK1_RESET();
			break;
		case 1:
			if(GpioAGetDout(DRDY_DOUT2_PIN) != 0)
				return false;
			
			for(i = 0; i < 24; i++) {
				SCLK2_SET();
				data <<= 0x01;
				__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
				SCLK2_RESET();
				__NOP(); __NOP(); 
				if(GpioAGetDout(DRDY_DOUT2_PIN) != 0)
					data |= 0x01;
			}
			SCLK2_SET();
			__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
			SCLK2_RESET();
			break;
		case 2:
			if(GpioBGetDout(DRDY_DOUT3_PIN) != 0)
				return false;
			
			for(i = 0; i < 24; i++) {
				SCLK3_SET();
				data <<= 0x01;
				__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
				SCLK3_RESET();
				if(GpioBGetDout(DRDY_DOUT3_PIN) != 0 )
					data |= 0x01;
			}
			SCLK3_SET();
			__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
			SCLK3_RESET();
			break;
		case 3:
			if(GpioBGetDout(DRDY_DOUT4_PIN) != 0 )
				return false;
			
			for(i = 0; i < 24; i++) {
				SCLK4_SET();
				data <<= 0x01;
				__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
				SCLK4_RESET();
				if(GpioBGetDout(DRDY_DOUT4_PIN) != 0 )
					data |= 0x01;
			}
			SCLK4_SET();
			__NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP();
			SCLK4_RESET();
			break;
		default:
			return false;

	}

	if(data <= 0x00ffffff) {
		if(data > 0x007fffff)
			*r_data = data|0xff000000;
		else
			*r_data = data;
	}
	else 
		return false;
	
	return true;
}
