MSDN 中serialPort类使用的C#范例(参考此范例可以完成一个自己的串口操作程序)

明亮 posted @ 2010年10月08日 18:48 in 【C#】 with tags 串口,C# , 8147 阅读
本文发表于:http://fml927.is-programmer.com

原文网址参见: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

代码修改和注释如下,可以直接在VS2005中新建一个“Windows控制台应用程序”类型的工程,直接将下面代码复制到主文件替换其自动生成的代码即可编译运行,目前可实现串口设置,串口发送和接收。

 

using System;
using System.IO.Ports;
using System.Threading;

public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;

    //基于控制台的应用程序入口,相当于C的main函数的作用
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);  //创建一个线程 用于监控串口的接收buff是否有新数据到来readThread 为线程句柄

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();        //用串口类 创建一个串口对象

        //设置串口的各个属性,处理方法:如果用户不修改则使用默认值
        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();           //打开串口
        _continue = true;
        readThread.Start();           //启动 读取串口接收数据的线程

        Console.Write("Name: ");      //向控制台 打印提示信息 提示用户为串口命令(用户自定的别名)
        name = Console.ReadLine();    //将用户的输入信息 保存到name变量中

        Console.WriteLine("Type QUIT to exit");

        while (_continue)   //主处理线程中的死循环,读取用户在控制台输入的字符串并负责串口发送数据/响应用户的退出命令    
        {
            message = Console.ReadLine();   //读取用户在控制台输入的字符串并负责串口发送数据

            if (message.Equals("quit"))     //如果用户输入了quit测设置变量 使循环退出   即可结束程序
            {
                _continue = false;
            }else if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else                            //如果用户输入了普通字符串 则通过串口发送
            {
                _serialPort.WriteLine(
                    String.Format("{0}\r\n",  message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }
 
    public static void Read()         //等待读取串口接收的数据的线程 处理函数
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();  //如果串口没有接收到数据的话 本线程将一直在这条语句等待
                Console.WriteLine(message);  //将接受的信息显示出来
            }
            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

        Console.WriteLine("Available Ports:");
        foreach (string s in SerialPort.GetPortNames())
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("COM port({0}): ", defaultPortName);
        portName = Console.ReadLine();

        if (portName == "")
        {
            portName = defaultPortName;
        }
        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
        baudRate = Console.ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        Console.WriteLine("Available Parity options:");
        foreach (string s in Enum.GetNames(typeof(Parity)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Parity({0}):", defaultPortParity.ToString());
        parity = Console.ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        Console.Write("Data Bits({0}): ", defaultPortDataBits);
        dataBits = Console.ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        Console.WriteLine("Available Stop Bits options:");
        foreach (string s in Enum.GetNames(typeof(StopBits)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
        stopBits = Console.ReadLine();

        if (stopBits == "")
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        Console.WriteLine("Available Handshake options:");
        foreach (string s in Enum.GetNames(typeof(Handshake)))
        {
            Console.WriteLine("   {0}", s);
        }

        Console.Write("Stop Bits({0}):", defaultPortHandshake.ToString());
        handshake = Console.ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}
  • 无匹配
  • 无匹配
Emma Colman 说:
2018年7月15日 15:45

Porting of the MSDN by the blogs of the every serial and the codes are of the generically occurring of the immense. By too much codes of the software that is for to do my assignment for me is serial wise on the backward directions.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter