refer the code and give me any correction required. i am using rl78 controller in e2studio ccrl. i am planning to read rfid and send teh data to another device, via bit banging, main.c code  '
/***********************************************************************************************************************
 * DISCLAIMER
 * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products.
 * No other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
 * applicable laws, including copyright laws.
 * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED
 * OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NON-INFRINGEMENT.  ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY
 * LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE FOR ANY DIRECT,
 * INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR
 * ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability
 * of this software. By using this software, you agree to the additional terms and conditions found by accessing the
 * following link:
 * http://www.renesas.com/disclaimer
 *
 * Copyright (C) 2011, 2024 Renesas Electronics Corporation. All rights reserved.
 ***********************************************************************************************************************/

/***********************************************************************************************************************
 * File Name    : r_main.c
 * Version      : CodeGenerator for RL78/G13 V2.05.08.02 [03 Jun 2024]
 * Device(s)    : R5F140PL
 * Tool-Chain   : CCRL
 * Description  : This file implements main function.
 * Creation Date: 13/03/2025
 ***********************************************************************************************************************/

/***********************************************************************************************************************
Includes
 ***********************************************************************************************************************/
#include "r_cg_macrodriver.h"
#include "r_cg_cgc.h"
#include "r_cg_port.h"
#include "r_cg_intc.h"
#include "r_cg_serial.h"
#include "r_cg_adc.h"
#include "r_cg_timer.h"
/* Start user code for include. Do not edit comment generated here */
#include <string.h>
#include "r_cg_userdefine.h"
#include "rfid_uart.h"
/* End user code. Do not edit comment generated here */
#include "r_cg_userdefine.h"

/***********************************************************************************************************************
Pragma directive
 ***********************************************************************************************************************/
/* Start user code for pragma. Do not edit comment generated here */
#define MISPA_I2 0
#define INPUT 0
#define OUTPUT 1
#define LOW 0
#define HIGH 1
#define UART_BUFFER_SIZE 700  // Define buffer size
#define DEBUG_ENABLE 0
#define ERASE_RFID 0
#define TEMP_BUFF_ENABLE 0
#define GENRIC_NO_ERROR         (0x0000)   // indicate Success of Operation
#define LENGTH_ERROR            (0xFF01)   // Length/Bcc Error
#define AUTHNTICATE_ERROR       (0xFF02)   // Authenticate Error
#define READ_ERROR              (0xFF03)   // Read Error
#define INVALID_DATA_LENGTH     (0xFF07)   // Invalid Data Length
#define GENRIC_ERROR            (0xFFFF)   // Indicate Any other error
#define CARD_TYPE_NIL           0   // Indicate Any other error
#define CARD_TYPE_RFID          1   // Indicate Any other error
#define CARD_TYPE_SMARTCARD     2   // Indicate Any other error
#define MAX_BUFFER_SIZE 512

/* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
Global variables and functions
 ***********************************************************************************************************************/
/* Start user code for global. Do not edit comment generated here */
char Sw_state=0;
uint8_t u_n8RFIDDataZoneAll[512];

#if TEMP_BUFF_ENABLE
/*TEST DATA TO LOAD DATA FROM BUFFER*/
//Read,from,card,Zone,6,Address,0,No,of,Bytes,128
uint8_t tempData6[]={0x95,0xC9,0x87,0x67,0x8B,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x03,0x91,0x00,0x02,0x00,0x03,0x00,0x05,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x01,0x03,0x00,0x05,0x01,0x00,0x03,0x00,0x00,0x00,0x0F,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x87,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x2D,0x00,0x00,0x30,0x30,0x30,0x33,0x32,0x33,0x30,0x39,0x34,0x37,0x30,0x35,0x31,0x32,0x32,0x30,0x32,0x35,0x00,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
//Read,from,card,Zone,7,Address,0,No,of,Bytes,128
uint8_t tempData7[]={0x03,0x01,0x00,0x01,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x01,0x87,0xD3,0xC7,0xE5,0xE5,0xCF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00};
//Read,from,card,Zone,8,Address,0,No,of,Bytes,128
uint8_t tempData8[]={0xFF,0x00,0x00,0x00,0x0A,0x65,0x33,0x33,0x8F,0x56,0xFE,0x00,0x12,0x6E,0x15,0xC0,0xFF,0x00,0x00,0x00,0x02,0x40,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x0A,0x65,0x33,0x33,0x8F,0x56,0xFE,0x00,0x12,0x6E,0x15,0xC0,0xFF,0x00,0x00,0x00,0x02,0x40,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x09,0x66,0x01,0x47,0x8C,0x7A,0x9E,0x66,0x0E,0x7F,0xA8,0x66,0xFF,0x00,0x00,0x00,0x02,0x40,0x00,0x00,0x41,0x4C,0xCC,0xCC,0xFF,0x00,0x00,0x00,0x0A,0x41,0xF5,0x1E,0x8D,0x46,0xE3,0x33,0x0E,0x6E,0x7A,0x00,0xFF,0x00,0x00,0x00,0x02,0x40,0x00,0x00,0x80,0x4C,0xCC,0xCC,0x00,0x00,0x00,0x41,0x00,0x00,0x0B,0xC6,0x00,0x00,0x21,0xCA,0xFF,0xFF,0xFF,0xFF};
//Read,from,card,Zone,9,Address,0,No,of,Bytes,128
uint8_t tempData9[]={0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x09,0x4B,0x00,0x00,0x02,0x46,0x66,0x66,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x09,0x4B,0x00,0x00,0x02,0x4C,0xCC,0xCC,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF};
/*END TEST BUFFER*/
#endif
uint8_t u_n8RFIDWrite[20];
int nDataLength=0;
extern uint16_t count_ms;// declare same variable like in timer_user function
extern uint8_t RxBuffer[700] ;
extern uint8_t ReceivedData[640];
extern volatile uint16_t u_n16TimeCounter;
extern volatile _Bool bWriteStart;
extern volatile uint8_t ZoneNumber;
extern volatile uint8_t NumberByte;
extern volatile uint8_t StartAddress;
extern volatile uint16_t StartBufferAddress;
extern volatile uint8_t WriteAddress;
extern volatile uint8_t Testleft_0th;
extern volatile uint8_t Testleft_1th;
extern volatile uint8_t Usedcard;
extern volatile uint8_t UsedcardDate;
extern volatile uint8_t UsedcardMonth;
extern volatile uint8_t UsedcardYear;
extern volatile uint8_t u_n8RFIDPresence;
extern volatile uint16_t u_n8RfidCheckCounter;
extern volatile uint8_t RFIDReadSuccess;
extern volatile uint32_t TempCount;
extern volatile uint8_t u_n8DataWaitOver;
extern volatile uint8_t u_n8RFIDChekInterrupt;
extern char buffer[];  // Buffer to hold ASCII representation
extern volatile _Bool bDataReceived;

volatile uint16_t TemporyLength = 0x0000;
volatile uint16_t CheckRFIDReplaced=0;
volatile uint8_t uart_rx_buffer[UART_BUFFER_SIZE]; // Global buffer for received UART data
volatile uint8_t uart_rx_index = 0;  // Buffer index
volatile uint8_t u_n8RFIDSense=0;
volatile uint8_t uart_data_ready = 0; // Flag for received data

char Flag1=0; // Buffer to hold ASCII representation
extern volatile uint8_t rx_data;
volatile uint8_t uart_rx_byte = 0;


int u_n8Count=0;
int u_n16Count=0;
int n16Count=0;
int i=0;
int bit = 0;
uint16_t ADC_Value=0;
uint16_t ADC_TEMP=0;
uint8_t ADC_FLAG=0;
uint8_t RfidFlag=0;
uint8_t Tx_buffer[30]={0};
uint8_t BCC=0;
uint16_t timeout;
uint8_t bitMaskNew;
uint8_t Data=0;
uint16_t DataValidity(uint8_t *OutBuffer, uint16_t Read_Data_Length);
uint16_t IsValidBCC(uint8_t *Data);
uint16_t WriteRFID(const char Data[]);
uint8_t bitwise_xor(uint8_t a, uint8_t b);
uint16_t Get_ADCStepValue(uint8_t channel);
uint8_t P41_SDA_Read(void);
uint8_t P47_SCL_Read(void);
void ReadRFID(void);
void ValiadteAndFillZone(void);

void R_MAIN_UserInit(void);
void delay(long d);
void TimerdelayMs(uint16_t delay);
void P47_SCL_Direction(_Bool INorOUT);
void P41_SDA_Direction(_Bool INorOUT);
void P41_SDA_Write(_Bool HighOrLow);
void P47_SCL_Write(_Bool HighOrLow);
void SDAAcknowledgement(void);
void SDAAcknowledgementDefault(void);
void SDAReadAcknowledgement(void);
void UART_SendString(const char *str);
static void BitDelay(void);
void Stable_ACK_Sequence(void);

/* End user code. Do not edit comment generated here */
void R_MAIN_UserInit(void);

/***********************************************************************************************************************
 * Function Name: main
 * Description  : This function implements main function.
 * Arguments    : None
 * Return Value : None
 ***********************************************************************************************************************/

void main(void)
{
	R_MAIN_UserInit();
	/* Start user code. Do not edit comment generated here */


	R_INTC3_Start(); // Enable external interrupt 3
	R_INTC6_Start(); // Enable external interrupt 6
	R_UART1_Start(); // Start UART0 for communication
	//R_UART0_Start(); // Start UART0 for communication

	u_n16TimeCounter=0;
	bWriteStart=0;
	bDataReceived=0;
	TempCount=0;
	memset(u_n8RFIDDataZoneAll,0,sizeof(u_n8RFIDDataZoneAll));
	P2 &= ~(1 << 4); // TURN OFF BUZZ (optional)
	P1 |= (1 << 4);    //  HIGH SNS

	while (1U)
	{
		//Sw_state=((P5&(1<<1))>>1);


		//if (Sw_state == 1)
		//{

			P1 |= (1 << 7);    // TURN ON GLED
			//        P2 |= (1 << 4);  // TURN ON BUZZ (optional)
			//P2 &= ~(1 << 4);
			P1 &= ~(1 << 6);   // TURN OFF RLED

			P2 &= ~(1 << 5);  // TURN ON RFID MOSFET DRIVE
			P14 &= ~(1 << 7);  // MUX SEL = LOW (RFID Mode/Read Smart Card)

			// Check if new data has been received
			if(bDataReceived==1)
			{
				R_TAU0_Channel2_Start(); //TIMER INTERRUPT START
				R_INTC6_Stop();				// Disable external interrupt 3
				u_n8RfidCheckCounter=1;
				if(bWriteStart==0)
				{
					SDAAcknowledgement();// Send acknowledgement
						delay(4);
					SDAAcknowledgementDefault();
//					Stable_ACK_Sequence();
					bDataReceived=0;
				}
				else
				{
					if(RFIDReadSuccess==1)
					{
						SDAAcknowledgement();// Send acknowledgement
						SDAReadAcknowledgement();
						__nop();
						u_n16Count=StartBufferAddress;
						//					u_n16Count=0;
						// Loop through and process received RFID data
						if(WriteAddress==54)
						{
							uint16_t initialCount = ((uint16_t)u_n8RFIDDataZoneAll[54] << 8) | u_n8RFIDDataZoneAll[55];
							uint16_t newCount = ((uint16_t)Testleft_1th << 8) | Testleft_0th;

							// Validate count: new must be exactly one less than initial
							if (initialCount == 0 || newCount != (initialCount - 1))
							{
								UART_SendString(" TC_ER ");  // Error: mismatch
								return;
							}

							UART_SendString(" TC_OK ");  // OK: valid transition  // Count OK, update rfid
							SDAAcknowledgementDefault();
							WriteAddress=0;
							u_n8RFIDDataZoneAll[55]=Testleft_0th;
							u_n8RFIDDataZoneAll[54]=Testleft_1th;
							u_n8RFIDWrite[0]=Testleft_1th;
							u_n8RFIDWrite[1]=Testleft_0th;
							u_n8RFIDWrite[2]=1;
							SDAReadAcknowledgement();


#if DEBUG_ENABLE
							UART_SendString("WTN");
#endif
							// Prepare transmission buffer
							Tx_buffer[0] = 0x00;
							Tx_buffer[1] = 0x18;
							Tx_buffer[2] = 0x2F;
							Tx_buffer[3] = 0x0C;
							for(u_n8Count = 0;u_n8Count < 20 ; u_n8Count++)
							{
								Tx_buffer[u_n8Count+4] = u_n8RFIDWrite[u_n8Count];             // stcSmartCardData.u_n32OpenDate;
							}
							// Compute and append checksum
							BCC = Tx_buffer[0];
							for (u_n8Count = 1; u_n8Count < Tx_buffer[1];u_n8Count++)
								BCC ^= Tx_buffer[u_n8Count];
							Tx_buffer[24] = BCC;
#if DEBUG_ENABLE
							R_UART1_Send((uint8_t *)"W", 1);  // Sends character 'W'
#endif
							R_UART1_Send(Tx_buffer,25);
							delay(10000);
							u_n8DataWaitOver=0;
							R_UART1_Receive(&RxBuffer[0],6);
							while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
							u_n8DataWaitOver=0;
#if DEBUG_ENABLE

							R_UART1_Send((uint8_t *)"C", 1);  // Sends character 'C'
							sprintf(buffer, "RWR: %d",RxBuffer[0]);//RFID WRITE RESPONSE
							UART_SendString(buffer);
#endif

						}
						else if(WriteAddress==92)
						{
							SDAAcknowledgementDefault();
							WriteAddress=0;
							u_n8RFIDDataZoneAll[220]=Usedcard;
							u_n8RFIDWrite[3]=1;
#if DEBUG_ENABLE

							UART_SendString("W");// Prepare transmission buffer
#endif
							Tx_buffer[0] = 0x00;
							Tx_buffer[1] = 0x18;
							Tx_buffer[2] = 0x2F;
							Tx_buffer[3] = 0x0C;
							for(u_n8Count = 0;u_n8Count < 20 ; u_n8Count++)
							{
								Tx_buffer[u_n8Count+4] = u_n8RFIDWrite[u_n8Count];             // stcSmartCardData.u_n32OpenDate;
							}
							// Compute and append checksum
							BCC = Tx_buffer[0];
							for (u_n8Count = 1; u_n8Count < Tx_buffer[1];u_n8Count++)
								BCC ^= Tx_buffer[u_n8Count];
							Tx_buffer[24] = BCC;
#if DEBUG_ENABLE

							R_UART1_Send((uint8_t *)"U", 1);  // Sends character 'W'
#endif
							R_UART1_Send(Tx_buffer,25);
							delay(10000);
							u_n8DataWaitOver=0;
							R_UART1_Receive(&RxBuffer[0],6);
							while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
							u_n8DataWaitOver=0;
#if DEBUG_ENABLE
							sprintf(buffer, "C: %d",RxBuffer[0]);//RFID WRITE RESPONSE
							UART_SendString(buffer);
#endif
							//						break;

						}
						else if(ZoneNumber>5&&ZoneNumber<10)
						{
							for(u_n8Count=0;u_n8Count<NumberByte;u_n8Count++)
							{
								bitMaskNew = 0x80;
								do
								{
									P41_SDA_Write(u_n8RFIDDataZoneAll[u_n16Count] & bitMaskNew);
									// Wait for the clock signal (handled externally)
									while (!((P3 >> 0) & 1)); // Wait for clock high
									while (((P3 >> 0) & 1));  // Wait for clock low
									bitMaskNew >>= 1;
								}while(bitMaskNew > 0);
								u_n16Count++;
//								bitMaskNew = 0x80;
								//							PacketByteWriteZone8(u_n16Count++);
								// Send acknowledgement for each packet
								if(u_n8Count < 127)
									SDAReadAcknowledgement();
							}
							ZoneNumber=0;
						}
						StartAddress=0;
						NumberByte=0;
						// Reset zone number if needed
						if((ZoneNumber>=6)&&(ZoneNumber<=13))
						{
							ZoneNumber=0;
						}
#if DEBUG_ENABLE
						R_UART1_Send((uint8_t *)"*", 1);  // Sends character 'W'
#endif
					}
					delay(2);
#if DEBUG_ENABLE
					R_UART1_Send((uint8_t *)"#", 1);  // Sends character 'W'
#endif
					SDAAcknowledgementDefault();
					bWriteStart=0;
					bDataReceived=0;
				}
				WriteAddress=0;
				R_TAU0_Channel2_Stop(); //TIMER INTERRUPT STOP
				R_INTC6_Start();// EXTI
				bDataReceived=0;
			}

			if(u_n8RFIDChekInterrupt==CARD_TYPE_RFID)
			{
#if DEBUG_ENABLE
				R_UART1_Send((uint8_t *)"R", 1);  // Sends character 'b'
#endif
				R_INTC3_Stop();
				u_n8RFIDChekInterrupt=0;
				P1=P1&(~(1<<6));//Turn ON on board LED
				//ReadRFID();
				//ValiadteAndFillZone();

															Tx_buffer[0] = 0x00;
															Tx_buffer[1] = 0x04;
															Tx_buffer[2] = 0x2F;
															Tx_buffer[3] = 0x0D;
															Tx_buffer[4] = 0x26;
															R_UART1_Send(Tx_buffer,5);
															delay(10000);
												#if DEBUG_ENABLE
															R_UART1_Send((uint8_t *)"F", 1);  // Indicate data processing
												#endif
															u_n8DataWaitOver=0;
															nDataLength =0;
															R_UART1_Receive(&RxBuffer[0],1);
															while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
															u_n8DataWaitOver=0;
															R_UART1_Receive(&RxBuffer[1],1);
															while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
															nDataLength =  (RxBuffer[0]<<8)+RxBuffer[1] ; // Extract total data length from received buffer
															u_n8DataWaitOver=0;
															R_UART1_Receive(&RxBuffer[2],1);
															while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
															u_n8DataWaitOver=0;
												//			nDataLength>651
															R_UART1_Receive(&RxBuffer[3],nDataLength-2);
															delay(400000);//wait delay000000);//wait delay
															while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
			R_UART1_Send((uint8_t *)"I", 1);  // Indicate data processing

			#if DEBUG_ENABLE
						R_UART1_Send((uint8_t *)"I", 1);  // Indicate data processing
			#endif
						if(GENRIC_NO_ERROR==DataValidity(ReceivedData,640))
						{
							if(ReceivedData[0]==2)
							{
								//memset(u_n8RFIDDataZoneAll,0,sizeof(u_n8RFIDDataZoneAll));
								// Copy received data into respective zones
								for (i = 0; i < 512; i++)
								{
									u_n8RFIDDataZoneAll[i]= ReceivedData[i + 1];
								}
								if(ReceivedData[623]==0)//!check for not used RFID
								{
									if(ReceivedData[622]==1)//!check for fresh RFID
									{
										u_n8RFIDDataZoneAll[55]=ReceivedData[621];//Testleft_0th
										u_n8RFIDDataZoneAll[54]=ReceivedData[620];//Testleft_1th
									}
									else
									{
										//!fresh rfid
									}
								}
								else
								{
									if(ReceivedData[622]==1)//!check for fresh RFID
									{
										u_n8RFIDDataZoneAll[55]=ReceivedData[621];//Testleft_0th
										u_n8RFIDDataZoneAll[54]=ReceivedData[620];//Testleft_1th
									}
									//!enable this for used card
									u_n8RFIDDataZoneAll[220]=1;
								}
								RFIDReadSuccess=1; // Indicate RFID data ready
								P1 &= ~(1 << 4);//LOW

								u_n8RFIDChekInterrupt=0;
			#if DEBUG_ENABLE
								R_UART1_Send((uint8_t *)"D", 1);   // Indicate RFID data ready
			#endif
							}
							else if(ReceivedData[0]==1)
							{
								RFIDReadSuccess=1;
								u_n8RFIDChekInterrupt=CARD_TYPE_NIL;
							}

							for(n16Count=0;n16Count<20;n16Count++)
							{
								u_n8RFIDWrite[n16Count]=ReceivedData[620+n16Count];
							}
			#if ERASE_RFID
							// Clear RFID Write area

							Tx_buffer[0] = 0x00;
							Tx_buffer[1] = 0x18;
							Tx_buffer[2] = 0x2F;
							Tx_buffer[3] = 0x0C;
							for(u_n8Count = 0;u_n8Count < 20 ; u_n8Count++)
							{
								Tx_buffer[u_n8Count+4] =0;             // stcSmartCardData.u_n32OpenDate;
							}
							BCC = Tx_buffer[0];
							for (u_n8Count = 1; u_n8Count < Tx_buffer[1];u_n8Count++)
								BCC ^= Tx_buffer[u_n8Count];
							Tx_buffer[24] = BCC;

							R_UART1_Send(Tx_buffer,25);
							delay(10000);
							UART_SendString("RFID_Erased");

			#endif
							//!RFID Success
						}

				/* Clear RFID Write area */
				memset(Tx_buffer,0,sizeof(Tx_buffer));
				memset(ReceivedData,0,sizeof(ReceivedData));
				memset(RxBuffer,0,sizeof(RxBuffer));
				R_INTC3_Start();
			}
			//		TempCount++;
		//}// SW STATUS
		else
		{
			//        P14 |= (1 << 6);   // MUX EN = HIGH (Pullup is in hardware default ON)
			P14 |= (1 << 7);   // MUX SEL = HIGH (By pass Smart card)
			//        Redundant: P14 &= ~(1 << 6); // This line disables MUX again (conflict!) — REMOVE this line

			P1 &= ~(1 << 7);   // TURN OFF GLED
			//        P2 &= ~(1 << 4); // TURN OFF BUZZ (optional)
			//P1 |= (1 << 6);    // TURN ON RLED
			//P2 |= (1 << 5);    // TURN OFF RFID MOSFET DRIVE
			//P2 &= ~(1 << 5);
		}
		/* End user code. Do not edit comment generated here */
	}
}


/***********************************************************************************************************************
 * Function Name: R_MAIN_UserInit
 * Description  : This function adds user code before implementing main function.
 * Arguments    : None
 * Return Value : None
 ***********************************************************************************************************************/
void R_MAIN_UserInit(void)
{
	/* Start user code. Do not edit comment generated here */
	EI();
	/* End user code. Do not edit comment generated here */
}

/* Start user code for adding. Do not edit comment generated here */

/* Delays execution for a specified time.
   Note: This is a blocking delay and is not precise. */
void delay(long d)
{
	while(d--);
}

/* Delays execution in milliseconds using a timer-based approach. */
void TimerdelayMs(uint16_t delay)
{
	count_ms=0;
	R_TAU0_Channel2_Start();
	while(count_ms<delay);
	R_TAU0_Channel2_Stop();
}

/* Configures P47 (SCL) as input or output for I2C communication. */
void P47_SCL_Direction(_Bool INorOUT)
{
	if(INorOUT==INPUT)//i/p
	{
		//PM4 |= _80_PMn7_MODE_INPUT;// Set as input
		PM3 |= _01_PMn0_MODE_INPUT;// Set as input
	}
	else
	{
		//PM4 &= ~(1 << 7);// Set as output
		PM3 &= ~(1 << 0); // Set as output
	}
}

/* Configures P41 (SDA) as input or output for I2C communication. */
//void P41_SDA_Direction(_Bool INorOUT)
//{
//	if(INorOUT==INPUT)//i/p
//	{
//		//PM4 |= _02_PMn1_MODE_INPUT;// Set as input
//		PM5 |= _01_PMn0_MODE_INPUT;
//	}
//	else
//	{
////		PM4 &= ~(1 << 1); // Set as output
//		PM5 &= ~(1 << 0);// Set as output
//	}
//}
		void P41_SDA_Direction(_Bool INorOUT)
		{
			if(INorOUT == INPUT)
				PM5 |= (1 << 0);   // Input
			else
				PM5 &= ~(1 << 0);  // Output
		}

void P41_SDA_Write(_Bool HighOrLow)
{
	if (HighOrLow == LOW)
	{
//		P4 &= ~(1 << 1);  // SDA LOW
		P5 &= ~(1 << 0);  // SDA LOW
	}
	else
	{
//		P4 |= (1 << 1);   // SDA HIGH
		P5|= (1 << 0);   // SDA HIGH
	}
}
///
/* Writes a logic HIGH or LOW to P47 (SCL). */
void P47_SCL_Write(_Bool HighOrLow)
{
	if(HighOrLow==LOW)//i/p
	{
//		P4 &= ~(1 << 7);// Set SCL to LOW
		P3 &= ~(1 << 0);// Set SCL to LOW
	}
	else
	{
//		P4 |=0x80;// Set SCL to HIGH
		P3 |=0x01;// Set SCL to HIGH
	}
}

/* Reads the current state of P41 (SDA) and returns 1 (HIGH) or 0 (LOW). */
uint8_t P41_SDA_Read(void)
{
//	return ((P4>>1)&1);
	return ((P5>>0)&1);
}

/* Reads the current state of P47 (SCL) and returns 1 (HIGH) or 0 (LOW). */
uint8_t P47_SCL_Read(void)
{
//	return ((P4>>7)&1);
	return ((P3>>0)&1);
}

/* Sends an acknowledgment by setting SDA low. */
void SDAAcknowledgement(void)
{
	P47_SCL_Direction(OUTPUT);
	P41_SDA_Direction(OUTPUT);
	P41_SDA_Write(LOW);
}

/* Resets SDA and SCL to default input states. */
void SDAAcknowledgementDefault(void)
{
	P47_SCL_Direction(INPUT);
	P41_SDA_Direction(INPUT);
}

/* Configures SCL as an input for acknowledgement reading. */
void SDAReadAcknowledgement(void)
{
	P47_SCL_Direction(INPUT);
}

/* Reads ADC step value for a given channel. */
uint16_t Get_ADCStepValue(uint8_t channel)
{
	R_ADC_Start();//START ADC
	R_ADC_Set_OperationOn();//SETTING OPERATION
	ADS= channel;//SELECTING ADC CHANNEL
	if(ADC_FLAG==1)//CHECK OF CONERTION COMPLETE OR NOTE
	{
		ADC_FLAG=0;
		R_ADC_Get_Result(&ADC_TEMP);// RAD ADC STSP VALUE (0-1023)
		R_ADC_Stop();//STOP ADC
	}
	return ADC_TEMP;
}

/* Validates the checksum (BCC) of received data. */
uint16_t IsValidBCC(uint8_t *Data)
{
	uint16_t length;
	uint8_t MyBCC = 0x00;

	uint16_t Function_status = GENRIC_ERROR;
	TemporyLength =(RxBuffer[0]<<8)+RxBuffer[1] ;
	for (length = 0; length < TemporyLength; length++){
		MyBCC ^= RxBuffer[length]; // Compute checksum
	}
	if (RxBuffer[length] == MyBCC)
		Function_status = GENRIC_NO_ERROR;
	return Function_status;
}

/* Checks if received data is valid and extracts necessary information. */
uint16_t DataValidity(uint8_t *OutBuffer, uint16_t Read_Data_Length)
{
	uint16_t Error_code = GENRIC_ERROR;
	uint16_t current_cmd=0;
	uint16_t i = 0;
	uint16_t received_current_cmd = 0;
	uint16_t Temp_Length = 0x0000;

	uint16_t DataValid = GENRIC_ERROR;

	// Extract error code from received buffer
	Error_code = (((uint16_t)RxBuffer[4] << 8) | ((uint16_t)RxBuffer[5]));
	// Check if the received response has no errors
	if (Error_code == GENRIC_NO_ERROR)
	{
		DataValid=IsValidBCC(RxBuffer);	// Validate the checksum (BCC - Block Check Character)
		if (DataValid == GENRIC_NO_ERROR) // Proceed only if the checksum is valid
		{

			current_cmd =(((uint16_t)Tx_buffer[2] << 8) | ((uint16_t)Tx_buffer[3])); // Extract the command sent
			received_current_cmd= (((uint16_t)RxBuffer[2] << 8) | ((uint16_t)RxBuffer[3])); // Extract the command received
			if (received_current_cmd == current_cmd) // Verify if the received command matches the sent command
			{
				Temp_Length =  (RxBuffer[0]<<8)+RxBuffer[1] ; // Extract total data length from received buffer
				if((Read_Data_Length+11)==Temp_Length) // Check if the received data length matches expected length (+11 offset)
				{
					for(i = 0; i < Read_Data_Length ; i++)
						*(OutBuffer + i) = RxBuffer[11 + i]; // Copy the received data to the output buffer
				}
				else if(Temp_Length == (Read_Data_Length+14)) // Check if the received data length matches expected length (+14 offset)
				{
					for(i = 0; i < Read_Data_Length ; i++)
						*(OutBuffer + i) = RxBuffer[14 + i]; // Copy the received data to the output buffer
				}
				else{
					Error_code = LENGTH_ERROR;// Set error code for invalid length
				}

			}
			else
			{
				Error_code = GENRIC_ERROR;// Set error code for command mismatch
			}
		}
		else
		{

			Error_code = LENGTH_ERROR;// Set error code for checksum validation failure
		}
	}
	else
	{
		return Error_code;// Return error code if response indicates failure
	}

	return Error_code;// Return final status/error code
}
void ReadRFID(void)
{
	Tx_buffer[0] = 0x00;
	Tx_buffer[1] = 0x04;
	Tx_buffer[2] = 0x2F;
	Tx_buffer[3] = 0x0D;
	Tx_buffer[4] = 0x26;
	R_UART1_Send(Tx_buffer,5);
	delay(10000);
#if DEBUG_ENABLE
	R_UART1_Send((uint8_t *)"F", 1);  // Indicate data processing
#endif
	u_n8DataWaitOver=0;
	nDataLength =0;
	R_UART1_Receive(&RxBuffer[0],1);
	while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
	u_n8DataWaitOver=0;
	R_UART1_Receive(&RxBuffer[1],1);
	while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
	nDataLength =  (RxBuffer[0]<<8)+RxBuffer[1] ; // Extract total data length from received buffer
	u_n8DataWaitOver=0;
	R_UART1_Receive(&RxBuffer[2],1);
	while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
	u_n8DataWaitOver=0;
	//			nDataLength>651
	R_UART1_Receive(&RxBuffer[3],nDataLength-2);
	delay(4000000);//wait delay000000);//wait delay
	while(!u_n8DataWaitOver&&u_n8RFIDPresence==1);
}
void ValiadteAndFillZone(void)
{
#if DEBUG_ENABLE
	R_UART1_Send((uint8_t *)"I", 1);  // Indicate data processing
#endif
	if(GENRIC_NO_ERROR==DataValidity(ReceivedData,640))
	{
		if(ReceivedData[0]==2)
		{
			//memset(u_n8RFIDDataZoneAll,0,sizeof(u_n8RFIDDataZoneAll));
			// Copy received data into respective zones
			for (i = 0; i < 512; i++)
			{
				u_n8RFIDDataZoneAll[i]= ReceivedData[i + 1];
			}
			if(ReceivedData[623]==0)//!check for not used RFID
			{
				if(ReceivedData[622]==1)//!check for fresh RFID
				{
					u_n8RFIDDataZoneAll[55]=ReceivedData[621];//Testleft_0th
					u_n8RFIDDataZoneAll[54]=ReceivedData[620];//Testleft_1th
				}
				else
				{
					//!fresh rfid
				}
			}
			else
			{
				if(ReceivedData[622]==1)//!check for fresh RFID
				{
					u_n8RFIDDataZoneAll[55]=ReceivedData[621];//Testleft_0th
					u_n8RFIDDataZoneAll[54]=ReceivedData[620];//Testleft_1th
				}
				//!enable this for used card
				u_n8RFIDDataZoneAll[220]=1;
			}
			RFIDReadSuccess=1; // Indicate RFID data ready
			P1 &= ~(1 << 4);//LOW

			u_n8RFIDChekInterrupt=0;
#if DEBUG_ENABLE
			R_UART1_Send((uint8_t *)"D", 1);   // Indicate RFID data ready
#endif
		}
		else if(ReceivedData[0]==1)
		{
			RFIDReadSuccess=1;
			u_n8RFIDChekInterrupt=CARD_TYPE_NIL;
		}

		for(n16Count=0;n16Count<20;n16Count++)
		{
			u_n8RFIDWrite[n16Count]=ReceivedData[620+n16Count];
		}
#if ERASE_RFID
		/* Clear RFID Write area */

		Tx_buffer[0] = 0x00;
		Tx_buffer[1] = 0x18;
		Tx_buffer[2] = 0x2F;
		Tx_buffer[3] = 0x0C;
		for(u_n8Count = 0;u_n8Count < 20 ; u_n8Count++)
		{
			Tx_buffer[u_n8Count+4] =0;             // stcSmartCardData.u_n32OpenDate;
		}
		BCC = Tx_buffer[0];
		for (u_n8Count = 1; u_n8Count < Tx_buffer[1];u_n8Count++)
			BCC ^= Tx_buffer[u_n8Count];
		Tx_buffer[24] = BCC;

		R_UART1_Send(Tx_buffer,25);
		delay(10000);
		UART_SendString("RFID_Erased");

#endif
		//!RFID Success
	}
}
uint16_t WriteRFID(const char Data[])
{
	uint16_t Error_code = GENRIC_ERROR; // Initialize error code with a generic error value
	uint8_t i = 0;
	uint8_t TxBuf[30] = {0}; // Transmission buffer to store command data
	uint8_t RxBuf[6] = {0};  // Reception buffer to store response data
	uint8_t txIndex = 0; // Index to track the position in TxBuf

	// Construct the RFID write command packet
	TxBuf[txIndex++] = 0x00;// Start of command sequence
	TxBuf[txIndex++] = 0x18;// Command length
	TxBuf[txIndex++] = 0x2F;// Command identifier for RFID write operation
	TxBuf[txIndex++] = 0x0C;// Sub-command identifier

	// Copy 20 bytes of data into the TxBuf
	for(i = 0; i < 20 ; i++)
	{
		TxBuf[txIndex++] = Data[i];            // data to be written to the RFID tag
	}
	// Send the command and receive the response
	Error_code =  Transceiver(TxBuf, RxBuf);   //Pass Command in TxBuf and Get response in RxBuf
	return Error_code;// Return the status/error code received from the transceiver
}

void UART_SendString(const char *str)
{
	R_UART1_Send((uint8_t *)str, strlen(str));  // Send entire string at once
}
// Helper delay loop (NOPs for timing)
static void BitDelay(void)
{
	__nop(); __nop(); __nop();
	__nop(); __nop(); __nop();
	__nop(); __nop(); __nop();
	__nop(); __nop(); __nop();
}
void Stable_ACK_Sequence(void)
{
//    DI();  // Disable interrupts to protect SDA/SCL transition

    P41_SDA_Direction(OUTPUT);
    P41_SDA_Write(LOW);     // Pull SDA low to ACK
	__nop();__nop(); __nop(); __nop(); __nop(); __nop();
				__nop();__nop(); __nop(); __nop(); __nop(); __nop();
				__nop();__nop(); __nop(); __nop(); __nop(); __nop();
				__nop();__nop(); __nop(); __nop(); __nop(); __nop();
				__nop();__nop(); __nop(); __nop(); __nop(); __nop();
//								__nop();__nop(); __nop(); __nop(); __nop(); __nop();
//								__nop();__nop(); __nop(); __nop(); __nop(); __nop();
//								__nop();__nop(); __nop(); __nop(); __nop(); __nop();
				BitDelay();
				BitDelay();
    P41_SDA_Direction(INPUT);   // Release SDA for next byte
    __nop(); __nop(); __nop();  // Allow rise time (from pull-up)

//    EI();  // Re-e/nable interrupts
}
/* End user code. Do not edit comment generated here */

' intrupt.c "/***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products.
* No other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
* applicable laws, including copyright laws. 
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT.  ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY
* LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE FOR ANY DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR
* ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability 
* of this software. By using this software, you agree to the additional terms and conditions found by accessing the 
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2011, 2024 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/

/***********************************************************************************************************************
* File Name    : r_cg_intc_user.c
* Version      : CodeGenerator for RL78/G13 V2.05.08.02 [03 Jun 2024]
* Device(s)    : R5F100GG
* Tool-Chain   : CCRL
* Description  : This file implements device driver for INTC module.
* Creation Date: 07-07-2025
***********************************************************************************************************************/

/***********************************************************************************************************************
Includes
***********************************************************************************************************************/
#include "r_cg_macrodriver.h"
#include "r_cg_intc.h"
/* Start user code for include. Do not edit comment generated here */
///* End user code. Do not edit comment generated here */
#include "r_cg_userdefine.h"

/***********************************************************************************************************************
Pragma directive
***********************************************************************************************************************/
#pragma interrupt r_intc3_interrupt(vect=INTP3)
#pragma interrupt r_intc6_interrupt(vect=INTP6)
/* Start user code for pragma. Do not edit comment generated here */
#define MISPA_I2 0
///* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
Global variables and functions
***********************************************************************************************************************/
/* Start user code for global. Do not edit comment generated here */
void delay1(long d)
{
	while(d--);
}

extern uint8_t u_n8RFIDDataZoneAll[512];
volatile uint8_t u_n8BoolBuffer[5000];
volatile uint16_t u_n16BoolCount=0;
char buffer[10];  // Buffer to hold ASCII representation
volatile uint8_t u_n8PeakCount=0;
volatile uint8_t u_n8TotalPeakCount;
volatile uint16_t u_n16Data=0;
volatile uint16_t u_n16DataEeprom=0;
volatile uint16_t u_n16DataStart=0;
volatile uint8_t u_n8DataBufferNew[50];
volatile _Bool bCardPresence=0;
volatile _Bool bDataReceived=0;
volatile _Bool bWriteStart=0;
volatile uint8_t ZoneNumber=0;
volatile uint8_t RWrequest=0;
volatile uint8_t WriteAddress=0;
volatile uint8_t Testleft_0th=0;
volatile uint8_t Testleft_1th=0;
volatile uint8_t Usedcard=0;
volatile uint8_t UsedcardDate=0;
volatile uint8_t UsedcardMonth=0;
volatile uint8_t UsedcardYear=0;
volatile uint8_t Byte_size=0;
volatile uint8_t CmdType=0;
volatile uint8_t RFID_Detect=0;
volatile uint8_t RFIDReadSuccess=0;
volatile uint8_t u_n8RFIDChekInterrupt=0;
volatile uint8_t u_n8DataWaitOver=0;
volatile uint8_t u_n8RFIDPresence=0;
volatile uint8_t u_n8CardPresence=0;
volatile uint16_t coming8check=0;
volatile uint16_t Timer_A0=0;
volatile uint8_t First_B4=0;
volatile uint8_t M_B4=0;
volatile _Bool First_B4_Flag=0;
volatile uint8_t stuckCounter=0;
volatile uint8_t NumberByte=0;
volatile uint8_t StartAddress=0;
volatile uint16_t StartBufferAddress=0;
uint8_t t1=0;
uint8_t t2=0;
uint8_t ti=0;
extern int i;
int t_sum=0;
volatile uint32_t TempCount=0;
extern void UART_SendString(const char *str);
char debugStr[100];  // Global or local debug buffer
char temp[5];        // Temporary string for each byte

void ClearDataBuffer(void);
///* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
* Function Name: r_intc3_interrupt
* Description  : This function is INTP3 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_intc3_interrupt(void)
{

    /* Start user code. Do not edit comment generated here */
	static _Bool eepromWait = 0;  // Flag to indicate EEPROM communication
		static _Bool b4Processing = 0; // Flag for B4 processing
		static _Bool stopDetected = 0; // Track if I2C stop condition was seen
		_Bool i2cStop = 0;
		_Bool i2cStart = 0;
		TempCount++;
		if (bDataReceived == 0)//&&u_n8CardPresence==1
		{
			R_INTC6_Stop(); // Disable EXTI during processing
			u_n16Data <<= 1; // Shift left by 1 to accommodate next bit

			// Read data bit from P4.1
			if (((P5 >> 0) & 1) == 1)
			{
				u_n16Data += 1;
			}

			P1 |= (1 << 6); // LED OFF indicator

			// **Check for I2C Stop Condition (Clock High & Data Rising)**
			i2cStop = (((P3 >> 0) & 1) == 1) && (((P5 >> 0) & 1) == 1);

			// **Check for I2C Start Condition (Clock High & Data Falling)**
			i2cStart = (((P3 >> 0) & 1) == 1) && (((P5 >> 0) & 1) == 0);

			// **Detect I2C Stop and Set Flag**
			if (i2cStop)
			{
				stopDetected = 1; // Mark that a stop condition has occurred
			}
			// ------- Check for 0xA0 (EEPROM Communication) -------
			if ((u_n16Data & 0x00FF) == 0xA0 && u_n8PeakCount == 0)
			{

				//sprintf(buffer, "A0:%ld ",TempCount);
				//UART_SendString(buffer);

				if(TempCount<20)
				{
					First_B4=1;
				}
				else if(TempCount>180&&TempCount<220)
				{
					M_B4=1;
				}
				else
				{
					First_B4=0;
					M_B4=0;
				}
				TempCount=0;
				u_n16Data=0;
				eepromWait=1;
				return;         // Do not process this byte further

			}

			// ------- If waiting for EEPROM, check for I2C stop condition -------
			if (eepromWait && i2cStop)
			{
				eepromWait = 0; // EEPROM sequence completed, reset flag
				return;         // Wait for next valid command
			}
			// ------- Detect New 0xB4 Start (Only when b4Processing is 0) -------
			if (!b4Processing && (u_n16Data & 0x00FF) == 0xB4 && u_n8PeakCount == 0&&M_B4==0)
			{
				if (stopDetected)
				{
					stopDetected = 0; // Clear stop detection before processing B4
				}

				u_n16Data = 0;
				u_n8DataBufferNew[0] = 0xB4;
				CmdType = 0xB4;
				u_n8TotalPeakCount = 1;
				u_n8PeakCount = 1;
				bDataReceived = 1;
				u_n16DataStart = 0;
				b4Processing = 1; // Mark B4 as in progress
				if(First_B4==1)
				{
					First_B4=0;
	#if DEBUG_ENABLE

					UART_SendString("XB4");
	#endif

					First_B4_Flag=1;
				}

				else if(M_B4==1)
				{
					M_B4=0;
	#if DEBUG_ENABLE

					UART_SendString("MB4");
	#endif
				}
				else
				{
	#if DEBUG_ENABLE

					UART_SendString("B4");
	#endif
				}
				M_B4=0;
				return;
			}

			// ------- If STOP condition occurs, end B4 processing only when fully received -------
			if (b4Processing && i2cStop)
			{
				stopDetected = 1; // Mark stop but **do not reset processing immediately**
			}

			// ------- Handle subsequent data bytes if B4 is detected -------
			if (b4Processing && u_n8PeakCount > 0)
			{
				u_n16DataStart++;
				if (u_n16DataStart == 8)  // After 8 bits, form a byte
				{
					u_n8DataBufferNew[u_n8TotalPeakCount++] = (uint8_t)(u_n16Data & 0x00FF);
					u_n8PeakCount++;
					bDataReceived = 1;
					u_n16DataStart = 0;
					u_n16Data=0;
					// **When 8 bytes are received, extract RWrequest & ZoneNumber**
					if (u_n8PeakCount == 8)
					{
						RWrequest = u_n8DataBufferNew[u_n8TotalPeakCount - 4];
						ZoneNumber = u_n8DataBufferNew[u_n8TotalPeakCount - 6];
						StartAddress= u_n8DataBufferNew[u_n8TotalPeakCount-2];
						NumberByte = u_n8DataBufferNew[u_n8TotalPeakCount-1];
						// Add check: ZoneNumber must be between 6 and 13
						if (ZoneNumber < 6 || ZoneNumber > 9)
						{
							ClearDataBuffer();
							b4Processing = 0;
							bDataReceived = 0;
							u_n8PeakCount = 0;
							u_n8TotalPeakCount = 0;
							R_INTC6_Start();
							return;
						}
						else{
							StartBufferAddress=StartAddress+((ZoneNumber-6)*128);
						}
						if (RWrequest == 0xB2)  // Write start command B2
						{
							u_n8PeakCount = 0;
							bDataReceived = 1;
							bWriteStart = 1;
							b4Processing = 0; // Reset to allow new B4 detection
	#if DEBUG_ENABLE

							sprintf(buffer, "B2Z:%d",ZoneNumber);
	#endif

							UART_SendString(buffer);
							ClearDataBuffer();
						}
						else if (RWrequest == 0xB0)  // Write address command
						{
							WriteAddress = u_n8DataBufferNew[u_n8TotalPeakCount - 2];
							Byte_size = u_n8DataBufferNew[u_n8TotalPeakCount - 1];
	#if DEBUG_ENABLE
							UART_SendString("B0");
	#endif

							ClearDataBuffer();
						}
					}

					// **Zone 7 & Zone 6 Handling**
					if ((u_n8PeakCount == 8 + Byte_size) && (RWrequest == 0xB0))
					{
						if (ZoneNumber == 7)
						{
							bWriteStart=1;
							bDataReceived=1;
							WriteAddress=92;
	#if DEBUG_ENABLE

							UART_SendString("L7");
	#endif
							Usedcard = u_n8DataBufferNew[u_n8TotalPeakCount - 1];
							ClearDataBuffer();
						}
						else if (ZoneNumber == 6)
						{
							bWriteStart=1;
							bDataReceived=1;
							WriteAddress=54;
							//                        UART_SendString("L6");
							Testleft_0th = u_n8DataBufferNew[u_n8TotalPeakCount - 1];
							Testleft_1th = u_n8DataBufferNew[u_n8TotalPeakCount - 2];
							UART_SendString(buffer);
							ClearDataBuffer();
						}

						// **Reset after processing**
						u_n8PeakCount = 0;
						bDataReceived = 1;
						bWriteStart = 1;
						u_n8TotalPeakCount = 0;
						b4Processing = 0; // Reset to detect new B4 commands
					}

					// **Prevent buffer overflow**
					if (u_n8TotalPeakCount >= 32)
					{
						u_n8TotalPeakCount = 0;
						b4Processing = 0; // Reset to allow new B4 detection
						ClearDataBuffer();
					}
				}
			}
			// **Reset b4Processing only after B4 is fully received**
			if (stopDetected && b4Processing && u_n8PeakCount >= 8)
			{
				b4Processing = 0;
				stopDetected = 0;
			}
			// **Final reset of I2C Stop Detection**
			if (i2cStart)
			{
				stopDetected = 0; // Clear stop detection on new start
			}
			// ------- Keep only lower byte of u_n16Data -------
			u_n16Data &= 0x00FF;

			R_INTC6_Start(); // Re-enable EXTI
		}
    /* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_intc6_interrupt
* Description  : This function is INTP6 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_intc6_interrupt(void)
{
    /* Start user code. Do not edit comment generated here */
	u_n8CardPresence=((P14>>0)&1);

		//u_n8RFIDChekInterrupt=((P14>>2)&1); // connected to rfid detect pin
		//write code to enable RFID

		if (u_n8CardPresence==1)
		{
	#if DEBUG_ENABLE

			UART_SendString("1");
	#endif
			u_n8RFIDPresence=((P13>>7)&1);// connected to rfid detect pin
			if (u_n8RFIDPresence==1)			//Check RFID Reader Detect
			{
	#if DEBUG_ENABLE

				UART_SendString("2");
	#endif

				u_n8RFIDChekInterrupt=1;
				R_TAU0_Channel0_Start();//Turn ON Start Timer(Timer1)
			}
			else
			{
	#if DEBUG_ENABLE

				UART_SendString("3");
	#endif

				R_TAU0_Channel0_Stop();//Turn OFF Start Timer(Timer1)
				P1=P1|(1<<4);//HIGH
				//P1=P1&(~(1<<4));
				ClearDataBuffer();
				memset(u_n8RFIDDataZoneAll,0,sizeof(u_n8RFIDDataZoneAll));

				//write code to Enable IC Card MUX
			}
		}
		else
		{
			P1=P1|(1<<4);//HIGH

			ClearDataBuffer();
			memset(u_n8RFIDDataZoneAll,0,sizeof(u_n8RFIDDataZoneAll));
	#if DEBUG_ENABLE

			UART_SendString("X");
	#endif

		}
    /* End user code. Do not edit comment generated here */
}

/* Start user code for adding. Do not edit comment generated here */
void ClearDataBuffer(void)
{
	uint16_t i;
	for (i = 0; i < sizeof(u_n8DataBufferNew); i++)
	{
		u_n8DataBufferNew[i] = 0;  // Reset all buffer values to zero
	}
	u_n8TotalPeakCount = 0;  // Reset data tracking variables
}
' timer.c"/***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products.
* No other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
* applicable laws, including copyright laws. 
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT.  ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY
* LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE FOR ANY DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR
* ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability 
* of this software. By using this software, you agree to the additional terms and conditions found by accessing the 
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2011, 2024 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/

/***********************************************************************************************************************
* File Name    : r_cg_timer_user.c
* Version      : CodeGenerator for RL78/G13 V2.05.08.02 [03 Jun 2024]
* Device(s)    : R5F100GG
* Tool-Chain   : CCRL
* Description  : This file implements device driver for TAU module.
* Creation Date: 28-06-2025
***********************************************************************************************************************/

/***********************************************************************************************************************
Includes
***********************************************************************************************************************/
#include "r_cg_macrodriver.h"
#include "r_cg_timer.h"
/* Start user code for include. Do not edit comment generated here */
///* End user code. Do not edit comment generated here */
#include "r_cg_userdefine.h"

/***********************************************************************************************************************
Pragma directive
***********************************************************************************************************************/
#pragma interrupt r_tau0_channel0_interrupt(vect=INTTM00)
#pragma interrupt r_tau0_channel2_interrupt(vect=INTTM02)
#pragma interrupt r_tau0_channel7_interrupt(vect=INTTM07)
/* Start user code for pragma. Do not edit comment generated here */
///* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
Global variables and functions
***********************************************************************************************************************/
/* Start user code for global. Do not edit comment generated here */
volatile uint16_t u_n16TimeCounter=0;
volatile uint16_t u_n16StartTimeCounter=0;
volatile uint16_t u_n8RfidCheckCounter=0;

void ClearDataBuffer(void);
uint16_t count_ms=0;// declare count_ms variable as 0.

/* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
* Function Name: r_tau0_channel0_interrupt
* Description  : This function is INTTM00 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_tau0_channel0_interrupt(void)
{
    /* Start user code. Do not edit comment generated here */
	R_INTC3_Stop();
	u_n16StartTimeCounter++;
#if DEBUG_ENABLE
	UART_SendString("_");
#endif

	if(u_n16StartTimeCounter>100)
	{
		u_n8RfidCheckCounter++;
		R_INTC3_Start();
		R_TAU0_Channel0_Stop();//Turn OFF Start Timer(Timer1)
	}
	else
	{
		//P1=P1|(1<<4);//u_n8RFIDSense set to high, CARD SENSE IN MACHINE PUT HIGH

		ClearDataBuffer();

	}


	/* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_tau0_channel2_interrupt
* Description  : This function is INTTM02 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_tau0_channel2_interrupt(void)
{
    /* Start user code. Do not edit comment generated here */
	u_n16TimeCounter++;

    /* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_tau0_channel7_interrupt
* Description  : This function is INTTM07 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_tau0_channel7_interrupt(void)
{
    /* Start user code. Do not edit comment generated here */
    /* End user code. Do not edit comment generated here */
}

/* Start user code for adding. Do not edit comment generated here */
///* End user code. Do not edit comment generated here */
" serial.c /***********************************************************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products.
* No other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
* applicable laws, including copyright laws. 
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT.  ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY
* LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE FOR ANY DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR
* ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability 
* of this software. By using this software, you agree to the additional terms and conditions found by accessing the 
* following link:
* http://www.renesas.com/disclaimer
*
* Copyright (C) 2011, 2024 Renesas Electronics Corporation. All rights reserved.
***********************************************************************************************************************/

/***********************************************************************************************************************
* File Name    : r_cg_serial_user.c
* Version      : CodeGenerator for RL78/G13 V2.05.08.02 [03 Jun 2024]
* Device(s)    : R5F100GG
* Tool-Chain   : CCRL
* Description  : This file implements device driver for Serial module.
* Creation Date: 04-07-2025
***********************************************************************************************************************/

/***********************************************************************************************************************
Includes
***********************************************************************************************************************/
#include "r_cg_macrodriver.h"
#include "r_cg_serial.h"
/* Start user code for include. Do not edit comment generated here */
/* End user code. Do not edit comment generated here */
#include "r_cg_userdefine.h"

/***********************************************************************************************************************
Pragma directive
***********************************************************************************************************************/
#pragma interrupt r_uart1_interrupt_send(vect=INTST1)
#pragma interrupt r_uart1_interrupt_receive(vect=INTSR1)
/* Start user code for pragma. Do not edit comment generated here */
/* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
Global variables and functions
***********************************************************************************************************************/
extern volatile uint8_t * gp_uart1_tx_address;         /* uart1 send buffer address */
extern volatile uint16_t  g_uart1_tx_count;            /* uart1 send data number */
extern volatile uint8_t * gp_uart1_rx_address;         /* uart1 receive buffer address */
extern volatile uint16_t  g_uart1_rx_count;            /* uart1 receive data number */
extern volatile uint16_t  g_uart1_rx_length;           /* uart1 receive data length */
/* Start user code for global. Do not edit comment generated here */
uint8_t a=0;
uint8_t Rx_Data;
#define UART_BUFFER_SIZE 700  // Define buffer size
extern volatile uint8_t u_n8DataWaitOver;
volatile uint8_t rx_data;

/* End user code. Do not edit comment generated here */

/***********************************************************************************************************************
* Function Name: r_uart1_interrupt_receive
* Description  : This function is INTSR1 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_uart1_interrupt_receive(void)
{
    volatile uint8_t rx_data;
    volatile uint8_t err_type;
    
    err_type = (uint8_t)(SSR03 & 0x0007U);
    SIR03 = (uint16_t)err_type;

    if (err_type != 0U)
    {
        r_uart1_callback_error(err_type);
    }
    
    rx_data = RXD1;

    if (g_uart1_rx_length > g_uart1_rx_count)
    {
        *gp_uart1_rx_address = rx_data;
        gp_uart1_rx_address++;
        g_uart1_rx_count++;

        if (g_uart1_rx_length == g_uart1_rx_count)
        {
            r_uart1_callback_receiveend();
        }
    }
    else
    {
        r_uart1_callback_softwareoverrun(rx_data);
    }
}

/***********************************************************************************************************************
* Function Name: r_uart1_interrupt_send
* Description  : This function is INTST1 interrupt service routine.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void __near r_uart1_interrupt_send(void)
{
    if (g_uart1_tx_count > 0U)
    {
        TXD1 = *gp_uart1_tx_address;
        gp_uart1_tx_address++;
        g_uart1_tx_count--;
    }
    else
    {
        r_uart1_callback_sendend();
    }
}

/***********************************************************************************************************************
* Function Name: r_uart1_callback_receiveend
* Description  : This function is a callback function when UART1 finishes reception.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void r_uart1_callback_receiveend(void)
{
    /* Start user code. Do not edit comment generated here */
	u_n8DataWaitOver=1;
    /* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_uart1_callback_softwareoverrun
* Description  : This function is a callback function when UART1 receives an overflow data.
* Arguments    : rx_data -
*                    receive data
* Return Value : None
***********************************************************************************************************************/
static void r_uart1_callback_softwareoverrun(uint16_t rx_data)
{
    /* Start user code. Do not edit comment generated here */
    /* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_uart1_callback_sendend
* Description  : This function is a callback function when UART1 finishes transmission.
* Arguments    : None
* Return Value : None
***********************************************************************************************************************/
static void r_uart1_callback_sendend(void)
{
    /* Start user code. Do not edit comment generated here */
    /* End user code. Do not edit comment generated here */
}

/***********************************************************************************************************************
* Function Name: r_uart1_callback_error
* Description  : This function is a callback function when UART1 reception error occurs.
* Arguments    : err_type -
*                    error type value
* Return Value : None
***********************************************************************************************************************/
static void r_uart1_callback_error(uint8_t err_type)
{
    /* Start user code. Do not edit comment generated here */
    /* End user code. Do not edit comment generated here */
}

/* Start user code for adding. Do not edit comment generated here */
/* End user code. Do not edit comment generated here */
' chek all, currrently it experinceing a 30 error in data sending. 128 bytes /512 is get wrong