我正在尝试在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的值的增量,但这是行不通的,我继续从主机发送数据,但不能从从机发送数据。
也许我没记错,能帮帮我吗?谢谢。
亲切的问候,
最佳答案
最终我找到了解决方案,它只是在“ 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);
}
再次感谢家伙! ;)