Background
I'm trying to write code to read signals from a six-channel RC receiver on an Arduino Mega 2560. Currently I am keeping the code to just read one channel to make things easy to troubleshoot. The problem is my shared variable is not updating, leading me to believe that my interrupt service routine is not detecting any rising edges.
I thought my receiver was broken, so I tested it using the standard Arduino attach interrupt function. It worked perfectly, so my receiver is fine.
I used Serial.print() to see if my volatile channel variable was updating (that is, change its value to the channel 1 flag value). It was not updating, so my ISR must be wrong. You can find the original code in the blog post.
What's wrong? I'm out of ideas.
#include <PinChangeInt.h>
//Pin assignment
#define channel1PIN 10
//Bit flags
#define Channel1FLAG 1
//Flag holder
volatile uint8_t bFLAGUPDATESHARED;
//Shared variables: Accessed by the interrupt service routine and read in 'void loop'.
volatile uint16_t unCHANNEL1SHARED;
//Start time variables: These are used to set the start time of the rising edge of
//a pulse. They are only accessed by the ISR, and thus they are unsigned integers and
//not volatiles.
uint32_t ulCHANNEL1START;
void setup()
{
Serial.begin(9600);
Serial.print("RC Channel PWM Read Interrupt Test");
//PinChangInt library function. Used to set attach interrupts.
PCintPort::attachInterrupt(channel1PIN, calcCHANNEL1, CHANGE);
}
void loop()
{
//In-loop variables to hold local copies of channel inputs.
//This is static so it retains values between call loops.
static uint16_t unCHANNEL1IN;
//The in-loop copy of the bSHAREDFLAGUPDATE volatile flag holder
static uint8_t bFLAGUPDATELOCAL;
//Check to see if any channels have received signals. If so, copy
//shared variables to local in loop variables.
if (bFLAGUPDATESHARED)
{
//Switch off interrupts when I copy shared variables to local variables
noInterrupts();
bFLAGUPDATELOCAL = bFLAGUPDATESHARED;
if (bFLAGUPDATELOCAL & Channel1FLAG)
{
unCHANNEL1IN = unCHANNEL1SHARED;
}
bFLAGUPDATESHARED = 0;
interrupts();
}
Serial.println(unCHANNEL1IN);
//Clear local update flags copy as all values have been copied to local variables
bFLAGUPDATELOCAL = 0;
}
void calcCHANNEL1()
{
if (digitalRead(channel1PIN) == HIGH)
{
//If pin goes high, start timer and set ulCHANNEL1START to timer start
ulCHANNEL1START = micros();
}
else
{
//If it is not rising, it must be falling so set shared
//variable to current time-start time
unCHANNEL1SHARED = (uint16_t)(micros() - ulCHANNEL1START);
//Tell that channel 1 has received a signal
bFLAGUPDATESHARED |= Channel1FLAG;
}
}