如何从不同的方法访问串口数据

本文关键字:方法 访问 串口 数据 | 更新日期: 2023-09-27 18:15:20

我目前正在使用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;
     }

首先,发送给我的字节数改变了。那么如何使用全局变量呢?对于数据(用于存储如上所述接收的串行数据的变量)?

如何从不同的方法访问串口数据

您需要创建一个全局变量,并在接收到数据触发时将数据保存到该变量中。这并不难。

下面是一个代码示例:
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...
}