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

基于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
) |/ E0 G* ~  i1 {; x  U- ~2 b{& a  S) Z# f. U. b' i
    HAL_StatusTypeDef  status =HAL_OK;; f; b2 q2 R( l7 e$ d- T4 E- S6 s
    uint16_t deviceWriteAddr = (addr << 1);    //7 bit write address shall be pre-processed
  g5 X( G0 `" y% J' m$ k    status = HAL_I2C_Mem_Write(&hi2c1,deviceWriteAddr,(uint16_t)reg_addr,1,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT);
6 U+ N8 U) j$ g9 \1 }    if (HAL_OK != status)
  Z. x% z9 ~$ d: n* z& _    {
" N. a+ L' Q3 K) ?" t4 ?% m        printf("I2C Write Fail:%d\n\r",status);
6 E4 q6 j; A* f+ d        return status;' o% R% @' F9 Q2 l4 M& u
    }  }' Y; N6 Q, n
    return HAL_OK;
  d" Z. d5 B* R0 j9 Q}
* X1 ~5 U  n; P1 a, U; [3 e( M0 `5 C, L6 Y
int8_t I2C_read(uint8_t addr, uint8_t reg_addr, const uint8_t* data, uint8_t len)  //re packet function- e: \9 b6 r. A: {
{( ^7 b" C8 r! w% _
    HAL_StatusTypeDef  status =HAL_OK;
" [1 d7 q# A- m% U   uint16_t deviceWriteAddr = addr << 1; //7 bit write address shall be pre-processed% j. N/ |0 _& R) r
      uint16_t deviceReadAddr = (addr << 1)|0x01;   //7 bit read address shall be pre-processed   
) g* E5 S2 E3 D2 z   uint8_t regAddr = reg_addr;
3 V# L  W2 g9 l* y8 w7 W. j          , S* C3 [3 y# J0 r, B- P
status = HAL_I2C_Master_Transmit(&hi2c1,deviceWriteAddr,&regAddr,1,I2C_READ_TIMEOUT);
5 _7 D+ S9 g- Y8 z   - n$ \/ z- n3 i# k# a. u% m
if (HAL_OK != status)7 d3 y; ^5 X8 d1 [8 p+ B$ {* y
    {
: s2 \5 i6 E$ m3 p( V1 F        printf("I2C readreg Fail:%d\n\r",status);3 T6 Q6 x0 ~1 ~- b. e( g6 \
        return status;
; A4 v. e. \' E5 w# e    }      ~: c7 O1 f. g+ e( _

2 h  A+ u% c) p+ a    status = HAL_I2C_Master_Receive(&hi2c1,deviceReadAddr,(uint8_t*)data,(uint16_t)len,I2C_READ_TIMEOUT); //
4 k; v. H: o: d: }/ ^# o( i    if (HAL_OK != status)
2 t; L% \: ]" ?& H" F    {
& H) |9 E# J% o4 f0 s        printf("I2C Read1 Fail:%d\n\r",status);  m* V& u. O* i
        return status;
9 D+ r5 C& c! R. K5 g9 g9 G& f' q    }
% n6 w: T# ^6 u9 W& p    return HAL_OK;
1 u$ D4 m* o2 G" n- U }$ h/ a. z  E/ s8 N
+ j% P/ M1 h9 @4 J  E5 }
写是用HAL_I2C_Mem_Write() 重新打包;, P8 w. w% J3 L: b6 x1 t. n% b
读操作原本要用HAL_I2C_Mem_Read,发现多字节request时,返回 I2C error.
) L/ s5 t6 x! V. W如上改过后,单字节,多字节 读写稳定。) d9 z/ B6 m8 |# S$ l; k* x2 N3 _
HAL_I2C_Mem_Write/HAL_I2C_Mem_Read 都是cubeMX 工具生成的HAL库。
2 m* o( \& N+ m9 \我是在STM32L4系列使用的。
6 A! m( `) k4 E) x/ a我参考的I2C 协议参考:http://www.cnblogs.com/aaronLinux/p/6218660.html0 t/ c' }( R1 ^- I
收藏 评论0 发布时间:2019-7-20 15:47

举报

0个回答

所属标签

相似分享

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