Here is the code:
#include#include #include #include //Definitions #define Trigger (PINC&_BV(PINC2)) #define Gearbox_Sensor (PINC&_BV(PINC0)) #define Turn_On_SW2 (PORTD |= _BV(PIND2)) #define Turn_Off_SW2 (PORTD &= ~_BV(PIND2)) #define Turn_On_SW3 (PORTD |= _BV(PIND3)) #define Turn_Off_SW3 (PORTD &= ~_BV(PIND3)) #define Turn_On_SW4 (PORTD |= _BV(PIND4)) #define Turn_Off_SW4 (PORTD &= ~_BV(PIND4)) #define Turn_On_Motor (PORTD |= _BV(PIND6)) #define Turn_Off_Motor (PORTD &= ~_BV(PIND6)) //Global Variables volatile static bool gearbox_sensor_flag; volatile uint8_t value; //Fucntion Prototypes bool Fire(bool t_flag); bool Stop_Firing(bool t_flag); void Count_Gearbox_Cycles(bool gs_flag); int main(){ //Sets pin direction, PD6 Motor Drive, PB1 Motor Brake DDRD |= 0x40; DDRB |= 0x02; //Sets initial state of PD6 and PB1 PORTD &= ~0x40; //Motor Drive off PORTB &= ~0x02; //Motor Brake off //Enable Pull Up Resistors PORTC |= 0x05; //PC0(Gbx. Pos.),PC2(Trig.) PORTD |= 0xA0; //PD5,PD7 PORTB |= 0x05; //PB0,PB2 //Enable Global Interrupts and PCINT8 sei(); PCICR |= 0x02; PCMSK1 |= 0x01; //Local Variables static bool trigger_flag; //Main Loop while(1){ trigger_flag = Fire(trigger_flag); trigger_flag = Stop_Firing(trigger_flag); Count_Gearbox_Cycles(gearbox_sensor_flag); if( gearbox_sensor_flag ){ Turn_On_SW2; } else{ Turn_Off_SW2; } if( trigger_flag ){ Turn_On_SW3; } else{ Turn_Off_SW3; } if( value > 3 ){ Turn_On_SW4; } }//End Main Loop } //Main Interrupt ISR(PCINT1_vect){ gearbox_sensor_flag = (Gearbox_Sensor != 0) ? true : false; }//End Main Interrupt //Function Deifinitions-------------------------------------------------------------------------- bool Fire(bool t_flag){ if( t_flag ){ if( Trigger == 0 ) { Turn_On_Motor; t_flag = false; } } return t_flag; }//End Fire bool Stop_Firing(bool t_flag){ if( Trigger != 0 ) { Turn_Off_Motor; t_flag = true; } return t_flag; }//End Stop Firing void Count_Gearbox_Cycles(bool gs_flag){ static bool cgc_flag; if( cgc_flag != gs_flag ) { if( gs_flag ) value++; cgc_flag = gs_flag; } }//End Gearbox Cycle Counter
We are concerned with the Count_Gearbox_Cycles function. I declared this function's return type void because it's only purpose is to increment value by 1 each time Gearbox_Sensor goes high in the main interrupt. However in order to do that properly cgc_flag needs to retain its value between calls and gs_flag needs to be brought into the function each time it is called. I don't see any issues with bringing in gearbox_sensor_flag as a local variable gs_flag in the Count_Gearbox_Cycles function, however it does not count properly when tested, I believe cgc_flag is the culprit, other than making it a global variable, which I actually tried and for some reason that didn't seem to work either, how to make it retain is value between calls?