C# 串口

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 CompassSerial01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
//設置波特率
int[] br = new int[12] { 1200, 2400, 4800, 9600, 12800, 14400, 19200, 25600,38400, 56000, 57600, 115200};
serialPort1.Close();
//根據參數打開窗口
if (button1.Text == "打開串口")
{
serialPort1.BaudRate = br[comboBox2.SelectedIndex]; //獲取波特率
serialPort1.PortName = comboBox1.SelectedItem.ToString();//獲取端口
serialPort1.Open(); //打開新的串口連接
timer1.Enabled = true;
button1.Text = "關閉串口";
}
else
{
button1.Text = "打開串口";
timer1.Enabled = false;
}
}

private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
{
comboBox2.SelectedIndex = 8;
byte[] buf = new byte[4095];
if (serialPort1.BytesToRead != 0)//獲取接受緩衝區中數據的字節數
{
serialPort1.Read(buf, 0, serialPort1.BytesToRead);
ASCIIEncoding encoding = new ASCIIEncoding();
string constructedString = encoding.GetString(buf); //將獲取的字節轉換成字符串

listBox1.Items.Add(constructedString); //將字符串顯示到listbox1上
//控制串口從下往上顯示
this.listBox1.TopIndex = this.listBox1.Items.Count - (int)(this.listBox1.Height / this.listBox1.ItemHeight);
}

}
}

private void Form1_Load(object sender, EventArgs e)
{
comboBox2.SelectedIndex = 1;
String[] ports = System.IO.Ports.SerialPort.GetPortNames();//獲取當前計算機串口數組的名稱
int i;
comboBox1.Items.Clear();
for (i = 0; i < ports.Length; i++) //遍歷獲取當前串口
{
comboBox1.Items.Add(ports[i]); //將獲取的端口添加到comboBox1中
}
}
private void 發送_Click(object sender, EventArgs e)
{
byte [] buf = new byte[10];
serialPort1.Write(buf, 0, 10);
// serialPort1.Read(buf,0,10);
// string strRecieve1 = serialPort1.ReadExisting();
}

private void Clear_Click(object sender, EventArgs e)
{
listBox1.Items.Clear(); //清屏
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章