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]
}
} 展开
1个回答
展开全部
你确定的波特率、数据位、奇偶校验等都设置到串口上了?你这些似乎只设置在combox了,并没有真正绑定到串口上
更多追问追答
追问
绑定到串口上了,在这个事件buttonOpen_Click()中绑定的。
运行的时候在:textBoxTemp.Text = Convert.ToString(buf[0]); 位置
弹出错误“对控件的修改和。。。。。不在同一个进程”,是啥意思呀?
追答
不允许跨线程操作,解决方式:禁止跨线程检查(Control.CheckForIllegalCrossThreadCalls = false;)或使用委托
意法半导体(中国)投资有限公司
2023-06-12 广告
2023-06-12 广告
单片机汇编程序是用汇编语言编写的程序,用于控制单片机的操作。汇编语言是一种比较接近计算机硬件语言的低级语言,相对于高级语言来说更容易理解和实现。下面是单片机汇编程序的基本步骤:1. 将代码和数据汇编到规定的段中。2. 在存储器中用未初始化的...
点击进入详情页
本回答由意法半导体(中国)投资有限公司提供
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询