Hi there,
I am working on a RFID-reading sketch on Arduino, of which three tags can be recognized. These tags will make the Arduino choose between Serial.println("1"), Serial.println("2") or Serial.println("3"). This works, but there is a small problem: the Arduino outputs these values ("1","2"or "3") twice or three times at once! That is not quite the desired effect, as I want the output to be printed only once at a time.
Here is the code:
//Code to read data from Parallax RFID reader/writer 28440 via Arduino
//Program reads data from the old EM4100-based tags and prints their value in the serial monitor.
//Code courtesy from http://prototypeit.blogspot.nl/2011/02/arduino-parallax-rfid-readwrite-module_20.html
// Adapted by Jeroen Rood, as of 19-03-2013
// changes made to this sketch are only for school project
// purposes.
#include <SoftwareSerial.h>
#define txPin 6
#define rxPin 8
SoftwareSerial mySerial(rxPin, txPin);
int val = 0; // the variable for temporary storage of a char from the RFID-tag ID (10 times used in a ID loop)
char code[12]; //space for 12 chars in the read result
// blue 08000B1673
// yellow 08000AC96E
// red 280015F22E
char tag1[12] = {
'0', '8', '0', '0', '0', 'A', 'C', '9', '6', 'E'}; // tag YELLOW
char tag2[12] = {
'0', '8', '0', '0', '0', 'B', '1', '6', '7', '3'}; // tag BLUE
char tag3[12] = {
'2', '8', '0', '0', '1', '5', 'F', '2', '2' ,'E'}; // tag RED
int bytesread = 0; // a counter for the amount of bytes that have been read (10 is correct for usage - this is the amount of chars from the RFID ID)
int i = 0; // the representation of the port number that has to be set to HIGH (LED)
void establishContact() { // establish a connection with the RFID reader
while (mySerial.available() <= 0) {
mySerial.print("!RW");
mySerial.write(0x0F);
mySerial.flush();
delay(1000);
}
}
void setup()
{
Serial.begin(9600);
mySerial.begin(9600);
establishContact();
pinMode(7, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
pinMode(4, OUTPUT);
pinMode(txPin, OUTPUT); //pin 6
pinMode(rxPin, INPUT); //pin 8
}
void loop()
{
bytesread=0;
if (mySerial.available()>0) {
while (bytesread<10) {
val=mySerial.read();
if((val == 10)||(val == 13)) { // if header or stop bytes before the 10 digit reading
break;
} // stop reading
code[bytesread] = val; // add the digit
bytesread++;
}
if(strcmp(code,tag1) == 0) {
Serial.println("1");
i = 4;
}
else if(strcmp(code,tag3) == 0) {
Serial.println("3");
i = 12;
}
else if(strcmp(code,tag2) == 0) {
Serial.println("2");
i = 7;
}
for(int a=13;a>3;a--){
if((a != 6)&&(a != 8)){
if(a==i){
digitalWrite(a,HIGH);
}
else{
digitalWrite(a,LOW);
}
}
}
}
else {
establishContact();
}
}
And here is the output (2=blue tag, 1=yellow tag, 3=red tag ... see the Arduino sketch):
2
2
1
1
3
3
It looks like the Serial.println() lines are somehow called twice or three times in a very short period of time. Could anyone explain to me what is going on, or what I can do to fix this problem?
Thanks!
Jeroen