I am creating an application that communicates serially.
We have created a single data transmission/reception process, but actually we need to read multiple data.
However, when sending multiple data as shown below, data reception processing starts during loop processing.
public void Send()
{
if (!_serialPort.IsOpen) return;
try
{
var setDataIds = new string[]
{
// Test Send Data A
"04-02-43-33-30-20-41-03",
// Test Send Data B
"04-02-43-33-33-20-41-03",
// Test Send Data C
"04-02-43-33-36-20-41-03",
};
foreach(var id in setDataIds)
{
var tmp = id.Split("-").Select(hex => Convert.ToByte(hex, 16));
byte[] sendData = tmp.ToArray();
_serialPort.Write(sendData, 0, sendData.Length);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Therefore, the next data transmission is performed without judging whether the received data is the correct value.
I want to check the result of each data transmission before processing the next data transmission, but I can't think of a way to do that.
In other words, if the result of A's data transmission is normal, I want to send B's data, and if B's data is normal, I want to send C's data.
I'm sorry if the explanation is difficult to understand. I would like some advice.
Code
private SerialPort _serialPort = null;
public bool PortOpen(string comNum)
{
_serialPort ??= new SerialPort
{
PortName = comNum,
BaudRate = 9600,
DataBits = 8,
Parity = Parity.None,
StopBits = StopBits.One,
Handshake = Handshake.None,
Encoding = Encoding.UTF8,
WriteTimeout = 100000,
ReadTimeout = 100000,
NewLine = "\r\n",
};
_serialPort.DataReceived += new SerialDataReceivedEventHandler(EventReciveAsync);
if (!_serialPort.IsOpen)
{
try
{
_serialPort.Open();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
return true;
}
public void Send()
{
if (!_serialPort.IsOpen) return;
try
{
var setDataIds = new string[]
{
// Test Send Data A
"04-02-43-33-30-20-41-03",
// Test Send Data B
"04-02-43-33-33-20-41-03",
// Test Send Data C
"04-02-43-33-36-20-41-03",
};
foreach(var id in setDataIds)
{
var tmp = id.Split("-").Select(hex => Convert.ToByte(hex, 16));
byte[] sendData = tmp.ToArray();
_serialPort.Write(sendData, 0, sendData.Length);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void EventReciveAsync(object sender, SerialDataReceivedEventArgs e)
{
if (!_serialPort.IsOpen) return;
var srtDataReceived = "";
var buf = new byte[_serialPort.BytesToRead];
try
{
_serialPort.Read(buf, 0, buf.Length);
srtDataReceived = BitConverter.ToString(buf);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
if (_serialPort.IsOpen)
{
//Process to check data
}
}