// 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 - MCP23017 #define MCP23017_ADDR 0x20 // I2C device adress #define LEDS 0xA1 // 10100001 - Some LED is ON, others is OFF // TABLE 1-2: REGISTER ADDRESSES - Default bank 0 #define MCP23017_IODIRB 1 // IODIRB register address #define MCP23017_GPIOB 0x013 // GPIOB register address #include "configurationbits.h" #include void I2C_error_handler(int error_code); // void main(void) // Program start here { 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 = MCP23017_ADDR << 1; // 7 bit address + Write bit IdleI2C(); // Wait until the bus is idle if (WriteI2C(addrRW) < 0) // Send address with R/W set for write - Error in WriteI2C() documentation! I2C_error_handler(-1); // Configure port B as output - see MCP23017 data sheet IdleI2C(); // Wait until the bus is idle if (WriteI2C(MCP23017_IODIRB) < 0) // Send register address I2C_error_handler(-1); IdleI2C(); // Wait until the bus is idle if (WriteI2C(0x00) < 0) // Send Output I2C_error_handler(-1); IdleI2C(); // Wait until the bus is idle StopI2C(); // Send STOP condition // On/Off some LEDs IdleI2C(); // Wait until the bus is idle StartI2C(); // Send START condition addrRW = MCP23017_ADDR << 1; // 7 bit address + Write bit IdleI2C(); // Wait until the bus is idle if (WriteI2C(addrRW) < 0) // Send address with R/W set for write I2C_error_handler(-1); // Put data to PortB IdleI2C(); // Wait until the bus is idle if (WriteI2C(MCP23017_GPIOB) < 0) // Send register address I2C_error_handler(-1); IdleI2C(); // Wait until the bus is idle if (WriteI2C(LEDS) < 0) // Send led ON/OFF I2C_error_handler(-1); IdleI2C(); // Wait until the bus is idle StopI2C(); // Send STOP condition CloseI2C(); while (1); } void I2C_error_handler(int error_code) { // Error handler... emty }