给串口发送16进制字符串命令和包括16进制命令转换为字节数组

using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace SerialPortControl
{
    public class PortControl
    {

        /// <summary>
        /// 向端口中发送命令。
        /// </summary>
        /// <param name="hexstring">"0A 46 0B 31 30 30 32 35"</param>
        /// <remarks>我本人对串口目前不是很熟悉,这次项目中需要,所以正在学习,后面我可能还会写一些。</remarks>
        /// <example>  SerialPortControl.PortControl.WriteCommand("0A 46 0B 31 30 30 32 35")</example>
        public static  void WriteCommand(string hexstring)
        {
            SerialPort sp = new SerialPort("COM1");
            byte[] buff=HexStringToBinary(hexstring.Trim()                );
            sp.WriteBufferSize = buff.Length ;
            sp.Open();
            sp.Write(buff ,0,buff.Length);
            sp.Close();
            sp.Dispose();
        }
        /// <summary>
        /// 16进制字符串转换为二进制数组
        /// </summary>
        /// <param name="hexstring">字符串每个字节之间都应该有空格,大多数的串口通讯资料上面的16进制都是字节之间都是用空格来分割的。</param>
        /// <returns>返回一个二进制字符串</returns>
        public static byte[] HexStringToBinary(string hexstring)
        {
            string[] tmpary = hexstring.Split(' ');
            byte[] buff = new byte[tmpary.Length];
            for (int i = 0; i < buff.Length ; i++)
   {
                buff[i] = Convert.ToByte(tmpary[i], 16);
   }
            return buff;
        }
    }
}


 
上一篇:把指定的DataSet中的内容导出到Excel中


下一篇:多线程委托回调