基本信息
源码名称:C#接收串口超声波传感器数据
源码大小:0.29M
文件格式:.rar
开发语言:C#
更新时间:2019-01-20
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍

设定连续读取时间后,从COM口获取超声波传感器传来的数据,并把数据写入文本文件,以便3后续分析使用

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;  
 using System.Threading;
using System.IO;
namespace CommTest2
{
    
    public partial class Form1 : Form
    {
    SerialPort MSComm1 = new SerialPort();
    string GetTxt = "";
    Int32  rTextNum   = 0;
    Int32 SendCount = 0;
    Int32 GetCount  = 0;
    Int32 ErrCount  = 0;
    Int32 SendLen  = 0;
    Int32 SendTime  = 0;
    Int32 Allsum = 0;
    Int32 CloseCount = 0;
    Byte[] arr_command = new Byte[0];
    Queue<byte>  QU  = new Queue<byte>(480);
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            MSComm1.ReadTimeout = 32;
            timer_send.Enabled = false;
            SendLen = Convert.ToInt32(TextBox3.Text);
            int i = 0;
            foreach (string port in ports)
            {
                ComboBox1.Items.Add(port);
                i  ;
            }
            if (i > 0)
            {
                ComboBox1.SelectedIndex = 0;
                if (MSComm1.IsOpen)
                {
                    MSComm1.Close();
                }
            }
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            if (RadioButton3.Checked)
            {
                open_232();
                GetTxt = "";
                timer2.Enabled = true;
                发送一组数();
            }
            else
            {
                open_232();
                发送一组数();
            }

           


        }
         private void open_232()
         {
             if (this.Button4.Text == "打开串口")
             {
                 try
                 {
                     SendLen = Convert.ToInt32(TextBox3.Text);
                   
                     SendTime = Convert.ToInt32(TextBox1.Text);
                     if (SendLen > 254) SendLen = 2;
                     if (SendTime <= 1) SendTime = 1;
                     Allsum = 0;
                     Array.Resize(ref arr_command, 1);
                    
                     arr_command[0] = (byte)(85);
                     
                     timer_send.Interval = SendTime;
                     timer_send.Enabled = true;
                     MSComm1.ReadTimeout = 200;
                     //MSComm1.DiscardOutBuffer();
                     MSComm1.PortName = ComboBox1.Text;
                     MSComm1.BaudRate = Convert.ToInt32(ComboBox2.Text);
                     MSComm1.Parity = Parity.None;
                     MSComm1.StopBits = StopBits.One;
                     this.MSComm1.DataReceived  = new System.IO.Ports.SerialDataReceivedEventHandler(this.MSComm1_DataReceived);
                     MSComm1.Open();
                     this.Button4.Text = "关闭串口";
                 }
                 catch
                 {
                     MessageBox.Show("串口操作失败");
                 }
             }
             else 
             {
                 try
                 {
                     MSComm1.Close();
                     this.Button4.Text = "打开串口";
                     timer_send.Enabled = false;
                 }
                 catch
                 {
                     MessageBox.Show("串口操作失败");
                 }
             }
         }



         private void MSComm1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
         {
             try
             {
                 if (this.RadioButton2.Checked || RadioButton3.Checked)
                 {
                     int outLen = MSComm1.BytesToRead;
                     byte[] AA = new byte[outLen];
                    
                     MSComm1.Read(AA, 0, outLen);
                     for (int i = 0; i < outLen; i  )
                     {
                         QU.Enqueue(AA[i]);
                     }
                 }
             }
             catch 
             {
                 
                 throw;
             }

             
         }



         private void 发送一组数()
         {
             try
             {
                 if (MSComm1.IsOpen)
                 {
                     MSComm1.Write(arr_command, 0, 1);
                     //String str_in = "";
                     //for (int i = 0; i < SendLen; i  )
                     //{
                     //    str_in  = (arr_command[i].ToString("X2").PadLeft(2, '0').PadRight(3, ' '));
                     //}
                     //RichTextBox1.Text = "发送:"   str_in   "\r\n"   RichTextBox1.Text;
                 }
                 else
                 {
                    // RichTextBox1.Text = "请打开串口先!"   "\r\n"   RichTextBox1.Text;
                 }
             }
             catch
             {
             }
         }

         private void timer1_Tick(object sender, EventArgs e)
         {
             try
             {
                 if (QU.Count >= SendLen)
                 {
                     byte upData = 0;
                     string tempStr = "";
                     bool IsErr = false;
                     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                     byte[] byteArray = new byte[2];
                     byte tempB = QU.Dequeue();
                      byteArray[0] =  tempB ;
                      tempB = QU.Dequeue();
                      byteArray[1] = tempB;
 
                     for (int i = 0; i < 2; i  )
                     {
                         tempStr  = (byteArray[i].ToString("X2").PadLeft(2, '0').PadRight(3, ' '));
                     }
                     发送一组数();

                     GetTxt  = tempStr   "\r\n";
                     RichTextBox1.Text = tempStr   "\r\n"   RichTextBox1.Text;
                     rTextNum = rTextNum   1;
                     if (rTextNum > 100)
                     {
                         RichTextBox1.Text = "";
                         rTextNum = 0;
                     }



               
                     if (IsErr)
                     {
                         ErrCount  ;
                         ToolLabel4.Text = "误码次数:"   ErrCount.ToString()   "次";
                         WriteError(tempStr);
                     }
                     GetCount  = SendLen;
                     ToolLabel3.Text = "接收字节:"   GetCount.ToString()   "Byte";
                     
                   
                     rTextNum = rTextNum   1;
                     if (rTextNum > 200)
                     {
                         RichTextBox1.Text = "";
                         rTextNum = 0;
                     }
                 }
             }
             catch 
             {
             }
         }
         /// <summary>
         /// 写入错误日志
         /// </summary>
         /// <param name="txt"></param>
         public static void WriteError(string txt)
         {
             try
             {
                 string datatxt = DateTime.Now.Year.ToString()   "-"   DateTime.Now.Month.ToString()   "-"   DateTime.Now.Day.ToString();
                 StreamWriter sw;
                 if (File.Exists("LOG/"   datatxt   ".txt") == true)
                 {
                     sw = File.AppendText("LOG/"   datatxt   ".txt");
                 }
                 else
                 {
                     sw = File.CreateText("LOG/"   datatxt   ".txt");
                 }
                 sw.WriteLine(DateTime.Now   "     "   txt);
                 sw.Close();
                 sw.Dispose();
             }
             catch { }
         }
       
         public static void WriteTxt(string txt)
         {
             try
             {
                 string datatxt = DateTime.Now.Month.ToString()   "_"   DateTime.Now.Day.ToString()   DateTime.Now.Hour.ToString()   DateTime.Now.Minute.ToString()   DateTime.Now.Second.ToString();
                 StreamWriter sw;
                 if (File.Exists("LOG/"   datatxt   ".txt") == true)
                 {
                     sw = File.AppendText("LOG/"   datatxt   ".txt");
                 }
                 else
                 {
                     sw = File.CreateText("LOG/"   datatxt   ".txt");
                 }
                 sw.WriteLine(txt);
                 sw.Close();
                 sw.Dispose();
             }
             catch { }
         }

         private void Button1_Click(object sender, EventArgs e)
         {
             GetCount = 0;
             SendCount = 0;
             ErrCount = 0;
             QU.Clear();
             ToolLabel3.Text = "接收次数:"   GetCount.ToString()   "次";
             ToolLabel4.Text = "误码次数:"   ErrCount.ToString()   "次";
             ToolLabel2.Text = "发送次数:"   SendCount.ToString()   "次";
         }

         private void Tim_232_sta_Tick(object sender, EventArgs e)
         {
             if (MSComm1.IsOpen)
             {
                 ToolLabel1.Text = "串口状态:开";
             }
             else
             {
                 ToolLabel1.Text = "串口状态:关";
             }
         }

         private void timer_send_Tick(object sender, EventArgs e)
         {
             try
             {
                 if (this.RadioButton1.Checked )
                 {
                    // 发送一组数();
                     rTextNum = rTextNum   1;
                     SendCount = SendCount   1;
                     ToolLabel2.Text = "发送次数:"   SendCount.ToString()   "次";
                     if (rTextNum > 200)
                     {
                         RichTextBox1.Text = "";
                         rTextNum = 0;
                     }
                 }
             }
             catch 
             {
                
             }
         }

         private void timer2_Tick(object sender, EventArgs e)
         {
             CloseCount  ;
             Int32 MaxCount = Convert.ToInt32(textBox2.Text) ;
             if (CloseCount > MaxCount)
             {
                 CloseCount = 0;
                 MSComm1.Close();
                 this.Button4.Text = "打开串口";
                 timer_send.Enabled = false;
                 timer2.Enabled = false;
                 WriteTxt(GetTxt);
                 GetTxt = "";
             }
         }
    }
}