As an undergraduate student, I am trying to use an incremental encoder to control a DC motor. I wrote the following code to receive the encoder value (it was the same even though it was originally unified as mbed code), but when an interrupt occurs and the operation is performed in the decode function, the GIGA's LED blinks red and does not work. I'm not sure what the cause is. help...
#include "motor.h"
#include "mbed.h"
#define R (0b011)
#define G (0b101)
#define B (0b110)
using namespace mbed;
BusOut myled(PI_12,PJ_13,PE_3);
BusIn phase(PA_3,PA_2);
void Red(){
myled =R;
}
void Green(){
myled = G;
}
void Blue(){
myled =B;
}
uint8_t pre_phase;
int32_t count;
uint32_t error_count;
void decode(){
volatile uint8_t new_phase=phase;
switch((pre_phase<<2) | new_phase)
{
case 0b0001:
case 0b0111:
case 0b1110:
case 0b1000:
count--;
break;
case 0b0010:
case 0b1011:
case 0b1101:
case 0b0100:
count++;
break;
default:
error_count++;
break;
}
pre_phase=new_phase;
}
Encoder enco;
void setup() {
// put your setup code here, to run once:
Green();
attachInterrupt(digitalPinToInterrupt(2),decode,CHANGE);
attachInterrupt(digitalPinToInterrupt(3),decode,CHANGE);
pinMode(2,INPUT_PULLUP);
pinMode(3,INPUT_PULLUP);
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(digitalRead(2),BIN);
Serial.println(digitalRead(3),BIN);
Serial.print("count: ");
Serial.println(count);
Serial.print("error: ");
Serial.println(error_count());
delay(1);
}