(c#2.0)serialPort串口通訊

來源:互聯網
上載者:User

標籤:datagridview   style   blog   http   java   color   

原文:(c#2.0)serialPort串口通訊

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.SqlClient;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Configuration;using System.IO;using System.IO.Ports;namespace WindowsApplication2{     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }         int iCount;         int numbers;         byte rlenth;         bool bRLenth;         int bRStart;         bool bRParam;         byte Rchk;         int LParam;         byte[] RParam;         bool brcmd;         byte RCmd;         bool bRchk;         bool bfinish;         private void Form1_Load(object sender, EventArgs e)         {                         //Form1 Form1 = new Form1();             try             {             if (this.serialPort1.IsOpen)             {                 serialPort1.Close();             }             else             {                 serialPort1.PortName = "COM1"; //選擇串口COM1                 serialPort1.BaudRate = 9600;    //設定通訊口參數                 serialPort1.DataBits = 8;       //資料位元                  serialPort1.Parity = System.IO.Ports.Parity.None;//校正位 無校正                 serialPort1.StopBits = System.IO.Ports.StopBits.One;//停止位1位                 serialPort1.ReadBufferSize = 1024;                  //接收緩衝區大小                 serialPort1.WriteBufferSize = 1024;                 //發送緩衝區大小                 serialPort1.Open();                 serialPort1.ReadExisting();                         //設定Input從接收緩衝讀取全部資料                 serialPort1.ReceivedBytesThreshold = 1;             //設定引發OnComm事件的位元組長度                 serialPort1.DiscardInBuffer() ;                     //清除接收緩衝區                 serialPort1.DiscardOutBuffer() ;                    //清除發送緩衝區             }                             string connstr = System.Configuration.ConfigurationManager.AppSettings["myConnectionString"];                 SqlConnection conn = new SqlConnection(connstr);                 conn.Open();                 string sql = "select   name   as 時間,price,card from test01";                 SqlDataAdapter da = new SqlDataAdapter(sql, conn);                 DataSet ds = new DataSet();                 da.Fill(ds, "baomin");                 ultraChart1.DataSource = ds.Tables[0].DefaultView;                 dataGridView1.DataSource = ds.Tables[0].DefaultView;                 ultraChart1.Axis.Y.LogBase = 1000;                 ultraChart1.Axis.Y.RangeMax = 30000;                 ultraChart1.Axis.Y.RangeMin = 0;                 Application.EnableVisualStyles();                 Application.DoEvents();             }             catch (Exception ex)             {                 MessageBox.Show("dd",ex.Message,MessageBoxButtons.OK,MessageBoxIcon.Error);             }             //ultraChart1.         }         /// <summary>         /// 取前後儲存空間兩個值對比,應付電腦異常退出         /// </summary>         /// <param name="sender">XOR異域校正</param>         /// <param name="e"></param>         private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)         {                             try             {                 //Byte[] dataread = new Byte[8] ;                                 //serialPort1.Read(dataread, 0, dataread.Length);                 //int productline=dataread[0]; //介面號                 //iCount=dataread[5];                 string connstr = System.Configuration.ConfigurationManager.AppSettings["myConnectionString"];                 SqlConnection conn = new SqlConnection(connstr);                 conn.Open();                 //if (dataread[0] == 0xAA)                 //{                 //    // MessageBox.Show(productline.ToString(), "ddd", MessageBoxButtons.OK, MessageBoxIcon.Error);                 //     numbers = 0;                 //     numbers = Convert.ToInt32(dataread[4]) * 256 ^ 1 + Convert.ToInt32(dataread[5]);                  //     numbers = Convert.ToInt32(dataread[4]) * Convert.ToInt32(System.Math.Pow(256, 1)) + Convert.ToInt32(dataread[5]);                 //     SqlCommand cmd = new SqlCommand("SP_SC_IN_AUTONUMBER", conn);                 //     cmd.CommandType = CommandType.StoredProcedure;                 //     cmd.Parameters.Add("@quantity", SqlDbType.Int);                 //     cmd.Parameters["@quantity"].Value = numbers;                 //     cmd.Parameters.Add("@ports", SqlDbType.Int);                 //     cmd.Parameters["@ports"].Value = dataread[3];                 //     cmd.ExecuteNonQuery();                 //}                 byte[] DataRead;                 int bytData ;                 int bytnum;                 //bytnum = serialPort1.ReadByte; ;                                                 // TODO: NotImplemented statement: ICSharpCode.SharpRefactory.Parser.AST.VB.OnErrorStatement                 if (serialPort1.ReceivedBytesThreshold == serialPort1.ReceivedBytesThreshold)                 {                     bytnum = serialPort1.BytesToRead;                     DataRead = new byte[bytnum];                     // TODO: NotImplemented statement: ICSharpCode.SharpRefactory.Parser.AST.VB.ReDimStatement                     for (int k = 0; k <= (bytnum - 1); k++)                     {                         bytData= serialPort1.ReadByte();                         DataRead[k] =(byte) bytData;                         bfinish = RFJ(DataRead[k]);                         if (bfinish)                         {                             //System.Convert.ToInt32(RCmd)為連接埠號碼                             iCount = 0;                             for (int j = 0; j <= 1; j++)                             {                                 iCount += System.Convert.ToInt32(RParam[j]) * Convert.ToInt32(Math.Pow(256, j));                             }                             SqlCommand cmd = new SqlCommand("SP_SC_IN_AUTONUMBER", conn);                             cmd.CommandType = CommandType.StoredProcedure;                             cmd.Parameters.Add("@quantity", SqlDbType.Int);                             cmd.Parameters["@quantity"].Value = iCount;                             cmd.Parameters.Add("@ports", SqlDbType.Int);                             cmd.Parameters["@ports"].Value = System.Convert.ToInt32(RCmd);                             cmd.ExecuteNonQuery();                         }                     }                 }                                               }             catch (IOException ex)                   {                 throw (ex);             }         }         private void timer1_Tick(object sender, EventArgs e)         {             //this.Opacity -= -0.1;             //if (this.Opacity==0)             //{             //     timer1.Enabled = false;             //     this.Close();             //}         }         private void Form1_FormClosing(object sender, FormClosingEventArgs e)         {             Win32.AnimateWindow(this.Handle, 2500, Win32.AW_SLIDE | Win32.AW_HIDE | Win32.AW_BLEND);              // e.Cancel = true;             //timer1.Enabled = true;         }         private void Btn_OK_Click(object sender, EventArgs e)         {             popupNotifier1.Popup();         }         private bool RFJ(byte Data)         {             bool result=false;             if (bRStart == 0)             {                 if (Data == 0xAA)                 {                     bRStart = 1;                 }             }             else if   (bRStart == 1)             {                 if (Data == 0x55)                 {                     bRStart = 2;                 }                 else if (Data == 0xAA)                 {                     bRStart = 1;                 }                 else                 {                     bRStart = 0;                 }             }             else if (bRLenth == false)             {                 if (Data < 20)                 {                     bRLenth = true;                      rlenth = Data;                      Rchk = Data;                      LParam = (int)(rlenth) - 3;                     RParam = new byte[2];                 }                 else                 {                     bRStart = 0;                 }             }             else if (brcmd == false)              {                 brcmd = true;                 RCmd = Data;                 Rchk = (byte)(Rchk ^ Data);              }              else if (bRParam == false)             {                 if (LParam >= 0)                 {                     RParam[LParam] = Data;                     Rchk = (byte)(Rchk ^ Data);                     LParam = LParam - 1;                 }                 if (LParam < 0)                 {                     bRParam = true;                 }                             }             else if (bRchk == false)             {                 if (Rchk == Data)                 {                     result = true;                 }                 else                 {                     bRStart = 0;                     bRLenth = false;                     brcmd = false;                     bRParam = false;                 }             }             return result;         }     }}

其它相關:
      
轉自:http://www.cnblogs.com/jyshi/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.