【问题标题】:Error I2C Communication B-L072Z-LRWAN(Master) And Arduino(Slave)错误 I2C 通信 B-L072Z-LRWAN(Master) 和 Arduino(Slave)
【发布时间】:2019-09-25 08:42:20
【问题描述】:

我正在尝试在 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 值的增量,但它也不起作用,我继续从我的主人发送数据,但我不能从我的奴隶发送。

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

亲切的问候,

【问题讨论】:

  • 第一个 sn-p 中的 while (1) 循环永远不会终止。所以是的,主人不断地发送数据。它必须在某个时候停止,并切换到接收。
  • 毫不拖延地同时添加HAL_I2C_Master_Transmit &amp; HAL_I2C_Master_Receive in same while(1)。然后你会看到Transmit & Receive Both
  • 您好 user58697,@ntshetty,感谢您的回复!好吧,我同时添加了所有内容,但没有任何变化:rec_data[0] 不会更改他的默认值“4”!这是我的代码截图imgur.com/vwPDzgJ

标签: c arduino stm32 i2c nucleo


【解决方案1】:

最后我找到了解决方案,只是将“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);
  }

再次感谢伙计! ;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-15
    • 2011-11-17
    • 1970-01-01
    • 2021-08-27
    • 2022-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多