using System.IO.Ports; //Creating SerialPort object SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); //Open Serial Port serialPort.Open(); while (true) { //Read Serial Data string receivedData = serialPort.ReadLine(); //Display read data Console.WriteLine(receivedData); }
using System.IO.Ports; //Creating SerialPort object SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One); //Open Serial Port serialPort.Open(); //Send command to Arduino board to toggle an LED serialPort.WriteLine("LED1"); //Read response from Arduino board string response = serialPort.ReadLine(); if (response.Equals("OK")) { Console.WriteLine("LED toggled!"); }In this example, we create a SerialPort object and open the serial port. Then we send a command "LED1" to an Arduino board using the WriteLine method. The Arduino board processes the command and sends a response "OK" back to the C# application, which is read by the ReadLine method. If the response is "OK", we display a message "LED toggled!". Package Library: The System.IO.Ports namespace is part of the .NET framework base class library.