#include <stdio.h>
#include <assert.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <netdb.h>
#include <string.h>
#include <strings.h>
void BCC(char a[])
{
int len = a[0];
int bcc = 0;
int i =0;
for( i=0; i<a[0]-2; i++)
{
bcc ^= a[i];
}
a[a[0]-2] = ~bcc;
}
int get_cardid()
{
int fd = open("/dev/ttySAC1", O_RDWR);
if(fd == -1)
{
perror("打开串口失败");
exit(0);
}
//配置串口
struct termios cfg;
bzero(&cfg, sizeof(cfg));
//设置8位数据域+无奇偶校验
cfmakeraw(&cfg);
//设置波特率
cfsetispeed(&cfg, B9600);
cfsetospeed(&cfg, B9600);
//设置1停止位+1起始位
cfg.c_cflag &= ~CSTOPB;
// CLOCAL和CREAD分别用于本地连接和接受使能
// 首先要通过位掩码的方式激活这两个选项。
cfg.c_cflag |= (CREAD | CLOCAL);
//阻塞读操作(超时)
cfg.c_cc[VTIME] = 0; //单位0.1秒
cfg.c_cc[VMIN] = 1; //当有1个字符可读时,read成功返回
// 清空输入/输出缓冲区
tcflush (fd, TCIFLUSH);
tcflush (fd, TCOFLUSH);
// 使用指定的属性立刻配置串口
int ret = tcsetattr(fd, TCSANOW, &cfg);
if(ret != 0)
{
perror("设置串口属性失败");
exit(0);
}
//这个数组用来接收串口返回的消息
char response[100];
while(1)
{
// 发送请求指令
char detect[] = {0x07,
0x02,
0x41,
0x01,
0x52,
0x00, // BCC校验码
0x03};
BCC(detect);//配置校验码
write(fd, detect,7);//发送请求命令
bzero(response, 100);//清空用来接收回馈的数组
read(fd, response, 100);//把这个数组用来接收读卡器发回的信息
// 如果没有探测到卡片在附近,那么重新发送探测指令
if(response[2] != 0x00)//探测失败,说明没有卡在
{
usleep(10*1000);//延时0.01秒
fprintf(stderr, ".");
continue;
}
//printf("探测到卡片在附近!!\n");
// 编写防碰撞的命令
char PiccAnticoll[] = {0x08,
0x02,
0x42,
0x02,
0x93,
0x00,
0x00, // BCC校验码
0x03};
BCC(PiccAnticoll);
write(fd, PiccAnticoll,8);//发送给串口,这是获取卡号的命令
bzero(response, 100);//清空用来接收回馈的数组
read(fd, response, 100);//把这个数组用来接收读卡器发回的信息
// 如果没有探测到卡片在附近,那么重新发送探测指令
if(response[2] != 0x00)
{
printf("获取卡号失败!\n");
continue;
}
printf("卡号: %#hhx%hhx%hhx%hhx\n",
response[7],
response[6],
response[5],
response[4]);
int id = response[7]<<24 | response[6] << 16 |response[5]<<8 |response[4];
printf("%d\n", id);
return(id);
}
return 0;
}
RC522读卡
最新推荐文章于 2025-04-12 22:32:27 发布