Hi,
I am trying to read the encoder of a motor (Pololu - 75:1 Metal Gearmotor 25Dx66L mm LP 6V with 48 CPR Encoder (No End Cap))
I don't have any problems on reading it with interrupts, however when I use Serial communication to print the encoder position on the Serial monitor. The code just stops working. Is there any problem on using interrupts with Serial communication?
Here is the working code:
#define EncoderA 2
#define EncoderB 3
#define LED1 13
#define LED2 11
boolean A_set;
boolean B_set;unsigned long time;
int encpos=0;
int interval = 100;
byte prevA=0;
byte prevB=0;
byte EncA=0;
byte EncB=0;
long previous=0;
void setup(){
pinMode(EncoderA,INPUT);
pinMode(EncoderB,INPUT);
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
attachInterrupt(0,doencA,CHANGE);
attachInterrupt(1,doencB,CHANGE);
}void loop(){
time =millis();if (abs(encpos)==900){
if(encpos>0){
{digitalWrite(LED1,HIGH);
previous=time;
encpos=0;
}
}
else if(encpos<0)
{digitalWrite(LED2,HIGH);
previous=time;
encpos=0;
}
}
if(time-previous>interval)
{digitalWrite(LED2,LOW);
digitalWrite(LED1,LOW);
}
}void doencA()
{
if (digitalRead(EncoderA) == HIGH) {
A_set = true;
if (!B_set) {
encpos += 1;
}
}
if (digitalRead(EncoderA) == LOW) {
A_set = false;
}}
void doencB()
{
// Low-to-high transition?
if (digitalRead(EncoderB) == HIGH) {
B_set = true;
if (!A_set) {
encpos -= 1;
}
}// High-to-low transition?
if (digitalRead(EncoderB) == LOW) {
B_set = false;
}}
and here is the one not working:
#define EncoderA 2
#define EncoderB 3
#define LED1 13
#define LED2 11
boolean A_set;
boolean B_set;unsigned long time;
int encpos=0;
int interval = 100;
byte prevA=0;
byte prevB=0;
byte EncA=0;
byte EncB=0;
long previous=0;
void setup(){
pinMode(EncoderA,INPUT);
pinMode(EncoderB,INPUT);
pinMode(LED1,OUTPUT);
pinMode(LED2,OUTPUT);
attachInterrupt(0,doencA,CHANGE);
attachInterrupt(1,doencB,CHANGE);
Serial.begin(9600);
}void loop(){
time =millis();if (abs(encpos)==900){
if(encpos>0){
{digitalWrite(LED1,HIGH);
previous=time;
encpos=0;
}
}
else if(encpos<0)
{digitalWrite(LED2,HIGH);
previous=time;
encpos=0;
}
}
if(time-previous>interval)
{digitalWrite(LED2,LOW);
digitalWrite(LED1,LOW);
}
Serial.println(encpos);
}void doencA()
{
if (digitalRead(EncoderA) == HIGH) {
A_set = true;
if (!B_set) {
encpos += 1;
}
}
if (digitalRead(EncoderA) == LOW) {
A_set = false;
}}
void doencB()
{
// Low-to-high transition?
if (digitalRead(EncoderB) == HIGH) {
B_set = true;
if (!A_set) {
encpos -= 1;
}
}// High-to-low transition?
if (digitalRead(EncoderB) == LOW) {
B_set = false;
}}