123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Generic;
- using System.IO.Ports;
- using System.Linq;
- using System.Text;
- using System.Windows;
- namespace UAS_MES.PublicMethod
- {
- /// <summary>
- /// 从串口获取数据
- /// </summary>
- class ReadDataFromSerialPort
- {
- static List<string> OpenPort = new List<string>();
- SerialPort serial = new SerialPort();
- string SerialPort;
- public ReadDataFromSerialPort(string Port)
- {
- if (!OpenPort.Contains(Port))
- {
- try
- {
- SerialPort = Port;
- serial.PortName = Port;
- OpenPort.Add(Port);
- serial.DataReceived += Serial_DataReceived;
- serial.Open();
- }
- catch (Exception ex) { MessageBox.Show(ex.Message); }
- }
- else
- MessageBox.Show(Port + "已开启,请勿重复打开");
- }
- private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
-
- }
- /// <summary>
- /// 读取串口数据
- /// </summary>
- /// <returns></returns>
- public string Read()
- {
- string Data = "";
- if (serial.IsOpen)
- {
- try
- {
- Data = serial.ReadLine();
- serial.DiscardInBuffer();
- }
- catch (Exception e) { MessageBox.Show(e.Message); }
- }
- return Data;
- }
- /// <summary>
- /// 如果打开的串口不为空则进行关闭
- /// </summary>
- public void Close()
- {
- if (serial.IsOpen)
- {
- serial.Close();
- OpenPort.Remove(SerialPort);
- }
- }
- }
- }
|