⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 form1.cs

📁 使用C#实现串口编程
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;



namespace HexCommPort
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (mycomm.IsOpen)
            {
                mycomm.Close();
            }
            mycomm.ReadTimeout = 32;
            try
            {
                mycomm.Open();
                button3.Text = "关闭串口1";
            }
            catch
            {
                button3.Text = "打开串口1";
                MessageBox.Show("没发现此串口或串口已经在使用");
            }
        }

        private byte[] getdata()
        {
            int len = tsend.Text.Length;
            int j = 0;
            byte []datat = new byte[len];
            for(int i=0;i<len-2;i++)
            {
                if((tsend.Text[i]<='9')&&(tsend.Text[i]>='0')&&(tsend.Text[i+1]>='0')&&(tsend.Text[i+1]<='9')&&(tsend.Text[i+2]<=' '))
                {
                    datat[j] = (byte)((tsend.Text[i]-'0')*16+(tsend.Text[i+1]-'0'));
                    j++;
                }
            }
            byte[] datarev = new byte[j];
            for(int k=0;k<j;k++)
            {
                datarev[k] = datat[k];
            }
            return datarev;
        }

        private bool ishex(char x)
        {
            bool re = false;
            if((x<='9')&&(x>='0'))
            {
                re = true;
            }
            else if((x<='F')&&(x>='A'))
            {
                re =  true;
            }
            else if ((x <= 'f') && (x >= 'a'))
            {
                re = true;
            }

            return re;
        }

        private byte[] GetByteData(string s)
        {
            byte[] data = new byte[s.Length / 2];
            for (int i = 0; i < s.Length / 2; i++)
            {
                if (s[i * 2] <= '9')
                {
                    data[i] = (byte)((s[i * 2] - '0') * 16);
                }
                else if (s[i * 2] <= 'f' && s[i * 2] >= 'a')
                {
                    data[i] = (byte)((s[i * 2] - 'a' + 10) * 16);
                }
                else if (s[i * 2] <= 'F' && s[i * 2] >= 'A')
                {
                    data[i] = (byte)((s[i * 2] - 'A' + 10) * 16);
                }

                if (s[i * 2 + 1] <= '9')
                {
                    data[i] = (byte)(data[i] + (byte)((s[i * 2 + 1] - '0')));
                }
                else if (s[i * 2 + 1] <= 'f' && s[i * 2 + 1] >= 'a')
                {
                    data[i] = (byte)(data[i] + (byte)((s[i * 2 + 1] - 'a' + 10)));
                }
                else if (s[i * 2 + 1] <= 'F' && s[i * 2 + 1] >= 'A')
                {
                    data[i] = (byte)(data[i] + (byte)((s[i * 2 + 1] - 'A' + 10)));
                }
            }
            return data;
        }

        private string GetHexString(string str)
        {
            int len = str.Length;
            string datarev = "";
            int i=0;
            for(i=0;i<(len)/3;i++)
            {
                if ((ishex(str[3 * i])) && (ishex(str[3 * i + 1])) && (str[3 * i + 2] == ' '))
                {
                    datarev = datarev + str[3 * i] + str[3 * i + 1];
                }
                else if ((ishex(str[3 * i])) && (ishex(str[3 * i + 1])) && (3 * i + 2 == len))
                {
                    datarev = datarev + str[3 * i] + str[3 * i + 1];
                }
            }
            if(len-i*3==2)
            {
                if ((ishex(str[len-1])) && (ishex(str[len-2])))
                {
                    datarev = datarev + str[len-2] + str[len-1];
                }
            }
            return datarev;
        }
        private bool ishexstring(string strl)
        {
            string del = "  ";
            string str = strl.Trim(del.ToCharArray());
            int len = str.Length;
            bool re = false;
            for (int i = 0; i < (len) / 3; i++)
            {
                if ((ishex(str[3 * i])) && (ishex(str[3 * i + 1])) && (str[3 * i + 2] == ' '))
                {
                    re = true;
                }
                else if ((ishex(str[3 * i])) && (ishex(str[3 * i + 1])) && (3 * i + 2 == len))
                {
                    re = true;
                }
                else
                {
                    re = false;
                }
            }
            return re;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if(mycomm.IsOpen)
            {
                //byte[] datat = System.Text.Encoding.ASCII.GetBytes(tsend.Text); 
                string del = " ";
                string str = tsend.Text.TrimStart(del.ToCharArray());
                if (str != "")
                {
                    if (ishexstring(str))
                    {
                        string str2 = GetHexString(str);
                        byte[] datat = GetByteData(str2);
                        mycomm.Write(datat, 0, datat.Length);
                    }
                    else
                    {
                        byte[] datat = System.Text.Encoding.ASCII.GetBytes(tsend.Text);
                        mycomm.Write(datat, 0, datat.Length);
                    }
                }
            }
        }

        public static char[] hexDigits = {       
      '0',     '1',     '2',     '3',     '4',     '5',     '6',     '7',       
      '8',     '9',     'A',     'B',     'C',     'D',     'E',     'F'};

        public static string ToHexString(byte[] bytes)
        {
            char[] chars = new char[bytes.Length * 3];
            for (int i = 0; i < bytes.Length; i++)
            {
                int b = bytes[i];
                chars[i * 3] = hexDigits[b >> 4];
                chars[i * 3 + 1] = hexDigits[b & 0xF];
                chars[i * 3 + 2] = ' ';
            }
            return new string(chars);
        }

        private void mycomm_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int length = mycomm.BytesToRead;
            byte[] data = new byte[length];
            for (int i = 0; i < length; i++)
            {
                data[i] = (byte)mycomm.ReadByte();
            }

            string str = ToHexString(data);
            drev.Text = str;
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -