【发布时间】: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 = "";
}
}
}
【问题讨论】:
-
也许是一个更好的地方问:electronics.stackexchange.com
标签: c# serial-port arduino