搜索
bottom↓
回复: 4

怎样实现CSharp的串口通讯

[复制链接]

出0入0汤圆

发表于 2011-3-18 15:28:26 | 显示全部楼层 |阅读模式
小弟在学CSharp,想用CSharp做上位机与单片机通讯,不知道该怎么做,网上也没有找到资料,求高手指点指点!!!

阿莫论坛20周年了!感谢大家的支持与爱护!!

一只鸟敢站在脆弱的枝条上歇脚,它依仗的不是枝条不会断,而是自己有翅膀,会飞。

出0入134汤圆

发表于 2011-3-18 15:59:33 | 显示全部楼层
C#有串口控件的  坛上有个开源的串口工具

出0入0汤圆

发表于 2011-3-18 17:22:49 | 显示全部楼层
找vb.net的串口源码多的是,然后代码网上有转化器,直接一转就能转成c#

出0入0汤圆

发表于 2011-9-1 01:55:24 | 显示全部楼层
C#里面有SerialPort对象,利用它可以方便的实现串口通信。下面是例子程序。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace TestSerialPort
{
    public partial class frmTESTSerialPort : Form
    {
        public frmTESTSerialPort()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private Button button1;
        private TextBox txtSend;
        private TextBox txtReceive;
        private Label label1;
        private Label label2;

        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.txtSend = new System.Windows.Forms.TextBox();
            this.txtReceive = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(440, 379);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "发送";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // txtSend
            //
            this.txtSend.Location = new System.Drawing.Point(59, 12);
            this.txtSend.Multiline = true;
            this.txtSend.Name = "txtSend";
            this.txtSend.Size = new System.Drawing.Size(456, 164);
            this.txtSend.TabIndex = 2;
            //
            // txtReceive
            //
            this.txtReceive.Location = new System.Drawing.Point(59, 200);
            this.txtReceive.Multiline = true;
            this.txtReceive.Name = "txtReceive";
            this.txtReceive.Size = new System.Drawing.Size(456, 164);
            this.txtReceive.TabIndex = 2;
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(13, 15);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 12);
            this.label1.TabIndex = 0;
            this.label1.Text = "发送";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(13, 213);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(41, 12);
            this.label2.TabIndex = 0;
            this.label2.Text = "接收";
            //
            // frmTESTSerialPort
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(546, 434);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtReceive);
            this.Controls.Add(this.txtSend);
            this.Controls.Add(this.button1);
            this.Name = "frmTESTSerialPort";
            this.Text = "串口试验";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion
private void button1_Click(object sender, EventArgs e)
        {
            //实例化串口对象(默认:COMM1,9600,e,8,1)            
            SerialPort serialPort1 = new SerialPort();
            //更改参数
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 19200;
            serialPort1.Parity = Parity.Odd;
            serialPort1.StopBits = StopBits.Two;

            //上述步骤可以用在实例化时调用SerialPort类的重载构造函数
            //SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two);

            //打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改)
            serialPort1.Open();

            //发送数据
            SendStringData(serialPort1);
            //也可用字节的形式发送数据
            //SendBytesData(serialPort1);
            
            //开启接收数据线程
            ReceiveData(serialPort1);
            
        }

出0入0汤圆

发表于 2011-9-1 01:55:46 | 显示全部楼层
//发送字符串数据
        private void SendStringData(SerialPort serialPort)
        {
            serialPort.Write(txtSend.Text);
        }

        /// <summary>
        /// 开启接收数据线程
        /// </summary>
        private void ReceiveData(SerialPort serialPort)
        {
            //同步阻塞接收数据线程
            Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData));
            threadReceive.Start(serialPort);
            
             //也可用异步接收数据线程
            //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
            //threadReceiveSub.Start(serialPort);
            
        }

        //发送二进制数据
        private void SendBytesData(SerialPort serialPort)
        {
            byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text );
            serialPort.Write(bytesSend, 0, bytesSend.Length);
        }

        //同步阻塞读取
        private void SynReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            System.Threading.Thread.Sleep(0);
            serialPort.ReadTimeout = 1000;
            try
            {
                //阻塞到读取数据或超时(这里为2秒)
                byte firstByte=Convert.ToByte(serialPort.ReadByte());
                int bytesRead=serialPort.BytesToRead ;               
                byte[] bytesData=new byte[bytesRead+1];
                bytesData[0] = firstByte;
                for (int i = 1; i <=bytesRead; i++)
                    bytesData = Convert.ToByte( serialPort.ReadByte());
                txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                //处理超时错误
            }
            
            serialPort.Close();

        }

        //异步读取
        private void AsyReceiveData(object serialPortobj)
        {
            SerialPort serialPort = (SerialPort)serialPortobj;
            System.Threading.Thread.Sleep(500);
            try
            {
                 txtReceive.Text =   serialPort.ReadExisting();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                //处理错误
            }
            serialPort.Close();
        }

    }


    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmTESTSerialPort());
        }
    }

}
回帖提示: 反政府言论将被立即封锁ID 在按“提交”前,请自问一下:我这样表达会给举报吗,会给自己惹麻烦吗? 另外:尽量不要使用Mark、顶等没有意义的回复。不得大量使用大字体和彩色字。【本论坛不允许直接上传手机拍摄图片,浪费大家下载带宽和论坛服务器空间,请压缩后(图片小于1兆)才上传。压缩方法可以在微信里面发给自己(不要勾选“原图),然后下载,就能得到压缩后的图片】。另外,手机版只能上传图片,要上传附件需要切换到电脑版(不需要使用电脑,手机上切换到电脑版就行,页面底部)。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|Archiver|amobbs.com 阿莫电子技术论坛 ( 粤ICP备2022115958号, 版权所有:东莞阿莫电子贸易商行 创办于2004年 (公安交互式论坛备案:44190002001997 ) )

GMT+8, 2024-5-18 12:26

© Since 2004 www.amobbs.com, 原www.ourdev.cn, 原www.ouravr.com

快速回复 返回顶部 返回列表