c - I2C 通讯 B-L072Z-LRWAN(主) 与 Arduino(从) 错误

标签 c arduino stm32 i2c nucleo

我正在尝试在 B-L072Z-LRWAN(Master) 和 Arduino(Slave) 之间进行 I2C 通信。

我使用以下代码成功将数据从主站发送到从站:

B-L072Z-LRWAN 代码:

#include "main.h"

I2C_HandleTypeDef hi2c1;
uint8_t i2cData[2];
uint8_t rec_data[1];

int main(void)
 {
  //I do not copy all the lines of code

    if(HAL_I2C_IsDeviceReady(&hi2c1,0xD0,2,10) == HAL_OK)
       {
        HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);
       }
    i2cData[0] = 0x00;
    i2cData[1] = 0x7F;
    while (1)
       {   
          HAL_I2C_Master_Transmit(&hi2c1, 0xD0, i2cData, 2, 10);
       }

    //I do not copy all the lines of code
   }

Arduino 代码:

 #include <Wire.h>

 uint8_t i = 1;
 uint8_t data[2];

 void setup() 
 {
   Wire.begin(0b1101000);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Wire.onRequest(requestEvent);
   Serial.begin(9600);           // start serial for output
 }

void loop()
 {
   data[0] = i++;
   delay(500);
 }

// function that executes whenever data is received from master
// this function is registered as an event, see setup()

void receiveEvent(int howMany)
 {
   while (1 < Wire.available())
     { 
       // loop through all but the last
       int c = Wire.read(); // receive byte as a character
       Serial.print(c, HEX);         // print the character
     }
   int x = Wire.read();    // receive byte as an integer
   Serial.println(x);         // print the integer
  }

 void requestEvent()
   {
     Serial.println("request from master"); 
     Wire.write(data[0]); // respond with message of 6 bytes
      // as expected by master
   }

所以我可以将数据发送到我的从站,然后我尝试将数据从我的从站发送到我的主站,所以我添加此行代码:

B-L072Z-LRWAN 代码:

  rec_data[0] = 0x04;
  while (1)
    {
      //reception data
      HAL_I2C_Master_Receive(&hi2c1, 0xD0, rec_data[0], 1, 10);
      HAL_Delay(500);
    }

我想接收arduino发送的i值的增量,但这不起作用,我继续从我的主机发送数据,但我无法从我的从机发送数据。

也许我没有出错,可以帮助我吗?谢谢。

亲切的问候,

最佳答案

最后我找到了解决方案,只需将 while“rec_data[0]”替换为“rec_data”即可:

 rec_data[0] = 0x04;

 while (1)
  {
    //reception data
    HAL_I2C_Master_Transmit(&hi2c1, 0xD0, i2cData, 1, 10);
    HAL_Delay(500);
    HAL_I2C_Master_Receive(&hi2c1, 0xD0, rec_data, 1, 10);
    HAL_Delay(500);
  }

再次感谢小伙子!! ;)

关于c - I2C 通讯 B-L072Z-LRWAN(主) 与 Arduino(从) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026771/

相关文章:

c - jmp 到内联 AVR C 中的地址

c - 忽略尾部读取大小受限的输入行

c - 获取文件大小而不读取文件

c++ - Arduino 立体声音量表

使用 ARM DSP 库和在 MatLab 中计算 FFT 时出现冲突的结果

c - STM32 条件中断处理

ubuntu - linux更新后如何维护开发环境

c - 如何为硬件版权保护加密狗编写一个简单的usb驱动程序?

c - 使用 c REGEX 表达式列出和过滤文件

c++ - AVR-C 错误 : expected '=' , ','、 ';'、 'asm' 或 '__attribute__' token 之前的 '<'