using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 串口通信Winform
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM1"; //定义串口
serialPort1.BaudRate = 9600; //设置波特率,不同的波特率,数据将不同
serialPort1.Open(); //打开串口
byte[] data = Encoding.Unicode.GetBytes(textBox1.Text); //将数据进行编码
string str = Convert.ToBase64String(data);
serialPort1.WriteLine(str); //发送数据
MessageBox.Show("数据发送成功!", "系统提示");
serialPort1.Close(); //关闭串口
}
private void button2_Click(object sender, EventArgs e)
{
byte[] data = Convert.FromBase64String(serialPort1.ReadLine()); //从串口上得到数据
textBox1.Text = Encoding.Unicode.GetString(data); //换编码还原数据
serialPort1.Close(); //关闭串口
MessageBox.Show("数据接收成功!", "系统提示");
}
}
}