大家好我对C#和Arduino都很陌生。当我向我的Arduino发送文本时,它不会将其发送回应用程序中的文本框。我可以将它发送到我的Arduino但是当我发送的消息必须在应用程序的文本框中时我收到错误。
以下是我收到错误的部分:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Output.Text = serialPort1.ReadExisting();
}
这是我的代码:
public partial class ArduinoSerial : Form
{
public ArduinoSerial()
{
InitializeComponent();
string[] serialPorts = System.IO.Ports.SerialPort.GetPortNames();
cboPorts.Items.AddRange(serialPorts);
cboBaud.Items.Add(2400);
cboBaud.Items.Add(4800);
cboBaud.Items.Add(9600);
cboBaud.Items.Add(14400);
cboBaud.Items.Add(19200);
cboBaud.Items.Add(28800);
cboBaud.Items.Add(38400);
cboBaud.Items.Add(57600);
cboBaud.Items.Add(115200);
cboPorts.SelectedIndex = 0;
cboBaud.SelectedIndex = 2;
}
private void cboPorts_SelectedIndexChanged(object sender, EventArgs e)
{
string[] serialPorts = System.IO.Ports.SerialPort.GetPortNames();
cboPorts.Items.AddRange(serialPorts);
}
private void cboBaud_SelectedIndexChanged(object sender, EventArgs e)
{
cboBaud.Items.Add(2400);
cboBaud.Items.Add(4800);
cboBaud.Items.Add(9600);
cboBaud.Items.Add(14400);
cboBaud.Items.Add(19200);
cboBaud.Items.Add(28800);
cboBaud.Items.Add(38400);
cboBaud.Items.Add(57600);
cboBaud.Items.Add(115200);
}
private void btnStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = cboPorts.SelectedItem.ToString();
serialPort1.BaudRate = Convert.ToInt32(cboBaud.SelectedItem.ToString());
if (!serialPort1.IsOpen)
{
btnStart.Enabled = false;
btnStop.Enabled = true;
serialPort1.Open();
}
}
private void btnStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
btnStart.Enabled = true;
btnStop.Enabled = false;
serialPort1.Close();
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen) return;
serialPort1.Write(txtInput.Text + "\n");
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Output.Text = serialPort1.ReadExisting();
}
}
我的ino文件
/*
Name: LOOP_C.ino
Created: 9/8/2017 10:51:31 AM
Author: Jari
*/
// the setup function runs once when you press reset or power the board
void setup() {
Serial.begin(9600);
}
// the loop function runs over and over again until power down or reset
void loop() {
while (Serial.available()) {
Serial.write(Serial.read());
}
}
我已经尝试了2个多小时,我无法在任何地方找到答案。
答案 0 :(得分:0)
如果遇到CrossThreadException,请尝试此操作:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SetText(serialPort1.ReadExisting());
}
private void SetText(string text)
{
if (Output.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
Output.Text = text;
}
}
我这里没有编译器,所以也许你需要修复一些东西。如果是的话 - 抱歉