首页  ·  知识 ·  编程语言
NET最简单的串口通信代码
leezjs  http://www.jinsongzhang.com  .NET  编辑:dezai  图片来源:网络
由于马上可能要用到这方面的代码,先帖出来学习一下. "FONT-SIZE: 11px; COLOR: black; FONT-FAMILY

由于马上可能要用到这方面的代码,先帖出来学习一下.

using System.IO;
using System.IO.Ports;
using System.Text;

class
Program
{
  static SerialPort ComPort;
  static ASCIIEncoding ASCIIEncoder = new ASCIIEncoding();

  public static void OnSerialDataReceived(
  object sender, SerialDataReceivedEventArgs args)
{
      string data = ComPort.ReadExisting();
Console.Write(data.Replace(“\r”, “\n”));
}

  static void Main(string[] args)
{
      string port = “COM1″;
      int baud = 9600;
      if (args.Length >= 1)
{
port = args[0];
}
      if (args.Length >= 2)
{
baud = int.Parse(args[1]);
}

InitializeComPort(port, baud);

      string text;
      do
      {
          text = Console.ReadLine();
          ComPort.Write(text + ‘\r’);
      }
      while (text.ToLower() != “q”);
}

  private static void InitializeComPort(string port, int baud)
{
ComPort = new SerialPort(port, baud);
      // ComPort.PortName = port;
      // ComPort.BaudRate = baud;
      ComPort.Parity = Parity.None;
      ComPort.StopBits = StopBits.One;
      ComPort.DataBits = 8;
      ComPort.Handshake = Handshake.None;
      ComPort.DataReceived += OnSerialDataReceived;
      ComPort.Open();
}
}

I agree, replacing ‘\r’ with ‘\n’ is a primitive way to deal with line feed issues especially considering there is a SerialPort.NewLine property.

本文作者:leezjs 来源:http://www.jinsongzhang.com
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读