1、监测串口通讯状态
namespace CheckPLC
{
public partial class Form1 : Form
{
SerialPort plc = new SerialPort("COM2", 9600, Parity.Odd, 8, StopBits.One);
System.Timers.Timer Timer1 = new System.Timers.Timer(5000);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
plc.DataReceived += new SerialDataReceivedEventHandler(plc_DataReceived);
plc.Open();
Timer1.Elapsed += new System.Timers.ElapsedEventHandler(CheckPlc);
Timer1.AutoReset = true;
Timer1.Enabled = true;
}
private void plc_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[plc.ReadBufferSize];
plc.Read(readBuffer, 0, readBuffer.Length);
string readstr = Encoding.UTF8.GetString(readBuffer);
if (readstr.Substring(0,2) == "ok")
{
Timer1.Enabled = false;
Timer1.Enabled = true;
}
//MessageBox.Show(readstr);//调试用
}
public void CheckPlc(Object source, System.Timers.ElapsedEventArgs e)
{
MessageBox.Show("真是惨,PLC坏了!");
Timer1.Enabled = false;
}
}
}