|
int8_t I2C_write(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) // packet function0 u: j+ b; v* {6 o* x% h7 h! v {; V }& D8 x5 m6 U2 b HAL_StatusTypeDef status =HAL_OK;4 Q. `+ t/ J# e' O/ t uint16_t deviceWriteAddr = (addr << 1); //7 bit write address shall be pre-processed$ A' U7 S7 u8 W, o0 F status = HAL_I2C_Mem_Write(&hi2c1,deviceWriteAddr,(uint16_t)reg_addr,1,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT);# P1 ^: s7 _6 x5 k: O& ^ if (HAL_OK != status)( Z! j+ d; W' j' D# @9 N) f { printf("I2C Write Fail:%d\n\r",status); \: p) \' ]% O# O- M return status; }1 l7 `! A% z c5 A$ x% d9 T return HAL_OK; }+ u+ s/ b/ O2 X- a+ {$ [4 X& m ; y: G6 O$ A r$ e) g int8_t I2C_read(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len) //re packet function {/ |, F& J6 J& B1 d" v HAL_StatusTypeDef status =HAL_OK;, H+ p/ Y. E& Q+ N" i% D! S1 q uint16_t deviceWriteAddr = addr << 1; //7 bit write address shall be pre-processed uint16_t deviceReadAddr = (addr << 1)|0x01; //7 bit read address shall be pre-processed uint8_t regAddr = reg_addr;+ b; ]( D7 Y+ l2 }7 W status = HAL_I2C_Master_Transmit(&hi2c1,deviceWriteAddr,®Addr,1,I2C_READ_TIMEOUT); 5 o5 d! P V9 B# a: Z& Q6 J if (HAL_OK != status)4 n% M/ X$ S5 U2 x6 z P2 ]; N! U { printf("I2C readreg Fail:%d\n\r",status);- z0 N" R6 \1 u* o, ]8 Y+ G$ { return status; } . q& H0 A6 k i + a+ g# {6 W2 k) G6 T4 c7 p status = HAL_I2C_Master_Receive(&hi2c1,deviceReadAddr,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); // : W& ?' G; L# Q4 g if (HAL_OK != status)! U- N/ w* Q7 i& i { printf("I2C Read1 Fail:%d\n\r",status);3 u, w A6 ?* Z8 A8 _: r/ `8 O return status; } return HAL_OK; }+ X- T* e5 K: d% a' T 写是用HAL_I2C_Mem_Write() 重新打包; 读操作原本要用HAL_I2C_Mem_Read,发现多字节request时,返回 I2C error.4 A6 Z$ s8 o: K* g ]8 I% o4 G 如上改过后,单字节,多字节 读写稳定。 HAL_I2C_Mem_Write/HAL_I2C_Mem_Read 都是cubeMX 工具生成的HAL库。5 W% o9 u7 L9 [ y9 J- {0 l m 我是在STM32L4系列使用的。- Y& x' `1 e' Y8 R2 X 我参考的I2C 协议参考:http://www.cnblogs.com/aaronLinux/p/6218660.html1 `2 |# Y' A; i' y9 l |
微信公众号
手机版