简体   繁体   English

C#与arduino串行通信

[英]C# Serial communication with arduino

I'm trying to communicate with my arduino from my pc. 我正试图通过我的电脑与我的arduino进行通信。 I'm sending 1,0,0,0 in a loop and the arduino sends the received data back. 我在循环中发送1,0,0,0并且arduino将接收的数据发回。 However, instead of getting 1,0,0,0 back, this is what I get: 但是,这不是获得1,0,0,0,而是我得到的:

1000
1000
1000
1000
1000
1000
1000
0011
0000
0010
0100
1001
0000
0011
0000

As you can see, it works at the beginning, but starts to get weird after a few messages. 正如你所看到的,它在开始时起作用,但在一些消息之后开始变得怪异。 Instead of sending 3 0's it sent 5. Why is that? 而不是发送3 0,它发送了5.为什么?

Here is my code: 这是我的代码:

C# Application: C#应用:

class Program
{
    SerialPort p;

    static void Main(string[] args)
    {
        Program p = new Program();
        p.initialize();
    }
    private void initialize()
    {
        p = new SerialPort("COM3", 115200);
        p.Open();

        byte[] data = { 1, 0, 0, 0 };

        Thread t = new Thread(reading);
        t.Start();

        while(true)
        { 
            p.Write(data, 0, data.Count());
        }
        Console.ReadLine();
    }
    private void reading()
    {
        while (true)
        {
            Console.WriteLine(p.ReadLine());
        }
    }
}

Arduino: Arduino的:

void setup()
{
    Serial.begin(115200);
    delay(5000);
    Serial.println("Program started....");
}

void loop()
{
    for (int i = 0;i<4;i++)
    {
        Serial.print(Serial.read());
    } 
    Serial.println(); 
    delay(500);
}

I think the problem is caused by your 500 ms delay in the Arduino loop. 我认为问题是由Arduino循环中的500 ms延迟引起的。

The PC is sending characters as fast as it can. PC正在尽可能快地发送字符。

However the the Arduino receives 4 characters and then delays 1/2 a second (during the delay the PC could send 62,000 characters). 然而,Arduino接收4个字符然后延迟1/2秒(在延迟期间PC可以发送62,000个字符)。

For a while the Arduino serial receive routine puts the characters into a buffer. 有一段时间,Arduino串行接收例程将字符放入缓冲区。 But after it receives a few correctly the buffer is full and starts overwriting old characters with the new characters received. 但是在收到一些正确的缓冲区已满并开始用接收到的新字符覆盖旧字符后。

To verify this is the problem, remove the line delay(500); 要验证这是问题,请删除线路延迟(500); from your Arduino code and add a delay to the PC after the line: p.Write(data, 0, data.Count()); 来自你的Arduino代码并在行之后向PC添加延迟:p.Write(data,0,data.Count());

Also, how does Console.ReadLine(); 另外,Console.ReadLine()如何; ever get executed since if is after your while(true) infinite loop? 永远被执行,因为如果是在你的while(真)无限循环之后?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM