How to Read Modbus String Using C# | Read RS232 Using C#
Hướng dẫn dùng C# đọc chuỗi qua RS485 hoặc RS232.
Đọc và xử lý Frame truyền RS485, RS232 qua cổng Serial Port.
Code:
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;using System.Runtime.CompilerServices;using System.IO;using System.Threading;namespace Test_Serial_Port{public partial class Form1 : Form{private SerialPort serialport;float net_we;float tare_we;public Form1(){InitializeComponent();}private void Btn_Connect_Click(object sender, EventArgs e){serialport.BaudRate = 1200;serialport.DataBits = 7;serialport.Parity = Parity.Odd;serialport.PortName = "COM2";serialport.StopBits = StopBits.One;serialport.Open();if (serialport.IsOpen){progressBar1.Value = 100;}}private void Form1_Load(object sender, EventArgs e){serialport = new SerialPort();}private void Btn_Read_Click(object sender, EventArgs e){serialport.DataReceived += new SerialDataReceivedEventHandler(Serialport_DataReceived);}private void Serialport_DataReceived(object sender, SerialDataReceivedEventArgs e){int bytes = serialport.BytesToRead;byte[] buffer = new byte[bytes];byte[] net = new byte[6];byte[] tare = new byte[6];TB_Read.Invoke(new MethodInvoker(delegate (){//TB_Read.Text = serialport.ReadExisting();serialport.Read(buffer, 0, bytes);if (bytes == 17){for (int h = 4; h <= 9; h++){net[h - 4] = buffer[h];tare[h - 4] = buffer[h + 6];}}int net_w;int tare_w;Int32.TryParse(Encoding.ASCII.GetString(net), out net_w);Int32.TryParse(Encoding.ASCII.GetString(tare), out tare_w);string dec = Convert.ToString(buffer[1], 2);string sign = Convert.ToString(buffer[2], 2);if(dec.Substring(3,3) == "100"){net_we = net_w / 100f;tare_we = tare_w / 100f;}if ( sign.Substring(4,1) == "1"){net_we = net_we * -1f;}TB_Read.Text ="Byte 0: " + Convert.ToString(buffer[0], 2) + "\r\n"+ "Byte 1: " + Convert.ToString(buffer[1], 2) + "\r\n"+ "Byte 2: " + Convert.ToString(buffer[2], 2) + "\r\n"+ "Net Weight: " + net_we+"\r\n" + "Tare Weight: " + tare_we;//TB_Write.Text = TB_Read.Text.Substring(3, 7) + " " + TB_Read.Text.Substring(10, 7) + " " + bytes.ToString();}));}}}
Link Source Code: Download
Video hướng dẫn:
No comments:
Post a Comment