急!串口开发,SerialPort接收不到数据

.Net技术 码拜 9年前 (2016-02-28) 2613次浏览
本人这几天在做串口通讯的开发,使用串口助手能够接收到串口发送过来的数据,但是用SerialPort就接收不到数据。定时读取获得的是空字符串,使用DataReceived事件则不能触发。
程序如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestBalance
{
    public partial class Form1 : Form
    {
        SerialPort sp;
        public Form1()
        {
            InitializeComponent();
            sp = new SerialPort("COM21", 9600, Parity.None, 8, StopBits.One);
            sp.Open();
            sp.ReceivedBytesThreshold = 1;
            sp.RtsEnable = true;
            sp.DtrEnable = true;
            sp.DataReceived+=sp_DataReceived;
            sp.Write("01 03 100b 0002 b109");
            Thread.Sleep(200);
            //string message= sp.ReadExisting();
            //MessageBox.Show(message);
        }
        private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string message = sp.ReadLine();
            MessageBox.Show(message);
        }
    }
}
解决方案

100

先去下个串口监控的软件:accessport、portmon之类的,调试看看助手和c#发送的数据有什么差别

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明急!串口开发,SerialPort接收不到数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)