简体   繁体   中英

C# SerialPort can't receive from Arduino Micro

Trying to communicate between .NET Framework 4.6.1 SerialPort and an Arduino Micro, I can successfully send bytes to the Micro but can't receive. Trying an echo test, the Arduino receive works (and RX lights up) but TX fails - no bytes or error sent. I've stripped the code down as much as possible to where the Arduino simply writes a character every second and the C# app just reads in a loop, but no bytes are received. The Micro TX light doesn't light up and the Serial.write call returns 0. I have turned on/off all the various flow control/handshake settings I can find, makes no difference. Confirmed Parity/Stop Bits etc. I can go back and forth between my test app and RealTerm, and everything works with RealTerm just fine, close it and launch the C# SerialPort app and nada. How is it possible for the SerialPort to fail this?

C#

class Program
{
    static void Main(string[] args)
    {
        readPacket();
    }

    private static void readPacket()
    {
        var spd_Port = new SerialPort("COM4", 115200);
        spd_Port.ErrorReceived += Spd_Port_ErrorReceived;
        spd_Port.Open();

        while (true)
        {
            while (spd_Port.BytesToRead > 0)
            {
                Console.WriteLine(spd_Port.ReadChar());
            }
            Thread.Sleep(10);
        }
    }

    private static void Spd_Port_ErrorReceived(Object sender, SerialErrorReceivedEventArgs e)
    {
        Console.WriteLine(e);
    }
}

Arduino

void setup()
{
    // set all pins as inputs (except serial pins)
    init_pins();

    pinMode(ARD_LED, OUTPUT);
    digitalWrite(ARD_LED, HIGH);

    // Configure serial port
    Serial.begin(115200);
}

int i = 0;
void loop()
{
    int j = Serial.write(0x24);
    if (j)
    {
        digitalWrite(ARD_LED, i == 0 ? HIGH : LOW);
        i = (i + 1) % 2;
    }

    delay(1000);
}

Please try enabling DTR and RTS :

_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;

EDIT

According to gregsmi it is working by enabling either DTR or RTS

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