110,536
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
int k = 0;
int[] crc_data1 = { 0, 0 };
int[] crc_data2 = { 0, 0, 0, 0, 0 };
int[] crc_data3 = { 0, 0, 0, 0, 0 };
int x = 0;
short qtemp;
byte[] new_byte1 = { 0, 0, 0, 0, 0, 0, 0 };
SolidBrush bush1 = new SolidBrush(Color.Red);
SolidBrush bush2 = new SolidBrush(Color.Green);
public Form1()
{
InitializeComponent();
}
//串口初始化
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.Open();
}
//向水浸传感器发送读指令
private void timer1_Tick(object sender, EventArgs e)
{
byte[] boutdata1 = { 0x01, 0x04, 0x01, 0xE3 };
serialPort1.Write(boutdata1, 0, 4);
}
//触发事件,读取温度传感器返回数据
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
System.Threading.Thread.Sleep(100);
int byte_num1 = serialPort1.Read(new_byte1, 0, 7);
this.Invoke(new EventHandler(DisplayText));
}
private void DisplayText(object sender, EventArgs e)
{
if (new_byte1[0] == 1) //水浸传感器
{
for (int i = 0; i < 2; i++)
crc_data1[i] = (int)new_byte1[i];
int[] crc1 = crc16(crc_data1);
if (crc1[0] == new_byte1[2] && crc1[1] == new_byte1[3]) //校验CRC
alarm1(); //显示,红灯报警,绿灯正常
else
MessageBox.Show("校验码错误,数据无效!", "");
byte[] boutdata2 = { 0x02, 0x03, 0x00, 0x01, 0x00, 0x01, 0xD5, 0xF9 }; //发送温度传感器数据
serialPort1.Write(boutdata2, 0, 8);
}
if (new_byte1[0] == 2 && new_byte1[1] == 3) //温度传感器
{
for (int i = 0; i < 5; i++)
crc_data2[i] = (int)new_byte1[i];
int[] crc2 = crc16(crc_data2);
if (crc2[0] == new_byte1[5] && crc2[1] == new_byte1[6])
DisplayText2(); //显示温度并画出温度曲线
else
MessageBox.Show("校验码错误,数据无效!", "");
byte[] boutdata3 = { 0x50, 0x03, 0x00, 0x03, 0x00, 0x01, 0x79, 0x8B }; //发送烟感传感器数据
serialPort1.Write(boutdata3, 0, 8);
}
if (new_byte1[0] == 80 && new_byte1[1] == 3) //烟感传感器
{
for (int i = 0; i < 5; i++)
crc_data3[i] = (int)new_byte1[i];
int[] crc3 = crc16(crc_data3);
if (crc3[0] == new_byte1[5] && crc3[1] == new_byte1[6])
alarm3(); //显示,红灯报警,绿灯正常
else
MessageBox.Show("校验码错误,数据无效!", "");
}
}
//关闭串口,退出程序
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Close();
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
}
//构建设备对象并放到数组中
while(true)
{
for( i = 0 ; i < 设备数组个数;i++)
{
try
{
设备[i].send(要数据命令);
Thread.sleep(500); //根据线路延迟可以设置一个较为合理的。超过时间没数据认为设备掉线
Receive()
}
catch
{设备[i]通讯错误}
}
}
[/quote]
谢谢!请问一下这段代码是放在timer_tick里面吗,那个true指的是timer.enabled?没有用过try catch,继续学习!
//构建设备对象并放到数组中
while(true)
{
for( i = 0 ; i < 设备数组个数;i++)
{
try
{
设备[i].send(要数据命令);
Thread.sleep(500); //根据线路延迟可以设置一个较为合理的。超过时间没数据认为设备掉线
Receive()
}
catch
{设备[i]通讯错误}
}
}