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、效果

 

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值