我有一个连接到Arduino的RFID阅读器..并成功接收到串行监视器的标签号。但是当我将LED闪烁在循环内部时,则rfid读数会延迟:每次闪烁后它会逐个接收标签号。
代码如下。我想我应该使用多线程或中断,但我不知道该怎么做。
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
pinMode(2, OUTPUT);
}
void loop() {
// blink led in pin 2
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
//Below Serial1.available() checks my rfid reader input signal and print on serial monitor of Arduino.. and Serial1 is on pin RX1 19 (RX1 19 is the default pin for serial1 defined by Arduino developers "http://arduino.cc/en/reference/serial#.Uyvbq6iSzIg") to which my rfid reader is connected
if (Serial1.available()) {
int i = Serial1.read();
Serial.print(i);
}
}
答案 0 :(得分:2)
有一个名为"Blink without Delay"的Arduino文件。它包含在Arduino示例中,我已链接到它。帮自己一个忙,花十分钟阅读教程和代码,以了解它的作用。
答案 1 :(得分:0)
您可以使用Arduino的计时器和相应的中断。所以这里是这样的:
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
pinMode(2, OUTPUT);
/* Initialize timer, e.g. timer1 */
noInterrupts(); //disable interrupts
TCCR1A = 0; //Timer1 control register A
TCCR1B = 0; //Timer1 control register B
TCNT1 = 0; //Counter of timer1
OCR1A = 15625; //Timer1 compare match register
TCCR1B |= (1<<WGM12); //Set timer1 in CTC mode
/* Define prescaler with 1024. If the clock is 16 MHz, then timer1 will run
* with 16 MHz / 1024 = 15625 Hz --> 64 us, to get one second, we
* need 15625 cycles, which is the OCR1A register */
TCCR1B |= (1<<CS10) | (1<<CS12); // clock prescaler = 1024
TIMSK1 |= (1<<OCIE1A); //enable timer compare interrupt
interrupts(); //enable interrupts
}
//This routine is called every time, timer1 counter reaches the compare register
ISR(Timer1_COMPA_vect) {
digitalWrite(2, digitalRead(2) ^ 1); //toggle LED
}
//the loop
void loop() {
if (Serial1.available()) {
int i = Serial1.read();
Serial.print(i);
}
}