|
int8_t I2C_write(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) // packet function {0 A+ x4 N; ]$ U* h HAL_StatusTypeDef status =HAL_OK;8 V9 q( x: s& M0 N* L) o( i% v 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) { printf("I2C Write Fail:%d\n\r",status); return status; } return HAL_OK; } 0 a0 I2 l1 A/ D5 U j/ E int8_t I2C_read(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) //re packet function% D- B5 ]& d4 U/ r4 |7 p0 a7 I {4 V3 ?4 P2 g: n) Q J HAL_StatusTypeDef status =HAL_OK;/ w' r7 X2 G2 Y uint16_t deviceWriteAddr = addr << 1; //7 bit write address shall be pre-processed) G& L" {. N3 s' w! R uint16_t deviceReadAddr = (addr << 1)|0x01; //7 bit read address shall be pre-processed uint8_t regAddr = reg_addr; status = HAL_I2C_Master_Transmit(&hi2c1,deviceWriteAddr,®Addr,1,I2C_READ_TIMEOUT); % |6 J1 j7 o+ z if (HAL_OK != status) {; A( f; n _! d- R1 `0 f printf("I2C readreg Fail:%d\n\r",status); return status; } 3 `8 J$ R% }, E; {. l status = HAL_I2C_Master_Receive(&hi2c1,deviceReadAddr,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); // if (HAL_OK != status)0 c/ W0 m8 N$ ^4 q* w- Q { printf("I2C Read1 Fail:%d\n\r",status);( h" b/ F- u D9 l0 p1 d" e return status;0 H8 E& Z& c7 T* }/ Z) z } return HAL_OK; } 写是用HAL_I2C_Mem_Write() 重新打包; 读操作原本要用HAL_I2C_Mem_Read,发现多字节request时,返回 I2C error.: u; K8 E4 u/ i# q 如上改过后,单字节,多字节 读写稳定。. X( f8 Q5 p) Y; g, u HAL_I2C_Mem_Write/HAL_I2C_Mem_Read 都是cubeMX 工具生成的HAL库。 我是在STM32L4系列使用的。( | M2 N" l; D; G 我参考的I2C 协议参考:http://www.cnblogs.com/aaronLinux/p/6218660.html |
微信公众号
手机版