关于c# serialport接受数据怪现象
荒凉1 2013-11-27 10:45:49
private void Form1_Load(object sender, EventArgs e)
{
this.serialPort1.PortName = "com8";
this.serialPort1.BaudRate = 9600;
this.serialPort1.DataBits = 8;
this.serialPort1.StopBits = StopBits.One;
this.serialPort1.Parity = Parity.Even;
this.serialPort1.Open();
this.timer1.Enabled = true;
this.timer1.Interval = 500;
}
private void button1_Click(object sender, EventArgs e)
{
this.serialPort1.Close();
this.Close();
}
private void ReceiveText(object sender, EventArgs e)
{
double datareceive_2;
short datareceive_4 = 8;
short datareceive_5 = 4;
string datareceive_6;
string datareceive_7;
string datareceive_8;
int datareceive_9;
char[] datareceive_0 = datareceive.ToCharArray();//字符串转换成字符串数组
//byte[] datareceive_0 = Convert.FromBase64String(datareceive);
int i = datareceive_0.Length;//判断长度
if (i == 7)
{
datareceive_4 = (short)datareceive_0[3];//获取所需
datareceive_5 = (short)datareceive_0[4];
datareceive_6 = Convert.ToString(datareceive_4, 16);//十进制转化十六进制
datareceive_7 = Convert.ToString(datareceive_5, 16);
if (datareceive_6.Length < 2)
{
datareceive_6 = "0" + datareceive_6;//长度不足两位补 0
}
if (datareceive_7.Length < 2)
{
datareceive_7 = "0" + datareceive_7;
}
datareceive_8 = "";
datareceive_8 = datareceive_6 + datareceive_7;//拼接十六进制数
datareceive_9 = int.Parse(datareceive_8, System.Globalization.NumberStyles.HexNumber);//十六进制转化为十进制
datareceive_2 = datareceive_9 / 100.0;
this.label1.Text = datareceive_2.ToString();
}
}
private void timer1_Tick(object sender, EventArgs e)//发送数据
{
byte[] senddata = { 0x01, 0x03, 0x21, 0x03, 0x00, 0x01, 0x7e, 0x36 };
serialPort1.Write(senddata, 0, senddata.Length);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(10);
datareceive = null;
datareceive = serialPort1.ReadExisting();
this.Invoke(new EventHandler(ReceiveText));
}
}
奇怪的情况是这样的:
这里用的Modbus来得到数据的,情况如下所示:得到的数据:01 03 02 13 88 B5 12得到的是:01 03 02 13 3f 3f 12有的时候数据正常有时候就像这样不正确,不知道怎么回事,想了很多不知道问题所在,希望得到解答! 我刚刚试了一下,原来是我的char[]里面存0-7的数的时候都是正常的,也就是8进制的,但是我接收到的都是16进制的,一旦超过8以上的就编程3f了,但是我看char的值是这养:
// 摘要:
// 表示 System.Char 的最大可能值。此字段为常数。
public const char MaxValue = (char)0xffff;
//
// 摘要:
// 表示 System.Char 的最小可能值。此字段为常数。
public const char MinValue = '\0';
怎么会出现这样的情况呢,求解释!
还有个问题:c#中CHAR的取值是-128--127,怎么编程0-255的,我试了好像写不了!