实例介绍
【实例简介】
RFID236028-使用其串口命令实现的控制。
代码还在测试,没有整理好,不够简洁,大家可以稍微看一下,给点建议。哈哈
【实例截图】
【核心代码】
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
{
public partial class Form1 : Form
{
bool btn = false;
int received_count = 0;//Convert.ToInt32(ContentValue(strSec, "SendCount"));//接收计数
int send_count = 0;//Convert.ToInt32(ContentValue(strSec, "ReceCount"));//发送计数
bool send_hex = false; //发送标志位
/****************************************************/
int len = 2;//命令数据
private string str = " ";//命令数据
private byte Cmd = 0xff; //命令代码
private byte fComAdr = 0xff; //当前操作的ComAdr
private byte[] Get = new byte[50];//响应数据块
private byte Result = 0xff; //命令执行结果状态值
private double fdminfre;//Bit7-Bit6 用于频段设置用;Bit5-Bit0 表示当前读写器工作 的最小频率
private double fdmaxfre;//Bit7-Bit6 用于频段设置用;Bit5-Bit0 表示当前读写器工作 的最大频率。
public string datain;
//byte[] FormatHEX;
/***************************************************/
//int WriteTextFlag = 1;
int chekFlag;
string localFilePath = "";
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
{
//button1.BackgroundImage = Properties.Resources.chinaz3;
toolStripSplitButton1.Image = Properties.Resources.chinaz3;
}
{
if (btn == false && comboBox1.Text != "")
{
//button1.BackgroundImage = Properties.Resources.chinaz5;
try
{
serialPort1.PortName = comboBox1.Text;//串口号
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);//波特率
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity),comboBox3.Text);//校验位
serialPort1.DataBits = Convert.ToInt32(comboBox4.Text.ToString().Substring(0,1));//数据位
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.Text.ToString().Substring(0, 1)); //停止位
serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
serialPort1.Open();
toolStripStatusLabel1.Text = "串口已连接";
button1.Text = "关闭串口";
//button1.BackgroundImage = Properties.Resources.chinaz5;
toolStripSplitButton1.Image = Properties.Resources.chinaz5;
}
catch {
//button1.BackgroundImage = Properties.Resources.chinaz4;
MessageBox.Show("打开串口失败,请重新选择端口号或检查连接", "提示");
serialPort1.Close();
button1.Text = "打开串口";
}
btn = true;
}
else {
serialPort1.Close();
button1.Text = "打开串口";
toolStripStatusLabel1.Text = "串口未连接";
toolStripSplitButton1.Image = Properties.Resources.chinaz4;
btn = false;
}
}
{
if (btn == true)
{
toolStripSplitButton1.Image = Properties.Resources.chinaz5;
}
else {
toolStripSplitButton1.Image = Properties.Resources.chinaz4;
}
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
toolStripStatusLabel1.Text = "请先打开串口";
toolStripStatusLabel8.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
richTextBox1.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
richTextBox2.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
dataGridView1.AllowUserToAddRows = false;
int i = 0;
this.Width = 750;
comboBox1.Items.Clear();
foreach (string vPortName in SerialPort.GetPortNames())
{
comboBox1.Items.Add(vPortName);
}
//richTextBox1.Text = comboBox1.Items.Count.ToString() vPortName1 comboBox1.Items[comboBox1.Items.Count - 1];
for (i = 0x03; i <= 0xff; i ) //响应时间
ComboBox_scantime.Items.Add(Convert.ToString(i) "*100ms");
ComboBox_scantime.SelectedIndex = 7;
ComboBox_baud.SelectedIndex = 3;//波特率
comboBox6.SelectedIndex = 3;
if (comboBox1.Items.Count != 0)
{
comboBox2.Text = "9600";
comboBox3.Text = "None";
comboBox4.Text = "8位";
comboBox5.Text = "1位";
ReadIni();
try
{
comboBox1.Text = Convert.ToString(comboBox1.Items[comboBox1.Items.Count - 1]);
received_count = Convert.ToInt32(ContentValue(strSec, "SendCount"));//接收计数
send_count = Convert.ToInt32(ContentValue(strSec, "ReceCount"));//发送计数
}
catch {
}
}
else {
MessageBox.Show("当前设备不存在串口,请检查硬件后点击“扫描”", "提示");
}
/*****************非常重要************************/
}
{
richTextBox1.Clear();
}
{
richTextBox2.Clear();
}
{
if (checkBox4.Checked)
{
send_hex = true;
}
else
{
send_hex = false;
}
}
private byte[] StringToBytes(string TheString) //转字符 //utf8编码转GB2132编码
{
Encoding FromEcoding = Encoding.GetEncoding("UTF-8"); //UTF8编码
Encoding ToEcoding = Encoding.GetEncoding("gb2312"); //GB2312编码
byte[] FromBytes = FromEcoding.GetBytes(TheString); //获取汉字UTF8字节序列
byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, FromBytes); //转换为GB2132字节码
return Tobytes; //返回
}
{
string Mystring;
Encoding FromEcoding = Encoding.GetEncoding("gb2312");
Encoding ToEcoding = Encoding.GetEncoding("UTF-8");
byte[] Tobytes = Encoding.Convert(FromEcoding, ToEcoding, Bytes);
Mystring = ToEcoding.GetString(Tobytes); //得到的是UTF8字节码序列,需要转换为UTF8字符串
return Mystring; //转换
}
{
byte[] Data = new byte[1];
if (serialPort1.IsOpen && richTextBox2.Text != "")
{
if (!checkBox6.Checked)
{
toolStripStatusLabel7.Text = richTextBox2.Text;
try
{
serialPort1.Write(richTextBox2.Text);
send_count = richTextBox2.Text.Length;
toolStripStatusLabel3.Text = send_count.ToString();
}
catch
{
toolStripStatusLabel7.Text = "串口数据写入错误";
//serialPort1.Close();
}
}
else
{
try
{
string buffer = richTextBox2.Text;
buffer = buffer.Replace("0x", ""); //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
buffer = buffer.Replace(" ", string.Empty);
for (int i = 0; i < buffer.Length / 2; i )
{
Data[0] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
toolStripStatusLabel7.Text = Data[0];
serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
send_count = 1;
toolStripStatusLabel3.Text = send_count.ToString();
}
if (buffer.Length % 2 != 0)
{
Data[0] = Convert.ToByte(buffer.Substring(buffer.Length - 1, 1), 16);//单独发送B(0B)
serialPort1.Write(Data, 0, 1);//发送
send_count = 1;
toolStripStatusLabel3.Text = send_count.ToString();
}
}
catch {
//toolStripStatusLabel7.Text = "数据错误,请重新输入";
}
}
toolStripStatusLabel7.Text = "数据发送成功";
timer2.Start();
}
}
{
if (serialPort1.IsOpen && richTextBox2.Text != "")
{
if (button2.Text == "发 送")
{
if (send_hex) //自动发送
{
timer1.Start();
button2.Text = "停止发送";
button1.Enabled= false;
}
else
{
SendData();
}
if (checkBox5.Checked) richTextBox2.Clear();
}
else
{
timer1.Stop();
button2.Text = "发 送";
button1.Enabled = true;
}
}
else if(!serialPort1.IsOpen)
toolStripStatusLabel7.Text = "请打开串口";
else if (richTextBox2.Text == "")
toolStripStatusLabel7.Text = "请在发送区输入数据";
timer2.Start();
}
{
timer1.Stop();
SendData();
timer1.Start();
}
{
timer1.Interval = Convert.ToInt32(textBox1.Text);
}
{
//Control.CheckForIllegalCrossThreadCalls = false;
System.Threading.Thread.Sleep(50);//延时50ms等待接收完数据
//timer2.Start();
if (!checkBox1.Checked)//如果接收模式为字符模式
{
try
{
int len = serialPort1.BytesToRead;
Byte[] readBuffer = new Byte[len];
serialPort1.Read(readBuffer, 0, len);
richTextBox1.Text = BytesToString(readBuffer);
}
catch {
}
}
else
{ //如果接收模式为数值接收
try
{
int len = serialPort1.BytesToRead;//获取接收缓冲区中数据的字节数
Byte[] readBuffer = new Byte[len];//定义字节数组buf,长度为接收缓冲区中数据的字节数
//从 SerialPort 输入缓冲区读取一些字节(长度为buf.Length,缓存区的字节数)并将那些字节写入buf数组中,返回的是读取的字节数
serialPort1.Read(readBuffer, 0, readBuffer.Length);
/**********************/
Get = readBuffer;
/*********************/
foreach (byte str in readBuffer)
{
if (!checkBox2.Checked)
richTextBox1.AppendText(str.ToString("X2") " ");
int rowCount = richTextBox1.Lines.Count();
}
received_count = readBuffer.Length;
}
catch {
}
}
if (checkBox3.Checked && !checkBox2.Checked) richTextBox1.AppendText("\r\n"); //自动换行
toolStripStatusLabel5.Text = received_count.ToString(); //接收的次数
//timer2.Start();
toolStripStatusLabel7.Text = "接收到数据";
try
{
serialPort1.DiscardInBuffer();//释放接收缓冲区数据
}
catch {
}
timer2.Start();
}
//{
// timer2.Stop();
// toolStripStatusLabel7.Text = "";
//}
{
comboBox1.Items.Clear();
foreach (string vPortName in SerialPort.GetPortNames())
{
comboBox1.Items.Add(vPortName);
}
if (comboBox1.Items.Count != 0)
{
comboBox1.Text = Convert.ToString(comboBox1.Items[comboBox1.Items.Count - 1]);
comboBox2.Text = "9600";
comboBox3.Text = "None";
comboBox4.Text = "8位";
comboBox5.Text = "1位";
}
toolStripStatusLabel7.Text = "扫描出" comboBox1.Items.Count.ToString() "个串口,请选择";
}
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "";
//sfd.InitialDirectory = @"D:\";
sfd.InitialDirectory = @localFilePath;
sfd.Filter = "文本文件| *.txt";
//sfd.ShowDialog();
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
localFilePath = sfd.FileName.ToString();
string path = sfd.FileName;
if (path == "")
{
return;
}
{
byte[] buffer = Encoding.Default.GetBytes(richTextBox1.Text);
fsWrite.Write(buffer, 0, buffer.Length);
MessageBox.Show("保存成功");
//FileStream file = new FileStream("记录.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);//建立一个文件
//StreamWriter writer = new StreamWriter(file); //设置文件时可以写的
//writer.WriteLine(textBox2.Text);
//writer.Close();
//file.Close();
}
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "请选择要打开的文件";
//多选
ofd.Multiselect = true;
//初始目录
ofd.InitialDirectory = @localFilePath;
//设定文件类型
ofd.Filter = "文本文件 | *.txt";
ofd.ShowDialog();
string path = ofd.FileName;
if (path == "")
{
return;
}
using (FileStream fsRead = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = fsRead.Read(buffer, 0, buffer.Length);
richTextBox2.Text = Encoding.Default.GetString(buffer, 0, r);
}
}
/// 写入INI文件
/// </summary>
/// <param name="section">节点名称[如[TypeName]]</param>
/// <param name="key">键</param>
/// <param name="val">值</param>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
/// <summary>
/// 读取INI文件
/// </summary>
/// <param name="section">节点名称</param>
/// <param name="key">键</param>
/// <param name="def">值</param>
/// <param name="retval">stringbulider对象</param>
/// <param name="size">字节大小</param>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath);
private string strSec = ""; //INI文件名
//读取
private void ReadIni() //btnRead_Click(object sender, EventArgs e)
{
if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
{
comboBox1.Text = ContentValue(strSec, "PortName");
comboBox2.Text = ContentValue(strSec, "BandRate");
comboBox3.Text = ContentValue(strSec, "Parity");
comboBox4.Text = ContentValue(strSec, "DataBits") "位";
comboBox5.Text = ContentValue(strSec, "StopBits") "位";
checkBox1.Checked = bool.Parse(ContentValue(strSec, "ReceivHex"));
checkBox2.Checked = bool.Parse(ContentValue(strSec, "ReceivBlank"));
checkBox3.Checked = bool.Parse(ContentValue(strSec, "ReceivLine"));
checkBox6.Checked = bool.Parse(ContentValue(strSec, "SendHex"));
checkBox5.Checked = bool.Parse(ContentValue(strSec, "SendBlank"));
checkBox4.Checked = bool.Parse(ContentValue(strSec, "SendAuto"));
textBox1.Text = ContentValue(strSec, "SendMs");
toolStripStatusLabel3.Text = ContentValue(strSec, "SendCount");
toolStripStatusLabel5.Text = ContentValue(strSec, "ReceCount");
this.Width = Convert.ToInt32(ContentValue(strSec, "FormWidth"));
if (this.Width == 1125) label12.Text = "扩展功能收回<<";
else label12.Text = "扩展功能展开>>";
int CountN = Convert.ToInt32(ContentValue(strSec, "RowCount"));
for (int i = 0; i < CountN; i )//dataGridView1.Rows.Count;//所有行数
{
int index = dataGridView1.Rows.Add();
//dataGridView1.Rows[index].Cells[0].Value = richTextBox2.Text;
dataGridView1.Rows[index].Cells[0].Value = ContentValue(strSec, "ComandCount" i.ToString());
}
}
else
{
//MessageBox.Show("INI文件不存在");
}
}
/// 自定义读取INI文件中的内容方法
/// </summary>
/// <param name="Section">键</param>
/// <param name="key">值</param>
/// <returns></returns>
private string ContentValue(string Section, string key)
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, key, "", temp, 1024, strFilePath);
return temp.ToString();
}
{
try
{
//根据INI文件名设置要写入INI文件的节点名称
//此处的节点名称完全可以根据实际需要进行配置
if (comboBox1.Text != "")
{
serialPort1.Close();
strSec = Path.GetFileNameWithoutExtension(strFilePath);
WritePrivateProfileString(strSec, "PortName", comboBox1.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "BandRate", comboBox2.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "Parity", comboBox3.Text.Trim(), strFilePath);
WritePrivateProfileString(strSec, "DataBits", comboBox4.Text.Substring(0, 1).Trim(), strFilePath);
WritePrivateProfileString(strSec, "StopBits", comboBox5.Text.Substring(0, 1).Trim(), strFilePath);
WritePrivateProfileString(strSec, "ReceivHex", checkBox1.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "ReceivBlank", checkBox2.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "ReceivLine", checkBox3.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "SendHex", checkBox6.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "SendBlank", checkBox5.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "SendAuto", checkBox4.Checked ? "true" : "false", strFilePath);
WritePrivateProfileString(strSec, "SendMs", textBox1.Text, strFilePath);
WritePrivateProfileString(strSec, "SendCount", toolStripStatusLabel3.Text, strFilePath);
WritePrivateProfileString(strSec, "ReceCount", toolStripStatusLabel3.Text, strFilePath);
WritePrivateProfileString(strSec, "FormWidth", this.Size.Width.ToString(), strFilePath);
WritePrivateProfileString(strSec, "RowCount", dataGridView1.Rows.Count.ToString(), strFilePath);
for (int i = 0; i < dataGridView1.Rows.Count; i )//dataGridView1.Rows.Count;//所有行数
{
this.dataGridView1.CurrentCell = this.dataGridView1[0, i];
WritePrivateProfileString(strSec, "ComandCount" i.ToString(), dataGridView1.CurrentCell.Value.ToString(), strFilePath);
}
//MessageBox.Show("写入成功");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
{
if (checkBox6.Checked && chekFlag == 0)
{
string str = richTextBox2.Text;
if (str.Length > 2)
{
int WriteTextNum = str.Length / 3;
if (str.Length == (WriteTextNum * 3) && str.Substring(str.Length - 2, 1) != " ")
{
//WriteTextNum ;
if (str.Substring(str.Length - 1, 1) != " ")
richTextBox2.Text = str.Substring(0, str.Length - 1) " " str.Substring(str.Length - 1, 1);
else richTextBox2.Text = str.Substring(0, str.Length - 1);
richTextBox2.Select(richTextBox2.Text.Length, 0);//选择文本末尾位置
richTextBox2.ScrollToCaret();//将光标滚动到末尾位置,不然追加一个空格光标会跳转到开头位置
}
}
}
}
private void richTextBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if(checkBox6.Checked)
{
if ((int)e.KeyChar >= 48 & (int)e.KeyChar <= 57 | (int)e.KeyChar == 8 | (int)e.KeyChar >= 65 & (int)e.KeyChar <= 70 | (int)e.KeyChar >= 97 & (int)e.KeyChar <= 102)
{
e.Handled = false;
}
else
{
e.Handled = true;
toolStripStatusLabel7.Text = "请输入合法数字0~9,A~F";
timer2.Start();
}
{
e.KeyChar = (char)((int)e.KeyChar - 32);
}
//{
// string str = richTextBox2.Text;
// try
// {
// if (str.Substring(str.Length - 1, 1) == " ") WriteTextFlag = 0;
// else WriteTextFlag = 1;
// if (WriteTextFlag == 0)
// {
// //WriteTextNum--;
// //if (WriteTextNum == 1) WriteTextNum = 1;
// }
// richTextBox2.Select(richTextBox2.Text.Length, 0);//选择文本末尾位置
// richTextBox2.ScrollToCaret();//将光标滚动到末尾位置,不然追加一个空格光标会跳转到开头位置
// }
// catch { }
// //richTextBox2.Text = str.Substring(0, str.Length - 2);
// //richTextBox2.Select(richTextBox2.Text.Length, 0);
// //richTextBox2.ScrollToCaret();
//}
}
}
{
this.Height = 514;
if (this.Size.Width <= 512) this.Width = 512;
}
{
toolStripStatusLabel8.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
{
received_count = 0;//接收计数
send_count = 0;//发送计数
toolStripStatusLabel3.Text = send_count.ToString();
toolStripStatusLabel5.Text = received_count.ToString();
}
{
received_count = 0;//接收计数
send_count = 0;//发送计数
toolStripStatusLabel3.Text = send_count.ToString();
toolStripStatusLabel5.Text = received_count.ToString();
}
{
chekFlag = 1;
if (checkBox6.Checked)
{
string str = richTextBox2.Text;
richTextBox2.Text = "";
foreach(byte bty in str)
{
richTextBox2.AppendText(bty.ToString("X2") " ");
}
chekFlag = 0;
}
else {
byte data;
string str = richTextBox2.Text;
richTextBox2.Text = "";
str = str.Replace(" ","");
str = str.Replace("0x","");
for(int i = 0;i<str.Length/2;i )
{
try
{
data = Convert.ToByte(str.Substring(i * 2, 2), 16);
richTextBox2.Text = (char)data;
//send_count = richTextBox2.Text.Length / 3;
}
catch { }
}
chekFlag = 0;
}
}
{
//timer2.Stop();
//timer2.Enabled =
toolStripStatusLabel7.Text = "";
}
//{
// int index = dataGridView1.Rows.Add();
// dataGridView1.Rows[index].Cells[0].Value = richTextBox2.Text;
// //WriteTextNum = 1;
// richTextBox2.Text = "";
//}
{
byte[] Data = new byte[1];
if (serialPort1.IsOpen && dataGridView1.CurrentCell.Value.ToString() != "")
{
if (!checkBox6.Checked)
{
try
{
serialPort1.Write(dataGridView1.CurrentCell.Value.ToString());
send_count = richTextBox2.Text.Length;
toolStripStatusLabel3.Text = send_count.ToString();
}
catch
{
toolStripStatusLabel7.Text = "串口数据写入错误";
//serialPort1.Close();
}
}
else
{
try
{
string buffer = dataGridView1.CurrentCell.Value.ToString();
buffer = buffer.Replace("0x", ""); //为了保证汉字转编码输出结果(0xXX)可以通用,所以程序允许输入0xXX(可以带空格),程序会将0x和空格自动去除
buffer = buffer.Replace(" ", string.Empty);
for (int i = 0; i < buffer.Length / 2; i )
{
Data[0] = Convert.ToByte(buffer.Substring(i * 2, 2), 16);
toolStripStatusLabel7.Text = Data[0];
serialPort1.Write(Data, 0, 1);//循环发送(如果输入字符为0A0BB,则只发送0A,0B)
send_count = 1;
toolStripStatusLabel3.Text = send_count.ToString();
}
if (buffer.Length % 2 != 0)
{
Data[0] = Convert.ToByte(buffer.Substring(buffer.Length - 1, 1), 16);//单独发送B(0B)
serialPort1.Write(Data, 0, 1);//发送
send_count = 1;
toolStripStatusLabel3.Text = send_count.ToString();
}
}
catch
{
//toolStripStatusLabel7.Text = "数据错误,请重新输入";
}
}
toolStripStatusLabel7.Text = "数据发送成功";
timer2.Start();
}
}
//{
// //richTextBox2.Text = dataGridView1.CurrentCell.Value.ToString();
// if (serialPort1.IsOpen && dataGridView1.CurrentCell.Value.ToString() != "")
// {
// SendData0();
// }
// else if (!serialPort1.IsOpen)
// toolStripStatusLabel7.Text = "请打开串口";
// else if (richTextBox2.Text == "")
// toolStripStatusLabel7.Text = "请在发送区输入数据";
// timer2.Start();
//}
//{
// try
// {
// int RowNumber;
// if (null == dataGridView1.CurrentCell)
// {
// return;
// }
// RowNumber = dataGridView1.CurrentCell.RowIndex;
// dataGridView1.Rows.RemoveAt(RowNumber);
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.ToString());
// }
//}
private void label12_Click(object sender, EventArgs e)
{
if (this.Width == 750)
{
this.Width = 1125;
label12.Text = "扩展功能收回<<";
}
else {
this.Width = 750;
label12.Text = "扩展功能展开>>";
}
}
{
{
private byte[] HexStringToByteArray(string s) //字符串转字节
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i = 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));//
return sb.ToString().ToUpper();//.ToUpper()转大写
/****************************CRC校验**********************************************/
private string CRCCalc(string data)
{
string[] datas = data.Split(' ');
List<byte> bytedata = new List<byte>();
{
bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier));
}
byte[] crcbuf = bytedata.ToArray();
//计算并填写CRC校验码
int crc = 0xffff;
len = crcbuf.Length;
for (int n = 0; n < len; n )
{
byte i;
crc = crc ^ crcbuf[n];
for (i = 0; i < 8; i )
{
int TT;
TT = crc & 1;
crc = crc >> 1;
crc = crc & 0x7fff;
if (TT == 1)
{
crc = crc ^ 0x8408;
}
crc = crc & 0xffff;
}
string[] redata = new string[2];
redata[1] = Convert.ToString((byte)((crc >> 8) & 0xff), 16);
redata[0] = Convert.ToString((byte)((crc & 0xff)), 16);
}
{
byte[] TrType = new byte[2];//读写器支持的协议信息
byte[] VersionInfo = new byte[2];//版本
byte ReaderType = 0;//读写器类型代号
byte ScanTime = 0; //查询时间
byte dmaxfre = 0; //最大频率。
byte dminfre = 0; //最小频率。
byte powerdBm = 0;//输出功率
byte FreBand = 0;//频段
byte ComAdr = 0xff;
Edit_Version.Text = ""; //版本
Edit_scantime.Text = ""; //响应时间
Edit_Type.Text = ""; //型号
ISO180006B.Checked = false;
EPCC1G2.Checked = false;
Edit_powerdBm.Text = ""; //功率
Edit_dminfre.Text = ""; //最低频率
Edit_dmaxfre.Text = ""; //最高频率
//string data = "04 FF 21";
//CRCCalc(data);
//textBox2.Clear();
//string user = CRCCalc(data).ToString();
//this.textBox2.Text = user;
richTextBox2.Text = str;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e);
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
int len = Get[0]; //长度len
ComAdr = Get[1]; //地址adr
fCmdRet = Get[2]; //recmd
Result = Get[3]; //命令结果返回值Status
VersionInfo[0] = Get[4];//版本号
VersionInfo[1] = Get[5];//版本号
ReaderType = Get[6];//读写器类型代号
TrType[0] = Get[7];//读写器支持的协议信息
dmaxfre = Get[8];
dminfre = Get[9];
powerdBm = Get[10];//输出功率
ScanTime = Get[11];//查询时间
temps=ByteArrayToHexString(Get);
textBox2.Clear();
string user = temps.ToString();
this.textBox2.Text = user;
///////////////////////////////////////////////////////////////7/20 21:10
Edit_ComAdr.Text = Convert.ToString(fComAdr, 16).PadLeft(2, '0');
/***************版本号**********************/
Edit_Version.Text = Convert.ToString(VersionInfo[0], 10).PadLeft(2, '0') "." Convert.ToString(VersionInfo[1], 10).PadLeft(2, '0');
/***************型号**********************/
if (ReaderType == 0x03)
Edit_Type.Text = "";
if (ReaderType == 0x06)
Edit_Type.Text = "";
if (ReaderType == 0x09)
Edit_Type.Text = "236028";
/****************支持协议*********************/
if ((TrType[0] & 0x02) == 0x02) //第二个字节低第四位代表支持的协议“ISO/IEC 15693”
{
ISO180006B.Checked = true;
EPCC1G2.Checked = true;
}
else
{
ISO180006B.Checked = false;
EPCC1G2.Checked = false;
}
/***************频段***********************/
FreBand = Convert.ToByte(((dmaxfre & 0xc0) >> 4) | (dminfre >> 6));
switch (FreBand)
{
case 0:
{
radioButton_band1.Checked = true;
fdminfre = 902.6 (dminfre & 0x3F) * 0.4;
fdmaxfre = 902.6 (dmaxfre & 0x3F) * 0.4;
}
break;
case 1:
{
radioButton_band2.Checked = true;
fdminfre = 920.125 (dminfre & 0x3F) * 0.25;
fdmaxfre = 920.125 (dmaxfre & 0x3F) * 0.25;
}
break;
case 2:
{
radioButton_band3.Checked = true;
fdminfre = 902.75 (dminfre & 0x3F) * 0.5;
fdmaxfre = 902.75 (dmaxfre & 0x3F) * 0.5;
}
break;
case 3:
{
radioButton_band4.Checked = true;
fdminfre = 917.1 (dminfre & 0x3F) * 0.2;
fdmaxfre = 917.1 (dmaxfre & 0x3F) * 0.2;
}
break;
case 4:
{
radioButton_band5.Checked = true;
fdminfre = 865.1 (dminfre & 0x3F) * 0.2;
fdmaxfre = 865.1 (dmaxfre & 0x3F) * 0.2;
}
break;
}
Edit_dminfre.Text = Convert.ToString(fdminfre) "MHz";
Edit_dmaxfre.Text = Convert.ToString(fdmaxfre) "MHz";
Edit_powerdBm.Text = Convert.ToString(powerdBm, 10).PadLeft(2, '0');
Edit_scantime.Text = Convert.ToString(ScanTime, 10).PadLeft(2, '0') "*100ms";
//string s = System.Text.Encoding.Default.GetString(Get);
{
{
/***************设置工作频率***********************/
//频段选择按钮设置
private void radioButton_band1_CheckedChanged(object sender, EventArgs e)
{
int i;
ComboBox_dmaxfre.Items.Clear();
ComboBox_dminfre.Items.Clear();
for (i = 0; i < 63; i )
{
ComboBox_dminfre.Items.Add(Convert.ToString(902.6 i * 0.4) " MHz");
ComboBox_dmaxfre.Items.Add(Convert.ToString(902.6 i * 0.4) " MHz");
}
ComboBox_dmaxfre.SelectedIndex = 62;
ComboBox_dminfre.SelectedIndex = 0;
}
private void radioButton_band2_CheckedChanged(object sender, EventArgs e)
{
int i;
ComboBox_dmaxfre.Items.Clear();
ComboBox_dminfre.Items.Clear();
for (i = 0; i < 20; i )
{
ComboBox_dminfre.Items.Add(Convert.ToString(920.125 i * 0.25) " MHz");
ComboBox_dmaxfre.Items.Add(Convert.ToString(920.125 i * 0.25) " MHz");
}
ComboBox_dmaxfre.SelectedIndex = 19;
ComboBox_dminfre.SelectedIndex = 0;
}
private void radioButton_band3_CheckedChanged(object sender, EventArgs e)
{
int i;
ComboBox_dmaxfre.Items.Clear();
ComboBox_dminfre.Items.Clear();
for (i = 0; i < 50; i )
{
ComboBox_dminfre.Items.Add(Convert.ToString(902.75 i * 0.5) " MHz");
ComboBox_dmaxfre.Items.Add(Convert.ToString(902.75 i * 0.5) " MHz");
}
ComboBox_dmaxfre.SelectedIndex = 49;
ComboBox_dminfre.SelectedIndex = 0;
}
private void radioButton_band4_CheckedChanged(object sender, EventArgs e)
{
int i;
ComboBox_dmaxfre.Items.Clear();
ComboBox_dminfre.Items.Clear();
for (i = 0; i < 32; i )
{
ComboBox_dminfre.Items.Add(Convert.ToString(917.1 i * 0.2) " MHz");
ComboBox_dmaxfre.Items.Add(Convert.ToString(917.1 i * 0.2) " MHz");
}
ComboBox_dmaxfre.SelectedIndex = 31;
ComboBox_dminfre.SelectedIndex = 0;
}
//频段选择按钮设置
//频率选择框
private void ComboBox_dfreSelect(object sender, EventArgs e)
{
if (CheckBox_SameFre.Checked)
{
ComboBox_dminfre.SelectedIndex = ComboBox_dmaxfre.SelectedIndex;
}
else if (ComboBox_dminfre.SelectedIndex > ComboBox_dmaxfre.SelectedIndex)
{
ComboBox_dminfre.SelectedIndex = ComboBox_dmaxfre.SelectedIndex;
MessageBox.Show("最低频率应小于或等于最高频率", "错误提示");
}
}
//频率选择框
//单频点
private void CheckBox_SameFre_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox_SameFre.Checked)
ComboBox_dmaxfre.SelectedIndex = ComboBox_dminfre.SelectedIndex;
}
//单频点
//设置工作频率
private void RFRate_Click(object sender, EventArgs e)
{
byte dminfre, dmaxfre,band = 0;
byte[] Data = new byte[4];
string cmd1 = "22";
/////////////////////频率选择///////////////////////////////////////
progressBar1.Visible = true;
progressBar1.Minimum = 0;
band = 0;
if (radioButton_band2.Checked)
band = 1;
if (radioButton_band3.Checked)
band = 2;
if (radioButton_band4.Checked)
band = 3;
if (radioButton_band5.Checked)
band = 4;
dminfre = Convert.ToByte(((band & 3) << 6) | (ComboBox_dminfre.SelectedIndex & 0x3F)); //MaxFre
dmaxfre = Convert.ToByte(((band & 0x0c) << 4) | (ComboBox_dmaxfre.SelectedIndex & 0x3F));//MinFre
////////////////////// 校验码 ///////////////////////////////////////
Data[0] = fComAdr;//adr
byte[] cmd = new byte[1];
byte cmd2 = 0;
cmd = HexStringToByteArray(cmd1);
cmd2 = cmd[0];
Data[1] =cmd2;
Data[2] = dminfre;//MaxFre
Data[3] = dmaxfre;//MinFre
string data;
data = ByteArrayToHexString(Data);
data = data.Substring(0, data.Length - 1);//去掉最后一个空格
CRCCalc(data);//校验码
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToString(len 2).PadLeft(2, '0').PadRight(3, ' '));
sb.Append(Convert.ToString(data).PadLeft(2, '0').PadRight(3, ' ') " ");
sb.Append(Convert.ToString(CRCCalc(data)).PadLeft(2, '0').PadRight(3, ' '));
//str.Append(len);
//str.Append(data);
//str.Append(CRCCalc(data));
//////////////////////转为字符串交给 button2_Click(sender, e); 发送///////////////////////////////////////
progressBar1.Value = 70; System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
string code = sb.ToString();
richTextBox2.Text = code;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e); //发送
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
/////////////////////////////////////////////////////////////
progressBar1.Visible = false;
//readRF_Click(sender, e); //读取读写器信息
}
//设置工作频率
private void ComAddr_Click(object sender, EventArgs e)
{
byte aNewComAdr=0xff;
byte[] Data = new byte[3];
string cmd1 = "24";
progressBar1.Visible = true;
progressBar1.Minimum = 0;
MessageBox.Show("请输入读写器地址", "提示");
try
{
aNewComAdr = Convert.ToByte(Edit_NewComAdr.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Data[0] = fComAdr;//adr
byte cmd2 = 0;
cmd = HexStringToByteArray(cmd1);
cmd2 = cmd[0];
Data[2] = aNewComAdr;//address
string data;
data = ByteArrayToHexString(Data);
data = data.Substring(0, data.Length - 1);//去掉最后一个空格
CRCCalc(data);//校验码
////////////////////// 拼接 ///////////////////////////////////////
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToString(len 2).PadLeft(2, '0').PadRight(3, ' '));
sb.Append(Convert.ToString(data).PadLeft(2, '0').PadRight(3, ' ') " ");
sb.Append(Convert.ToString(CRCCalc(data)).PadLeft(2, '0').PadRight(3, ' '));
//str.Append(len);
//str.Append(data);
//str.Append(CRCCalc(data));
//////////////////////转为字符串交给 button2_Click(sender, e); 发送///////////////////////////////////////
progressBar1.Value = 70; System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
string code = sb.ToString();
richTextBox2.Text = code;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e); //发送
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
/////////////////////////////////////////////////////////////
progressBar1.Visible = false;
//readRF_Click(sender, e); //读取读写器信息
//设置查询响应时间
private void Qtime_Click(object sender, EventArgs e)
{
byte[] Data = new byte[3];
string cmd1 = "25";
progressBar1.Visible = true;
progressBar1.Minimum = 0;
scantime = Convert.ToByte(ComboBox_scantime.SelectedIndex 3);
Data[0] = fComAdr;//adr
byte cmd2 = 0;
cmd = HexStringToByteArray(cmd1);
cmd2 = cmd[0];
Data[2] = scantime;//address
string data;
data = ByteArrayToHexString(Data);
data = data.Substring(0, data.Length - 1);//去掉最后一个空格
CRCCalc(data);//校验码
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToString(len 2).PadLeft(2, '0').PadRight(3, ' '));
sb.Append(Convert.ToString(data).PadLeft(2, '0').PadRight(3, ' ') " ");
sb.Append(Convert.ToString(CRCCalc(data)).PadLeft(2, '0').PadRight(3, ' '));
//str.Append(len);
//str.Append(data);
//str.Append(CRCCalc(data));
//////////////////////转为字符串交给 button2_Click(sender, e); 发送///////////////////////////////////////
progressBar1.Value = 70; System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
string code = sb.ToString();
richTextBox2.Text = code;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e); //发送
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
/////////////////////////////////////////////////////////////
progressBar1.Visible = false;
//readRF_Click(sender, e); //读取读写器信息
{
byte fBaud = 0xff;
byte[] Data = new byte[3];
string cmd1 = "28";
progressBar1.Visible = true;
progressBar1.Minimum = 0;
fBaud = Convert.ToByte(comboBox6.SelectedIndex); //波特率
if (fBaud > 2)
fBaud = Convert.ToByte(fBaud 2);
////////////////////// 校验码 ///////////////////////////////////////
Data[0] = fComAdr;//adr
byte cmd2 = 0;
cmd = HexStringToByteArray(cmd1);
cmd2 = cmd[0];
Data[2] = fBaud;//address
string data;
data = ByteArrayToHexString(Data);
data = data.Substring(0, data.Length - 1);//去掉最后一个空格
CRCCalc(data);//校验码
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToString(len 2).PadLeft(2, '0').PadRight(3, ' '));
sb.Append(Convert.ToString(data).PadLeft(2, '0').PadRight(3, ' ') " ");
sb.Append(Convert.ToString(CRCCalc(data)).PadLeft(2, '0').PadRight(3, ' '));
//str.Append(len);
//str.Append(data);
//str.Append(CRCCalc(data));
//////////////////////转为字符串交给 button2_Click(sender, e); 发送///////////////////////////////////////
progressBar1.Value = 70; System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
string code = sb.ToString();
richTextBox2.Text = code;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e); //发送
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
/////////////////////////////////////////////////////////////
progressBar1.Visible = false;
//readRF_Click(sender, e); //读取读写器信息
}
{
{
byte powerDbm = 0xff;
byte[] Data = new byte[3];
string cmd1 = "2F";
progressBar1.Visible = true;
progressBar1.Minimum = 0;
////////////////////// 校验码 ///////////////////////////////////////
Data[0] = fComAdr;//adr
byte cmd2 = 0;
cmd = HexStringToByteArray(cmd1);
cmd2 = cmd[0];
Data[2] = powerDbm;//powerDbm
string data;
data = ByteArrayToHexString(Data);
data = data.Substring(0, data.Length - 1);//去掉最后一个空格
CRCCalc(data);//校验码
StringBuilder sb = new StringBuilder();
sb.Append(Convert.ToString(len 2).PadLeft(2, '0').PadRight(3, ' '));
sb.Append(Convert.ToString(data).PadLeft(2, '0').PadRight(3, ' ') " ");
sb.Append(Convert.ToString(CRCCalc(data)).PadLeft(2, '0').PadRight(3, ' '));
//str.Append(len);
//str.Append(data);
//str.Append(CRCCalc(data));
//////////////////////转为字符串交给 button2_Click(sender, e); 发送///////////////////////////////////////
progressBar1.Value = 70; System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
string code = sb.ToString();
richTextBox2.Text = code;
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
button2_Click(sender, e); //发送
System.Threading.Thread.Sleep(100);//延时50ms等待接收完数据
/////////////////////////////////////////////////////////////
progressBar1.Visible = false;
//readRF_Click(sender, e); //读取读写器信息
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论