【问题标题】:How can I receive data from a PC to an Arduino?如何从 PC 接收数据到 Arduino?
【发布时间】:2011-11-27 01:58:26
【问题描述】:

我开发了一个通过串口为 Arduino 发送数据的应用程序,但我不明白如何在 Arduino 上接收它。我通过串口为 Arduino 发送一个字符串,Arduino 接收它,但它在我的代码中不起作用(在 Arduino 上,我一次接收一个字节)。

更新:它正在工作 ;)

发送数据的C#代码:

using System;
using System.Windows.Forms;

using System.Threading;
using System.IO;
using System.IO.Ports;

pulic class senddata() {

    private void Form1_Load(object sender, System.EventArgs e)
    {
        //Define a serial port.
        serialPort1.PortName = textBox2.Text;
        serialPort1.BaudRate = 9600;
        serialPort1.Open();
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        serialPort1.Write("10");  //This is a string. The 1 is a command. 0 is interpeter.
    }
}

Arduino 代码:

我已更新代码

#include <Servo.h>

Servo servo;
String incomingString;
int pos;

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    incomingString = "";
}

void loop()
{
    if(Serial.available())
    {
        // Read a byte from the serial buffer.
        char incomingByte = (char)Serial.read();
        incomingString += incomingByte;

        // Checks for null termination of the string.
        if (incomingByte == '0') { //When 0 execute the code, the last byte is 0.
            if (incomingString == "10") { //The string is 1 and the last byte 0... because incomingString += incomingByte.
                servo.write(90);
            }
            incomingString = "";
        }
    }
}

【问题讨论】:

标签: c# serial-port arduino


【解决方案1】:

一些让我挑眉的事情:

serialPort1.Write("1");

这将完全写入一个字节,1,但没有换行符,也没有尾随的 NUL 字节。 但是在这里你正在等待一个额外的 NUL 字节:

if (incomingByte == '\0') {

您应该使用WriteLine 而不是Write,并等待\n 而不是\0

这有两个副作用:

首先:如果配置了一些缓冲,那么有一定的机会,一个新的行会将缓冲的数据推送到 Arduino。为了确定您必须深入研究 MSDN 上的文档。

第二:这使您的协议仅 ASCII。这对于更容易调试很重要。然后,您可以使用普通的终端程序,如 Hyperterm 或 HTerm (edit) 甚至 Arduino IDE 本身中的串行监视器 (edit) 来调试您的 Arduino 代码,而不必担心 C# 代码中的错误。当 Arduino 代码工作时,您可以专注于 C# 部分。分而治之。

编辑:我在挖出自己的 Arduino 后注意到的另一件事:

incomingString += incomingByte;
....
if (incomingByte == '\n') { // modified this
  if(incomingString == "1"){

这当然不会按预期工作,因为此时字符串将包含“1\n”。要么与“1\n”进行比较,要么将+= 行移到if 之后。

【讨论】:

  • 您是否尝试使用终端程序来调试 Arduino?
  • 串行监视器?是的,我试试。
  • 我有解决方案,它有效,但我现在不知道是否更正确
  • @FredVaz:您的解决方案只是使用数字 0 而不是换行符作为分隔符。所以也是正确的。请投票并接受FAQ 中描述的对您有帮助的答案。
【解决方案2】:

您也可以尝试使用Firmata library - 这是在 Arduino 上安装标准固件并从 .net 管理它的更好方法

我相信,Firmata 2.0+ 已经支持 I2C 和伺服控制。

http://firmata.org/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多