关于C#/WPF的SerialPort类串口接受数据异常的问题

如题所说,在软件测试过程中,发现COM口接收到的数据存在异常。我的硬件设备是海任科技的车辆光幕分离器,数据为16进制码。

1.起初怀疑是缓冲区的问题,但是经过清理的缓冲区依旧存在这个问题;

2.怀疑是SerialPort类的DataReceived的线程优先级问题,但是将其他线程优先级降低后仍未解决;

3.怀疑是SerialPort类的ReadByte的同步读取方法问题,而后用原厂C++编写的测试软件,显示正常,用网上的串口调试软件也都正常。

在网上搜了很久,也没能解决这个问题,然后一次偶然的测试,我发现USB转换器在响,恰好此时数据也出现了异常,这才想到可能是这个转换器的问题,然后把USB转换器拔了,直接把串口线插在PC机上调试,很稳定。无奈笔记本上没有9针的COM口,只好另寻稳定的转换器了……

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在C#中使用OxyPlot动态显示工程机串口数据,可以按照以下步骤进行: 1. 首先,需要安装OxyPlot和OxyPlot.Wpf NuGet包。可以在Visual Studio中通过NuGet包管理器安装。 2. 创建一个WPF窗口,在其中添加一个OxyPlot控件,用于显示图表数据。 3. 在C#代码中,使用SerialPort来读取串口数据。可以使用DataReceived事件来处理串口数据的接收。 4. 在DataReceived事件中,将接收到的数据解析并存储在一个数据结构中。 5. 在另一个线程中,定时更新OxyPlot控件中的数据。可以使用DispatcherTimer来实现定时更新。 6. 在定时更新的函数中,使用OxyPlot的PlotModel来更新图表数据,并将其绑定到OxyPlot控件中。 7. 在窗口关闭时,记得关闭串口连接。 下面是代码示例: ``` // 定义数据结构 public class DataPoint { public double X { get; set; } public double Y { get; set; } } // 定义窗口 public partial class MainWindow : Window { private SerialPort serialPort; // 串口对象 private List<DataPoint> dataPoints = new List<DataPoint>(); // 存储数据点 private PlotModel plotModel = new PlotModel(); // OxyPlot图表模型 public MainWindow() { InitializeComponent(); // 初始化OxyPlot控件 plot.Model = plotModel; // 初始化串口对象 serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); serialPort.DataReceived += SerialPort_DataReceived; serialPort.Open(); // 定时更新图表数据 var timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += Timer_Tick; timer.Start(); } // 处理串口数据接收 private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { // 解析数据并存储到dataPoints中 } // 定时更新图表数据 private void Timer_Tick(object sender, EventArgs e) { // 更新plotModel中的数据 plotModel.Series.Clear(); var series = new LineSeries(); series.ItemsSource = dataPoints; series.XBinding = new Binding("X"); series.YBinding = new Binding("Y"); plotModel.Series.Add(series); plot.InvalidatePlot(true); } // 关闭窗口时关闭串口连接 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { serialPort.Close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

公西雒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值