// PIC18 in C - Versione 0.1a - Settembre 2014 // Copyright (c) 2014 VincenzoV.net // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/PIC18/i2c-PLIB.htm // I2C master - LM92 #define LM92_ADDR 0x4B #define LM92_RES 0.0625 // Resolution (see LM92 data sheet) #include "configurationbits.h" #include void I2C_error_handler(int error_code); // Errors handler function void main(void) // Program start here { unsigned char i; int buffer[2]; unsigned int data; double temperature; unsigned char addrRW; OSCCON = 0x70; // Set internal clock to 16 MHz SSPADD = 0x27; // Set 100 kHz clock ( @ 16 MHz ) OpenI2C(MASTER, SLEW_ON); // I2C Master mode, Slew rate enabled IdleI2C(); // Wait until the bus is idle StartI2C(); // Send START condition addrRW = (LM92_ADDR << 1) | 0x01; // 7 bit address + R/W bit IdleI2C(); // Wait until the bus is idle if (WriteI2C(addrRW) < 0) // Send address with R/W set for read I2C_error_handler (-1); // Error in WriteI2C() documentation! IdleI2C(); // Wait until the bus is idle buffer[0] = ReadI2C(); // Read first byte of data AckI2C(); // Send ACK IdleI2C(); // Wait until the bus is idle buffer[1] = ReadI2C(); // Read nth byte of data AckI2C(); // Send ACK IdleI2C(); // Wait until the bus is idle StopI2C(); // Hang up, send STOP condition IdleI2C(); // Wait until the bus is idle CloseI2C(); data = buffer[0]; // LM92 specific - See LM92 data sheet data = data << 8; data = data | buffer[1]; data = data >> 3; temperature = LM92_RES * data; // Temperature in °C while (1); } void I2C_error_handler(int error_code) { // Error handler... emty }