Nathan Yonkee / Mbed OS Nucleo_i2c_master
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002  
00003 #define LM75_REG_TEMP (0x00) // Temperature Register
00004 #define LM75_REG_CONF (0x01) // Configuration Register
00005 #define LM75_ADDR     (0x90) // LM75 address
00006  
00007 I2C i2c(I2C_SDA, I2C_SCL);
00008  
00009 DigitalOut myled(LED1);
00010  
00011 Serial pc(SERIAL_TX, SERIAL_RX);
00012  
00013 volatile char TempCelsiusDisplay[] = "+abc.d C";
00014  
00015 int main()
00016 {
00017  
00018     char data_write[2];
00019     char data_read[2];
00020  
00021     /* Configure the Temperature sensor device STLM75:
00022     - Thermostat mode Interrupt
00023     - Fault tolerance: 0
00024     */
00025     data_write[0] = LM75_REG_CONF;
00026     data_write[1] = 0x02;
00027     int status = i2c.write(LM75_ADDR, data_write, 2, 0);
00028     if (status != 0) { // Error
00029         while (1) {
00030             myled = !myled;
00031             wait(0.2);
00032         }
00033     }
00034  
00035     while (1) {
00036         // Read temperature register
00037         data_write[0] = LM75_REG_TEMP;
00038         i2c.write(LM75_ADDR, data_write, 1, 1); // no stop
00039         i2c.read(LM75_ADDR, data_read, 2, 0);
00040  
00041         // Calculate temperature value in Celcius
00042         int tempval = (int)((int)data_read[0] << 8) | data_read[1];
00043         tempval >>= 7;
00044         if (tempval <= 256) {
00045             TempCelsiusDisplay[0] = '+';
00046         } else {
00047             TempCelsiusDisplay[0] = '-';
00048             tempval = 512 - tempval;
00049         }
00050  
00051         // Decimal part (0.5°C precision)
00052         if (tempval & 0x01) {
00053             TempCelsiusDisplay[5] = 0x05 + 0x30;
00054         } else {
00055             TempCelsiusDisplay[5] = 0x00 + 0x30;
00056         }
00057  
00058         // Integer part
00059         tempval >>= 1;
00060         TempCelsiusDisplay[1] = (tempval / 100) + 0x30;
00061         TempCelsiusDisplay[2] = ((tempval % 100) / 10) + 0x30;
00062         TempCelsiusDisplay[3] = ((tempval % 100) % 10) + 0x30;
00063  
00064         // Display result
00065         pc.printf("temp = %s\n", TempCelsiusDisplay);
00066         myled = !myled;
00067         wait(1.0);
00068     }
00069  
00070 }
00071