通过串口从C#发送字符串
我试图通过串行端口将一串数据从计算机发送到主板。数据字符串由一些标识符字母和两个值组成。一个值介于0和240之间(因此可能是两位数或三位数),第二个值是介于-45和+45之间的数字。我已经设法用C#编写了发送字符串的代码,如下所示通过串口从C#发送字符串,c#,arduino,C#,Arduino,我试图通过串行端口将一串数据从计算机发送到主板。数据字符串由一些标识符字母和两个值组成。一个值介于0和240之间(因此可能是两位数或三位数),第二个值是介于-45和+45之间的数字。我已经设法用C#编写了发送字符串的代码,如下所示 private void goButton_Click(object sender, EventArgs e) { if (!serialPort1.IsOpen) return; command
private void goButton_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
return;
command = 43;
outBuffer += "E" + command1 + "F";
outBuffer += "G" + command2 + "H";
// Therefore send through serial port a string in the following format:
// E<command1>FG<command2>H
// Where <command1> will be an int value between 0 - 240, and
// <command2> will be be a value between -45 and + 45
serialPort1.Write(outBuffer);
outBuffer = "";
}
private void goButton_单击(对象发送方,事件参数e)
{
如果(!serialPort1.IsOpen)
回来
命令=43;
突发事件+=“E”+命令1+“F”;
突发事件+=“G”+命令2+“H”;
//因此,通过串行端口发送以下格式的字符串:
//EFGH
//其中,将是介于0-240和之间的int值
//将是介于-45和+45之间的值
串行端口1.写入(突发);
“爆发”;
}
现在,当Arduino板接收到字符串时,我遇到了从字符串中提取值的问题。我已经编写了一些代码,这些代码似乎正确地显示了字符串,但我无法找到我做错了什么,或者如何实际过滤/提取这两个值,并将它们存储在两个单独的变量中。我目前拥有的Arduino代码是:
if (Serial.available() > 0)
{
char inData;
String inDataString;
inData = Serial.read();
inDataString = inData;
// Shows the string of E<command1>FG<command2>H
Serial.print(inDataString);
}
if(Serial.available()>0)
{
查林达;
字符串inDataString;
inData=Serial.read();
inDataString=inData;
//显示EFGH的字符串
串行打印(inDataString);
}
如何使Arduino上的代码正确,以便从计算机发送两个值?我不知道Arduino,但您可以执行以下操作:
int start = inDataString.indexOf('E')
int end = inDataString.indexOf('F')
char str_char[end - start];
inDataString.substring(start, end).toCharArray(str_char, sizeof(str_char));
int my_integer_data = atoi(str_char);
发送字符串时,可以在每个命令后添加回车符/换行符。比如:
outBuffer = string.Format("E{1}F{0}G{2}H{0}", Environment.NewLine, command1, command2);
读入后,您就会知道每个命令都存在于自己的行中,因此您可以拆分它:
string[] commands = inDataString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
在Arduino上执行此类操作的一个简单方法是使用TextFinder库()。例如:
#include <TextFinder.h>
TextFinder finder(Serial);
void setup()
{
Serial.begin(9600);
}
void loop()
{
finder.find("E");
long command1 = finder.getValue();
finder.find("FG");
long command2 = finder.getValue();
finder.find("H");
// Do something with command1 and command 2
}
#包括
文本查找器(串行);
无效设置()
{
Serial.begin(9600);
}
void循环()
{
查找者。查找(“E”);
long command1=finder.getValue();
查找者。查找(“FG”);
long command2=finder.getValue();
finder.find(“H”);
//使用command1和command2执行某些操作
}