[英]C# .net serial port receive buffer always emtpy
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.我正在尝试从通过 USB 连接到 windows PC 的微控制器接收一些数据。我正在使用 .net SerialPort 功能执行此操作,您可以在下面的代码中看到。 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.基本上我有一个 Arduino 发送一些我可以用 Arduino 串行监视器接收的数据,但我的 c# 程序只输出空行,接收缓冲区总是空的。 (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.
(你在这里看到的确切代码将是每秒 output 一个零和一个空行,即使每 200 毫秒发送一个随机数)我已经确认两端的波特率是正确的,我也切换到一个树莓派 pico同样的结果。 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
如果有人能在这里提供帮助,我将不胜感激,据谷歌所知,我一定是第一个遇到这个问题的人: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.您可能希望订阅端口的 DataReceived 事件,而不是运行无限循环。 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.
如果您从未收到任何数据,那么您可能遇到了握手问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.