我正在尝试通过串口向RFID阅读器发送命令(它就像键盘,KKMOON制造的M302)。
我有这段代码才能发送说明:
SerialPort sp = new SerialPort();
sp.PortName = "COM3";
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.DataBits = 8;
sp.StopBits = StopBits.One;
sp.DataReceived += myRecieved;
sp.Open();
byte[] bytestosend = { 0x03, 0x0a, 0x00, 0x0d };
sp.Write(bytestosend, 0, bytestosend.Length);
bytestosend = new byte[]{ 0x04, 0x05, 0x00, 0x00, 0x09 };
sp.Write(bytestosend, 0, bytestosend.Length);
bytestosend = new byte[] { 0x03, 0x06, 0x00, 0x09 };
sp.Write(bytestosend, 0, bytestosend.Length);
if (beep)
{
running = false;
bytestosend = new byte[] { 0x02, 0x13, 0x15 };
sp.Write(bytestosend, 0, bytestosend.Length);
}
sp.Close();
sp.Dispose();
sp = null;
答案 0 :(得分:1)
所以在Hans Passant的评论之后,我意识到这个问题实际上并没有正确读取串口!
为了读取消息的完整范围,我构建了一个读取整个缓冲区的方法:
private static string readData()
{
int reads = sp.BytesToRead;
byte[] bytesRead = new byte[reads];
try
{
sp.Read(bytesRead, 0, reads);
return BitConverter.ToString(bytesRead).Trim(' ') != "" ? BitConverter.ToString(bytesRead) : "-1";
}
catch
{
return "-1";
}
}
然后读取整个缓冲区,直到找到想要的返回数据
while ((data += readData()) != "02-05-07")
{
if (data.Contains("-1"))
{
data = "";
}
Console.WriteLine(data);
Console.ReadLine();
}
这样我就可以读取RFID阅读器的所有数据,希望这能帮助其他可能出现问题的人!