我目前正在与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;
}
首先,发送给我的字节数发生了变化。那么如何使用全局变量呢?对于数据(用于存储上面给出的串行数据的变量)?
答案 0 :(得分:0)
您需要创建一个全局变量,并在收到数据时将数据保存到该变量。这并不难。
这是一个代码示例:
public class myclass{
public string arduinoData = "";
private void serialPort1_DataReceived(
object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.arduinoData = serialPort1.ReadLine(data, 0, data.Length);
}
//....The rest of your code, such as main methods, etc...
}