我正在开发一个从 ATmega8A 接收信息的 GUI 界面。GUI 中的以下代码必须执行以下操作:
- 检查标头:在这里,我正在将数据读入一个字节数组 (
byte[] test
),该字节数组正在被检查OxFF
- 如果
header == 0xFF
,读取第二个字节数组 (byte[] data
)
请看下面的代码。
现在,我有以下问题。如果我只发送一个数字,例如 1,则该数字将textBox1
毫无问题地显示在 中。但是,如果我尝试发送 433 之类的号码,我总是收到 4,33 会丢失。我认为这是由于我包含了 if 语句,但我无法解释为什么这些数据会丢失。
namespace RS232
{
public partial class fclsRS232Tester : Form
{
string InputData = String.Empty;
string initText = "waiting...";
delegate void SetTextCallback(string text);
public fclsRS232Tester()
{
InitializeComponent();
// Nice methods to browse all available ports:
string[] ports = SerialPort.GetPortNames();
// Add all port names to the combo box:
foreach (string port in ports)
{
cmbComSelect.Items.Add(port);
}
cmbBaud.Items.Add(2400);
cmbBaud.Items.Add(9600);
cmbComSelect.SelectedIndex = 0;
cmbBaud.SelectedIndex = 1;
button4.Enabled = false;
textBox1.Text = initText;
textBox2.Text = initText;
}
private void cmbComSelect_SelectionChangeCommitted(object sender, EventArgs e)
{
if (port.IsOpen) port.Close();
port.PortName = cmbComSelect.SelectedItem.ToString();
stsStatus.Text = port.PortName + ": 9600,8N1";
// try to open the selected port:
try
{
port.Open();
button4.Enabled = true;
textBox1.Clear();
textBox2.Clear();
}
// give a message, if the port is not available:
catch
{
MessageBox.Show("Serial port " + port.PortName + " cannot be opened!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Warning);
cmbComSelect.SelectedText = "";
stsStatus.Text = "Select serial port!";
}
}
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
int bytenumber;
int bufferSize = port.BytesToRead;
byte[] test = new byte[1];
byte[] data = new byte[bufferSize];
byte[] data2 = new byte[bufferSize];
port.Read(test, 0, 1);
if (test[0] == 0xFF) //Receive X-andY- coordinates from MCU and plot the coordinates
{
bytenumber = port.Read(data, 0, bufferSize);
string info = System.Text.Encoding.ASCII.GetString(data);
this.Invoke((MethodInvoker)delegate
{
this.txtIn.Text += info;
}
}
}
}