Answer the question
In order to leave comments, you need to log in
How to accept a hex array and display in textbox?
I send a message of the form byte [] writestring = {0x10, 0x03, 0x00, 0x04, 0x00, 0x04, 0x06, 0x89} to the microcontroller.
Must accept the answer and display the box in the text, the answer should be the following 10 03 08 14 00 3D 00 66 00 8F 00 BB 4.
The problem is the following, sometimes the answer is correct, and sometimes incomprehensible zeros are mixed into the response message. Those. sometimes the answer is normal, sometimes not. I didn’t find any dependency, I think maybe it’s because of the conversion. Please tell me what could be causing this.
<code lang="cs">
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace Terminal
{
public partial class Form1 : Form
{
int date;
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.DiscardInBuffer();
serialPort1.DiscardOutBuffer();
byte[] writestring = { 0x10, 0x03, 0x00, 0x04, 0x00, 0x04, 0x06, 0x89 };
try
{
serialPort1.Write(writestring, 0, writestring.Length);
textBox2.Clear();
}
catch (TimeoutException)
{
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] readstring = new byte[13];
serialPort1.Read(readstring, 0, readstring.Length);
string stringMessage = BitConverter.ToString(readstring);
textBox1.AppendText(stringMessage + "\r\n\r\n");
}
}
}
</code>
<img src="https://habrastorage.org/files/f45/753/449/f45753449924495db9a2267f4ff5a292.JPG" alt="image"/>
Answer the question
In order to leave comments, you need to log in
The DataReceived event occurs when the port is polled (which probably happens every tick) if there is data in the buffer. The data is written to the buffer asynchronously (as it arrives).
Therefore, when the DataReceived event occurs, all bytes may not yet have time to be written to the buffer, to solve this problem, I did this:
Class "ComPort" http://pastie.org/10814442
private void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] inBuf = new byte[256];
int rxCount = _comPort.Read(ref inBuf, 2); //Максимальное время между байтами одной посылки
if (rxCount < 5) return; //Не наше
//Обрабатываем массив inBuf
}
private ComPort _comPort = new ComPort();
private void LoadPortSettings() //Повесить на загрузку формы
{
_comPort.DataReceived += ComPort_DataReceived;
cmbPort.Items.Clear();
cmbPort.Items.AddRange(_comPort.PortNames());
cmbBaudRate.Items.Clear();
cmbBaudRate.Items.AddRange(_comPort.BaudRates());
cmbPort.SelectedItem = Properties.Settings.Default.Port;
cmbBaudRate.SelectedItem = Properties.Settings.Default.BaudRate;
}
private void UpdatePortSettings() //Повесить на изменение комбобоксов cmbPort и cmbBaudRate
{
int cpi = cmbPort.SelectedIndex;
int bri = cmbBaudRate.SelectedIndex;
if (cpi >= 0 && bri >= 0)
{
string port = cmbPort.Items[cpi].ToString();
string baudRate = cmbBaudRate.Items[bri].ToString();
if (!string.IsNullOrWhiteSpace(port) && !string.IsNullOrWhiteSpace(baudRate)
&& _comPort.isPortChange(port,baudRate))
{
_comPort.Open(port, baudRate);
}
}
}
And why are you sure that DataReceived will always work exactly when 13 bytes add up in the port buffer? I can say that the microcontroller can send you even three bytes as 2+1 or 1+1+1 or 1+2. That is, DataReceived will work for you 2 or 3 times during the transfer.
The most optimal, it seems to me, is to read everything available from the port buffer and look for the beginning and end of the response from the microcontroller as a result of reading.
In my case, 4 types of response came from the controller: XX, F0 XX, E0 XX and E0 F0 XX, that is, standard keyboard scan codes (if you do not take into account the break and print screen keys, there are multibyte packages).
I just read the contents of the port buffer and if there was only XX, then the data went further, if only E0 or F0, then E0 was written to my buffer and the read continuation flag was set. Well, and so on. Thus, I was guaranteed to correctly read the data from the controller. If necessary, I can copy-paste my code here from work tomorrow.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question