我今天早些时候问过这个问题,但是我已经改进了我的代码,所以我在这里提出了一个新问题。
这是我目前的代码:
Arduino代码:
void setup()
{
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
Serial.begin(9600);
}
void loop()
{
if(Serial.available() > 0)
{
char letter = Serial.read();
if (letter == 'A')
{
digitalWrite(13,HIGH);
Serial.println("THE LED IS ON");
}
else if (letter == 'B')
{
digitalWriter(13,LOW);
Serial.println("THE LED IS OFF");
}
}
}
我有一个带有onButton,offButton和textboxInterface的C#程序。这是我在C#中的代码。
C#代码:
using System.IO.Ports;
public partial class Form1: Form
{
public static System.IO.Ports.SerialPort serialPort1;
private delegate void LineReceivedEvent(string line);
public Form1()
{
InitizlizeComponent();
System.ComponentModel.IContainer components = new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = "COM7";
serialPort1.BaudRate = 9600;
serialPort1.DtrEnable = true;
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private static void serialPort1_DataReceived(object sender, SerialDataEventReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
textboxInterface.Text = indata;
}
我认为这大多是正确的(?),我得到的唯一错误是作为最后一个 textboxInterface ,出现错误说:*非静态字段需要对象引用,方法或属性'Arduino_Interface.Form1.textboxInterface'*
有人可以告诉我我正在做什么蠢事......
答案 0 :(得分:0)
首先,从static
的声明中删除serialPort1_DataReceived
。您需要访问表单的实例字段,因此它不能是static
。
其次,此事件将在后台线程上引发,您无法从该线程更新UI。您需要封送对UI线程的调用以更新文本框。像这样:
private void serialPort1_DataReceived(object sender, SerialDataEventReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
this.BeginInvoke(new Action(() => textboxInterface.Text = indata));
}