首页

c#232串口通讯源码

c#

2020-9-6

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);
        }

    }
}
资源下载此资源下载价格为2D币(VIP免费),请先
资源文件列表
┤«┐┌═¿╨┼DEMO/SerialCommunication.sln , 947
┤«┐┌═¿╨┼DEMO/SerialCommunication.v11.suo , 95744
┤«┐┌═¿╨┼DEMO/SerialCommunication/App.config , 167
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.exe , 11264
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.exe.config , 167
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.pdb , 28160
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe , 22472
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe.config , 167
┤«┐┌═¿╨┼DEMO/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe.manifest , 490
┤«┐┌═¿╨┼DEMO/SerialCommunication/Form1.cs , 7102
┤«┐┌═¿╨┼DEMO/SerialCommunication/Form1.Designer.cs , 2812
┤«┐┌═¿╨┼DEMO/SerialCommunication/Form1.resx , 5817
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferences.cache , 1159
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache , 6942
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.csproj.FileListAbsolute.txt , 1910
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.csproj.GenerateResource.Cache , 975
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.csprojResolveAssemblyReference.cache , 2209
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.exe , 11264
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.Form1.resources , 180
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.pdb , 28160
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/SerialCommunication.Properties.Resources.resources , 180
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs , 0
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs , 0
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs , 0
┤«┐┌═¿╨┼DEMO/SerialCommunication/obj/Debug/TempPE/Properties.Resources.Designer.cs.dll , 4608
┤«┐┌═¿╨┼DEMO/SerialCommunication/Program.cs , 531
┤«┐┌═¿╨┼DEMO/SerialCommunication/Properties/AssemblyInfo.cs , 1376
┤«┐┌═¿╨┼DEMO/SerialCommunication/Properties/Resources.Designer.cs , 2878
┤«┐┌═¿╨┼DEMO/SerialCommunication/Properties/Resources.resx , 5612
┤«┐┌═¿╨┼DEMO/SerialCommunication/Properties/Settings.Designer.cs , 1119
┤«┐┌═¿╨┼DEMO/SerialCommunication/Properties/Settings.settings , 249
┤«┐┌═¿╨┼DEMO/SerialCommunication/SerialCommunication.csproj , 3886
没有账号? 忘记密码?

社交账号快速登录