简体   繁体   English

Arduino至C#数据接收

[英]Arduino to C# Data Receive

I've asked this question earlier today, but have refined my code so am putting a new question up here. 我今天早些时候已经问过这个问题,但是已经完善了我的代码,所以在这里提出了一个新问题。

This is the code I have at the moment: 这是我目前的代码:

Arduino Code: 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");
  }
 }
}

I have a C# program with an onButton, offButton, and textboxInterface. 我有一个带有onButton,offButton和textboxInterface的C#程序。 This is the code I have in C#. 这是我在C#中拥有的代码。

C# Code: 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;
 }

I think that is mostly right (?), the only error I am getting is as the last textboxInterface with an error coming up saying: *An object reference is required for the non-static field, method, or property 'Arduino_Interface.Form1.textboxInterface'* 我认为大多数情况下是对的(?),我得到的唯一错误是最后一个textboxInterface出现错误:*非静态字段,方法或属性'Arduino_Interface.Form1需要对象引用。 textboxInterface'*

Can someone please show me what stupid thing I'm doing... 有人可以告诉我我在做什么愚蠢的事...

First, remove static from the declaration of serialPort1_DataReceived . 首先,从serialPort1_DataReceived的声明中删除static You need access to the form's instance fields so it cannot be static . 您需要访问表单的实例字段,因此它不能是static

Second, this event will be raised on a background thread and you cannot update the UI from that thread. 其次,此事件将在后台线程上引发,并且您无法从该线程更新UI。 You will need to marshal the call to UI thread to update the textbox. 您将需要整理对UI线程的调用才能更新文本框。 Something like this: 像这样:

private void serialPort1_DataReceived(object sender, SerialDataEventReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    this.BeginInvoke(new Action(() => textboxInterface.Text = indata));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM