你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

基于STM32 HAL库的I2C 兼容单字节多字节读写例程

[复制链接]
慎微 发布时间:2019-7-20 15:47
int8_t I2C_write(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len)  // packet function
; m7 Y2 @1 c1 V1 N2 r; N{
2 D: e8 b# t  o/ M    HAL_StatusTypeDef  status =HAL_OK;1 V# y$ Y) A8 T5 E, H1 k9 u( ^
    uint16_t deviceWriteAddr = (addr << 1);    //7 bit write address shall be pre-processed
  }7 q/ P: d; Z1 }0 l* M% U- W    status = HAL_I2C_Mem_Write(&hi2c1,deviceWriteAddr,(uint16_t)reg_addr,1,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT);0 b, `) w# c2 Z4 v& a
    if (HAL_OK != status). _9 o! ]# \6 t
    {
3 \0 R6 q6 y" X+ _2 }        printf("I2C Write Fail:%d\n\r",status);
2 V3 b- V# b* y0 |' w+ `$ g        return status;0 j3 P+ v. W9 F: V' q& M2 v4 u# S: A
    }( S" ]3 G+ V) o! b1 v0 i6 \: d& ]
    return HAL_OK;
; \! Y# B3 i' ?: {8 h}7 A# g3 m/ m' H, F) [: N9 w) p
& e9 E# ^' e( O
int8_t I2C_read(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len)  //re packet function
+ p: P# d* S6 {8 ?{
/ O5 n" z+ S5 V; ?1 c    HAL_StatusTypeDef  status =HAL_OK;# y/ C5 I3 E3 G8 _  _. Q, w
   uint16_t deviceWriteAddr = addr << 1; //7 bit write address shall be pre-processed. [# P' `+ r! |( n$ A
      uint16_t deviceReadAddr = (addr << 1)|0x01;   //7 bit read address shall be pre-processed   
( h* f/ x, b; y1 C   uint8_t regAddr = reg_addr;
7 ~2 G8 h. a! E; d2 q( _          4 j1 X3 ]6 p: b: y$ |2 \
status = HAL_I2C_Master_Transmit(&hi2c1,deviceWriteAddr,&regAddr,1,I2C_READ_TIMEOUT); : O. k, }( c0 J3 J
   
- T$ @1 U9 `  `, v! l: z if (HAL_OK != status)+ E' K+ h6 j4 y$ ?7 f9 b. [, O
    {. ~; g  h: c& A* {8 _& Y2 ^
        printf("I2C readreg Fail:%d\n\r",status);  Q) i6 z9 [+ H5 Q/ N4 {
        return status;
$ r" q8 |7 J) N' W2 i# J" n. m& t7 D* v    }   
. w. \( P0 x' E% {: L! z' c
5 H1 M) P2 T: ^( [    status = HAL_I2C_Master_Receive(&hi2c1,deviceReadAddr,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); //
) A! J: f% W4 {0 @    if (HAL_OK != status)
7 J1 a6 [& V/ E2 o0 j0 [    {
+ H8 {& O/ L! ~* g' G" X        printf("I2C Read1 Fail:%d\n\r",status);
+ n- U) p" Z( L# v  a3 y7 w        return status;
* Y; w0 Z2 G9 |+ d( w    }
2 s5 ^. }0 z- t# Y1 c0 E    return HAL_OK;. v) M/ c! Z* f# f6 z1 `( v( P
}
* A2 g: @9 v  m# _' |0 {  p1 U4 J! |# d! E' n: Y
写是用HAL_I2C_Mem_Write() 重新打包;
! t( x0 a) o" x读操作原本要用HAL_I2C_Mem_Read,发现多字节request时,返回 I2C error.2 Z; k! q3 i" v- X5 `
如上改过后,单字节,多字节 读写稳定。
; D/ t/ t& h: f* a  {HAL_I2C_Mem_Write/HAL_I2C_Mem_Read 都是cubeMX 工具生成的HAL库。
' {( G7 I- g, f/ i* m8 D7 e我是在STM32L4系列使用的。* g4 y" v; j+ {7 `( s
我参考的I2C 协议参考:http://www.cnblogs.com/aaronLinux/p/6218660.html
: W0 i' t1 v' q* G
收藏 评论0 发布时间:2019-7-20 15:47

举报

0个回答

所属标签

相似分享

关于意法半导体
我们是谁
投资者关系
意法半导体可持续发展举措
创新和工艺
招聘信息
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
关注我们
st-img 微信公众号
st-img 手机版