I have set up a project using a 16-bit Microcontroller called Thunderbird12, similar to the 9s12/Freescale 68HC12 family. It does a few things but mainly turn on an external water pump. Everything works fine except I need to implement an interrupt. I want to be able to stop the motor using an interrupt through a push button.
I have set up the button which sets pin 0 of port P to high when pressed. Using C, I have initialized the hardware and written the code but the flag is not called. Please see code below.
// Interrupt function
int interruptFlag;
void interrupt 56 WaterPumpRoutine() {
if ((PIFP & 0x01) == 0x01) { // check if pin 0 of port p is high (when button is pressed)
interruptFlag = 1; // set the flag to 1
}
// Main
void main() {
DDRP = 0x00; // set port P as input
PIEP = PIEP | 0x01; // enable interrupts on port P, pin 0
PERP = PERP | 0x01; // enable pull-up/down on port P, pin 0
if ( interruptFlag == 1)
PORTB = (PORTB & 0x00) // Here I'm turning off all the pins in Port B, which includes the pump.
}
If I put this code PORTB = (PORTB & 0x00) inside the WaterPumpRoutine() function, it works fine, but I need to be able to call the flag anywhere. I'm not sure what I'm missing. Any help would be appreciated!
Assuming that the interrupt call works fine..
Change the variable int interruptFlag; to volatile int interruptFlag;. This is to avoid optimizing away the if condition in main by the compiler.
In main you need to reset the interruptFlag on some condition. This is program dependent. Maybe you can do it like this.
if ( interruptFlag == 1)
{
PORTB = (PORTB & 0x00) // Here I'm turning off all the pins in Port B, which includes the pump.
interruptFlag = 0;
}
If you are using a push button, you should introduce a debounce mechanism to avoid detecting multiple inputs.
You need to add the if condition in main inside a while(1) loop as the interrupt can come at any time.
while(1)
{
if(interruptFlag == 1)
{
...
}
}
If u still can't get interrupt to fire , after things that other suggested, you should check if you got global interrupts or interrupt for specific part (GPIO) enabled since in most uc setting GPIO to generate interrupts doesn't enable interrupts
Related
Objective
I am trying to interface a 4x3 matrix keypad and 7 segment LED display to PIC18f4550 microcontroller. When I press buttons on keypad, I want the 7 segment display to show the number accordingly.
What I have done so far
Based on my research, I can either use scanning (continuously polling) or use interrupts to interface the keypad with the MCU. I decided to use interrupts as that way the microcontroller can be free up for other operations.
The following is the connection of keypad to MCU.
I am using RB0-2 as input to MCU and RB4-7 are set as output from MCU. RB4-7 are permanently set high so when the user press on the keypad button, it will trigger the RB0-2(INT0-INT2) interrupt to process.
For simplicity in this post, I will only discuss about the Column 1 of the keypad.
This is how I initialize and setup the registers.
void main(void)
{
OSCCON = 0x72;
TRISD = 0;
LATD = 0;
ADCON1 = 0x0F;
TRISB = 0x07;
LATB = 0xF0;// keep the RB4-7 high
INTCONbits.GIE = 1;
INTCONbits.INT0IF = 0;
INTCONbits.INT0IE = 1;
INTCON2bits.INTEDG0 = 1;
while (1);
}
My interrupt handling is as below:
if(INTCONbits.INT0IF == 1)
{
for(char scan=0x10; scan>=0x80; scan <<= 1) // send 1 to each row starting from RB4 till RB7
{
LATB = scan;
if (PORTBbits.RB0 = 1)
{
if(scan == 0x10)
{
display_number(1);
}
if(scan == 0x20)
{
display_number(4);
}
if(scan == 0x40)
{
display_number(7);
}
}
}
LATB = 0xF0;
INTCONbits.INT0IF == 0;
My problem
When I run the simulation, I noticed that the GIE bit keep toggling very fast between 0 and 1 as soon as I press on any button in Column 1 and no display of any number on 7segment as well. I added the watch window screenshot and highlighted the GIE bit that is toggling.
What have I done wrong? Is my logic of handling interrupt flawed?
UPDATE 1
As DavidHoadley suggested, I have changed to use use unsigned char instead of char.
I have also corrected the for loop condition.
What I observed was, If I keep the loop inside the interrupt routine, the loop will get stuck for some reason.
For now, I have given up trying to use loop inside the interrupt function and instead resort to have a function in main while loop to output high at each row sequentially forever and the interrupt function is only used to check the output using switch statement.
Your for loop end condition looks like the loop will immediately exit. The line:
for(char scan=0x10; scan>=0x80; scan <<= 1)
Should probably be:
for(char scan=0x10; scan<=0x80; scan <<= 1)
Can’t test this - hope it works
It is a normal behaviour for PIC micros. When PIC goes to the interrrupt vector the GIE bit reset by hardware and when it finishes servicing the interrupt, it returns with the RETFIE assembly instruction by setting the GIE bit which is not visible in C code. So there is no fault in your code for this matter, this is not even a matter.
I see in your code you are using only INT0 interrupt to detect presses and the rest of INTx pins are not activated. That's why the PIC micro will be able to detect the changes of the only first column. I suggest you to use interrupt on change (IOC) which features on RB<7:4> bits. This way you can free the INTx pins for other purposes. And you can move the 3 pins to a PORT other than PORTB. Here is the procedure or my suggestion if you interest:
Configure RB<7:4> pins as inputs and enable their IOC feature.
Configure any 3 pins as output of any port.
If you use the positive logic set the 3 pins high otherwise, low.
In your ISR poll the RBIF to know if there is a change on RB<7:4> pins.
If so make a button scan to detect the pressed key.
Unfortunately can't tell you anything for your display issue since you haven't shared the codes and the configuration of display.
I am working on an auto-parking car robot and I am using 8 (hc-sr04) ultrasonic sensors (2 at each side) but the problem is that I am using atmega32 which has limited resources only 3 external interrupts and 3 timers (and even if using interrupts somehow works I might run into risk to have two interrupts triggered at the same time).
I am using this sensor : http://ram-e-shop.com/oscmax/catalog/product_info.php?products_id=907
I've tried using digital I/O pins with polling procedure but it didn't work.
here is the code for polling procedure:
unsigned int read_sonar(){
int dist_in_cm = 0;
init_sonar(); // Setup pins and ports
trigger_sonar(); // send a 10us high pulse
while(!(ECHO_PIN & (1<<ECHO_BIT))){ // while echo pin is still low
USART_Message("echo pin low\r\n");
trig_counter++;
uint32_t max_response_time = SONAR_TIMEOUT;
if (trig_counter > max_response_time){ // SONAR_TIMEOUT
return TRIG_ERROR;
}
}
TCNT1=0; // reset timer
TCCR1B |= (1<<CS10); // start 16 bit timer with no prescaler
TIMSK |= (1<<TOIE1); // enable overflow interrupt on timer1
overFlowCounter=0; // reset overflow counter
sei(); // enable global interrupts
while((ECHO_PIN & (1<<ECHO_BIT))){ // while echo pin is still high
USART_Message("echo pin high\r\n");
if (((overFlowCounter*TIMER_MAX)+TCNT1) > SONAR_TIMEOUT){
USART_Message("timeout");
return ECHO_ERROR; // No echo within sonar range
}
};
TCCR1B = 0x00; // stop 16 bit timer with no prescaler
cli(); // disable global interrupts
no_of_ticks = ((overFlowCounter*TIMER_MAX)+TCNT1); // counter count
dist_in_cm = (no_of_ticks/(CONVERT_TO_CM*CYCLES_PER_US)); // distance in cm
return (dist_in_cm );}
This method doesn't work if I want to read all sensors at the same time, because it gets stuck in the loop for a while.
I also tried using freeRTOS to build a task that checks the state of pins like every 1msec but this won't be a time accurate.
any help?
Assuming that You use internal clock which is 8MHz I would try to handle this inside timer overflow interrupt and would use whole port to connect the sensors.
Use Timer in normal mode or CTC mode (which I find quite intuitive) to ensure periodical interrupts. Set the appropriate period. Remember that the clock has pretty low frequency so don't exaggerate (I think that 0,25 ms will fit).
Connect the sensors to one port, e.g. PORTB. This is a nice situation because ATmega32 has 4 ports with pins numbered from 0-7 and you use 8 sensors so the register for the specific port can cover all of the pins and You can use one read to get states of all of the pins.
Implement the logic:
volatile uint8_t sensors_states;
volatile uint8_t read_flag = 0;
ISR(TIMER0_OVF_vect)
{
sensors_states = PORTB;
read_flag = 1;
}
int main()
{
// Initialize peripherals ...
// You must assume on your own how much time could the pin be held
// in the same state. This is important because the number must not
// be bigger than max value for the type of the array
uint8_t states_time[8] = {0, 0, 0, 0, 0, 0, 0, 0};
uint8_t prev_sensors_states = PORTB;
while(1)
{
// Wait until the flag will be set in the ISR
if(read_flag)
{
for(uint8_t i = 0, mask = 0x80 ; i < 8 ; i ++, mask >>= 1)
{
states_time[i]++;
// Compare the previous state and present state on each pin
uint8_t state = mask & sensors_states;
if((mask & prev_sensors_states) != state)
{
// Here you can use the state of the pin and the duration of that state.
// Remember that when 'state' is > 0 it means that previous state of the
// pin was '0' and if if 'state' is == 0 then the previous pin state
// was '1' (negation).
do_something_with_pin_change(states_time[i], state);
states_time[i] = 0;
}
}
// Save the previous states of the pins
prev_sensors_states = sensors_states;
// Clear the flag to await next data update
read_flag = 0;
}
}
}
If You will try to use FreeRTOS You could use ulTaskNotifyTake and vTaskNotifyGiveFromISR, instead of using read_flag, to implement a simple mechanism which will notify a task from the interrupt that the port has been read. The processor will go into idle state for a while and you could then invoke a sleep function to minimize power consumption.
I don't know what You want to do with this data so I've invoked do_something_with_pin_change function to indicate the point where You can use the data.
To sum up for this solution You would only use one interrupt and of course 8 pins.
I'm trying to get the external interrupt running on a
Nucleo-F030R8
and hit a wall.
Everything is configured and runs just fine in step mode but when I'm connecting my board to another testboard with a simple jumper wire and run the same code, an External Interrupt is triggered even when that testboard (a second
Nucleo-F302R8,
which should only produce a single signal peak that I want to measure with the first) is not turned on.
I'm using a mix of the HAL Library from STM and a bit code of my own.
Has somebody eventually encountered a similar problem?
I'm using the System Workbench for STM32.
Part of the ISR, Interrupthandler is cut
void EXTI0_1_IRQHandler(void)
{
/* USER CODE BEGIN EXTI0_1_IRQn 0 */
if ((EXTI->IMR & EXTI_IMR_MR0) && (EXTI->PR & EXTI_PR_PR0))
{
int_flag_pin.copen = 1;
}
if ((EXTI->IMR & EXTI_IMR_MR1) && (EXTI->PR & EXTI_PR_PR1))
{
int_flag_pin.ma1 = 1;
}
/* USER CODE END EXTI0_1_IRQn 0 */
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_1);
/* USER CODE BEGIN EXTI0_1_IRQn 1 */
/* USER CODE END EXTI0_1_IRQn 1 */
}
Between setting the Pin low and change rising, the Interrupt triggers.
TEST_GPIO_Port->BSRR = (uint32_t) TEST_Pin;
//HAL_GPIO_WritePin(TEST_GPIO_Port, TEST_Pin, GPIO_PIN_RESET);
TEST_GPIO_Port->BRR = (uint32_t) TEST_Pin;
change_rising(0);
Update:
Could it be that resetting the Pin through BSRR or BRR generates an interrupt?
I'm checking my code step-by-step and everytime the pin is getting resetted the interrupt is generated.
if TEST_Pin is GPIO_PIN_0 or GPIO_PIN_1 pin, you will receive irq legally. EXTI0_1_IRQHandler catches irq from any port but from #0 or #1 pin.
I am currently using an interrupt to reset an ATTiny20. Here is the relevant code:
int main(void)
{
...
// Set up interrupt for reset button (PCINT5)
SREG |= 1<<7; // Enable global interrupts
GIMSK |= 1<<PCIE0; // Enable Pin Change Interrupt 0 (enables interrupts on PCINT[7:0]
PCMSK0 |= 1<<PCINT5; // Enable PCINT5 (physical pin 8) interrupt
...
}
The interrupt-handling function:
ISR(PCINT0_vect)
{
if (!(BUTTON_1_PORT & 1<<BUTTON_1_PIN)) // Only reset if button is pushed
{
wdt_enable(WDTO_2S);
while(1){};
}
}
This works quite well - when the button is pushed the system freezes for 2 seconds and then resets... and promptly gets stuck in a reset loop. A bit of googling uncovered the culprit: on newer chips the watchdog timer is left enabled (at its shortest delay setting) after a watchdog reset. The following code is meant to remedy this issue:
// Disable watchdog on reset
void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
void wdt_init(void)
{
// MCUSR = 0; // See below for reason for commenting this line
wdt_disable();
return;
}
*N.B. MCUSR = 0 is commented out because MCUSR does not exist on the ATTiny20. I have tried replacing it with SREG = 0 but to no avail.
Even with this code in place, which should disable the watchdog timer, the issue persists. Flashing LEDs on the device indicate that the program is running through part of the main() function before it resets, but putting wdt_disable(); at the top of main() has not helped either.
Is there something critical that I'm missing re: the ATTiny20? Something I've missed in the datasheet? The problem - and solution - seem so obvious, but I'm stumped. I'm using Atmel Studio 6.1.
// Disable watchdog on reset
void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
void wdt_init(void)
{
// This is the flag that must be cleared on an ATTiny20 before the WDT can be disabled
/***************/
/* RSTFLR = 0; */
/***************?
wdt_disable();
return;
}
I am trying to read analogic signal for a sort of mouse with a pic18f14k50 controller. Here the simple circuit: http://dl.dropbox.com/u/14663091/schematiconew.pdf . I have to read analogic signal from AN9 circuit port. Main function reads from the port, and blinks 30 time if threshold is reached:
void main(void) {
InitializeSystem();
#if defined(USB_INTERRUPT)
USBDeviceAttach();
#endif
while(1) {
if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) continue;
if(!HIDTxHandleBusy(lastTransmission))
{
int readed = myReadADC2(); //Here i tried both myReadADC2() or myReadADC1()
if(readed>40) { //If read threshold > 40, blink led 30 times
int i;
for(i=0; i<30; i++) {
Delay1KTCYx(0);
mLED_1_On();
Delay1KTCYx(0);
mLED_1_Off();
}
}
lastTransmission = HIDTxPacket(HID_EP, (BYTE*)hid_report_in, 0x03);
}//end while
}//end main
I used two method to read from the AN9 port, myReadADC() that uses OpenADC() API method:
int myReadADC(void) {
#define ADC_REF_VDD_VDD_X 0b11110011
OpenADC(ADC_FOSC_RC & ADC_RIGHT_JUST & ADC_12_TAD, ADC_CH9 & ADC_INT_OFF, ADC_REF_VDD_VDD_X & ADC_REF_VDD_VSS, 0b00000010); // channel 9
SetChanADC(ADC_CH9);
ConvertADC(); // Start conversion
while(BusyADC()); // Wait for completion
return ReadADC(); // Read result
}
and myReadADC2(), that implements manual read from the port.
int myReadADC2() {
int iRet;
OSCCON=0x70; // Select 16 MHz internal clock
ANSEL = 0b00000010; // Set PORT AN9 to analog input
ANSELH = 0; // Set other PORTS as Digital I/O
/* Init ADC */
ADCON0=0b00100101; // ADC port channel 9 (AN9), Enable ADC
ADCON1=0b00000000; // Use Internal Voltage Reference (Vdd and Vss)
ADCON2=0b10101011; // Right justify result, 12 TAD, Select the FRC for 16 MHz
iRet=100;
ADCON0bits.GO=1;
while (ADCON0bits.GO); // Wait conversion done
iRet=ADRESL; // Get the 8 bit LSB result
iRet += (ADRESH << 8); // Get the 2 bit MSB result
return iDelay;
}
Both cases doesn't works, i touch (sending analogic signal) port AN9 but when I set high threshold (~50) led don't blinks, with low threshold (~0) it blinks immidiatly when i provide power to the PIC. Maybe i'm using wrong port? I'm actually passing AN9 as reading port? Or maybe threshold is wrong? How can i found the right value? Thank you
Here the MPLAB C18 Apis http://dl.dropbox.com/u/14663091/API%20microchip%20C18.pdf .
Regarding function myReadADC2(): you need to switch ANSEL and ANSELH configs as RC7/AN9 is configured in bit 1 of ANSELH. Also call me paranoid but for the line
iRet += (ADRESH << 8);
I always like to either save it a temporary variable first or cast explicitly the value ADRESH before shifting it up:
iRet += (((UINT) ADRESH) << 8);
That way I know for sure the bits won't get lost when shifting up which has bitten me before.
Regarding function myReadADC():
OpenADC() only takes two parameters. I presume that bitfield in the third parameter field is for the analog enable (ADRESH/ADRES). I'm assuming that's handled by SetChanADC() but you may have to set ADRESH/ADRES manually. It may help to set a breakpoint in the debugger and stop after configuration is complete to make sure your registers are set appropriatley.