我用vs写了一个上位机,为了修改我的单片机的两个参数,现在遇到了一个问题就是,发送的命令格式对了,可是单片机没有回传应答数据,看不出来什么问题了,请教各位大牛们帮忙解决一下!
这是正常应该返回的单片机数据
这是我自己写的,如图,并没有数据返回
话不多说,直接上代码看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace 串口助手
{
public partial class 串口助手 : Form
{
public 串口助手()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void Updata_Serialport_Name(ComboBox MycomboBox)
{
string[] ArryPort;
ArryPort = SerialPort.GetPortNames();
MycomboBox.Items.Clear();
for (int i = 0; i < ArryPort.Length; i++)
{
MycomboBox.Items.Add(ArryPort[i]);
}
}
private void 串口助手_Load(object sender, EventArgs e)
{
Updata_Serialport_Name(comboBoxPort);
}
private void timer1_Tick(object sender, EventArgs e)
{
Updata_Serialport_Name(comboBoxPort);
}
private void btnOpenSerialPort_Click(object sender, EventArgs e)
{
if (btnOpenSerialPort.Text == "打开串口")
{
try
{
serialPort1.PortName = comboBoxPort.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBoxBaudRate.Text);
serialPort1.Open();
comboBoxPort.Enabled = false;
comboBoxBaudRate.Enabled = false;
btnOpenSerialPort.BackColor = Color.Red;
btnOpenSerialPort.Text = "关闭串口";
}
catch
{
MessageBox.Show("打开串口失败,请检查串口", "错误");
}
}
else
{
try
{
serialPort1.Close();
comboBoxPort.Enabled = true;
comboBoxBaudRate.Enabled = true;
btnOpenSerialPort.BackColor = Color.Lime;
btnOpenSerialPort.Text = "打开串口";
}
catch
{
MessageBox.Show("关闭串口失败,请检查串口", "错误");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
textBoxStatus.Text = "";
}
private void btnSendCommand_Click(object sender, EventArgs e)
{
if (serialPort1 != null && serialPort1.IsOpen)
{
int shakeTimesValue = (int)numericUpDownShakeTimes.Value;
int shakeDelayValue = (int)numericUpDownShakeDelay.Value;
string hexShakeTimes = shakeTimesValue.ToString("X2");
string hexShakeDelay = shakeDelayValue.ToString("X2");
string commandStr = $"AA BB 07 01 {hexShakeTimes} {hexShakeDelay} FF";
byte[] commandBytes =
{
0xAA, 0xBB, 0x07, 0x01,
Convert.ToByte(hexShakeTimes, 16),
Convert.ToByte(hexShakeDelay, 16),
0xFF
};
try
{
serialPort1.Write(commandBytes, 0, commandBytes.Length);
textBoxStatus.AppendText($"发送的命令:{commandStr}\r\n");
}
catch (Exception ex)
{
textBoxStatus.AppendText($"发送命令失败:{ex.Message}\r\n");
}
}
else
{
MessageBox.Show("串口未打开,请先打开串口。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
byte[] buffer = new byte[serialPort1.BytesToRead];
serialPort1.Read(buffer, 0, buffer.Length);
string hexString = BitConverter.ToString(buffer).Replace("-", " ");
textBoxStatus.AppendText($"接收到的数据:{hexString}\r\n");
}
catch (Exception ex)
{
textBoxStatus.AppendText($"接收数据时发生错误: {ex.Message}\r\n");
}
}
}
}
这是我串口的属性
希望能看出问题的哥们帮忙指正一下,好人一生平安!