尊敬的老师:
下午好
我写了一段代码,运行后,我先点写入按钮,弹出02000200,然后我又点击确定,又弹出111940402000200EB,我再点击确定,居然软件死机,然后在com.Write(sWriteData);这里停下,弹出一个未处理的invalid Operation Exception 这是什么意思呢?为什么会弹出这样的异常?我哪里代码未处理了?那我该怎么处理呢?
请老师帮忙修改下代码。
我写的源代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace 三菱PLC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//串口初始化
com = new SerialPort("com5", 9600, Parity.Even, 7, StopBits.One);
if (com.IsOpen)
{ com.Close(); }
com.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
// ASCII转字符
public static string Chr(int asciiCode)
{
if (asciiCode >= 0 && asciiCode <= 255)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
byte[] byteArray = new byte[] { (byte)asciiCode };
string strCharacter = asciiEncoding.GetString(byteArray);
return (strCharacter);
}
else
{
throw new Exception("ASCII Code is not valid");//ASCII 缺失
}
}
//字符转ASCII
public static int Asc(string character)
{
if (character.Length == 1)
{
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
return (intAsciiCode);
}
else
{
throw new Exception("character is not valid");
}
}
// 写入串口的命令字符的和校验
public string SumCheck(string data)
{
int sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += Asc(data.Substring(i, 1));
// sum += Convert.ToInt16(data.Substring(i, 1));
}
string res = sum.ToString("X");
res = res.Substring(res.Length - 2, 2);
return res;
}
private void btnWrite_Click(object sender, EventArgs e)
{
string[] write = new string[] { "2", "2" };//将准备写入PLC的值
// 将要写入PLC的值转化为16进制数,补齐2个字节,注意高低字节需要交换
string sWriteData = "";
for (int i = 0; i < write.Length; i++)
{
int val = Convert.ToInt32(write[i].Length > 0 ? write[i] : "0");
string s = val.ToString("X");
while (s.Length < 4)
{
s = "0" + s;
}
sWriteData += s.Substring(2, 2) + s.Substring(0, 2);
}
MessageBox.Show(sWriteData);
//写入命令,1表示写入,1194表示D202这个地址的16进制,04表示D202,D203为4个BYTE,
//1194=(202*2)+4096的16进制数,至于用它表示D202的起始位置,三菱故意要这么麻烦了。
sWriteData = "1119404" + sWriteData + Chr(3);
// chr(2)和chr(3)是构成命令的标识符,然后加上校验和,命令组织完成。
sWriteData = Chr(2) + sWriteData + SumCheck(sWriteData);
MessageBox.Show(sWriteData);
//写入串口
com.Write(sWriteData);
//byte[]data = Encoding.ASCII.GetBytes(sWriteData);
//com.Write(data,0,data.Length);
}
}
}
异常图片如下: