arduino iic发送如下共用体 union data { struct bag//结构体名称 { byte bytee; float PID1[3]; float PID2[3]; long PWM_PN; long PWM_Pump; float T1=11.2; float T2; }bag; byte bytes[41]; }; 另一个arduino iic接收请写出两方代码
时间: 2023-06-12 22:03:40 浏览: 163
基于arduino采用pid控制的一款板球系统的全套资料.zip
5星 · 资源好评率100%
发送端代码:
```
#include<Wire.h>
union data {
struct bag {
byte bytee;
float PID1[3];
float PID2[3];
long PWM_PN;
long PWM_Pump;
float T1;
float T2;
}bag;
byte bytes[41];
};
data myData;
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
// 更新数据
myData.bag.PID1[0] = 1.0;
myData.bag.PID1[1] = 2.0;
myData.bag.PID1[2] = 3.0;
myData.bag.PID2[0] = 4.0;
myData.bag.PID2[1] = 5.0;
myData.bag.PID2[2] = 6.0;
myData.bag.PWM_PN = 100;
myData.bag.PWM_Pump = 200;
myData.bag.T1 = 11.2;
myData.bag.T2 = 22.4;
// 发送数据
Wire.beginTransmission(8);
Wire.write(myData.bytes, 41);
Wire.endTransmission();
delay(100);
}
```
接收端代码:
```
#include<Wire.h>
union data {
struct bag {
byte bytee;
float PID1[3];
float PID2[3];
long PWM_PN;
long PWM_Pump;
float T1;
float T2;
}bag;
byte bytes[41];
};
data myData;
void receiveEvent(int numBytes) {
int i = 0;
while(Wire.available() > 0) {
myData.bytes[i] = Wire.read();
i++;
}
}
void setup() {
Wire.begin(8);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop() {
Serial.print("bytee: ");
Serial.println(myData.bag.bytee);
Serial.print("PID1: ");
Serial.print(myData.bag.PID1[0]);
Serial.print(", ");
Serial.print(myData.bag.PID1[1]);
Serial.print(", ");
Serial.println(myData.bag.PID1[2]);
Serial.print("PID2: ");
Serial.print(myData.bag.PID2[0]);
Serial.print(", ");
Serial.print(myData.bag.PID2[1]);
Serial.print(", ");
Serial.println(myData.bag.PID2[2]);
Serial.print("PWM_PN: ");
Serial.println(myData.bag.PWM_PN);
Serial.print("PWM_Pump: ");
Serial.println(myData.bag.PWM_Pump);
Serial.print("T1: ");
Serial.println(myData.bag.T1);
Serial.print("T2: ");
Serial.println(myData.bag.T2);
delay(100);
}
```
阅读全文