近期一个配料系统项目,采用modbus rtu与称重仪表通讯,为节约成本,不使用PLC采集工业平板GPIO进行控制。由于很久没有进行高级语言编程(以前的modbus通讯都是自己写),现在有点吃力了,网上找了一圈,采用NModbus4开源库进行通讯(rtu,tcp都能用)。以前自己写的ModbusTcp通讯正常情况下虽然没有问题,但是在断网时往往需要50秒左右程序才会知道(想了很多办法都没有解决,不晓得大家有没有遇到),好在这个控件解决了问题,自己真的不专业,还是用歪国人写的,毕竟人家专业的,自己也不会头疼。。。。
有兴趣的可以留下邮箱 ,发项目源码,源码发出后,请执行你们的安装项目生成的安装包,才能运行(因为要访问数据库,安装包将会包数据库安装到计算机上)
技术点:
1 NModbus4 多线程rtu通讯。
2、控制计算机板卡GPIO,包含调用库
3、数据采用Access存储,包含access工具类
4、采用XML文件配置文件通讯等参数
通讯代码:
void gm8802fstart()
{
try
{
addlist("GM8802通讯参数:" + mysys.COM + " " + mysys.BaudRate.ToString() + " " + mysys.Parity.ToString() + " " + mysys.DataBits.ToString() + " " + mysys.StopBits.ToString() + " "+mysys.SlaveID.ToString()+" " + mysys.RegisterAddress.ToString() + " " + mysys.ZeroAddress.ToString());
System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort(mysys.COM);
port.BaudRate = mysys.BaudRate;
port.DataBits = mysys.DataBits;
port.Parity = mysys.Parity;
port.StopBits = mysys.StopBits;
port.Open();
Modbus.Device.IModbusSerialMaster master = Modbus.Device. ModbusSerialMaster.CreateRtu(port);
master.Transport.ReadTimeout = 1000;
gm8802 = true;
gm8802Zero = false;
while (gm8802)
{
try
{
{
byte[] recBuf = new byte[6];
ushort[] reg = master.ReadHoldingRegisters(mysys.SlaveID, mysys.RegisterAddress, 3);
byte[] recBuf1 = BitConverter.GetBytes(reg[0]);
byte[] recBuf2 = BitConverter.GetBytes(reg[1]);
byte[] recBuf3 = BitConverter.GetBytes(reg[2]);
recBuf[0] = recBuf1[0];
recBuf[1] = recBuf1[1];
recBuf[2] = recBuf2[0];
recBuf[3] = recBuf2[1];
int sl = (recBuf[3] << 8) + (recBuf[2]) + (recBuf[1] << 16) + (recBuf[0] << 24);
//int sl = BitConverter.ToInt32(recBuf,0);//********************test********************
if (!test)
{
myweight.Weighter = Convert.ToDecimal(sl.ToString());
}
string stat = "0000" + Convert.ToString(reg[2], 2);
myweight.Stat = stat.Substring(stat.Length - 4, 4);//000222
fs.Visible = myweight.Negative;
lw.Visible = myweight.ZeroPoint;
yc.Visible = myweight.OverFlow;
wd.Visible = myweight.Stable;
txt_stable.Visible = myweight.Stable;
if (myweight.ZeroPoint)
{
if (b_zero.BackColor != Color.LimeGreen)
{
b_zero.BackColor = Color.LimeGreen;
}
}
else
{
if (b_zero.BackColor != Color.Gainsboro)
{
b_zero.BackColor = Color.Gainsboro;
}
}
if (gm8802Zero)
{
if (myweight.Stable)
{
addlist("清零操作" + mysys.SlaveID.ToString() + ":" + mysys.ZeroAddress);
//master.WriteSingleCoil(mysys.SlaveID, mysys.ZeroAddress, true);
master.WriteSingleRegister(mysys.SlaveID, mysys.ZeroAddress, 1);
//Thread.Sleep(200);
}
gm8802Zero = false;
}
l_weight.Text = myweight.Weighter.ToString();
}
tx.Visible = true;
}
catch (Exception ex)
{
addlist("仪表通讯错误:"+ex.Message);
tx.Visible = false;
fs.Visible = false;
lw.Visible = false;
yc.Visible = false;
wd.Visible = false;
txt_stable.Visible = false;
}
}
port.Close();
tx.Visible = false;
}
catch(Exception ex)
{
addlist(ex.Message);
myweight.Weighter = 0;
}
tx.Visible = false;
}
楼主最近还看过