using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace TestSerialPort
{
public partial class frmTESTSerialPort : Form
{
//实例化串口对象(默认:COM1,9600,e,8,1)
SerialPort myserialPort = new SerialPort();
//串口控件初始化
public frmTESTSerialPort()
{
InitializeComponent();
}
//窗口载入
private void frmTESTSerialPort_Load(object sender, EventArgs e)
{
//更改参数
myserialPort.PortName = "COM1 ";
myserialPort.BaudRate = 9600;
myserialPort.Parity = Parity.None;
myserialPort.DataBits = 8;
myserialPort.StopBits = StopBits.One;
myserialPort.ReadBufferSize = 4096;
//上述步骤可以用在实例化时调用SerialPort类的重载构造函数
//SerialPort serialPort = new SerialPort("COM1 ", 9600, Parity.None, StopBits.One);
}
//开启串口
private void button1_Click(object sender, EventArgs e)
{
//打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改)
if (myserialPort.IsOpen == false)
{
myserialPort.Open();
MessageBox.Show("串口开启成功");
}
}
//发送数据
private void button2_Click(object sender, EventArgs e)
{
//发送数据
SendStringData(myserialPort);
}
//发送字符串数据
private void SendStringData(SerialPort serialPort)
{
serialPort.Write(txtSend.Text);
}
//发送二进制数据
private void SendBytesData(SerialPort serialPort)
{
byte[] bytesSend = System.Text.Encoding.Default.GetBytes(txtSend.Text);
serialPort.Write(bytesSend, 0, bytesSend.Length);
}
//接收\读取数据
public void button3_Click(object sender, EventArgs e)
{
//同步阻塞接收数据线程
Thread threadReceive = new Thread(new ThreadStart(SynReceiveData));
threadReceive.Start(serialPort);
//也可用异步接收数据线程
//Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
//threadReceiveSub.Start(serialPort);
}
//同步阻塞读取
private static void SynReceiveData(object serialPortobj)
{
MessageBox.Show("同步阻塞读取线程启动");
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(0);
try
{
//阻塞到读取数据或超时(这里为1分钟)
serialPort.ReadTimeout = 60000;
int bytesRead = serialPort.BytesToRead;
byte[] bytesData = new byte[bytesRead];
for (int i = 0; i <= bytesRead - 1; i++)
{
bytesData = Convert.ToByte(serialPort.ReadByte());
}
txtReceive.Text = txtReceive.Text + System.Text.Encoding.Default.GetString(bytesData, 0, bytesRead);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//处理超时错误
}
}
//异步读取
private void AsyReceiveData(object serialPortobj)
{
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(500);
try
{
txtReceive.Text = txtReceive.Text + serialPort.ReadExisting();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//处理错误
}
}
private void button4_Click(object sender, EventArgs e)
{
if (myserialPort.IsOpen == true)
{
myserialPort.Close();
MessageBox.Show("串口关闭成功");
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
static class Program
{
static void Main()
{
Application.Run(new frmTESTSerialPort());
}
}
}