jessyhoule

Read from COM port

Jul 18th, 2017
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.04 KB | None | 0 0
  1. using System;
  2. using System.IO.Ports;
  3. using System.Windows.Forms;
  4.  
  5. namespace SerialPortExample
  6. {
  7.   class SerialPortProgram
  8.   {
  9.     // Create the serial port with basic settings
  10.     private SerialPort port = new SerialPort("COM1",
  11.       9600, Parity.None, 8, StopBits.One);
  12.  
  13.     [STAThread]
  14.     static void Main(string[] args)
  15.     {
  16.       // Instatiate this class
  17.       new SerialPortProgram();
  18.     }
  19.  
  20.     private SerialPortProgram()
  21.     {
  22.       Console.WriteLine("Incoming Data:");
  23.  
  24.       // Attach a method to be called when there
  25.       // is data waiting in the port's buffer
  26.       port.DataReceived += new
  27.         SerialDataReceivedEventHandler(port_DataReceived);
  28.  
  29.       // Begin communications
  30.       port.Open();
  31.  
  32.       // Enter an application loop to keep this thread alive
  33.       Application.Run();
  34.     }
  35.  
  36.     private void port_DataReceived(object sender,
  37.       SerialDataReceivedEventArgs e)
  38.     {
  39.       // Show all the incoming data in the port's buffer
  40.       Console.WriteLine(port.ReadExisting());
  41.     }
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment