PC通過串口接收Arduino UNO的數據(WinForm)

參考:http://msdn.microsoft.com/zh-cn/library/system.io.ports.serialport(VS.80).aspx

0、Arduino程序

/*
  Serial Event example

  When new serial data arrives, this sketch adds it to a String.
  When a newline is received, the loop prints the string and clears it.

  A good test for this is to try it with a GPS receiver that sends out
  NMEA 0183 sentences.

  NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
  other ATmega32U4 based boards.

  created 9 May 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/SerialEvent
*/

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);  
}

void loop() {
  serialSend();
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialSend() {
    Serial.print("This is an arduino.\n");
    delay(300);
}

1、目錄結構

2、界面

3、 Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace SerialPortModel
{
    public partial class Form1 : Form
    {
        MySerialCom mySerialCom = new MySerialCom();
        public Form1()
        {
            InitializeComponent();            
            mySerialCom.openSerialPort();
            //註冊事件
            MySerialCom.serialPort.DataReceived += this.addStringToTextBox;
        }

        public void addStringToTextBox(object sender, SerialDataReceivedEventArgs e) //事件處理方法
        {
            //使用Lambda表達式匿名委託設置文本
            this.Invoke(new Action(() =>
            {
                
                this.textBox1.AppendText(mySerialCom.readLine());
                
                this.textBox1.AppendText("\r\n");
            }));            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1.AppendText("yyyyyyy");
            this.textBox1.AppendText("\n");
        }
    }
}

4、MySerialCom.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Collections;

namespace SerialPortModel
{
    class MySerialCom
    {
        public static SerialPort serialPort = new SerialPort();
        string[] portNamesStr;

        public MySerialCom()
        {
            this.setBaudRate(9600);
            this.setParity(Parity.None);
            this.setReadBufferSize(256);
            this.setReadTimeout(800);
            this.setEncoding(Encoding.GetEncoding("UTF-8"));
            this.setPort("COM5");
        }

        public MySerialCom(int baudRate)
        {
            this.setBaudRate(baudRate);
            this.setParity(Parity.None);
            this.setReadBufferSize(256);
            this.setReadTimeout(800);
            this.setEncoding(Encoding.GetEncoding("UTF-8"));
        }

        public MySerialCom(int baudRate, string comPort)
        {
            this.setBaudRate(baudRate);
            this.setParity(Parity.None);
            this.setReadBufferSize(256);
            this.setReadTimeout(800);
            this.setEncoding(Encoding.GetEncoding("UTF-8"));
            this.setPort(comPort);
        }

        public string[] getPortNames() //掃描COM端口名
        {
            portNamesStr = SerialPort.GetPortNames();
            return portNamesStr; //返回string數組
        }

        //設置波特率
        public void setBaudRate(int x)
        {
            if (x > 0)
                serialPort.BaudRate = x;
        }

        //設置端口
        public void setPort(string x)
        {
            this.getPortNames();
            SortedSet<string> portNamesSet = new SortedSet<string>();
            if (portNamesStr.Length > 0)
            {
                foreach (string portName in portNamesStr)
                {
                    portNamesSet.Add(portName); //丟入集合,自動去重
                }

                if (portNamesSet.Contains(x)) //查詢集合中是否包含某個元素
                {
                    serialPort.PortName = x; //設置端口
                }
            }
        }

        //設置停止位
        public void setStopBits(StopBits x) //設置每個字節的標準停止位數
        {
            serialPort.StopBits = x; //
        }

        //設置奇偶校驗
        public void setParity(Parity x)
        {
            serialPort.Parity = x; //設置奇偶校驗檢查協議
        }

        //設置編碼格式
        public void setEncoding(Encoding x)
        {
            serialPort.Encoding = x;
        }

        //設置超時時間
        public void setReadBufferSize(int x)
        {
            serialPort.ReadBufferSize = x;
        }

        //設置超時時間
        public void setReadTimeout(int x)
        {
            serialPort.ReadTimeout = x;
        }

        //打開串口
        public void openSerialPort()
        {
            serialPort.Open();
        }

        //關閉串口
        public void closeSerialPort()
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
        }

        //按行讀取
        public string readLine()
        {
            string line;

            line = serialPort.ReadLine();

            return line;
        }

        //狀態
        public bool isOpen()
        {
            return serialPort.IsOpen;
        }
    }
}

5、效果

 

 

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