Fre*_*Vaz 9 c# serial-port arduino
我开发了一个通过串口发送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.
}
}
Run Code Online (Sandbox Code Playgroud)
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 = "";
}
}
}
Run Code Online (Sandbox Code Playgroud)
有些事情让我扬眉吐气:
serialPort1.Write("1");
Run Code Online (Sandbox Code Playgroud)
这将恰好写入一个字节,1但没有换行符,也没有尾随 NUL 字节。但在这里你正在等待一个额外的 NUL 字节:
if (incomingByte == '\0') {
Run Code Online (Sandbox Code Playgroud)
您应该使用WriteLine代替Write,并等待\n代替\0。
这有两个副作用:
首先:如果配置了一些缓冲,那么有一定的机会,新的一行会将缓冲的数据推送到 Arduino。为了确定这一点,您必须深入研究 MSDN 上的文档。
第二:这使得你的协议仅支持 ASCII。这对于更轻松地调试很重要。然后,您可以使用Hyperterm 或 HTerm(编辑)等普通终端程序,甚至 Arduino IDE 本身中的串行监视器(编辑)来调试 Arduino 代码,而不必担心 C# 代码中的错误。当 Arduino 代码运行时,您可以专注于 C# 部分。分而治之。
编辑:在挖掘出我自己的 Arduino 后我注意到的另一件事:
incomingString += incomingByte;
....
if (incomingByte == '\n') { // modified this
if(incomingString == "1"){
Run Code Online (Sandbox Code Playgroud)
这当然不会按预期工作,因为此时字符串将包含“1\n”。要么与“1\n”进行比较,要么将该+=行移到if.