串口发送数据类

该博客主要介绍了如何通过C#实现串口通信,包括设置串口参数、发送和接收数据。具体涉及到将字符串转换为16进制字节,然后以特定格式组合并发送,同时提供了发送不同数据类型(如字符串、指定格式的数据包)的方法。
摘要由CSDN通过智能技术生成
using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.IO.Ports;
using  System.ComponentModel;
namespace  StringToLed
{
    
class stringtoLed
    
{
        
private System.IO.Ports.SerialPort serialPort1 = new SerialPort();

        
public  void write(string senStr)
        
{
            
string headStr = "23 14 24 15 13 18 58 58 58 58 58 58 44 01 01 00 01 01 02 04";
            
string footStr = "0A 2C 0E 16 04 02 08 6F";
            
string midStr = "";
            
string myStr = string.Empty;
            
// " 23 14 24 15 13 18 58 58 58 58 58 58 44 01 01 00 01 01 02 04C4 E3 BA C3 B0 A1 A3 A10A 2C 0E 16 04 02 08 6F";
            midStr = BitConverter.ToString(ASCIIEncoding.Default.GetBytes(senStr.Trim())).Replace("-"" ");
            
//midStr = "C4 E3 BA C3 B0 A1 A3 A1";
            myStr = headStr.Trim() + " "+midStr.Trim()+" "+ footStr.Trim();

            serialPort1.PortName 
= "COM1";  //端口号
            serialPort1.BaudRate = 9600;   //比特率
            serialPort1.Parity = Parity.None;//奇偶校验
            serialPort1.StopBits = StopBits.One;//停止位
            serialPort1.ReadTimeout = 1000//读超时,即在1000内未读到数据就引起超时异常
            serialPort1.Open();

            
byte[] myByte = StringToByte(myStr.Trim());

            serialPort1.Write(myByte, 
0, myByte.Length);
            serialPort1.Close();
          
//  MessageBox.Show("数据发送成功!", "系统提示");
        }

        
/// <summary>
        
/// 默认发送:左推,速度1,停留0
        
/// </summary>
        
/// <param name="sendStr">发送得数据</param>

        public void writeCom(string sendStr)
        
{

            
string headStr = "23 14 24 15 13 18 58 58 58 58 58 58 44 01 01 0F 01 01 02";
            
            
string footStr = "0A 2C 0E 16 04 02 08";
            
string midStr = string.Empty;
            
string myStr = string.Empty;
            
string last = string.Empty;
            
string  sentLenth = sendStr.Length.ToString("X");
            
if (sentLenth.Length<2)
            
{
                sentLenth 
="0"+sentLenth;
            }

            headStr 
+=" "+sentLenth;//第一部分

            midStr 
= BitConverter.ToString(ASCIIEncoding.Default.GetBytes(sendStr.Trim())).Replace("-"" ");
            
string HexStr = "44 01 01 0F 01 01 02"+" "+sentLenth+ " " + midStr + " " + footStr;
            last 
= getLast(HexStr);
            
//最终发送字节
            myStr = headStr.Trim() + " " + midStr.Trim() + " " + footStr.Trim()+" "+last;

            serialPort1.PortName 
= "COM1";  //端口号
            serialPort1.BaudRate = 9600;   //比特率
            serialPort1.Parity = Parity.None;//奇偶校验
            serialPort1.StopBits = StopBits.One;//停止位
            serialPort1.ReadTimeout = 1000//读超时,即在1000内未读到数据就引起超时异常
            serialPort1.Open();
            
byte[] myByte = StringToByte(myStr.Trim());
            serialPort1.Write(myByte, 
0, myByte.Length);
            serialPort1.Close();
        
        }

       
/// <summary>
       
/// 测试
       
/// </summary>
       
/// <param name="type"></param>
       
/// <param name="speed"></param>
       
/// <param name="time"></param>
       
/// <param name="count"></param>
       
/// <returns></returns>

        private static string gettype(int type, int speed, int time, int count)
        
{
            
//出场方式
            string typeStr = "44 01 01 00 01 01 02";
            
switch (type)
            
{
                
case 0:
                    typeStr 
= "44 00 01 00 01 01 02";
                    
break;
                
case 1:
                    typeStr 
= "44 01 01 01 01 01 02";
                  
                    
break;
                
case 2:
                    typeStr 
= "44 02 01 02 01 01 02";
                    
break;
                
case 3:
                    typeStr 
= "44 03 01 03 01 01 02";
                    
break;
                
case 4:
                    typeStr 
= "44 04 01 04 01 01 02";
                    
break;
                
case 5:
                    typeStr 
= "44 05 01 05 01 01 02";
                    
break;
                
case 6:
                    typeStr 
= "44 06 01 06 01 01 02";
                    
break;
                
case 7:
                    typeStr 
= "44 07 01 07 01 01 02";
                    
break;

                
default:
                    typeStr 
= "44 01 01 00 01 01 02";
                     
break;
            }

            
return typeStr;
        }

        
//
        private static string get_head(int type, int speed, int time, int count)
        
{
           
// string headStr="44 01 01 00 01 01 02";
            string typeStr = " 01";
            
string speedStr = " 01";
            
string timeStr = " 00";
            
string countStr=" 01";

            
string headStr ="44"+typeStr+speedStr+timeStr+countStr+" 01 02";
            
//出场方式
            switch (type)
            
{
                
case 0:
                    typeStr 
= " 00";
                    
break;
                
case 1:
                    typeStr 
= " 01";

                    
break;
                
case 2:
                    typeStr 
= " 02";
                    
break;
                
case 3:
                    typeStr 
= " 03";
                    
break;
                
case 4:
                    typeStr 
= " 04";
                    
break;
                
case 5:
                    typeStr 
= " 05";
                    
break;
                
case 6:
                    typeStr 
= " 06";
                    
break;
                
case 7:
                    typeStr 
= " 07";
                    
break;

                
default:
                    typeStr 
=" 01";
                    
break;
            }

            
//移动速度
            switch (speed)
            
{
                
case 1:
                    speedStr 
= " 01";
                    
break;
                
case 2:
                    speedStr 
= " 02";
                    
break;
                
case 3:
                    speedStr 
= " 03";
                    
break;
                
case 4:
                    speedStr 
= " 04";
                    
break;
                
case 5:
                    speedStr 
= " 05";
                    
break;
                
case 6:
                    speedStr 
= " 06";
                    
break;
                
case 7:
                    speedStr 
= " 07";
                    
break;
                
case 8:
                    speedStr 
= " 08";
                    
break;
                
case 9:
                    speedStr 
= " 09";
                    
break;
                
case 10:
                    speedStr 
= " 0A";
                    
break;
                
case 11:
                    speedStr 
= " 0B";
                    
break;
                
case 12:
                    speedStr 
= " 0C";
                    
break;
                
case 13:
                    speedStr 
= " 0D";
                    
break;
                
case 14:
                    speedStr 
= " 0E";
                    
break;
                
case 15:
                    speedStr 
= " 0F";
                    
break;
              
                
default:
                    speedStr 
= " 01";
                    
break;
            }


            
//停留时间
            switch (time)
            
{
                
case 1:
                    timeStr 
= " 01";
                    
break;
                
case 2:
                    timeStr 
= " 02";
                    
break;
                
case 3:
                    timeStr 
= " 03";
                    
break;
                
case 4:
                    timeStr 
= " 04";
                    
break;
                
case 5:
                    timeStr 
= " 05";
                    
break;
                
case 6:
                    timeStr 
= " 06";
                    
break;
                
case 7:
                    timeStr 
= " 07";
                    
break;
                
case 8:
                    timeStr 
= " 08";
                    
break;
                
case 9:
                    timeStr 
= " 09";
                    
break;
                
case 10:
                    timeStr 
= " 0A";
                    
break;
                
case 11:
                    timeStr 
= " 0B";
                    
break;
                
case 12:
                    timeStr 
= " 0C";
                    
break;
                
case 13:
                    timeStr 
= " 0D";
                    
break;
                
case 14:
                    timeStr 
= " 0E";
                    
break;
                
case 15:
                    timeStr 
= " 0F";
                    
break;

                
default:
                    timeStr 
= " 01";
                    
break;
            }

           headStr 
="44"+typeStr+speedStr+timeStr+countStr+" 01 02";
           
return headStr;
        
        }

        
/// <summary>
        
/// 发送数据含(方式)
        
/// </summary>
        
/// <param name="sendStr">发送的字符串,注意前后不得有空格</param>
        
/// <param name="type">出场方式</param>
        
/// <param name="speed">移动速度</param>
        
/// <param name="time">停留时间</param>

        public void writeCom_type(string sendStr,int type, int speed, int time)
        
{

            
string headStr = "23 14 24 15 13 18 58 58 58 58 58 58";
            
string typeStr = get_head(type, speed, time, 0);
            
string footStr = "0A 2C 0E 16 04 02 08";
            
string midStr = string.Empty;
            
string myStr = string.Empty;
            
string last = string.Empty;
            
string sentLenth = sendStr.Length.ToString("X");
            
if (sentLenth.Length < 2)
            
{
                sentLenth 
= "0" + sentLenth;
            }

            
//最终headstr值
            headStr=headStr+" "+typeStr+" " + sentLenth;//第一部分

            midStr 
= BitConverter.ToString(ASCIIEncoding.Default.GetBytes(sendStr.Trim())).Replace("-"" ");
            
string HexStr = typeStr + " " + sentLenth + " " + midStr + " " + footStr;
            last 
= getLast(HexStr);
            
//最终发送字节
            myStr = headStr.Trim() + " " + midStr.Trim() + " " + footStr.Trim() + " " + last;

            serialPort1.PortName 
= "COM1";  //端口号
            serialPort1.BaudRate = 9600;   //比特率
            serialPort1.Parity = Parity.None;//奇偶校验
            serialPort1.StopBits = StopBits.One;//停止位
            serialPort1.ReadTimeout = 1000//读超时,即在1000内未读到数据就引起超时异常
            serialPort1.Open();
            
byte[] myByte = StringToByte(myStr.Trim());
            serialPort1.Write(myByte, 
0, myByte.Length);
            serialPort1.Close();

        }

       
/// <summary>
       
/// 字符数组转字符串16进制
       
/// </summary>
       
/// <param name="InBytes"></param>
        
/// <returns>类似"01 02 0F"</returns>

        private static string ByteToString(byte[] InBytes)
        
{
            
string StringOut = "";
            
foreach (byte InByte in InBytes)
            
{
                StringOut 
= StringOut + String.Format("{0:X2}", InByte) + " ";
            }


            
return StringOut.Trim();
        }

       
/// <summary>
       
/// strhex 转字节数组
       
/// </summary>
        
/// <param name="InString">类似"01 02 0F"</param>
       
/// <returns></returns>

        private static byte[] StringToByte(string InString)
        
{
            
string[] ByteStrings;
            ByteStrings 
= InString.Split(" ".ToCharArray());
            
byte[] ByteOut;
            ByteOut 
= new byte[ByteStrings.Length];
            
for (int i = 0; i <= ByteStrings.Length - 1; i++)
            
{
                ByteOut[i] 
= byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
            }

            
return ByteOut;
        }

        
/// <summary>
        
/// 计算最后一个字节
        
/// </summary>
        
/// <param name="hexString">类似"01 02 0F"</param>
        
/// <returns>十六进制和去除高位溢出</returns>

        private static string getLast(string hexString)
        
{
            
string hexValues = "44 01 01 00 01 04 C4 E3 BA C3 B0 A1 A3 A1 26 39 0E 16 04 02 08";

            
string[] hexValuesSplit = hexString.Split(' ');
            
int temp = 0;
            
foreach (String hex in hexValuesSplit)
            
{
                
// Convert the number expressed in base-16 to an integer.
                int value = Convert.ToInt32(hex, 16);
                
// Get the character corresponding to the integral value.
                string stringValue = Char.ConvertFromUtf32(value);
                
char charValue = (char)value;
                
//Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue);
                temp += value;
            }

            
string tempStr = temp.ToString("x");
            
return tempStr.Remove(0, tempStr.Length - 2).ToUpper();
            
//return tempStr.Substring(tempStr.Length-2, tempStr.Length - 1).ToUpper();
        }

    }

}

在发送6个字屏使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值