C#编写的上位机显示单片机发送的数据,但上位机始终收不到,用串口调试助手可以收到!求大神指教!
namespace串口上位机{publicpartialclassForm1:Form{privateSerialPortCom=newSerialPort();priv...
namespace 串口上位机
{
public partial class Form1 : Form
{
private SerialPort Com = new SerialPort();
private StringBuilder builder = new StringBuilder();
public Form1(){InitializeComponent();}
private void Form1_Load(object sender, EventArgs e)
{ string[] ports = SerialPort.GetPortNames();
Array.Sort(ports);
comboBox_ComName.Items.AddRange(ports);
comboBox_ComName.SelectedIndex = comboBox_ComName.Items.Count > 0 ? 0 : -1;
BaudRate.SelectedIndex = BaudRate.Items.IndexOf("9600");
comboBoxParity.SelectedIndex = comboBoxParity.Items.IndexOf("None");
comboBoxData.SelectedIndex = comboBoxData.Items.IndexOf("8");
comboBoxStop.SelectedIndex = comboBoxStop.Items.IndexOf("1");
comboBox_ComName.Enabled = true;
BaudRate.Enabled = true;
comboBoxParity.Enabled = true;
comboBoxData.Enabled = true;
comboBoxStop.Enabled = true;
Com.DtrEnable = true;
Com.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{//测试了好像连这个接收函数都没进去,但是有时候能进去,也就进去一下下就没有然后了
int n = Com.BytesToRead;
byte[] buf = new byte[n];
Com.Read(buf, 0, n);
textBoxTemp.Text = Convert.ToString(buf[0]); //只显示buf[0]
}
} 展开
{
public partial class Form1 : Form
{
private SerialPort Com = new SerialPort();
private StringBuilder builder = new StringBuilder();
public Form1(){InitializeComponent();}
private void Form1_Load(object sender, EventArgs e)
{ string[] ports = SerialPort.GetPortNames();
Array.Sort(ports);
comboBox_ComName.Items.AddRange(ports);
comboBox_ComName.SelectedIndex = comboBox_ComName.Items.Count > 0 ? 0 : -1;
BaudRate.SelectedIndex = BaudRate.Items.IndexOf("9600");
comboBoxParity.SelectedIndex = comboBoxParity.Items.IndexOf("None");
comboBoxData.SelectedIndex = comboBoxData.Items.IndexOf("8");
comboBoxStop.SelectedIndex = comboBoxStop.Items.IndexOf("1");
comboBox_ComName.Enabled = true;
BaudRate.Enabled = true;
comboBoxParity.Enabled = true;
comboBoxData.Enabled = true;
comboBoxStop.Enabled = true;
Com.DtrEnable = true;
Com.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{//测试了好像连这个接收函数都没进去,但是有时候能进去,也就进去一下下就没有然后了
int n = Com.BytesToRead;
byte[] buf = new byte[n];
Com.Read(buf, 0, n);
textBoxTemp.Text = Convert.ToString(buf[0]); //只显示buf[0]
}
} 展开
展开全部
你确定的波特率、数据位、奇偶校验等都设置到串口上了?你这些似乎只设置在combox了,并没有真正绑定到串口上
更多追问追答
追问
绑定到串口上了,在这个事件buttonOpen_Click()中绑定的。
运行的时候在:textBoxTemp.Text = Convert.ToString(buf[0]); 位置
弹出错误“对控件的修改和。。。。。不在同一个进程”,是啥意思呀?
追答
不允许跨线程操作,解决方式:禁止跨线程检查(Control.CheckForIllegalCrossThreadCalls = false;)或使用委托
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询