我目前正在使用 Arduino 进行机器人项目。我想在不同的时间从不同的方法访问串口。
例如,我想在时间 t1 读取 ADC 并在时间 t2 获取电机电流。所以我创建了 readADC() 和 motorCurrents() 方法,它们都应该返回不同大小的 int 数组。接收到的串口数据如下所示。
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
int n = serialPort1.BytesToRead;
serialPort1.Read(data, 0, data.Length);
}
我已经在 Arduino 端实现了所有相关的编码。我也设置了串口。我需要在 C# 中实现以下命令
private int[] ReadADC()
{
string input = "AN\n"; // This is the command for reading the ADC on the Wildthumper board.
serialPort1.Write(input);
// The Wildthumper now sends 11 bytes, the last of which is '*' and the first
// 10 bytes are the data that I want. I need to combine two bytes together
// from data received and make five values and return it.
for (int i = 0; i < 5; i++)
{
adcValues[i] = data[0 + i * 2] <<8+ data[1 + i * 2];
}
return adcValues;
// Where data is the bytes received on serial port;
}
相似地:
private int[] getMotorCurrents()
{
string input = "MC\n"; // Wildthumper board command
serialPort1.Write(input);
// The Wildthumper now sends 5 bytes with the last one being '*'.
// And the first four bytes are the data that I want.
for (int i = 0; i < 2; i++)
{
MotorCurrents[i] = data[0 + i * 2] <<8 +data[1 + i * 2];
}
return MotorCurrents;
}
首先,发送给我的字节数发生了变化。那么如何使用全局变量呢?对于数据(用于存储上述接收到的串行数据的变量)?