(c#2.0)serialPort串口通讯

时间:2022-05-22 20:32:35

原文:(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/