using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Modbus.Device;
using System.Threading;
namespace modbus
{
public partial class Form1 : Form
{
public Form1()
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
btnStop.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
serialPort1.Open();
btnStart.Enabled = false;
btnStop.Enabled = true;
timer1.Enabled = true;
}
public static object locker = new object();
Thread th1;
Thread th2;
private void timer1_Tick(object sender, EventArgs e)
{
th1 = new Thread(Recive);
th1.Start();
}
private void Recive()
{
ModbusSerialMaster master1 = ModbusSerialMaster.CreateRtu(serialPort1);
ushort[] t = master1.ReadHoldingRegisters(1, 0, 10);
string s = null;
for (int i = 0; i < t.Length; i++)
{
s += t[i].ToString();
}
textBox1.AppendText(s + "\r\n");
}
private void btnStop_Click(object sender, EventArgs e)
{
serialPort1.Close();
btnStart.Enabled = true;
btnStop.Enabled = false;
timer1.Enabled = false;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
btnSend.Enabled = true;
}
private void btnSend_Click(object sender, EventArgs e)
{
th2 = new Thread(Send);
th2.Start();
//Send(); 发送时不新开线程就不报错
}
private void Send()
{
lock (locker)
{
string s = textBox2.Text;
for (int i = 0; i < s.Length; i++)
{
ushort c = Convert.ToUInt16(i);
ushort b = Convert.ToUInt16(s[i].ToString());
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);
master.WriteSingleRegister(1, c, b);//由于线程退出或应用程序请求,已中止 I/O 操作。
}
}
}
}
}
odbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);拿到外面去
master这东西全局唯一