Ian Wolf
/
ReadingInLines_copy
Fork of TEMPFINALInterrupt_copy by
main.cpp
- Committer:
- iwolf32
- Date:
- 2017-08-31
- Revision:
- 2:4425049f4174
- Parent:
- 1:1de97b1145f3
- Child:
- 3:60a74a913c40
File content as of revision 2:4425049f4174:
#include "mbed.h" #include <string> // Read temperature from MAX1363 3-channel ADC I2C i2c(PB_9 , PB_8); DigitalOut Relay(D7); Serial pc(SERIAL_TX, SERIAL_RX); std::string str; char ch; double SetTemp=0; float x=0; // address information for the Serenity temperature sensor device const int SLAVE_ADDRESS = 0x34 << 1; // MAX1363 registers const unsigned char MAX1363_CONFIG_REG = 0x03; // single-ended inputs, read CH0-CH1 only const unsigned char MAX1363_SETUP_REG = 0xF2; // AIN3=output, INT REF always on // MAX1363 high byte format (byte 2 is D7-D0) const unsigned char MAX1363_VALID_MASK = 0x90; // HIGH bit and 12/10 bit should always be 1 const unsigned char MAX1363_HIGH_DATA_MASK = 0x0F; // channel address (0-3) is in CH1/CH0 (bits 5/6) const unsigned char MAX1363_CHANNEL_MASK = 0x60; const unsigned char MAX1363_CHANNEL_SHIFT = 5; /** conversion factors */ const float CONV_COEFF_A3 = 4.39403; const float CONV_COEFF_A2 = -11.15; const float CONV_COEFF_A1 = 36.4955; const float CONV_COEFF_A0 = 266.909; const int CONV_N = 12; const float CONV_VREF = 2.048; const float CONV_K_TO_C = -272.15; float AdcToC(unsigned int _adc) { float d = CONV_VREF * _adc / (1L << CONV_N); float d2 = d*d; float d3 = d2*d; float temp_k = (CONV_COEFF_A3 * d3) + (CONV_COEFF_A2 * d2) + (CONV_COEFF_A1 * d) + CONV_COEFF_A0; return temp_k + CONV_K_TO_C; } void callback(){ ch=pc.getc(); str+=ch; SetTemp= atof(str.c_str()); return; } int main() { pc.baud(115200); pc.attach(&callback); // reserve 4 bytes for transfer char cmd[4]; // initialize the adc device cmd[0] = MAX1363_CONFIG_REG; cmd[1] = MAX1363_SETUP_REG; i2c.write(SLAVE_ADDRESS, cmd, 2); // holds raw adc values as we convert them unsigned int adc[2] = {0}; float values[2] = {0}; while (1) { //Clear string holding the input from serial str.clear(); wait(1); // clear buffer, only to detect invalid data cmd[0] = 0x00; cmd[1] = 0x00; cmd[2] = 0x00; cmd[3] = 0x00; // read 4 bytes from i2c.read(SLAVE_ADDRESS, cmd, 4); for (int i=0; i<4; i+=2) { // first 4 bits contain expected bits and channel id if ((cmd[i] & MAX1363_VALID_MASK) == MAX1363_VALID_MASK) { unsigned char ch = ((cmd[i] & MAX1363_CHANNEL_MASK) >> MAX1363_CHANNEL_SHIFT); adc[ch] = ((int)(cmd[i] & MAX1363_HIGH_DATA_MASK) << 8) | cmd[i+1]; values[ch] = AdcToC(adc[ch]); } else { // handle invalid data } } x=values[1]; if (x<SetTemp){ Relay=0; } if (x>SetTemp+1){ Relay=1; } // output temperature data printf("%0.2f\t %0.2f\t %0.2f\r\n", SetTemp, values[0], values[1]); } }