一、引言
在本博客中,将会介绍如何使用C#编程语言来开发一个低频门禁卡系统。该系统将涵盖硬件设置、软件准备、编程代码以及系统操作等方面的内容。通过该系统,我们可以实现开关串口、读取卡号、新卡注册、手动读取卡数据以及判断并显示“开门”或“禁止入内”等功能。
二、硬件准备
NewLab实验台、M3模块、LF天线模块、低频卡数张、USB转串口驱动CH340。
1.1NewLab实验台
1.2M3模块
1.3低频卡数张
1.4LF 天线模块
1.5USB转串口驱动 CH340
三、界面设计
3.1注册界面
3.2门禁系统
当我们点击“注册”则通过写入文本流形式写入到文本里,点击“门禁”时则比对该卡是否注册了,比对文本里内容是否与该卡信息相同。
四、核心代码
using System;
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.Windows.Forms;
using System.IO.Ports;
using System.IO;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace 高频
{
public partial class Form1 : Form
{
public delegate void showReceiveDelegate(string text); //当采用响应模式,应申明一个委托,实现不同线程的控件实验
SerialPort com = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
int com_num = 0;
int timer_num, flag = 0;
string Da,Pa = "D:\\Date.txt";
Timer Timer1 = new Timer();
DateTime star = DateTime.Now;
DateTime stop = DateTime.Now;
/*-------------------------------------------------------------
* status_num状态字
* 1,表示读取信息
--------------------------------------------------------------*/
int status_num=0;//状态字
public Form1()
{
InitializeComponent();
}
//窗体加载
private void Form1_Load(object sender, EventArgs e)
{
//串口初始化
cmbPort.SelectedIndex = 2;
cmbBaudRate.SelectedIndex = 4;
cmbDataBits.SelectedIndex = 0;
cmbStopBits.SelectedIndex = 0;
cmbParity.SelectedIndex = 0;
//定时器初始化
System.Timers.Timer t = new System.Timers.Timer(50);//实例化Timer类,设置间隔时间为1000毫秒 就是1秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout); //到达时间的时候执行事件;
t.AutoReset = true; //设置是执行一次(false)还是一直执行(true);
t.Enabled = true; //是否执行System.Timers.Timer.Elapsed事件;
timer_num = 0;
}
//串口打开与关闭
private void btnOpen_Click(object sender, EventArgs e)
{
if (btnOpen.Text == "打开串口")
{
try
{
if (!com.IsOpen)
{
com.PortName = cmbPort.Text;
com.BaudRate = int.Parse(cmbBaudRate.Text);
com.DataBits = int.Parse(cmbDataBits.Text);
switch (cmbStopBits.SelectedIndex)
{
case 0:
com.StopBits = StopBits.One; break;
case 1:
com.StopBits = StopBits.Two; break;
case 2:
com.StopBits = StopBits.OnePointFive; break;
case 3:
com.StopBits = StopBits.None; break;
}
switch (cmbParity.SelectedIndex)
{
case 0: com.Parity = Parity.None; break;
case 1: com.Parity = Parity.Odd; break;
case 2: com.Parity = Parity.Even; break;
}
com.Open();//打开串口
}
btnOpen.Text = "关闭串口";
txtStatus.Text = "串口已打开!";
btnInformation.Enabled = true;
btnClear.Enabled = true;
button1.Enabled = true;
//button2.Enabled = true;
// 数据接收模式变化时,设置串口的数据接收侦听事件
try
{
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived); //加载接收事件
}
catch (Exception err)
{
txtStatus.Text = err.ToString();
}
}
catch
{ txtStatus.Text = "串口打开错误或串口不存在!"; }
}
else //关闭串口
try
{
if (com.IsOpen)
com.Close(); //关闭串口
btnOpen.Text = "打开串口";
txtStatus.Text = "串口已关闭!";
btnInformation.Enabled = false;
btnClear.Enabled = false;
button1.Enabled = false;
//button2.Enabled = false;
}
catch
{
txtStatus.Text = "串口关闭错误或串口不存在!";
}
}
//--------------------------------------------------------------------------------
//定时器相关设置
public void theout(object source, System.Timers.ElapsedEventArgs e)
{
timer_num++;
this.BeginInvoke(new TextOption(function1));//invok 委托实现跨线程的调用
}
delegate void TextOption();//定义一个委托
void function1()
{
if ((timer_num > 10)&&(com_num>5))
{
com_num = 0;
try
{
int count = com.BytesToRead;
byte[] readBuffer = new byte[count];
com.Read(readBuffer, 0, count);
//String strReceive = Encoding.Default.GetString(readBuffer); //字母、数字、汉字转换为字符串
String strReceive = getStringFromBytes(readBuffer); //转十六进制
this.Invoke(new showReceiveDelegate(doShowReceive), strReceive);
}
catch (Exception err)
{
txtStatus.Text = err.ToString();
}
}
}
//--------------------------------------------------------------------------------
// 响应模式时,串口接收数据事件
private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
com_num = com.BytesToRead;
timer_num = 0;
}
//异步线程处理接受的字符,显示在接收的文本框中
public void doShowReceive(string str)
{
txtReceive.Text = str;
//-----------------------------------------------------
//----------1---------2---------3---------4---------
//01234567890123456789012345678901234567890123456789
//FF 55 00 00 81 01 08 07 08 50 2A 82 D5 E5 5F 58 C2
//低频卡信息读取
if (status_num == 1)
{
status_num = 0;
int i;
for (i = 0; i < 10; i++)
{
if (str.Substring(i, 20).Equals("FF 55 00 00 81 01 08"))
{
txtInformation.Text = str.Substring(i + 21, 11);//截取4个字节
txtStatus.Text = "低频卡信息读取成功!";
break;
}
}
if (i >= 10)
{
txtStatus.Text = "无法获取低频卡信息!";
}
}
//-----------------------------------------------------
//----------1---------2---------3---------4---------
//01234567890123456789012345678901234567890123456789
//FF 55 00 00 82 04 01 00 EE 33
//低频卡初始化操作
if (status_num == 2)
{
status_num = 0;
int i;
for (i = 0; i < 5; i++)
{
if (str.Substring(i, 23).Equals("FF 55 00 00 82 04 01 00"))
{
txtStatus.Text = "低频卡初始化操作成功!";
break;
}
}
if (i >= 5)
{
txtStatus.Text = "无法进行低频卡初始化操作!";
}
}
//------------------------------------------------------------
//发送命令,常规写块操作
//----0---------1---------2---------3---------4---------5---------
//----012345678901234567890123456789012345678901234567890123456789
//发送FF 55 00 00 03 04 05 01 00 00 00 00 47 48
//接收FF 55 00 00 83 04 01 00 23 8E
if (status_num == 3)
{
status_num = 0;
int i;
for (i = 0; i < 5; i++)
{
if (str.Substring(i, 20).Equals("FF 55 00 00 83 03 04"))
{
txtStatus.Text = "常规读块操作操作成功!";
textBox2.Text = str.Substring(i + 21, 11);//截取4个字节
break;
}
}
if (i >= 5)
{
txtStatus.Text = "常规读块操作未成功!";
textBox1.Text = "";
}
}
if (status_num == 4)
{
status_num = 0;
int i;
for (i = 0; i < 5; i++)
{
if (str.Substring(i, 23).Equals("FF 55 00 00 83 04 01 00"))
{
txtStatus.Text = "常规写块操作成功!";
break;
}
}
if (i >= 5)
{
txtStatus.Text = "常规写块操作未成功!";
textBox1.Text = "";
}
}
if (status_num == 5)
{
status_num = 0;
FileStream F = new FileStream(Pa, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamWriter W = new StreamWriter(F);
W.WriteLine(textBox3.Text);
W.WriteLine(textBox4.Text);
W.Close();
}
if (status_num == 6)
{
status_num = 0;
string[] a = new string[2];
StreamReader sa = new StreamReader(Pa);
for (int k = 0; k < 2; k++)
{
a[k] = sa.ReadLine();
}
int i;
for (i = 0; i < 5; i++)
{
if (str.Substring(i, 20).Equals("FF 55 00 00 83 03 04"))
{
txtStatus.Text = "常规读块操作操作成功!";
Da = str.Substring(i + 21, 11);//截取4个字节
break;
}
}
if (i >= 5)
{
txtStatus.Text = "常规读块操作操作未成功!";
}
for (int j = 1; j >= 0; j--)
{
if (Da == a[j])
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if (flag == 1)
{
flag = 0;
textBox8.Text = a[0];
textBox7.Text = a[1];
textBox9.Text = "比对成功,正在开门";
}
else
{
textBox8.Text = "";
textBox7.Text = "";
textBox9.Text = "该卡无效!";
}
}
if (status_num == 7)
{
status_num = 0;
}
if (status_num == 8)
{
status_num = 0;
//TimeSpan T = new TimeSpan();
//T = stop.Subtract(star).Duration();
//textBox11.Text = T.Days.ToString()+"天"+T.Hours.ToString()+"小时"+T.TotalMinutes.ToString()+"分钟"+T.TotalSeconds.ToString()+"秒";
textBox11.Text = (stop-star).ToString();
}
}
// 把字节数组转换为十六进制格式的字符串。
// <param name="pByte">要转换的字节数组。</param>
// <returns>返回十六进制格式的字符串。</returns>
public static string getStringFromBytes(byte[] pByte)
{
string str = ""; //定义字符串类型临时变量。
//遍历字节数组,把每个字节转换成十六进制字符串,不足两位前面添“0”,以空格分隔累加到字符串变量里。
for (int i = 0; i < pByte.Length; i++)
str += (pByte[i].ToString("X").PadLeft(2, '0') + " ");
str = str.TrimEnd(' '); //去掉字符串末尾的空格。
return str; //返回字符串临时变量。
}
//<summary>
//把十六进制格式的字符串转换成字节数组。
//</summary>
//<param name="pString">要转换的十六进制格式的字符串</param>
//<returns>返回字节数组。</returns>
public static byte[] getBytesFromString(string pString)
{
string[] str = pString.Split(' '); //把十六进制格式的字符串按空格转换为字符串数组。
byte[] bytes = new byte[str.Length]; //定义字节数组并初始化,长度为字符串数组的长度。
for (int i = 0; i < str.Length; i++) //遍历字符串数组,把每个字符串转换成字节类型赋值给每个字节变量。
{ bytes[i] = Convert.ToByte(Convert.ToInt32(str[i], 16)); }
return bytes; //返回字节数组。
}
//------------------------------------------------------------
//清空接收框内容
private void btnClear_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
txtInformation.Text = "";
txtStatus.Text = "数据已经清除!";
}
//------------------------------------------------------------
//发送命令,获取低频卡信息
//0---------1---------2---------3---------4---------5---------
//012345678901234567890123456789012345678901234567890123456789
//FF 55 00 00 01 01 00 50 74
private void btnInformation_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 1;
String str1 = "FF 55 00 00 01 01 00 50 74";
byte[] data = getBytesFromString(str1);
com.Write(data, 0, data.Length);
txtSend.Text = str1;
}
//------------------------------------------------------------
//发送命令,低频卡初始化操作
//0---------1---------2---------3---------4---------5---------
//012345678901234567890123456789012345678901234567890123456789
//FF 55 00 00 02 04 00 00 87
//FF 55 00 00 82 04 01 00 EE 33
private void button1_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 2;
String str1 = "FF 55 00 00 02 04 00 00 87";
byte[] data = getBytesFromString(str1);
com.Write(data, 0, data.Length);
txtSend.Text = str1;
}
public static byte[] crc16(byte[] data, int len)
{
byte[] temdata = new byte[2];
int xda, xdapoly;
byte i, j, xdabit;
xda = 0xFFFF;
xdapoly = 0xA001;
for (i = 0; i < data.Length; i++)
{
xda ^= data[i];
for (j = 0; j < 8; j++)
{
xdabit = (byte)(xda & 0x01);
xda >>= 1;
if (xdabit == 1)
xda ^= xdapoly;
}
}
temdata[0] = (byte)(xda & 0xFF);
temdata[1] = (byte)(xda >> 8);
return temdata;
}
private void button2_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 3;
//-------------0---------1---------2---------3--
//-------------012345678901234567890123456789
String str1 = "FF 55 00 00 03 03 01 00 CF F1";
str1 = str1.Remove(21, 2);
str1 = str1.Insert(21, comboBox1.Text); //获取块地址
byte[] temdata1 = getBytesFromString(str1);//转换字节,准备CRC16校验
//-----------------------------------------------
int num_len1 = 6;//前2个字节FF 55不加入CRC校验
int num_len2 = 6;//后2个字节50 74是校验位
String str2 = str1.Substring(num_len1, str1.Length - num_len1 - num_len2);
byte[] temdata2 = getBytesFromString(str2);
byte[] temdata3 = crc16(temdata2, temdata2.Length);//CRC校验
temdata1[temdata1.Length - 2] = temdata3[1];//填充校验位
temdata1[temdata1.Length - 1] = temdata3[0];
//-----------------------------------------------
com.Write(temdata1, 0, temdata1.Length); //发到串口
txtSend.Text = getStringFromBytes(temdata1);//显示
}
private void button3_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 4;
String str1 = "FF 55 00 00 03 04 05 01 00 00 00 00 47 48";
str1 = str1.Remove(21, 2);
str1 = str1.Insert(21, comboBox2.Text); //获取块地址
str1 = str1.Remove(24, 11);
str1 = str1.Insert(24, textBox1.Text); //获取写入的数据内容
byte[] temdata1 = getBytesFromString(str1);//转换字节,准备CRC16校验
//-----------------------------------------------
int num_len1 = 6;//前2个字节FF 55不加入CRC校验
int num_len2 = 6;//后2个字节50 74是校验位
String str2 = str1.Substring(num_len1, str1.Length - num_len1 - num_len2);
byte[] temdata2 = getBytesFromString(str2);
byte[] temdata3 = crc16(temdata2, temdata2.Length);//CRC校验
temdata1[temdata1.Length - 2] = temdata3[1];//填充校验位
temdata1[temdata1.Length - 1] = temdata3[0];
//-----------------------------------------------
com.Write(temdata1, 0, temdata1.Length); //发到串口
txtSend.Text = getStringFromBytes(temdata1);//显示
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 5;
String str1 = "FF 55 00 00 03 04 05 01 00 00 00 00 47 48";
str1 = str1.Remove(21, 2);
str1 = str1.Insert(21, comboBox3.Text); //获取块地址
str1 = str1.Remove(24, 11);
str1 = str1.Insert(24, textBox4.Text); //获取写入的数据内容
byte[] temdata1 = getBytesFromString(str1);//转换字节,准备CRC16校验
//-----------------------------------------------
int num_len1 = 6;//前2个字节FF 55不加入CRC校验
int num_len2 = 6;//后2个字节50 74是校验位
String str2 = str1.Substring(num_len1, str1.Length - num_len1 - num_len2);
byte[] temdata2 = getBytesFromString(str2);
byte[] temdata3 = crc16(temdata2, temdata2.Length);//CRC校验
temdata1[temdata1.Length - 2] = temdata3[1];//填充校验位
temdata1[temdata1.Length - 1] = temdata3[0];
//-----------------------------------------------
com.Write(temdata1, 0, temdata1.Length); //发到串口
txtSend.Text = getStringFromBytes(temdata1);//显示
}
private void button5_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 2;
String str1 = "FF 55 00 00 02 04 00 00 87";
byte[] data = getBytesFromString(str1);
com.Write(data, 0, data.Length);
txtSend.Text = str1;
textBox5.Text = str1;
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
private void txtReceive_TextChanged(object sender, EventArgs e)
{
}
private void tabPage3_Click(object sender, EventArgs e)
{
}
private void button7_Click(object sender, EventArgs e)
{
status_num = 7;
timer1.Start();
textBox10.Text = star.ToString();
String str1 = "FF 55 00 00 02 04 00 00 87";
byte[] data = getBytesFromString(str1);
com.Write(data, 0, data.Length);
textBox14.Text = str1;
}
private void button8_Click(object sender, EventArgs e)
{
status_num = 8;
timer1.Stop();
textBox12.Text = stop.ToString();
}
private void button7_Click_1(object sender, EventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button6_Click(object sender, EventArgs e)
{
txtSend.Text = "";
txtReceive.Text = "";
status_num = 6;
//-------------0---------1---------2---------3--
//-------------012345678901234567890123456789
String str1 = "FF 55 00 00 03 03 01 00 CF F1";
str1 = str1.Remove(21, 2);
str1 = str1.Insert(21, comboBox1.Text); //获取块地址
byte[] temdata1 = getBytesFromString(str1);//转换字节,准备CRC16校验
//-----------------------------------------------
int num_len1 = 6;//前2个字节FF 55不加入CRC校验
int num_len2 = 6;//后2个字节50 74是校验位
String str2 = str1.Substring(num_len1, str1.Length - num_len1 - num_len2);
byte[] temdata2 = getBytesFromString(str2);
byte[] temdata3 = crc16(temdata2, temdata2.Length);//CRC校验
temdata1[temdata1.Length - 2] = temdata3[1];//填充校验位
temdata1[temdata1.Length - 1] = temdata3[0];
//-----------------------------------------------
com.Write(temdata1, 0, temdata1.Length); //发到串口
txtSend.Text = getStringFromBytes(temdata1);//显示
}
}
}
五、总结
通过本文的介绍,我们了解了如何使用C#编程语言来开发一个低频门禁卡系统。该系统涵盖了硬件设置、软件准备、编程代码以及系统操作等方面的内容。在实际开发中,我们可以根据具体需求进行功能扩展和优化。希望本文能对读者在低频门禁卡系统开发方面提供一些参考和帮助。