ioannk

i2c read write functions

May 3rd, 2021 (edited)
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.73 KB | None | 0 0
  1. uint8_t I2C_Read_Byte(uint8_t addr)
  2. {
  3.   uint8_t data = 0;
  4.   uint8_t d;
  5.   while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY);
  6.   d = HAL_I2C_Master_Transmit(&hi2c1, SLAVE_ADDR, &addr, 1, TIMEOUT);
  7.   if ( d != HAL_OK) {
  8.       return d;
  9.   }
  10.  
  11.   while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY);
  12.   d = HAL_I2C_Master_Receive(&hi2c1, SLAVE_ADDR, &data, 1, TIMEOUT);
  13.   if ( d != HAL_OK) {
  14.       return d;
  15.   }
  16.   return data;
  17. }
  18.  
  19. uint8_t I2C_Write_Byte(uint8_t addr, uint8_t data)
  20. {
  21.   uint8_t buf[] = {addr, data};
  22.   uint8_t d;
  23.   while (HAL_I2C_GetState(&hi2c1) != HAL_I2C_STATE_READY);
  24.   d = HAL_I2C_Master_Transmit(&hi2c1, SLAVE_ADDR, buf, 2, TIMEOUT);
  25.   if ( d != HAL_OK) {
  26.       return d;
  27.   }
  28.   return HAL_OK;
  29. }
Add Comment
Please, Sign In to add comment