上位机-串口通信-C#
一. 新建项目
二. 在组件中 拖拽serialPort空间
这样就默认产生了serialPort1对象。在串口的属性栏里面设置串口属性
设置串口属性的时候最好是在程序里面设置,用代码实现。直接在置属性可能会使串口的DateReceivd事件无法触发,(具体为什么我也不知道,高手们可以帮忙看看)这是亲身体验啊~~找了好久,都不知道问题在哪里。得出结论,最保险的方法还是用代码实现串口的属性设置。
具体代码如下:
(不要忘记导入命名空间usingSystem.IO.Ports; 否则会有错)
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;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
publicForm1()
{
InitializeComponent();
serialPort1.ReceivedBytesThreshold= 1;
serialPort1.BaudRate = 9600;
serialPort1.PortName = "COM1";
serialPort1.Parity = Parity.Even;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
}
}
}
三 、打开,关闭串口
serialPort类封装了 close();和open();方法 调用close方法时关闭端口连接,将isopen属性设置为false,并且释放内部的stream对象。调用open时打开