【前言】
I2C是最常见的MCU外设,在I2C下面最多可以挂载0xFF个从机,主机通过I2C地址来选择与从机的通信,这一篇将分享如何查找挂载在MAX7800下面的外设。
【开发板原理图】
在MAX7800FTR有一组I2C可以供用户外接使用,编号为I2C1,接口为P0_16(SCL),P0_17(SDA)用手说明书中标注如下:
【测试代码】
在MAX7800的示例工程中有I2CCAN的示例,根据他的示例,我编写代码如下:
/***** Includes *****/ #include <stdio.h> #include <stdint.h> #include <string.h> #include "board.h" #include "mxc_device.h" #include "mxc_delay.h" #include "nvic_table.h" #include "i2c.h" /***** Definitions *****/ #ifdef BOARD_EVKIT_V1 #define I2C_MASTER MXC_I2C2 // SCL P0_30; SDA P0_31 #define I2C_SCL_PIN 30 #define I2C_SDA_PIN 31 #else #define I2C_MASTER MXC_I2C1 // SCL P0_16; SDA P0_17 #define I2C_SCL_PIN 16 #define I2C_SDA_PIN 17 #endif #define I2C_FREQ 100000 // 100kHZ /***** Globals *****/ uint8_t counter = 0; // ***************************************************************************** int main(void) { printf("\n\n******** I2C SLAVE ADDRESS SCANNER *********\n"); printf("\nThis example finds the addresses of any I2C Slave devices connected to the"); printf("\nsame bus as I2C%d (SCL - P0.%d, SDA - P0.%d).\n", MXC_I2C_GET_IDX(I2C_MASTER), I2C_SCL_PIN, I2C_SDA_PIN); int error; //Setup the I2CM error = MXC_I2C_Init(I2C_MASTER, 1, 0); if (error != E_NO_ERROR) { printf("-->I2C Master Initialization failed, error:%d\n", error); return -1; } else { printf("\n-->I2C Master Initialization Complete\n"); } printf("-->Scanning started\n"); MXC_I2C_SetFrequency(I2C_MASTER, I2C_FREQ); mxc_i2c_req_t reqMaster; reqMaster.i2c = I2C_MASTER; reqMaster.addr = 0; reqMaster.tx_buf = NULL; reqMaster.tx_len = 0; reqMaster.rx_buf = NULL; reqMaster.rx_len = 0; reqMaster.restart = 0; reqMaster.callback = NULL; for (uint8_t address = 8; address < 120; address++) { printf("."); fflush(0); reqMaster.addr = address; if ((MXC_I2C_MasterTransaction(&reqMaster)) == 0) { printf("\nFound slave ID %03d; 0x%02X\n", address, address); counter++; } MXC_Delay(MXC_DELAY_MSEC(200)); } printf("\n-->Scan finished. %d devices found\n", counter); return 0; }
【测试】
我通过面包板将SSD1306与面板上面的MAX7800FTHR连接,下载程序后,打开串口助手,打印出如下日志:
找到了从机地址为0x3C,因此SSD1306与开发板连接正常。
【总结】
这一篇分享了如何使用I2C的从机地址查找功能。下一篇将分享如何驱动OLED屏。