读取到串口数据(str1)为01 02 01 01 60 48,我想让str1的数据等于str2的数据,但str2返回的数据却不是01 02 01 01 60 48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
namespace SerialPortReadData
{
internal class Program
{
public static string[] IpAddress = { "127.0.0.1", "192.168.1.11", "192.168.1.12", "192.168.1.13", "192.168.1.14", "192.168.1.15", "192.168.1.100" };//主机IP地址
public static string[] YiPinSendToData = { "B003D100110E", "B003D100211E", "B003D100312E", "B003D100110E", "B003D100211E", "B003D100312E", "B004D100010E", "B004D200011E", "B004D300012E", "B004D610016E", "B004D600015E" };//易拼打开场景1-3 发送十进制字符串
public static string[] ReceiveData = { "01 02 01 01 60 48", "01 02 01 00 A1 88" };
public static void UdpStringToHexString(string datapccket)//UDP协议,发送十进制字符串
{
byte[] buffer = new byte[1024];
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IpAddress[0]), 41235);//易拼端口
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
buffer = Encoding.ASCII.GetBytes(datapccket);
client.SendTo(buffer, buffer.Length, SocketFlags.None, ep);
client.Close();
}
public static void SerialReceive()
{
SerialPort mySerialPort = new SerialPort("com8");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("监听串口数据:");
Console.ReadKey();
mySerialPort.Close();
}
//字节数组转16进制字符串
public static string BytesToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2") + " ";
}
}
return returnStr;
}
public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
int _bytestoread = sp.BytesToRead;
byte[] recvData = new byte[_bytestoread];
sp.Read(recvData, 0, _bytestoread);
string str1 = BytesToHexStr(recvData);
string str2 = ReceiveData[0];
Console.Write(str1);
Console.Write(str2);
if (str1 ==str2)
{
UdpStringToHexString(YiPinSendToData[1]);
}
}
public static void Main(string[] args)
{
SerialReceive();
}
}
}
我想让接收到数据str1等于str1的数据,然后执行UDP控制
你的str1是BytesToHexStr转过来的16进制字符,转换一下吧,要么str2也转成16进制的字符