none
c#串口问题 RRS feed

  • 问题

  • 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.Ports;
    
    
    
    
    
    
    
    
    
    namespace 串口试验3
    
    {
    
     public partial class Form1 : Form
    
     {
    
     
    
     // SerialPort sp = new SerialPort("com4", 9600, Parity.None, 8, StopBits.One);
    
     private void Form1_Load(object sender, EventArgs e)
    
     {
    
    
    
     }
    
    
    
     public Form1()
    
     {
    
      InitializeComponent();  
    
     }
    
    
    
     private void button1_Click(object sender, EventArgs e)
    
     {
    
      
    
      SerialPort serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    
      serialPort.Open();
    
     }
    
    
    
    
    
    
    
    
    
     //string serialReadString;
    
     int s;
    
     private void serialPort_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    
     {
    
      //serialReadString = sp.ReadExisting();
    
    
    
      s = serialPort.ReadByte();
    
      this.richTextBox1.Invoke
    
      (
    
      new MethodInvoker
    
       (
    
       
    
       delegate
    
       {
    
    
    
        //this.richTextBox1.AppendText(serialReadString);
    
    
    
    
    
    
    
        int flag = 0;
    
        if (s == 0x01)
    
        {
    
        flag = 1;
    
        }
    
        else if (s == 0x02)
    
        {
    
        flag = 2;
    
        }
    
        else if (s == 0x03)
    
        {
    
        flag = 3;
    
        }
    
        else if (s == 0x04)
    
        {
    
        flag = 4;
    
        }
    
        else if (s == 0x05)
    
        {
    
        flag = 5;
    
        }
    
        switch (flag)
    
        {
    
        case 1:
    
         richTextBox1.Text = "桥梁";
    
         break;
    
        case 2:
    
         richTextBox1.Text = "车站";
    
         break;
    
        case 3:
    
         richTextBox1.Text = "隧道";
    
         break;
    
        case 4:
    
         richTextBox1.Text = "临时限速";
    
         break;
    
        case 5:
    
         richTextBox1.Text = "过分相";
    
         break;
    
        }
    
       }
    
    
    
       )
    
    
    
      );
    
      
    
     }
    
    
    
     
    
    
    
     
    
     
    
    
    
     }
    
    }
    
    
    
    
    我想读串口的数据,很据数据的不同在窗体的文本框上显示相应的文字,例如读到01,显示桥梁;读到02显示隧道;独到03显示车站;独到04显示临时限速,读到05显示过分相,可是代码没反应,哪位老师看看我哪里出错了,不胜感激!
    2011年5月15日 13:10

全部回复