辜渝傧

13037102709

027-87870986

教学实训

您当前的位置:首页 > 教学资源 > 实训方案 >

RFID实训|13.56M读卡电路搭建和程序实训

发布者:唯众    布时间:2020-12-02 15:23:19    点击量:

电路搭建
13.56M读卡电路搭建



程序实现

#include "OSAL.h"
#include "AF.h"
#include "ZDApp.h"
#include "ZDObject.h"
#include "ZDProfile.h"
#include "GenericApp.h"
#include "DebugTrace.h"
#if !defined( WIN32 )
#include "OnBoard.h"
#endif
/* HAL */
#include "hal_oled_chinese.h"
// This list should be filled with Application specific Cluster IDs.
const cId_t GenericApp_ClusterList[GENERICAPP_MAX_CLUSTERS] =
{
         GENERICAPP_CLUSTERID
};
 
const SimpleDescriptionFormat_t GenericApp_SimpleDesc =
{
         GENERICAPP_ENDPOINT,              //  int Endpoint;
         GENERICAPP_PROFID,                //  uint16 AppProfId[2];
         GENERICAPP_DEVICEID,              //  uint16 AppDeviceId[2];
         GENERICAPP_DEVICE_VERSION,        //  int   AppDevVer:4;
         GENERICAPP_FLAGS,                 //  int   AppFlags:4;
         GENERICAPP_MAX_CLUSTERS,          //  byte  AppNumInClusters;
         (cId_t *)GenericApp_ClusterList,  //  byte *pAppInClusterList;
         GENERICAPP_MAX_CLUSTERS,          //  byte  AppNumInClusters;
         (cId_t *)GenericApp_ClusterList   //  byte *pAppInClusterList;
};
 
RfPacket_t RfTx,RfRx;
 
uint8 *IeeeAddr;//物理地址
// This is the Endpoint/Interface description.  It is defined here, but
// filled-in in GenericApp_Init().  Another way to go would be to fill
// in the structure here and make it a "const" (in code space).  The
// way it's defined in this sample app it is define in RAM.
endPointDesc_t GenericApp_epDesc;
 
uint8 Str1[16],Str2[16],BlockData[16];
uint8 NfcWakeup[24]={0x55,0x55,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x03,0xFD,0xD4,0x14,0x01,0x17,0x00};
uint8 NfcDetect[11]={0x00,0x00,0xFF,0x04,0xFC,0xD4,0x4A,0x01,0x00,0xE1,0x00};//配置 106 kbps type A (ISO/IEC14443 Type A)
uint8 NfcVerifyKeyA[22]={0x00,0x00,0xFF,0x0F,0xF1,0xD4,0x40,0x01,0x60,0x03,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x94,0x8A,0x3B,0x0B,0x2A,0x00};//密码授权,验证KeyA
uint8 NfcReadBlock[12]={0x00,0x00,0xFF,0x05,0xFB,0xD4,0x40,0x01,0x30,0x02,0xB9,0x00};//默认 读 02区的16个字节
uint8 NfcWriteBlock[28]={0x00,0x00,0xFF,0x15,0xEB,0xD4,0x40,0x01,0xA0,0x02,0xff,0xff,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0xD1,0x00};//默认往 02区写 16个字节的第一个字节
 
uint16 Dht11Value;
enum
{
         NFC_ACK = 0,
         NFC_WAKEUP,
         NFC_DETECT,
         NFC_VARIFY,
         NFC_READ,
         NFC_WRITE
};
char* StrNfc[]={"NFCCMD","WAKEUP","DETECT","VERIFY","READ","WRITE"};
uint16 ShortAddr=0;
#define RX_DUMP            6
u8 RxBuffer1[MT_UART_RX_BUFF_MAX];
u8 flag_nfc_status;
u8 flag_rev_finish=0;    //1为接收完成
u8 flag_rev_count=0;      //通讯次数
u8 flag_rev_cmd=0;                  //通讯的命令
u8 UID[4];                                   //存储 UID
u8 UID_backup[4];           //UID备份  用于处理 不连续写同一卡
u8 tmp;
uint8 SensorId;
uint16 Dht11Value;
byte GenericApp_TaskID;   // Task ID for internal task/event processing
devStates_t GenericApp_NwkState;
byte GenericApp_TransID;  // This is the unique message ID (counter)
afAddrType_t GenericApp_DstAddr;
 
static void GenericApp_ProcessZDOMsgs( zdoIncomingMsg_t *inMsg );
static void GenericApp_HandleKeys( byte shift, byte keys );
static void GenericApp_MessageMSGCB( afIncomingMSGPacket_t *pckt );
static void GenericApp_SendTheMessage( void );
 
#if defined( IAR_ARMCM3_LM )
static void GenericApp_ProcessRtosMessage( void );
#endif
 
void GenericApp_Init( uint8 task_id )
{
         GenericApp_TaskID = task_id;
         GenericApp_NwkState = DEV_INIT;
         GenericApp_TransID = 0;
         // Device hardware initialization can be added here or in main() (Zmain.c).
         // If the hardware is application specific - add it here.
         // If the hardware is other parts of the device add it in main().
         halUARTCfg_t uartConfig;                           //定义个串口结构体
         uartConfig.configured = TRUE;                 //串口配置为真
         uartConfig.baudRate = HAL_UART_BR_115200;
         //波特率为9600
         uartConfig.flowControl = FALSE;               //流控制为假
         HalUARTOpen(HAL_UART_PORT_0,&uartConfig);
         init_buzzer();  
         init_key();        
         //初始化oled显示屏
         oled_initial();  
         oled_disp_string(1,1,"武汉唯众智创科技");
         oled_disp_string(3,1,"有限公司");
         Delay_ms(1000);
         SensorId = 13; 
         GenericApp_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;//单播
         GenericApp_DstAddr.endPoint = GENERICAPP_ENDPOINT;
         GenericApp_DstAddr.addr.shortAddr = 0x0000;//向协调器单播
         // Fill out the endpoint description.
         GenericApp_epDesc.endPoint = GENERICAPP_ENDPOINT;
         GenericApp_epDesc.task_id = &GenericApp_TaskID;
         GenericApp_epDesc.simpleDesc
                   = (SimpleDescriptionFormat_t *)&GenericApp_SimpleDesc;
         GenericApp_epDesc.latencyReq = noLatencyReqs;
        
         // Register the endpoint description with the AF
         afRegister( &GenericApp_epDesc );
        
         // Register for all key events - This app will handle all key events
         RegisterForKeys( GenericApp_TaskID );
        
         // Update the display
#if defined ( LCD_SUPPORTED )
         HalLcdWriteString( "GenericApp", HAL_LCD_LINE_1 );
#endif
         ZDO_RegisterForZDOMsg( GenericApp_TaskID, End_Device_Bind_rsp );
         ZDO_RegisterForZDOMsg( GenericApp_TaskID, Match_Desc_rsp );
#if defined( IAR_ARMCM3_LM )
         // Register this task with RTOS task initiator
         RTOS_RegisterApp( task_id, GENERICAPP_RTOS_MSG_EVT );
#endif
         sprintf(Str1,"ZID:%2d SID:%2d",GENERICAPP_ENDPOINT,SensorId);
         oled_clear_screen();
         oled_disp_string(1,1,Str1);      
 
}
void CleanBuffer(u16 num,u8 ch)//清零 前 多少个字节的数据
{
    u16 i=0;   
    for(i=0;i<num;i++)
    RxBuffer1[i]=ch;
}
u8 NfcReceiveAck(void)
{
         CleanBuffer(RX_DUMP,0);
         if(6==HalUARTRead(0,RxBuffer1,RX_DUMP)){
                   if(RxBuffer1[0]==0x00&&RxBuffer1[1]==0x00&&RxBuffer1[2]==0xFF&&
                      RxBuffer1[3]==0x00&&RxBuffer1[4]==0xFF&&RxBuffer1[5]==0x00){
                            return 0;  
                   }
         }
         HalUARTRead(0,RxBuffer1,sizeof(RxBuffer1));
         return 1;
}
void NfcReceive(uint8 imLen,uint8 imCmd)
{
         uchar readLen=0;
         u8 i;
    u8 CheckCode=0; //数据校验码
    u8 temp=0;
         CleanBuffer(sizeof(RxBuffer1),'*');
         readLen = HalUARTRead(0,RxBuffer1,imLen);
         if(readLen==imLen){
                   for(i=11-RX_DUMP;i<imLen-2;i++){
                            temp+=RxBuffer1[i];
                   }
                   CheckCode=0x100-temp;
                   if(CheckCode!=RxBuffer1[imLen-2]){
//PC->PN532:
//    00 00 FF 0F F1 D4 40 01 60 03 FF FF FF FF FF FF D5 42 76 48 B9 0
//PN532->PC:应答(间距5ms)
//    00 00 FF 00 FF 00
//PN532->PC:回复
//00 00 FF 03 FD D5 41 00 EA 00  
                            flag_rev_finish = 0;          
                   }else switch(imCmd){
                            case NFC_WAKEUP:
                                     flag_rev_finish|=(1<<imCmd);          //接收完毕,激活成功
                            break;
                            case NFC_DETECT:
                                     UID[0]=RxBuffer1[19-RX_DUMP];
                                     UID[1]=RxBuffer1[20-RX_DUMP];
                                     UID[2]=RxBuffer1[21-RX_DUMP];
                                     UID[3]=RxBuffer1[22-RX_DUMP];                                    
                                     flag_rev_finish|=(1<<imCmd);
                            break;
                            case NFC_VARIFY:                           
                                     flag_rev_finish|=(1<<imCmd);
                            break;
                            case NFC_READ:
                                     for(i=0;i<16;i++)BlockData[i]=RxBuffer1[i+14-RX_DUMP];                                         
                                     flag_rev_finish|=(1<<imCmd);
                            break;
                            case NFC_WRITE:
                                     flag_rev_finish|=(1<<imCmd);                           
                            break;
                            default:
                                     flag_rev_finish = 0;
                            break;
                   }                
         }else{
                   Delay_ms(1);
                   flag_rev_finish = 0;          
         }
}
uint8 NfcSend(uint8 cmd)
{
         uint8 temp=0,i,recLen=0;
         flag_rev_finish = 0;
         if(cmd == NFC_WAKEUP){
                   recLen = 15;
                   HalUARTWrite(0,NfcWakeup,sizeof(NfcWakeup));
         }
         if(cmd == NFC_DETECT){
                   recLen = 25;
                   HalUARTWrite(0,NfcDetect,sizeof(NfcDetect));     
         }
         if(cmd == NFC_VARIFY){
                   NfcVerifyKeyA[16]=UID[0];
                   NfcVerifyKeyA[17]=UID[1];
                   NfcVerifyKeyA[18]=UID[2];
                   NfcVerifyKeyA[19]=UID[3];
                   for(i=5;i<20;i++){
                            temp+=NfcVerifyKeyA[i];
                   }       
                   NfcVerifyKeyA[20]=0x100-temp;   //数据 校验   0x100-   
                   NfcVerifyKeyA[21]=0x00;                  
                   recLen = 16;
                   HalUARTWrite(0,NfcVerifyKeyA,sizeof(NfcVerifyKeyA));          
         }
         if(cmd == NFC_READ){    
                   recLen = 32;             
                   HalUARTWrite(0,NfcReadBlock,sizeof(NfcReadBlock));  
         }
         if(cmd == NFC_WRITE){
                   recLen = 16;             
                   for(i=5;i<26;i++){
                            temp+=NfcWriteBlock[i];
                   }
                   NfcWriteBlock[26]=0x100-temp; //数据 校验码
                   NfcWriteBlock[27]=0x00;
                   HalUARTWrite(0,NfcWriteBlock,sizeof(NfcWriteBlock));        
         }       
         if(0!=NfcReceiveAck()){                       //应答不成功
                   return 2;
         }
         NfcReceive(recLen-RX_DUMP,cmd);
         oled_clear_vertical(2);
         if(flag_rev_finish&(1<<cmd)){
                   LED1 = 1;
                   if(cmd == NFC_WAKEUP){
                            sprintf(Str2,"%s success!",StrNfc[cmd]);
                   }
                   if(cmd == NFC_DETECT){
                            sprintf(Str2,"ID:%x %x %x %x",UID[0],UID[1],UID[2],UID[3]);                 
                   }
                   if(cmd == NFC_VARIFY){                     //keyA验证成功,接下来可以进行读写
                            sprintf(Str2,"%s success!",StrNfc[cmd]);
                   }                          
                   if(cmd == NFC_READ){
                            //fg_BytesToString(16,BlockData,16);
                            RfTx.Pack.Sid[0] = 13;
                        RfTx.Pack.Len=16;
                        for(i=0;i<16;i++)
                        {
                            RfTx.Pack.Data[i]=BlockData[i];
                          
                        }
                         GenericApp_SendTheMessage();
                            //free(ptr);
                   }
                   if(cmd == NFC_WRITE){
                            sprintf(Str2,"%s success!",StrNfc[cmd]);
                   }       
                   oled_disp_string(3,1,Str2);
                   return 0;
         }
         LED1 = 0;
         if(cmd == NFC_WAKEUP){
                   sprintf(Str2,"%s repeat!",StrNfc[cmd]);                   
         }else if(cmd == NFC_DETECT){
                   sprintf(Str2,"%s no card!",StrNfc[cmd]);        
         }else if(cmd == NFC_VARIFY){
                   //sprintf(Str2,"%s failed!",StrNfc[cmd]);
         }else if(cmd == NFC_READ){
                   //sprintf(Str2,"%s failed!",StrNfc[cmd]);
         }else if(cmd == NFC_WRITE){
                   //sprintf(Str2,"%s failed!",StrNfc[cmd]);
         }                                   
         oled_disp_string(3,1,Str2);
         return 1;
}
uint16 GenericApp_ProcessEvent( uint8 task_id, uint16 events )
{
         afIncomingMSGPacket_t *MSGpkt;
         afDataConfirm_t *afDataConfirm;
        
         uint16 srcSaddr;
         // Data Confirmation message fields
         byte sentEP;
         ZStatus_t sentStatus;
         byte sentTransID;       // This should match the value sent
         (void)task_id;  // Intentionally unreferenced parameter
        
         if ( events & SYS_EVENT_MSG )
         {
                   MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( GenericApp_TaskID );
                   while ( MSGpkt )
                   {
                            switch ( MSGpkt->hdr.event )
                            {
                                     case ZDO_CB_MSG:
                                     GenericApp_ProcessZDOMsgs( (zdoIncomingMsg_t *)MSGpkt );
                                     break;
                                    
                                    
                                     case AF_DATA_CONFIRM_CMD:
                                     // This message is received as a confirmation of a data packet sent.
                                     // The status is of ZStatus_t type [defined in ZComDef.h]
                                     // The message fields are defined in AF.h
                                     afDataConfirm = (afDataConfirm_t *)MSGpkt;
                                     sentEP = afDataConfirm->endpoint;
                                     sentStatus = afDataConfirm->hdr.status;
                                     sentTransID = afDataConfirm->transID;
                                     (void)sentEP;
                                     (void)sentTransID;
                                    
                                     // Action taken when confirmation is received.
                                     if ( sentStatus != ZSuccess )
                                     {
                                               // The data wasn't delivered -- Do something
                                     }
                                     break;
                                    
                                     case AF_INCOMING_MSG_CMD:
                                     GenericApp_MessageMSGCB( MSGpkt );
                                     break;
                                    
                                     case ZDO_STATE_CHANGE:
                                     GenericApp_NwkState = (devStates_t)(MSGpkt->hdr.status);
                                     if ( (GenericApp_NwkState == DEV_ZB_COORD)
                                               || (GenericApp_NwkState == DEV_ROUTER)
                                                        || (GenericApp_NwkState == DEV_END_DEVICE) )
                                     {
                                               // Start sending "the" message in a regular interval.
                                               memset(RfTx.Buf,'x',sizeof(RfPacket_t));
                                               RfTx.Pack.Head = '#';
                                              
                                               IeeeAddr = NLME_GetExtAddr();                               
                                               memcpy(RfTx.Pack.Laddr,IeeeAddr,8);                      //8个字节 本设备IEEE地址
                                               srcSaddr = NLME_GetShortAddr();                             //2个字节 本设备网络地址                           
                                               RfTx.Pack.Saddr[0] = srcSaddr;
                                               RfTx.Pack.Saddr[1] = srcSaddr>>8;
                                              
                                               RfTx.Pack.Tail = '$';
                                              
                                               osal_start_timerEx( GenericApp_TaskID,
                                                                                       GENERICAPP_SEND_WAKEUP_EVT,
                                                                                       500 );
                                     }
                                     break;
                                    
                                     default:
                                     break;
                            }
                           
                            // Release the memory
                            osal_msg_deallocate( (uint8 *)MSGpkt );
                           
                            // Next
                            MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( GenericApp_TaskID );
                   }
                  
                   // return unprocessed events
                   return (events ^ SYS_EVENT_MSG);
         }
       
       
        if(events & GENERICAPP_SEND_WAKEUP_EVT){           
                   if(NfcSend(NFC_WAKEUP)!=0){
                       
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_WAKEUP_EVT,500);
                   }else{
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_WAKEUP_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT,500);
                   }
                   return (events ^ GENERICAPP_SEND_WAKEUP_EVT);
         }
         if(events & GENERICAPP_SEND_DETECT_EVT){             
                   if(NfcSend(NFC_DETECT)!=0){
                        RfTx.Pack.Sid[0]=0;
                        GenericApp_SendTheMessage();
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT,500);
                   }else{
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_VARIFY_EVT,500); 
                   }
                   return (events ^ GENERICAPP_SEND_DETECT_EVT);
         }
         if(events & GENERICAPP_SEND_VARIFY_EVT){      
                   if(NfcSend(NFC_VARIFY)==0){ 
                        tmp=0;
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_VARIFY_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_READ_EVT,500);
                       
                   }else{
                       tmp+=1;
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_VARIFY_EVT,500); 
                   }
                if(tmp>3){
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_VARIFY_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT,500);
               
                }
                   return (events ^ GENERICAPP_SEND_VARIFY_EVT);
         }
         if(events & GENERICAPP_SEND_READ_EVT){
                   if(NfcSend(NFC_READ)==0){   
                        tmp=0;                        
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_READ_EVT,500);
                   }else{
                         tmp+=1;
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_READ_EVT,500);   
                   }
                if(tmp>3){
                        tmp=0;
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_READ_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT,500);
                }
                   return (events ^ GENERICAPP_SEND_READ_EVT);
         }
         if(events & GENERICAPP_SEND_WRITE_EVT){      
                   if(NfcSend(NFC_WRITE)==0){ 
                        osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_WRITE_EVT);
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_DETECT_EVT,500);
                   }else{
                            osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_WRITE_EVT,500); 
                   }
                   return (events ^ GENERICAPP_SEND_WRITE_EVT);
         }
        
         return 0;
}
static void GenericApp_ProcessZDOMsgs( zdoIncomingMsg_t *inMsg )
{
         switch ( inMsg->clusterID )
         {
                   case End_Device_Bind_rsp:
                   if ( ZDO_ParseBindRsp( inMsg ) == ZSuccess )
                   {
                            // Light LED
                            HalLedSet( HAL_LED_4, HAL_LED_MODE_ON );
                   }
#if defined( BLINK_LEDS )
                   else
                   {
                            // Flash LED to show failure
                            HalLedSet ( HAL_LED_4, HAL_LED_MODE_FLASH );
                   }
#endif
                   break;
                  
                   case Match_Desc_rsp:
                   {
                            ZDO_ActiveEndpointRsp_t *pRsp = ZDO_ParseEPListRsp( inMsg );
                            if ( pRsp )
                            {
                                     if ( pRsp->status == ZSuccess && pRsp->cnt )
                                     {
                                               GenericApp_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;
                                               GenericApp_DstAddr.addr.shortAddr = pRsp->nwkAddr;
                                               // Take the first endpoint, Can be changed to search through endpoints
                                               GenericApp_DstAddr.endPoint = pRsp->epList[0];
                                              
                                               // Light LED
                                               HalLedSet( HAL_LED_4, HAL_LED_MODE_ON );
                                     }
                                     osal_mem_free( pRsp );
                            }
                   }
                   break;
         }
}
void InitIrCmd(uchar* ieBuf,uchar d0,uchar d1,uchar d2,uchar d3)
{
         ieBuf[0] = d0;
         ieBuf[1] = d1;
         ieBuf[2] = d2;
         ieBuf[3] = d3;
        
         ieBuf[4] = d0^d1^d2^d3;
}
static void GenericApp_MessageMSGCB( afIncomingMSGPacket_t *pkt ) {
RfPacket_t rf;
u8 i;
switch ( pkt->clusterId )
{
                   case GENERICAPP_CLUSTERID:
                   osal_memcpy(rf.Buf,pkt->cmd.Data,sizeof(RfPacket_t));
                if(rf.Pack.Head=='#'&&rf.Pack.Tail=='$')
                {
                      if(rf.Pack.Sid[0] == 13)
                      {
                              for(i=0;i<16;i++)
                              {
                                NfcWriteBlock[10+i]=rf.Pack.Data[i];
                               
                              }
                              osal_stop_timerEx( GenericApp_TaskID,GENERICAPP_SEND_READ_EVT);
                              osal_start_timerEx( GenericApp_TaskID,GENERICAPP_SEND_WRITE_EVT,500);
                      }            
                      break;
                }
         }
}
static void GenericApp_SendTheMessage( void )
{
         SENSOR_FUNC func;
         uint8 temp=0;
         char charbuf[15] = "KeyName:";
         uint8* ptr = NULL;
         RfTx.Pack.Sid[1] = ' ';
         RfTx.Pack.Cmd[0] = 'B';
         RfTx.Pack.Cmd[1] = 'R';
         if ( AF_DataRequest( &GenericApp_DstAddr, &GenericApp_epDesc,
                                                        GENERICAPP_CLUSTERID,
                                                        sizeof(RfPacket_t),
                                                        (byte *)&RfTx.Buf,
                                                        &GenericApp_TransID,
                                                        AF_DISCV_ROUTE, AF_DEFAULT_RADIUS ) == afStatus_SUCCESS )
         {
                   // Successfully requested to be sent.
         }
         else
         {
                   // Error occurred in request to send.
         }
}



上一篇:RFID实训|13.56M读卡之技术介绍

下一篇:RFID实训|第二部分 综合实验——智能门禁系统