jszy 2020-01-17
开发语言:C#
开发环境:VS2008(支持WINCE开发的最后一个版本)
运行环境:Windows CE 5.0~7.0
项目说明:多台涨格winpac系列的主机,原来使用泓格SDK开发的程序,采集7018系列模块的数据,主要有7018R和7018Z。现客户要求增加一个温湿度模块,此模块支持rs485 modbus rtu通讯。
首先尝试使用SDK方法,可以读取7018模块的数据,却读不到温湿度模块的数据,代码如下:
void Main() { var remoteIOPort = PACNET.UART.Open("COM2,9600"); var cmd = Encoding.ASCII.GetBytes("#01\r"); send(cmd, 0); //可以正常读取7018 send(cmd, 1); //可以正常读取7018 cmd = new byte[] { 0x65, 0x04, 0x00, 0x01, 0x00, 0x01, 0x68, 0x2E }; send(cmd, 1); //不能读取温湿度模块 } void send(byte[] cmd, int type) { if (type == 0) { float[] fValue = new float[10]; var readResult = PACNET.PAC_IO.ReadAIAll(remoteIOPort, PACNET.PAC_IO.PAC_REMOTE_IO(1), fValue); foreach (var item in fValue) { appendText(item); } } else if (type == 1) { var buffer = new byte[72]; PACNET.UART.SendCmdExt(remoteIOPort, cmd, (uint)cmd.Length, buffer, (uint)buffer.Length); appendText(BitConverter.ToString(buffer)); } }
直接读写串口,测试成功。代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.Threading; namespace TESTSERIALPORT { public partial class FrmSerialPort : Form { SerialPort serial; public FrmSerialPort() { InitializeComponent(); serial = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One); serial.Open(); } private void btnWrite_Click(object sender, EventArgs e) { serial.ReadTimeout = 1000; serial.WriteTimeout = 1000; if (!serial.IsOpen) { serial.Open(); appendText(serial.PortName); appendText(serial.BaudRate); appendText(serial.Parity); appendText(serial.DataBits); appendText(serial.StopBits); appendText(serial.IsOpen); } var cmd = Encoding.ASCII.GetBytes("#01\r"); send(cmd, 1); cmd = new byte[] { 0x65, 0x04, 0x00, 0x01, 0x00, 0x01, 0x68, 0x2E }; send(cmd, 1); cmd = new byte[] { 0x65, 0x04, 0x00, 0x02, 0x00, 0x01, 0x98, 0x2E }; send(cmd, 1); } void send(byte[] cmd, int type) { serial.Write(cmd, 0, cmd.Length); Thread.Sleep(300); var size = serial.BytesToRead; appendText(size); var buffer = new byte[size]; var result = serial.Read(buffer, 0, size); if (type == 0) { appendText(PACNET.MISC.WideString(buffer)); } else if (type == 1) { appendText(BitConverter.ToString(buffer)); } } void appendText(object obj) { textBox1.Text += obj.ToString() + "\r\n"; } } }