首页 新闻 会员 周边 捐助

C#串口读写

1
[已解决问题] 解决于 2012-08-15 12:11
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;
using System.IO.Ports;

namespace _2
{
    public partial class Form1 : Form
    {
         SerialPort spReceive = new SerialPort ();
        
        delegate void UpdateTextEventHandler(string text);
        UpdateTextEventHandler updateText;
        public Form1()
        {
            InitializeComponent();
            updateText = new UpdateTextEventHandler(UpdateTextBox);
           
            
            spReceive.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(spReceive_DataReceived );  
         }

             private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            spReceive.PortName  = "COM1";
            spReceive.BaudRate = 2400;
            spReceive.DataBits = 8;
            spReceive.StopBits = StopBits .One ;
            spReceive.Parity = Parity .Even ;
            spReceive.Open();
            spReceive.Write("FE FE FE 68 AA AA AA AA AA AA 68 13 00");
            string data = spReceive.ReadExisting();
            textBox1.Text =data ;
            spReceive.Close();
        }
        public void  spReceive_DataReceived(object sender,System .IO .Ports .SerialDataReceivedEventArgs e)
       {
          byte[]readBuffer = new byte[spReceive .ReadBufferSize];
          spReceive.Read(readBuffer,0,readBuffer.Length);
          this.Invoke(updateText ,new string []{Encoding .Unicode .GetString (readBuffer )});
          string readString = spReceive.ReadExisting();
          this.Invoke(updateText ,new string []{readString });
       }

        private void  UpdateTextBox(string text)
        {
            textBox1.Text =text; 
        }
    }
}
C#
问题补充:

为什么接收不到数据.哪位高人帮看看上面代码有什么问题啊.向串口发送一串16进制数字,然后接收串口返回的数据.

一坨黄色的主页 一坨黄色 | 初学一级 | 园豆:13
提问于:2012-05-14 20:01
< >
分享
最佳答案
0

你串口设置的和硬件的一致不?先用串口调试软件发帧看看能不能正常接收。

奖励园豆:5
wvsy | 菜鸟二级 |园豆:297 | 2012-05-17 09:09
其他回答(2)
0

一段代码什么意思?没有问题???

KimhillZhang | 园豆:209 (菜鸟二级) | 2012-05-14 20:51
0

先定义一个串口类,往串口中写数据,然后发送命令,当接收到数据时,就将收到的数据字节对应的Unicode码数据显示在textBox1文本框中

Samguist | 园豆:157 (初学一级) | 2012-05-15 08:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册