SerialPort应该已经封装了串口的操作,可以有相关的默认值处理,你可以看看其属性是否可以设置
建议首先查阅相关串口的通讯原理,其实串口相当简单,自己可以使用API写一个,网上相关的例子源码很多.

解决方案 »

  1.   

    使用控件SerialPort接收数据,定义端口号和波特率serialPort1.PortName = Convert.ToString(Registry.GetValue(RegPath, "PCOM", "COM5"));
    serialPort1.BaudRate = Convert.ToInt32(Registry.GetValue(RegPath, "PBaudRate", "9600"));//打开串口
    serialPort1.Open(); private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                //定义变量
                byte[] BufferBytes;
                string[] Data;            int Count;
                Count = serialPort1.BytesToRead;            //得到数据
                BufferBytes = new Byte[Count];
                serialPort1.Read(BufferBytes, 0, Count);            for (int i = 0; i < Count; i++)
                {
                    ReceivedString = ReceivedString + BufferBytes[i] + " ";
                }
            }差不多就是这样的,我只做过接收串口的数据,发送还没做过。不过这个应该先问问你们公司的硬件工程师比较好!
      

  2.   

    接上.其实发送的话,了解了DataReceived事件就知道了.具体用法看MSDN咯!
      

  3.   

    MS对串口的封装已经做得很好了,你肯定没看MSDN,里面有一堆例子。对于你提出的问题,答复如下:
    1、SerialPort 有好几个构造函数,你给出的例子中只是用了默认的无参构造函数来实例化对象,你在实例化后可以自己给他设置波特率、停止位、数据位和校验,然后OPEN就可以打开串口,如下例:
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);    // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();    // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);    // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;    _serialPort.Open();
        _continue = true;
        readThread.Start();    Console.Write("Name: ");
        name = Console.ReadLine();    Console.WriteLine("Type QUIT to exit");    while (_continue)
        {
            message = Console.ReadLine();        if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message) );
            }
        }    readThread.Join();
        _serialPort.Close();
    }public static void Read()
    {
        while (_continue)
        {
            try
            {
                string message = _serialPort.ReadLine();
                Console.WriteLine(message);
            }
            catch (TimeoutException) { }
        }
    }
        当然你也可以使用其他几个带参的构造函数,如:
     名称 说明 
       SerialPort()()()  初始化 SerialPort 类的新实例。 
       SerialPort(IContainer)  使用指定的 IContainer 对象初始化 SerialPort 类的新实例。 
       SerialPort(String)  使用指定的端口名称初始化 SerialPort 类的新实例。 
       SerialPort(String, Int32)  使用指定的端口名称和波特率初始化 SerialPort 类的新实例。 
       SerialPort(String, Int32, Parity)  使用指定的端口名称、波特率和奇偶校验位初始化 SerialPort 类的新实例。 
       SerialPort(String, Int32, Parity, Int32)  使用指定的端口名称、波特率、校验位和数据位初始化 SerialPort 类的新实例。 
       SerialPort(String, Int32, Parity, Int32, StopBits)  使用指定的端口名称、波特率、奇偶校验位、数据位和停止位初始化 SerialPort 类的新实例。 
    2、至于串口的处理流程,你可能在脑海中把问题放大了,我想你一定认为自己需要知道串口的硬件工作流程才能使用好串口吧,其实不然。
    MS吧串口抽象的很好,你完全可以把它当成 Socket 理解,用的时候,也已套用文件操作的那种模式,只是类名、方法名有点不同。
    所以,你可以简单的把流程归为:new-->open-->write-->open-->close,和文件、socket操作差不多,毕竟串口操作也是IO操作的一种。OK,我想这样你应该能够解决问题了,若你一定要在知道串口的硬件工作原理,那就按照2楼的兄弟的建议,找公司的硬件工程师,让他给你讲讲,当然,网络上也有很多资料可以参考,我虽然也知道,但懒得打字,而且这对你现在使用串口 不重要。
      

  4.   

    嗯,兩個com的發送接收沒做過,看看。
      

  5.   

    SerialPort类没用过,我的串口通讯程序都是用非托管方法实现。个人感觉应该差不多 ,关键是设置好串口号和波特率
      

  6.   

    定义两个serialport,port1,port2分别用来对COM1,COM2两个串口进行操作。
      

  7.   

    string message = _serialPort.ReadLine();也不报错。界面出现假死。。
    我的这句出错。怎么回事?谢谢各位帮帮忙。。
      

  8.   

    似乎大家用C#来编串口API得好少啊
      

  9.   

    知道为什么会有C#吗?
    C#作为.NET的主导语言,其目的就是让开发者无须了解底层的API函数.
    所以有的人说只会C#的程序员不能算真正意义上的程序员.
      

  10.   

    ReadLine是同步读取数据的只要是同步读取数据都会造成线程阻塞
    不过用DataReceived就是异步读取了,就是托管这种方法的异步读取就可以了
      

  11.   

    我在csdn上发表c#做的串口通讯的例子:
    http://d.download.csdn.net/down/275495/txf123
    收发都有,你可以拿去看看。
      

  12.   

    使用控件SerialPort可以从串口接收文件和发送文件吗?
    可以的话应该怎么写啊?
      

  13.   

    在WinCE6上,用SerialPort控件做的串口一直在SerialPort.Open()出异常,而在WinForm下却没问题,不知是什么回事?
      

  14.   

    可能WinCE上没这个端口或端口号不一样
      

  15.   


    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Threading;
    namespace BusApp
    {
     /// <summary>
     /// Form1 的摘要说明。
     /// </summary>
     public class Form1 : System.Windows.Forms.Form
     {
      private System.Windows.Forms.Label label1;
      private System.Windows.Forms.Label label2;
      private System.Windows.Forms.Button button1;
      private System.Windows.Forms.GroupBox groupBox1;
      private System.Windows.Forms.Label label3;
      private System.Windows.Forms.Label label4;
      private System.Windows.Forms.Label label5;
      private System.Windows.Forms.Label label6;
      private System.Windows.Forms.Button button2;
      private System.Windows.Forms.Button button3;
      private System.Windows.Forms.Button button4;
      private System.Windows.Forms.TextBox textBox8;
      private System.Windows.Forms.Label label7;  public int iPort=1; //1,2,3,4
      public int iRate=9600; //1200,2400,4800,9600
      public byte bSize=8; //8 bits
      public byte bParity=0; // 0-4=no,odd,even,,space 
      public byte bStopBits=1; // 0,1,2 = 1, 1.5, 2 
      public int iTimeout=1000;
      public mycom mycom1=new mycom();
      public byte[] recb;  private System.Windows.Forms.TextBox msg;
      private System.Windows.Forms.TextBox t_port;
      private System.Windows.Forms.TextBox t_rate;
      private System.Windows.Forms.TextBox t_bytesize;
      private System.Windows.Forms.TextBox t_stopbyte;
      private System.Windows.Forms.TextBox t_parity;
      private System.Windows.Forms.TextBox t_send;
      private System.Windows.Forms.Button button5; //readTimeOut
      /// <summary>
      /// 必需的设计器变量。
      /// </summary>
      private System.ComponentModel.Container components = null;  public Form1()
      {
       InitializeComponent();
      }  /// <summary>
      /// 清理所有正在使用的资源。
      /// </summary>
      protected override void Dispose( bool disposing )
      {
       if( disposing )
       {
        if (components != null) 
        {
         components.Dispose();
        }
       }
       base.Dispose( disposing );
      }
     /// <summary>
      /// 应用程序的主入口点。
      /// </summary>
      [STAThread]
      static void Main() 
      {
       Application.Run(new Form1());
      }
    //程序开启,串口初始化
      private void Form1_Load(object sender, System.EventArgs e)
      {
       mycom1.PortNum=iPort;
       mycom1.BaudRate=iRate;
       mycom1.ByteSize=bSize;
       mycom1.Parity=bParity;
       mycom1.StopBits=bStopBits;
       mycom1.ReadTimeout=iTimeout;
       if(this.OpenCom())
        msg.AppendText("串口初始化成功……\r\n");
       else
        msg.AppendText("串口初始化失败!\r\n");
      }
    //显示包信息
      public string dis_package(byte[] reb)
      {
       string temp="";
       foreach(byte b in reb)
        temp+=b.ToString("X2")+" ";
       return temp;
      }
    //开串口
      public bool OpenCom()
      {
       try
       {
         if (mycom1.Opened)
         {
          mycom1.Close();
          mycom1.Open(); //打开串口
         }
         else
         {
          mycom1.Open();//打开串口
         }
         return true;
       }
       catch(Exception e) 
       {
         MessageBox.Show("错误:" + e.Message);
         return false;
       }   }
    //发送按钮
      private void button1_Click(object sender, System.EventArgs e)
      {
       if(t_send.Text=="")
       {MessageBox.Show("发送数据为空!");return;}
       byte[] temp1=mysendb();
       int sendnumb=0;
       try
       {
        sendnumb=mycom1.Write(temp1);
         msg.AppendText("\r\n发送数据("+sendnumb+"):"+dis_package(temp1));
        recb=mycom1.Read(50);
        //if(recb.Length!=0)
         msg.AppendText("\r\n接收到数据包:"+dis_package(recb));
       }
       catch
       {msg.AppendText("\r\n发送失败!");return;}
       
       //OpenCom();
      }
    //去掉发送数组中的空格
      public string delspace(string putin)
      {
       string putout="";
       for(int i=0;i<putin.Length;i++)
       {
        if(putin[i]!=' ')
         putout+=putin[i];
       }
       return putout;
      }
    //提取数据包
      public byte[] mysendb()
      {
       string temps=delspace(t_send.Text);
       byte[] tempb=new byte[50];
       int j=0;
       for(int i=0;i<temps.Length;i=i+2,j++)
        tempb[j]=Convert.ToByte(temps.Substring(i,2),16);
       byte[] send=new byte[j];
       Array.Copy(tempb,send,j);
       return send;
      }
    //清空按钮
      private void button3_Click(object sender, System.EventArgs e)
      {
       t_send.Text=string.Empty;
       msg.Text=string.Empty;
      }//参数设置
      private void button2_Click(object sender, System.EventArgs e)
      {
        mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4
       mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600
       mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits
       mycom1.Parity=Convert.ToByte(t_parity.Text,10); // 0-4=no,odd,even,,space
       mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10); // 0,1,2 = 1, 1.5, 2 
       //iTimeout=3;
       if(this.OpenCom())
        msg.AppendText("串口初始化成功……\r\n");
       else
        msg.AppendText("串口初始化失败!\r\n");
      }
    //程序关闭,结束串口
      private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
      {
       mycom1.Close();
      }  private void button5_Click(object sender, System.EventArgs e)
      {
       if(mycom1.Opened)
       {
        mycom1.Close();
        button5.Text="开启串口";
        msg.AppendText("\r\n串口被关闭……");
       }
       else
       {
        mycom1.Open();
        button5.Text="关闭串口";
        msg.AppendText("\r\n串口成功开启……");
       }
      }
     }
    }
      

  16.   

    刚弄了一个串口通信的Demo,如果你还需要,留下邮箱吧。
      

  17.   

    我需要demo 。串口的。
    [email protected] 谢谢