I am trying to receive some data from a microcontroller connected to a windows PC through USB. I am doing this with the .net SerialPort functionality as you can see in my code below. I know the sleep is not very elegant but this is just my test code since I cannot get this to work.
Basically I have an Arduino sending some data which I can receive with the Arduino Serial Monitor, my c# program only outputs emtpy lines though, and the receive buffer is always emtpy. (the exact code you see here will output a zero and an emtpy line every second, even though a random number is sent every 200ms) I already confirmed the baudrate is correct on both ends, I also switched over to a raspberry pi pico which had the same result. I would really appreciate it if someone could help out here, as far as google is aware I must be the first one to run into this:D
using System;
using System.IO.Ports;
using System.Threading;
namespace serial_test
{
class Program
{
static void Main(string[] args)
{
SerialPort testPort = new SerialPort("COM9", 9600);
testPort.Open();
while (true)
{
Thread.Sleep(1000);
Console.WriteLine(testPort.BytesToRead);
Console.WriteLine(testPort.ReadExisting());
}
}
}
}
Instead of running an endless loop you may want to subscribe to the port's DataReceived event. You can then create a variable within the handler to read the data.
var port = (SerialPort)sender;
// Retrieve and write your data here
This may be easier to debug since you can place a breakpoint in the handler. If you never receive any data then you may have a handshake problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.