C#控制台操作串口实例例程

本文介绍一个C#控制台下操作串口的范例程序,基于多线程的一个接收,一个发送,可以用来作为参考,实测VS2010编译使用通过。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
///这里添加串口操作类
using System.IO.Ports;
///这里添加线程管理类
using System.Threading;

namespace HelloWorld
{
    class program
    {
        // 声明串口类实例
        private static SerialPort port = null;

        // 将char[]数组转换为string类型并返回
        private static string CharArrayTosting(char [] cha,int len)
        {
            string str = "";

            for (int i = 0; i < len; i++)
            {
                str += string.Format("{0}",cha[i]);
            }

            return str;
        }
        // 接收线程
        private static void receivedata()
        {
            while (true)
            {
                char[] rec = new char [100];
                
                port.Read(rec, 0, 100);

                string str = CharArrayTosting(rec, 100);

                Console.WriteLine("接收线程:{0}",str);

                Thread.Sleep(500);
            }
        }
        // 发送线程
        private static void senddata()
        {
            while (true)
            {
                string str = "hello world!";
                port.Write(str);
                Console.WriteLine("发送线程:" + str);
                Thread.Sleep(500);
            }
        }
        static void Main(string[] args)
        {
            // 配置串口
            port = new SerialPort("COM1");
            port.BaudRate = 115200;
            port.DataBits = 8;
            port.Open();

            // 打开
            if (port.IsOpen)
            {
                Console.WriteLine("串口打开成功");
            }
            else
            {
                Console.WriteLine("串口打开失败");
            }
            // 启动接收线程
            Thread th1 = new Thread(receivedata);
            if (th1 != null)
                th1.Start();

            // 启动发送线程
            Thread th2 = new Thread(senddata);
            if (th2 != null)
                th2.Start();
            
            while (true)
            {
                Thread.Sleep(1000);
            }
        }
    }
}
将串口的2,3两个管脚短接,测试程序效果如下:



  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值