[英]How to send serial data from Arduino to Visual Studio C# with zedgraph and vice versa simultaniously
I'm working on a project to read analog data from Arduino and then display it in Visual C# with zedgraph. 我正在一个项目中,从Arduino读取模拟数据,然后使用zedgraph在Visual C#中显示它。 I have a start button on my GUI that starts the reading of serial data from Arduino.
我的GUI上有一个开始按钮,用于开始从Arduino读取串行数据。 I can do that with
private void read_Tick
method that open the arduino port, read serial data, display data on zedgraph, and then close the arduino for every 1 second. 我可以使用
private void read_Tick
方法做到这一点, private void read_Tick
方法打开arduino端口,读取串行数据,在zedgraph上显示数据,然后每隔1秒关闭arduino。 If you having a trouble understanding my words, here's the method: 如果您在理解我的话时遇到问题,请使用以下方法:
private void read_Tick(object sender, EventArgs e)
{
try
{
arduino.Open();
LineItem kurvaKonsentrasi = zedGraphKonsentrasi.GraphPane.CurveList[0] as LineItem;
IPointListEdit listKonsentrasi = kurvaKonsentrasi.Points as IPointListEdit;
double time = (Environment.TickCount - timeStart) / 1000.0;
float dataKonsentrasi = float.Parse(arduino.ReadLine(), CultureInfo.InvariantCulture.NumberFormat);
listKonsentrasi.Add(time,Convert.ToDouble(dataKonsentrasi));
arduino.Close();
Scale xScale = zedGraphKonsentrasi.GraphPane.XAxis.Scale;
if (time > xScale.Max - xScale.MajorStep)
{
xScale.Max = time + xScale.MajorStep;
xScale.Min = xScale.Max - 30.0;
}
zedGraphKonsentrasi.AxisChange();
zedGraphKonsentrasi.Invalidate();
}
catch (Exception fail)
{
if (arduino.IsOpen)
{
arduino.Close();
}
}
}
This method is called when I clicked start button. 单击开始按钮时将调用此方法。 So, my problem is, I want to send string data "on" when I click start button.
所以,我的问题是,我想在单击开始按钮时“打开”发送字符串数据。 This string data is used for ordering Arduino to move the servo I attached with this code in
void loop()
before the analog readings. 该字符串数据用于命令Arduino在模拟读数之前将我附带此代码的伺服器移动到
void loop()
。
if(Serial.available()>0){
start = Serial.read();
if(start == "on"){
servoMotor.write(40);
}
}
I know there's something wrong with what I'm doing because I cant start the servo. 我知道我做的事情有问题,因为我无法启动伺服器。 Can you give me advice what should I do to make the Visual C# send the command to arduino to start the servo once then arduino start the readings and then Visual C# read it?
您能否给我一些建议,使Visual C#将命令发送到arduino以启动伺服,然后由arduino启动读数,然后由Visual C#读取它,我该怎么做?
Serial.read() only returns a single byte, so you're not going to get "on". Serial.read()仅返回一个字节,因此您不会“ on”。 You'll get "o" the first time, and if you read it again, you'll get "n."
您将第一次得到“ o”,如果再次阅读它,您将得到“ n”。
If you follow the "on" with a "\\n" (new line character), you can do something like this: 如果在“ on”后面加上“ \\ n”(换行符),则可以执行以下操作:
char command[3];
if (Serial.available() > 0) {
int bytesRead = Serial.readBytesUntil('\n', command, 2);
command[2] = '\0';
if strcmp(command, "on") == 0) {
servoMotor.write(40);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.