基本信息
源码名称:c#232串口通讯源码
源码大小:0.07M
文件格式:.zip
开发语言:C#
更新时间:2020-04-26
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 5 元 
   源码介绍

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

namespace SerialCommunication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private SerialPort serial = new SerialPort();

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }


        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="strPortName">串口号</param>
        /// <param name="nRate">波特率</param>
        /// <param name="nDataBit">数据位</param>
        /// <param name="stopBits">停止位</param>
        /// /// <param name="nParity">校验位</param>
        /// <returns></returns>
        public bool OpenSerial(string strPortName, int nRate, int nDataBit, float nStopBits, int nParity)
        {

            serial.DataReceived  = new SerialDataReceivedEventHandler(ReciveSerialData);
            serial.PortName = strPortName;//串口号
            serial.BaudRate = nRate;//波特率
            float f = nStopBits;//停止位
            if (f == 0)
            {
                serial.StopBits = StopBits.None;
            }
            else if (f == 1.5)
            {
                serial.StopBits = StopBits.OnePointFive;
            }
            else if (f == 1)
            {
                serial.StopBits = StopBits.One;
            }
            else
            {
                serial.StopBits = StopBits.Two;
            }
            serial.DataBits = nDataBit;//数据位
            if (nParity == 0) //校验位
            {
                serial.Parity = Parity.None;
            }
            else if (nParity == 1)
            {
                serial.Parity = Parity.Odd;
            }
            else if (nParity == 2)
            {
                serial.Parity = Parity.Even;
            }
            else
            {
                serial.Parity = Parity.None;
            }

            serial.ReadTimeout = 3000;//设置超时读取时间
            serial.WriteTimeout = 500;//超时写入时间
            try
            {
                if (!serial.IsOpen)
                {
                    serial.Open();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }

            return true;

        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="verifyIndex"></param>
        /// <param name="btyData"></param>
        /// <returns></returns>
        private bool SerialWrite(int verifyIndex, byte[] btyData)
        {
            try
            {
                int numAdjust = 0;

                for (; verifyIndex < btyData.Length - 1; verifyIndex  )
                {
                    numAdjust  = Convert.ToInt32(btyData[verifyIndex].ToString());
                }
                if (numAdjust > 0xff)
                {
                    string strAdjust = Convert.ToString(numAdjust, 16);
                    numAdjust = Convert.ToInt32(strAdjust.Substring(strAdjust.Length - 2), 16);
                }
                btyData[btyData.Length - 1] = (byte)numAdjust;
                serial.Write(btyData, 0, btyData.Length);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
            return true;
        }

        /// <summary>
        /// 接收数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReciveSerialData(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (serial.BytesToRead == 0)
                {
                    return;
                }
                byte[] btyReciveData = new byte[serial.BytesToRead];
                byte[] btyResoureData = new byte[btyReciveData.Length];
                string strData = string.Empty;
                int intSp = serial.Read(btyReciveData, 0, btyReciveData.Length);//在此就可以读取到当前缓冲区内的数据
                int i = 0;
                string[] hex = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
                for (i = 0; i < btyReciveData.Length; i  )
                {
                    btyResoureData[i] = Convert.ToByte(("0x"   (hex[btyReciveData[i] / 16]).ToString()   (hex[btyReciveData[i] % 16]).ToString()), 16);
                }
                for (int a = 0; a < btyReciveData.Length; a  )
                {
                    strData  = btyResoureData[a].ToString("X2");
                }

                //如果有接收,则发送成功
                if (strData.IndexOf("5A55000002D101186A69") >= 0)
                {                    
                }                    
                                     
                                     
                                     
            }                        
            catch (Exception ex)     
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 初始化串口命令
        /// </summary>
        public void InitialSerialCommand(int nStaus)
        {
            byte[] btyData = new byte[100];
            btyData[0] = 0x5A;
            btyData[1] = 0x55;
            btyData[2] = 0x00;
            btyData[3] = 0x00;
            btyData[4] = 0x02;
            btyData[5] = 0xD1;
            btyData[6] = 0x00;
            btyData[7] = 0x18;
            btyData[8] = 0x6A;
            btyData[9] = 0x69;

            //开灯
            if (nStaus == 0)
            {
                btyData[6] = 0x01;
            }
            //全关
            else 
            {
                btyData[6] = 0x00;
            }
           
            //发送指令
            if (serial != null)
            {
                try
                {
                    SerialWrite(0, btyData);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void btnOpenSerial_Click(object sender, EventArgs e)
        {
            if (!OpenSerial("COM1", 115200, 8, 1, 0))
            {
                //串口打开失败
                MessageBox.Show("串口打开失败!");
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            InitialSerialCommand(0);
        }

    }
}