Csharp/CSharp Tutorial/Development/COM Port SerialPort

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Open Serial port and read

using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
class Serial
{
 public static void Main()
 {
      byte[] buffer = new byte[256];
      using (SerialPort sp = new SerialPort("COM1", 19200))
      {
           sp.Open();
           //read directly
           sp.Read(buffer, 0, (int)buffer.Length);
           //read using a Stream
           sp.BaseStream.Read(buffer, 0, (int)buffer.Length);
      }
 }
}
Unhandled Exception: System.IO.IOException: The port "COM1" does not exist.
   at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataB
its, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnabl
e, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
   at System.IO.Ports.SerialPort.Open()
   at Serial.Main()

Set up serial port and write string to it

using System;
using System.IO.Ports;
static class MainClass
{
    static void Main(string[] args)
    {
        using (SerialPort port = new SerialPort("COM1"))
        {
            // Set the properties.
            port.BaudRate = 9600;
            port.Parity = Parity.None;
            port.ReadTimeout = 10;
            port.StopBits = StopBits.One;
            // Write a message into the port.
            port.Open();
            port.Write("Hello world!");
            Console.WriteLine("Wrote to the port.");
        }
    }
}