7 years, 11 months ago.

interrupt variable sharing ISR -- main

Hello, i have some trouble to unterstand the usage of exchange value between the ISR and main.

The variable "j" is only int he ISR usable, in main the value of "j" is unknown. If the Timer 2 interrupt ist stopped, it is possible to read the value correct.

Have anyone an idea about my mistake in the example ?

many thanks

/media/uploads/nora/tog_01.cpp

2 Answers

7 years, 11 months ago.

The way you are setting and reading i and j is fine.

There are two issues with your code that I can see.

1) You have a printf to a serial port inside the ISR. printf is slow, serial ports are slow. An ISR should be as fast as possible. If you need to show status in an ISR then either use putc to send a single character or toggle and LED.

2) You main code will check j once and then sit and wait for a key to be pressed. Use pc.readable() to check if there is data waiting and only call getc() is there is something to read.

if (pc.readable()) {
  char command = pc.getc();
        
        switch(command)
        {
            case 'B': case 'b':     // case: Begin
            printf("starting capture...\r\n");
                NVIC_DisableIRQ(TIMER3_IRQn);
                NVIC_EnableIRQ(TIMER2_IRQn);
                break;
            case 'E': case 'e':     // case: End
                NVIC_DisableIRQ(TIMER2_IRQn);
                NVIC_EnableIRQ(TIMER3_IRQn);
                printf("capture ended. \r\n");
                break;
        }
}

7 years, 11 months ago.

Hello,
Since the variable j is declared as global it is visible to both functions TIMER2_IRQHandler and main as well. Because one cannot pass a variable to the TIMER2_IRQHandler function as argument (since it must be void) and to get a result (as the TIMER2_IRQHandler function does not return anything) it is a common techniqe to use a global variable for such purposes. The volatile specifier is preventing the compiler from otimizing the associated code to make sure that the j variable always gets updated and holds the correct value. So I believe that j is updated correctly and agree with Andy that the code does not work as expected due to the bottlenecks pointed out by him.