我正在嘗試構建一個可以使用串口通信與服務器進行通信的應用程序。在C#中使用RS-485轉換器和服務器進行串口通信
場景:
我必須通過RS-485轉換器和USB我的筆記本電腦,安裝有電錶(充當服務器)。現在我想打開一個端口併發送與服務器通信的初始命令,並期望服務器發送一些響應。
這裏是我的代碼
void main(string args[])
{
SerialPort sp = new SerialPort();
sp.PortName = "COM5";
sp.BaudRate = 9600;
... // other parameters i.e. Parity, StopBits
// Databits etc
sp.Open();
sp.DataReceived = myPortDataReceived();
sp.WriteLine("/?!\r\n");
}
public static void myPortDataReceived(object sender, SerialPortDataReceivedEventArgs e)
{
SerialPort myPort = (SerialPort)sender;
String data = myPort.ReadExisting();
Console.WriteLine("Data Received");
Console.WriteLine(data);
}
當我運行的程序沒有輸出。這意味着對象myPort
什麼都不讀。
我是編程新手,不知道爲什麼會發生。
任何想法都是非常適合的。
感謝
更新1
我修改我的代碼並運行它,但它不能去的事件處理程序方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
namespace Communication
{
class Program
{
static void Main(string[] args)
{
SerialPort sp = new SerialPort();
sp.PortName = "COM5";
sp.Open();
// check port is open or not
if (sp.IsOpen==true)
Console.WriteLine("Port is open");
// set the port parameters
sp.BaudRate = 9600;
sp.DtrEnable = true;
sp.Handshake = Handshake.None;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
// write some command on port
sp.WriteLine("?/!\r\n");
// make DataReceived event handler
sp.DataReceived += sp_DataReceived;
//Console.WriteLine("Press any key to exit");
//Console.ReadLine();
Console.ReadKey();
}
public static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine("I am in event handler");
SerialPort sPort = (SerialPort)sender;
String data = sPort.ReadExisting();
foreach (char ch in data)
{
Console.WriteLine(ch);
}
}
}
}
而且我可以把sPort
爲while(true) {String data = sPort.ReadExisting(); Console.WriteLine(data); }
請回復,,,, – selflearner2014