通过本程序来获取连接到I2C总线上的外围设备,实验使用的是地址为0X78的OLED。
首先初始化串口与I2C。
- /* initial system clock */
- system_clock_config();
- /* config nvic priority group */
- nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
- /* at board initial */
- at32_board_init();
- uart_print_init(115200);
- hi2cx.i2cx = I2Cx_PORT;
- /* i2c config */
- i2c_config(&hi2cx);
- printf("i2c scan example: aim to find the i2c device on the bus\r\n");
接下来是核心代码:
- /* Scans for I2C client devices on the bus - that have an address within the
- *specified range [addr_min, addr_max]
- */
- void main_i2c_scan(uint8_t addr_min, uint8_t addr_max)
- {
- uint8_t client_address;
- uint8_t client_addr_str[5]={0};
- static uint8_t IIC_Client_Num = 0;
- printf("\r\n I2C Scan started from 0x%02X to 0x%02X:", addr_min, addr_max);
- //LCD_ShowString(0,35,"I2C Client:",RED,WHITE,12,0);
- for (client_address = addr_min; client_address <= addr_max; client_address++)
- {
- printf("\r\n Scanning client address = 0x%02X", (int)client_address);
- /* start the request reception process */
- //I2C_Send7bitAddress(I2C1, client_address, I2C_Direction_Transmitter);
- if((i2c_status = i2c_master_transmit(&hi2cx, client_address, &client_address, 1, I2C_TIMEOUT)) == I2C_OK )
- {
- printf("\r\n---- --> client (0x%02X) ACKED <-- ------ ", (int)client_address);
- client_addr_str[0] = '0';
- client_addr_str[1] = 'x';
- if(client_address/16 >= 10)
- client_addr_str[2] = client_address/16 -10 + 'A';
- else
- client_addr_str[2] = client_address/16 + '0';
- if(client_address%16 >= 10)
- client_addr_str[3] = client_address%16 -10 + 'A';
- else
- client_addr_str[3] = client_address%16 + '0';
- client_addr_str[4] = '\0';
- IIC_Client_Num++;
-
- printf("Yes, I2C Device found. Device Addr: %s",client_addr_str);
- }else{
- continue;
- }
-
- delay_ms(50);
- }//<--for--loop>
- printf("\r\n ----------------- I2C Scan ended -----------------");
- }
串口输出:
结果分析:
0x78与0x79实际上指向的是同一个设备(7 bit Address =0x3C 或者 0b'011-1100),因为每个I2C设备都有两个地址,一个用于写入,一个用于读取。
|