我正在尝试用windows窗体中的C#程序连接到arduino。我可以将数据从c#发送到arduino,但我希望将数据从arduino发送到C#程序。
我已经尝试过SerialDataReceivedEventHandler,但在构建表单后无法获得数据...
我能做什么?
public Form1()
{
InitializeComponent();
Init();
}//end form 1
private void Init()
{
try
{
arduinoPort = new SerialPort();
arduinoPort.BaudRate = 9600;
arduinoPort.PortName = "COM4";
arduinoPort.Handshake = Handshake.None;
arduinoPort.RtsEnable = true;//request to send true
arduinoPort.DtrEnable = true;//arduino can send messages to the c# program
arduinoPort.DataReceived += new SerialDataReceivedEventHandler(GetFromArduino);
arduinoPort.Open();
}//end try
catch (Exception ex) { MessageBox.Show(ex.Message); }
}//end init
private void GetFromArduino(object sender, SerialDataReceivedEventArgs e)
{
//string arduinoInputString = arduinoPort.ReadLine();
//Invoke(new Action(() => label1.Text = arduinoInputString));
MessageBox.Show("does it work?");
}//end get from arduino
发布于 2018-06-10 18:00:28
I don't know if it matters, but this what i did and it solved:
1. in the setup function of the arduino program i had a loop that ran on all the pins, now i specified it to the pins i really use.
2. i don't open the port in the form.cs, but in the program.cs and run a while loop that just check if the port is open. then, it gets the data without disturbing the form to run...
**in the Program.cs:**
public static SerialPort arduinoPort { get; set; }
public static string arduinoInputString { get; set; }
[STAThread]
static void Main()
{
arduinoPort = new SerialPort();
try
{
arduinoPort = new SerialPort();
arduinoPort.BaudRate = 250000;
arduinoPort.PortName = "COM4";
//arduinoPort.Handshake = Handshake.None;
//arduinoPort.RtsEnable = true;//request to send true
//arduinoPort.DtrEnable = true;//arduino can send messages to the c# program
////arduinoPort.DataReceived += new SerialDataReceivedEventHandler(GetFromArduino);
arduinoPort.DataReceived += DataReceivedHandler;
arduinoPort.Open();
}//end try
catch (Exception ex) { Console.WriteLine((ex.Message)); }
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
while (arduinoPort.IsOpen)//read data if the port is open
{
}
}//end main
static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort comm = (SerialPort)sender;
arduinoInputString = comm.ReadExisting();
Form1.label1.Text = arduinoInputString;//label to show the input string from arduino
}//end get data from arduino
https://stackoverflow.com/questions/50779414
复制相似问题