I am able to receive data using serial port debug tools with the Modbus protocol.
The parameters below are the same. However, I set a breakpoint in the DataReceived
method but it is never encountered. Below is my program:
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);
}
}
}
Okay, without having much information about how your device works. I can only take some guesses at what may be your problem.
In the case that your device is synchronous, make sure that you are sending an end-of-line (EOL) sequence to the device. Some devices will need an EOL in order to signal the sending of data. This EOL is often carriage-return followed by line-feed, or just carriage-return. So you may have to change your data to "01 03 100b 0002 b109\\r"
. Notice that I have added a carriage-return. Also, you can use "\\n"
for line-feed or "\\r\\n"
for both carriage-return and line-feed.
Also, not knowing what kind of a device you are using. You would do well to make sure that you have the serial-port settings all correct. Make sure that the baud-rate is actually supposed to be 9600. You can't just choose whatever you want, the device you are talking to will have a preset baud-rate inside the hardware that you are required to use.
Additionally, make sure you have the COM
port number correct. Open up device-manager and make sure you are talking to the correct port.
Finally, I have never seen anyone subscribe to the SerialPort
class how you did it. Change your code to properly match the MSDN example right here . Use:
this.sp.DataReceived
+= new SerialDataReceivedEventHandler(this.sp_DataReceived);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.