打开Arduino LED

The*_*Woo 0 c# arduino

我正在尝试在Arduino上获取要由我的C#程序联系的代码,以打开和关闭板载(插针13)LED。这是我已加载到Arduino中的代码:

void setup()
{
 Serial.begin(9600);
 pinMode(13, OUTPUT);
}
void loop()
{
 if (Serial.available() > 0)
 {
  int b = Serial.read();
  if (b == 1)
  {
   digitalWrite(13, HIGH);
  }
  else if (b == 0)
  {
   digitalWrite(13, LOW);
  }
  Serial.flush();
 }
}
Run Code Online (Sandbox Code Playgroud)

我找到并下载了此代码,并使LED正常工作!(万岁!)

我尝试使用简单的OnButton和OffButton将代码反向工程为我自己的代码,但无法正常工作。有人可以看看下面的代码,并告诉我是否缺少明显的内容。

using System.IO;
using System.IO.Ports;

public static System.IO.Ports.SerialPort serialPort1;
private delegate void LineReceivedEvent(string line);

private void establishConnection()
{
   System.CompnentModel.IContainer components = new System.ComponentModel.Container();
   serialPort1 = new System.IO.Ports.SerialPort(components);
   serialPort1.PortName = "COM7";
   serialPort1.BaudRate = 9600;
   serialPort1.DtrEnable = true;
   serialPort1.Open();
}
private void terminateConnection()
{
   serialPort1.Close();
}
private void OnButton_Click(object sender, EventArgs e)
{
   establishConnection();
   serialPort1.Write(new byte[] { Convert.ToByte("1") }, 0, 1);
   terminateConnection();
}
private void OffButton_Click(object sender, EventArgs e)
{
   establishConnection();
   serialPort1.Write(new byte[] {Convert.ToByte("0") }, 0, 1);
   terminateConnection();
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。我可以看到当我单击C#按钮时Ardiuno正在接收某种命令,并且它与我在上面的链接中下载的代码一起使用...我正在拔头发...

The*_*Woo 5

Arduino代码:

void setup()
{
 Serial.begin(9600);
 pinMode(13, OUTPUT);
}
void loop()
{
 if (Serial.available() > 0)
 {
  int b = Serial.read();
  if (b == 1)
  {
   digitalWrite(13, HIGH);
  }
  else if (b == 0)
  {
   digitalWrite(13, LOW);
  }
  Serial.flush();
 }
}
Run Code Online (Sandbox Code Playgroud)

C#代码:

using System.IO;
using System.IO.Ports;

public static System.IO.Ports.SerialPort serialPort1;
private delegate void LineReceivedEvent(string line);

public Form1()
{
   InitializeComponent();
   System.CompnentModel.IContainer components = new System.ComponentModel.Container();
   serialPort1 = new System.IO.Ports.SerialPort(components);
   serialPort1.PortName = "COM7";
   serialPort1.BaudRate = 9600;
   serialPort1.DtrEnable = true;
   serialPort1.Open();
}
private void OnButton_Click(object sender, EventArgs e)
{
   serialPort1.Write(new byte[] { Convert.ToByte("1") }, 0, 1);
}
private void OffButton_Click(object sender, EventArgs e)
{
   serialPort1.Write(new byte[] { Convert.ToByte("0") }, 0, 1);
}
Run Code Online (Sandbox Code Playgroud)