Receiving and sending data by C# application on PC (with Arduino Uno)

Hi.
I implemented some C# application which reads some state of other application on the PC and sends it to Arduino (Uno) and the Arduino according to the received data controls an addressed led strip.
It is works in 95% , but still has bugs , and I can"t get feedback data to serial monitor from the Arduino by the same serial port.
So , can I implement in the same C# application read-write communication with Arduino ?
Thank you in advance.

Yes, your c# application could have a thread listening on the Serial port and printing whatever it receives to a console. This way you would get a kind of "remote debugging" capability, as long as the Serial line works and the C# program runs

using System;
using System.IO.Ports;
using System.Threading;

class Program {
    static SerialPort serialPort;
    static Thread sendThread;
    static Thread receiveThread;

    static void Main() {
      string portName = "COM1"; // ➜ replace "COM1" with the Arduino serial port name
      int baudRate = 115200;    //  the code on the Arduino side needs to use the same baud rate in Serial.begin()
      serialPort = new SerialPort(portName, baudRate);
      serialPort.Open();        // ➜ careful, this will reboot the arduino

      // as the Arduino reboots, we need to wait until Serial is configured and so at the end of the setup()
      // the Arduino does Serial.println("OK");
      // so we wait for the "OK\r\n" message from the Arduino
      WaitForOKResponse();

      // Create and start threads
      sendThread = new Thread(SendDataToArduino);
      receiveThread = new Thread(ReceiveDataFromArduino);

      sendThread.Start();
      receiveThread.Start();

      Console.WriteLine("Press any key to stop the program.");
      Console.ReadKey();

      // Stop the threads and close the serial port
      sendThread.Abort();
      receiveThread.Abort();
      serialPort.Close();
    }

    static void WaitForOKResponse() {
      while (true) {
        string response = serialPort.ReadLine();
        if (response.Contains("OK\r\n")) {
          Console.WriteLine("Received 'OK' from Arduino. Proceeding...");
          break; // Exit the loop when "OK\r\n" is received
        }
      }
    }

    static void SendDataToArduino()  {
      while (true) {
        // send commands to the Arduino here
        string command = "Command to send to Arduino";
        serialPort.WriteLine(command);
        Thread.Sleep(1000); // don't send commands too often
      }
    }

    static void ReceiveDataFromArduino() {
      while (true) {
        try {
          int byteRead = serialPort.ReadByte();
          Console.Write((char)byteRead);
        } catch (TimeoutException) { }
      }
    }
}

(it has been years since I used C# so the code is not guaranteed to run, I'm on a Mac and did not test)

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.