int8_t I2C_write(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) // packet function { HAL_StatusTypeDef status =HAL_OK; uint16_t deviceWriteAddr = (addr << 1); //7 bit write address shall be pre-processed status = HAL_I2C_Mem_Write(&hi2c1,deviceWriteAddr,(uint16_t)reg_addr,1,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); if (HAL_OK != status)( ?6 [- g7 M) E( h8 ? {! m8 q4 s' A! |0 U- l" n% R printf("I2C Write Fail:%d\n\r",status); & I9 D( |* Y& |$ w9 O7 [ return status;3 M3 E2 T, k: A: C0 V } return HAL_OK; }# [9 L# i1 b( b q& j3 Z int8_t I2C_read(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) //re packet function$ J7 y# P: ?5 k, } {& P- x& x2 a& l5 d! V: q; _ HAL_StatusTypeDef status =HAL_OK;5 ]: ~9 Z0 h: |' W! D uint16_t deviceWriteAddr = addr << 1; //7 bit write address shall be pre-processed! q* D8 P) Y( A0 F- Z" w; X& W9 c uint16_t deviceReadAddr = (addr << 1)|0x01; //7 bit read address shall be pre-processed : a/ [2 [: v- [1 T uint8_t regAddr = reg_addr;, _0 V' ?8 q7 n0 T# a status = HAL_I2C_Master_Transmit(&hi2c1,deviceWriteAddr,®Addr,1,I2C_READ_TIMEOUT); if (HAL_OK != status) { printf("I2C readreg Fail:%d\n\r",status);8 j0 V5 p( h+ c2 N$ M return status;0 N0 V# C8 _/ d. D/ S8 i } # N- w% s( `7 B9 h( T3 q& P+ }1 \ 5 y# z0 I4 ^; ?: w& B status = HAL_I2C_Master_Receive(&hi2c1,deviceReadAddr,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); // if (HAL_OK != status); s9 b/ J+ b: l7 m- [ { printf("I2C Read1 Fail:%d\n\r",status);0 P6 e7 k" w% D6 ^5 [ return status;9 N, f4 _9 S- h: L& V } return HAL_OK;! h; z y; E; p8 _5 o) F } ! P: Q& n& _9 y) v6 r3 i 写是用HAL_I2C_Mem_Write() 重新打包;+ z. R E! B4 n% S9 k 读操作原本要用HAL_I2C_Mem_Read,发现多字节request时,返回 I2C error. 如上改过后,单字节,多字节 读写稳定。% F, R% k& w( n HAL_I2C_Mem_Write/HAL_I2C_Mem_Read 都是cubeMX 工具生成的HAL库。 我是在STM32L4系列使用的。. E1 q; X) m$ s4 Z7 f. V: R/ f* w 我参考的I2C 协议参考:http://www.cnblogs.com/aaronLinux/p/6218660.html |