当前位置:编程学习 > C#/ASP.NET >>

WINCE下 C# 串口编程问题

先上原码:
using System;

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

namespace USART
{
    public partial class uartForm : Form
    {
        private SerialPort com = new SerialPort();

        private long receive_count = 0;//接收计数
        private long send_count = 0; //发送计数
        StringBuilder builder = new StringBuilder();

        public uartForm()
        {
            InitializeComponent();
        }
        //十六进制转换字节数组
        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        //窗体初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = SerialPort.GetPortNames();
            Array.Sort(ports);
            foreach (string port in ports)
                comboPortBox.Items.Add(port);
            comboPortBox.SelectedIndex = comboPortBox.Items.Count > 0 ? 0 : -1;
            comboBuadBox.SelectedIndex = comboBuadBox.Items.IndexOf("9600");
            //初始化SerialPort对象
            com.NewLine = "/r/n";
            com.RtsEnable = false;
            //添加事件注册
            com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);


        }
        //事件处理函数
        void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //   throw new NotImplementedException();

            int n = com.BytesToRead;
            byte[] buf = new byte[n];
            receive_count = receive_count + n;
            com.Read(buf, 0, n); //从 SerialPort 输入缓冲区读取一些字节并将那些字节写入字节数组中指定的偏移量处
            this.Invoke((EventHandler)(delegate
            {
                //判断是否显示为16进制
                if (checkHexBox.Checked)
                {
                    //依次转换为16进制字符串
                    foreach (byte b in buf)
                        builder.Append(b.ToString("X2") + " ");
                }
                else
                {
                    //直接按ASCII规则转换成字符串
                    builder.Append((Encoding.ASCII.GetString(buf, 0, n)));
                }
                //追加的形式添加到文本框末端,并滚动到最后
                this.textReceiveBox.Text = builder.ToString();
                //修改接收计数器
                labelReceiveCount.Text = "Get:" + receive_count.ToString();
                //将光标移动到文本最后
                this.textReceiveBox.Select(textReceiveBox.Text.Length, 0);
                //滚动到光标处
                this.textReceiveBox.ScrollToCaret();

            }));

        }

        private void buttonOpenClose_Click(object sender, EventArgs e)
        {
            //获取当前串口状态来判断操作
            if (com.IsOpen)
            {
                //如果是打开状态则关闭串口
                com.Close();
            }
            else
            {
                //如果是关闭状态则设置并打开串口
                com.PortName = comboPortBox.Text;
                com.BaudRate = int.Parse(comboBuadBox.Text);
                try
                {
                    com.Open();
                }
                catch (System.Exception ex)
                {   //捕获到一场信息,创建一个新的com对象之前的不能用
                    com = new SerialPort();
                    //输出异常消息
                    MessageBox.Show(ex.Message);

                }
            }
            //设置按钮的状态
            buttonOpenClose.Text = com.IsOpen ? "Close" : "Open";
            buttonSend.Enabled = com.IsOpen;
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            if (!com.IsOpen)
            {
                MessageBox.Show("请先打开串口");
            }
            else
            {
                //定义一个变量记录发送字节数
                int n = 0;
                if (checkHexBox.Checked)
                {
                    
                    textSendBox.Text=textSendBox.Text.Replace(" ","");

                    //if (textSendBox.Text.Length % 2 != 0)
                    //{
                    //    textSendBox.Text+= " ";
                    //}
                    byte[] data = new byte[textSendBox.Text.Length / 2];
                    //for (int i = 0; i <data.Length;i++ )
                    //{
                    //    data[i] = Convert.ToByte(textSendBox.Text.Substring(i * 2, 2), 16);
                    //}
                    data = Encoding.ASCII.GetBytes(textSendBox.Text);
                    com.Write(data, 0,data.Length);
                }
                else
                {
                    //ASICC码直接发送
                    com.Write(textSendBox.Text);
                }

                n = textSendBox.Text.Length;

                send_count = send_count + n;
                labelSendCount.Text = "Send:" + send_count.ToString();

            }

        }

        private void buttonResetCount_Click(object sender, EventArgs e)
        {
            //按下复位键清零计数器
            send_count = receive_count = 0;
            labelReceiveCount.Text = "Receive:0";
            labelSendCount.Text = "Send:0";
        }

    }
}



以上程序一个串口自己收发没问题(就是232的2和3引脚相连),但是和PC的串口通信时,只能接受一次数据,必须先发送给pc机一次数据才能接收由PC机发过来的数据。不知道问题在哪里。
新手请指教!!



补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,