/***************************************** * Imports *****************************************/ #include /***************************************** * Precompiler Definitions *****************************************/ #define TMP_ADDRESS 0b1001011 // I2C address of the TMP2 Pmod #define ARRAY_SIZE 4 // Maximum size of the buffer #define BAUD 9600 // Rate at which the UART serial will communicate #define REQUEST 2 //number of bytes to request at a time from I2C /***************************************** * Global Variables *****************************************/ short buffer[ARRAY_SIZE]; // Create a buffer to hold values passed through I2C /***************************************** * Functions *****************************************/ /** * Establishes communication with the TMP2 Pmod, calculates the temperature in Celcius and then returns it as a short value */ short getTemp(){ Wire.requestFrom(TMP_ADDRESS, REQUEST); // Request two bytes of data from the temperature sensor while(Wire.available()){ //While there is still data to be transfered for (int i =0; i < REQUEST; i++){ // Put the data in a buffer array buffer[i] = Wire.receive(); } } short retTemp = 0; // define a short value that will be set and returned by the function for (int i = 0; i < REQUEST; i++){ // A loop to handle each byte contained in the buffer. This loop recombines the bytes sent over I2C into a single short retTemp = retTemp<<8; // shift all bits to the right 8 spaces retTemp |= buffer[i]; // This is equivalent to retTemp = retTemp | buffer[i]. This effectively concatenates the retrieved bytes into a single short } return retTemp*.0078; // Multiply by a scaling factor (found on the data sheet) to convert to Celsius } /***************************************** * Setup *****************************************/ void setup(){ Wire.begin(); // Enables I2C communication on the ChipKit board Serial.begin(BAUD); // Enables UART serial communication at the selected speed } /***************************************** * Main Loop *****************************************/ void loop(){ Serial.println(getTemp(), DEC); // Print the temperature through the serial port delay(500); // delay for 500ms }