(c#2.0)serialPort串口通讯

本文介绍了一个使用C#实现的串口通信程序,该程序能够读取串口数据并与数据库进行交互。程序通过串口接收数据包,并解析数据包中的信息来获取数量等参数,然后将这些参数写入数据库中。
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/

Option Explicit '------------------------------------------------------------------------------- ' ' This VB module is a collection of routines to perform serial port I/O without ' using the Microsoft Comm Control component. This module uses the Windows API ' to perform the overlapped I/O operations necessary for serial communications. ' ' The routine can handle up to 4 serial ports which are identified with a ' Port ID. ' ' All routines (with the exception of CommRead and CommWrite) return an error ' code or 0 if no error occurs. The routine CommGetError can be used to get ' the complete error message. '------------------------------------------------------------------------------- '------------------------------------------------------------------------------- ' Public Constants '------------------------------------------------------------------------------- ' Output Control Lines (CommSetLine) Const LINE_BREAK = 1 Const LINE_DTR = 2 Const LINE_RTS = 3 ' Input Control Lines (CommGetLine) Const LINE_CTS = &H10& Const LINE_DSR = &H20& Const LINE_RING = &H40& Const LINE_RLSD = &H80& Const LINE_CD = &H80& '------------------------------------------------------------------------------- ' System Constants '------------------------------------------------------------------------------- Private Const ERROR_IO_INCOMPLETE = 996& Private Const ERROR_IO_PENDING = 997 Private Const GENERIC_READ = &H80000000 Private Const GENERIC_WRITE = &H40000000 Private Const FILE_ATTRIBUTE_NORMAL = &H80 Private Const FILE_FLAG_OVERLAPPED = &H40000000 Private Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000 Private Const OPEN_EXISTING = 3 ' COMM Functions Private Const MS_CTS_ON = &H10& Private Const MS_DSR_ON = &H20& Private Const MS_RING_ON = &H40& Private Const MS_RLSD_ON = &H80& Private Const PURGE_RXABORT = &H2 Private Const PURGE_RXCLEAR = &H8 Private Const PURGE_TXABORT = &H1 Private Const PURGE_TXCLEAR = &H4 ' COMM Escape Functions Private Const CLRBREAK = 9 Private Const CLRDTR
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值