Hello,
Attempting to measure the output of the Mx2125 Accelerometer using interrupts. The Mx2125 outputs a 100 Hz PWM output signal with duty cycle proportional to acceleration. (This fact can be used to test any sketch attempting to measure duty cycle of a square wave with interrupts)
I believe my issue stems from implementing the ISR incorrectly or passing data from the main sketch to and from the ISR incorrectly.
The idea is that the ISR triggers on CHANGE (Rising or Falling Edge), then the current and previous pin state is compared to determine the direction of the change and read millis() as appropriate.
Code and datasheet below. I am using a Teensy 3.1 Much thanks
http://www.robotshop.com/media/files/PDF/memsic-2125-datasheet-28017.pdf
const int Y_Tilt = 11;
volatile unsigned long Y_Rising ;
volatile unsigned long Y_Falling ;
unsigned long Y_Time ;
unsigned long PrintThreshold = 3;
unsigned long PrevPrintTime = 0;
unsigned long AccelDataUpdateInterval = 2;
volatile boolean CurrentState;
volatile boolean PrevState;
volatile boolean StatePrint;
unsigned long Y_RiseCopy;
unsigned long Y_FallCopy;
unsigned long deltaY;
unsigned long PrevAccelTimeCheck;
unsigned long AccelTimeCheck;
unsigned long CurrentPrintTime;
unsigned long AccelYTime;
void setup()
{
Serial.begin(9600);
Serial.println("Tilt Test:");
pinMode(Y_Tilt,INPUT);
attachInterrupt(Y_Tilt,ISR_Y,CHANGE);
}
void loop()
{
AccelTimeCheck = millis();
CurrentPrintTime = millis();
AccelYTime = micros();
//Read X and Y accel Data fron Interupt
if ((AccelTimeCheck - PrevAccelTimeCheck )> AccelDataUpdateInterval){
noInterrupts();
Y_RiseCopy = Y_Rising;
Y_FallCopy = Y_Falling;
StatePrint = CurrentState;
PrevAccelTimeCheck = AccelTimeCheck;
interrupts();
}
deltaY = Y_RiseCopy - Y_FallCopy;
if ((CurrentPrintTime - PrevPrintTime ) > PrintThreshold ){
Serial.println(Y_RiseCopy);
Serial.println(Y_FallCopy);
Serial.println(CurrentState);
Serial.println("test");
PrevPrintTime = CurrentPrintTime;
}
}
void ISR_Y() {
CurrentState == digitalRead(Y_Tilt);
if (CurrentState == HIGH and PrevState == LOW)
{
Y_Rising = AccelYTime;
PrevState = CurrentState;
}
else if (CurrentState == LOW and PrevState == HIGH)
{
Y_Falling = AccelYTime;
PrevState = CurrentState;
}
else
{
PrevState = CurrentState;
}
}