Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
20
Indexable
Never
using System;
using System.IO.Ports;
using System.Threading;

namespace ArduinoSerialReader
{
    class Program
    {
        static SerialPort _serialPort;

        static void Main(string[] args)
        {
            string portName = "COM9"; // Specify the port name here
            int baudRate = 9600; // Change this to match your Arduino's baud rate

            _serialPort = new SerialPort(portName, baudRate);

            try
            {
                _serialPort.Open();
                Console.WriteLine($"Serial port {portName} opened at baud rate {baudRate}");

                // Subscribe to the DataReceived event
                _serialPort.DataReceived += SerialPort_DataReceived;

                // Start a separate thread to send data
                Thread sendThread = new Thread(SendData);
                sendThread.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error opening serial port: {ex.Message}");
                return;
            }

            Console.WriteLine("Press 'Ctrl + C' to exit.");
            // Keep the application running
            while (true) { }
        }

        static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                // Read the data from the serial port
                string data = _serialPort.ReadLine();
                Console.WriteLine($"Received: {data}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error reading data: {ex.Message}");
            }
        }

        static void SendData()
        {
            try
            {
                while (true)
                {
                    // Send a predefined message to the Arduino
                    string message = "Hello Arduino!";
                    _serialPort.WriteLine(message);
                    Console.WriteLine($"Sent: {message}");

                    // Wait for a short interval before sending the next message
                    Thread.Sleep(1000); // Adjust the delay as needed
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending data: {ex.Message}");
            }
        }
    }
}
Leave a Comment