Hi Arduino Geeks,
I'm new to Arduino programming, and currently, I'm doing a college project.
I'm creating an RFID-operated door using Uno, RC522 and Servo motor by help of sample projects in internet.
My goal is to continuously track RFID ID while the servo motor rotates 0 to 90 degrees and again rotates to 0 degrees. [Open door(servo motor 90 degree position) if RFID tag detects and close door(servo motor 0 degree position) with delay 2000 miliseconds, but within the duration 2000 miliseconds required to track RFID tags continuously and keep open door if RFID tag detects until end detection ].
As delay() freeze application i have use timer to revert Servo motor in the timer(example of BlinkWithoutDelay), but Servo motor function is not working fine for my expectation. Can you please explain what is the error in my code.
Thanks In Advance. (Power to servo will taken from external power-in)
#include<Servo.h>
#include <SPI.h>
#include <MFRC522.h>
#include <pt.h>
#define RST_PIN 9
#define SS_PIN 10
#define SERVO_PIN 3
byte oldId[4];
int countIdentical;
unsigned long prevMillis;
const unsigned long delayInterval = 2000; // interval to avoid double registration
unsigned long previousMillis = 0;
const long interval = 1000;
Servo servo;
int angle = 0;
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
static struct pt pt1; // each protothread needs one of these
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC1
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
for(int i=1; i<4; i++) {
oldId[i]=0x00;
}
prevMillis = millis();
PT_INIT(&pt1); // initialise the two
servo.attach(SERVO_PIN);
servo.write(angle); // rotate servo motor to 0°
}
static int protothread1(struct pt *pt) {
PT_BEGIN(pt);
servo.write(angle);
angle = 90;
//delay(2000);
//servo.write(0);
PT_END(pt);
}
void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
countIdentical = 0;
for ( uint8_t i = 0; i < 4; i++) {
if (mfrc522.uid.uidByte[i] == oldId[i]) {
countIdentical++;
}
}
if (countIdentical != 4) {
for ( uint8_t i = 0; i < 4; i++) {
if (mfrc522.uid.uidByte[i] < 0x10) {
Serial.print("0");
}
Serial.print(mfrc522.uid.uidByte[i], HEX);
oldId[i]=mfrc522.uid.uidByte[i];
prevMillis=millis();
}
protothread1(&pt1);
Serial.println();
}
unsigned long currentMillis = millis();
if ((currentMillis - prevMillis) > delayInterval) {
prevMillis=currentMillis;
if(angle == 90){
angle =0;
}
else{
angle = 90;
}
servo.write(angle);
for ( uint8_t i = 0; i < 4; i++) {
oldId[i]=0x00;
}
}
}