【问题标题】:How to access serial port data from different methods如何从不同的方法访问串口数据
【发布时间】:2013-05-19 12:51:51
【问题描述】:

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

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

【问题讨论】:

  • 不要永远忽略 Read() 方法的返回值。这不是你希望的那样。串口很慢,你通常只能得到 1 或 2 个字节。考虑改用 ReadLine(),它会阻塞直到收到 NewLine 字符串。或者在得到完整回复之前不要处理数据。
  • @HansPassant 我实际上并没有忽略 Read() 的值。我读取了所有发送的字节;虽然在少数情况下,它将 readADC() 发送的 11 个字节拆分为 10 和 1 或 8 和 3 等。
  • 你肯定会在你的 sn-p 中忽略它。你似乎想用 BytesToRead 做点什么,但也放弃了。就像你描述的那样出错,在下一个 Read() 调用中得到更少的东西。不要忽视它。

标签: c# serial-port arduino


【解决方案1】:

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

这是一个代码示例:

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...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2015-08-17
    • 2017-04-28
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多