private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8; //數據位
serialPort1.Parity = System.IO.Ports.Parity.None; //無奇偶校驗位
serialPort1.StopBits = System.IO.Ports.StopBits.One; //一個停止位
serialPort1.ReadBufferSize = 1024; //接收緩沖區大小
serialPort1.Encoding = Encoding.BigEndianUnicode;
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
textChanged += new UpdateTextEventHandler(ChangeText); //將事件處理方法添加到事件中去,不可缺少
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(string.Format("未能打開串口,請檢查是否連接。\n" + ex.Message));
return;
}
}
public static string ByteToHexStr(byte[] bytes) //函數,字節數組轉16進制字符串
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
private delegate void UpdateTextEventHandler(string text);//定義委托
private event UpdateTextEventHandler textChanged;//定義事件
private void ChangeText(string text) //事件處理方法 www.2cto.com
{
string text1 = string.Empty;
text1 = text.Trim().Substring(10, 1);
string s1 = string.Empty;
s1 = text.Trim().Substring(10, 4);
int dec1 = Convert.ToInt32(s1, 16); //s1 轉換成10進制
if (text1 == "0") //直接除10
{
decimal dda1 = Math.Round((decimal)dec1 / 10, 1); //除10,保留1位小數
textBox5.Text = dda1.ToString(CultureInfo.InvariantCulture).Trim();
}
else //xor ffff
{
int d1 = (dec1 ^ Convert.ToInt32("FFFF", 16)) + 1;
decimal dd1 = Math.Round((decimal)d1 / 10, 1); //除10,保留1位小數
textBox5.Text = dd1.ToString(CultureInfo.InvariantCulture).Trim();
}
string s2 = text.Trim().Substring(14, 4);
int d2 = Convert.ToInt32(s2, 16); //s2 轉換成10進制
Decimal dd2 = Math.Round((decimal)d2 / 10, 2); //除10,保留1位小數
textBox6.Text = dd2.ToString(CultureInfo.InvariantCulture).Trim();
string text3 = text.Trim().Substring(18, 1);
string s3 = text.Trim().Substring(18, 4);
int dec3 = Convert.ToInt32(s3, 16); //s3 轉換成10進制
if (text3 == "0")
{
decimal dda3 = Math.Round((decimal)dec3 / 10, 1); //除10,保留1位小數
textBox7.Text = dda3.ToString(CultureInfo.InvariantCulture).Trim();
}
else //xor ffff
{
int d3 = (dec3 ^ Convert.ToInt32("FFFF", 16)) + 1;
decimal dd3 = Math.Round((decimal)d3 / 10, 1); //除10,保留1位小數
textBox7.Text = string.Format("-{0}", dd3.ToString(CultureInfo.InvariantCulture).Trim());
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
Thread.Sleep(100); //讀取速度太慢,加Sleep延長讀取時間, 不可缺少
serialPort1.Read(buffer, 0, buffersize);
//string text = Encoding.ASCII.GetString(buffer); //ASCII卡碼
string txt = ByteToHexStr(buffer); //用到函數,作用:轉換16進制
serialPort1.DiscardInBuffer();
this.Invoke(textChanged, new string[] {txt}); //通過Invoke調用事件
}
摘自 brian0031的專欄