简体   繁体   中英

Serial Port not receiving any data

I'm trying to write a simple c# console application to read/write from a serial port that communicates to an Arduino that I have hooked up. The problem that I'm running into is that I can write to the Arduino no problem, but I am unable to receive any data back. My serial port's SerialDataReceivedEventHandler isn't ever being fired either, but I'm guessing those two issues are related.

I know it isn't my Arduino that is causing the problem because when using the Arduino IDE I am able to receive data without any problems. Here is what I've got code wise for now:

SerialPort sPort = new SerialPort();
sPort.PortName = SerialPort.GetPortNames()[0];
sPort.BaudRate = 9600;
sPort.Parity = Parity.None;
sPort.DataBits = 8;
sPort.StopBits = StopBits.One;
sPort.RtsEnable = false;
sPort.Handshake = Handshake.None;

sPort.DataReceived += new SerialDataReceivedEventHandler(sPort_dataReceived);
sPort.ErrorReceived += new SerialErrorReceivedEventHandler(sPort_ErrorReceived);

sPort.Open();

Console.Read();
sPort.Write("tt_calib");

while (true)
{
    if (sPort.ReadExisting() != string.Empty)
        Console.WriteLine(sPort.ReadExisting());
}

I am aware that I don't close the port in this code, that is not the issue as I am able to rerun and open it every time. This code is also not in its final form, I'm attempting to get the read event working so that I can react to various messages differently. I've read what seems like every question but no solution I've found seems to do the trick.

This is a C# .NET 4.5 console application running on Windows 8.1

It ended up being a stupid simple issue. Instead of sPort.RtsEnable = false; it should be true . All events now trigger and I am able to read.

mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

private static void DataReceivedHandler(
                    object sender,
                    SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    Console.WriteLine("Data Received:");
    Console.Write(indata);
}

I had the exact same issue and finally realized that my hardware flow control setting is bios configurable and my setting was DISABLED ! doh

With C# in VS2019 available cross-platform, I ran into the same issue on my VM (Parallels+Windows10) and my host machine (MacOS). Setting DTR to true did the trick

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM