zoukankan      html  css  js  c++  java
  • 给串口发送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;
            }
        }
    }

  • 相关阅读:
    装饰器
    静态文件---访问图片
    用户登录
    读写Session
    windows进入指定目录
    Response 与 Cookie
    处理HTTP请求
    pycharm中指定ip和端口
    python爬虫学习(三):使用re库爬取"淘宝商品",并把结果写进txt文件
    python爬虫学习(二):定向爬虫例子-->使用BeautifulSoup爬取"软科中国最好大学排名-生源质量排名2018",并把结果写进txt文件
  • 原文地址:https://www.cnblogs.com/bennylam/p/1590408.html
Copyright © 2011-2022 走看看