simple timer0 interrupt to light up ledch is a

Thread Starter

kuannygohcheetatt

Joined Oct 31, 2013
61
Rich (BB code):
//Student Name:Ooi Wei Sheng

#include <pic.h>
/*Lab1.c - Turn ON PORT B 0 LED*/

__CONFIG(0x3f38);

void interrupt timer()
{
	PORTA=1;

	for(int i= 0; i<16;i++)
	{
		while(!T0IF);
		T0IF=0;
		TMR0=0;
		}
		PORTA=PORTA<<1;
}



main()
{


TRISA=0;
OPTION_REG =7;
GIE=7;
T0IE=1;
while(1);


}

this is the code given by my lecturer in order to blink the led for 1 second, but i was wandering, how the led blink ? since after the delay 1s loop which is a for loop looping for 15 times, the program requires the led to shift by 1 bit to the left, however, there is no more delay after shifting it to the left by one bit, doesnt it meant the LED in RA0 will light up forever since the bliking is too fast for our naked eye to detect? can someone explain it to me?
 

takao21203

Joined Apr 28, 2012
3,702
Your code is a bit offtrack, there are some blatant errors as well.

for instance, you use while(!T0IF), which would mean, T0IF is 0, then after it is supposed to have changed, you set it to 0 again.

When a timer interrupt is raised, TMR0IF becomes 1.

Then you need to check if(TMR0IF==1), because there are many interrupts. You also need to reset it with TMR0IF=0 again.

I have put a complete code which blinks a LED slowly on my blog, try to understand how it works. I don't do things inside the interrupt, but I exit again immediately and set a flag.

Also I extend the timer to a 16bit timer (in software). Result, the LED blinks slowly.

http://aranna.altervista.org/dragonsnest/pic-microcontrollers/blinking-led-timer-interrupt-pic-16f/
 

spinnaker

Joined Oct 29, 2009
7,830
please use a capital at the start of a sentence and a period at the end, see how hard this is to read, we want to understand you, the best way to do that is do what you can to make yourself understood.

There is an excellent example of timer interrupts here:

http://www.mikroe.com/products/view/285/book-pic-microcontrollers-programming-in-c/

Along with a a number of other good examples,


If you have a PIC18F45K20, Microchip has some excellent prebuilt lessins, if You can find the code for the Debug Express Lesson Files.
 

takao21203

Joined Apr 28, 2012
3,702
Maybe not so well known is this.

you don't need to enable the interrupt. The flag will become set anyway.

So, you can poll the serial interrupt flag in a while loop without dealing with the latency.

I don't know if it works on all PICs and I don't recall if I ever tried that with the timer.

It's bad practice but when you can improve performance for reading from a serial FLASH *fast*, it is good.

Overclocking the PIC a little, I archieved high refresh rates on a serial TFT.

If you do a lot of testing in the interrupt that adds to the latency, so the display refreshs slower.
 

JohnInTX

Joined Jun 26, 2012
4,787
Here's something I posted in another thread. It shows how to generate and use a system tik using TIMER1 interrupts on a 12F683 using XC8. It flashes a couple of LEDs at different rates.

The key points include:

A single timer interrupt is used to generate a system tik that drives many different timers. TIMER1 is used in this example leaving TIMER0 free for other uses and to free up the WDT prescaler. Different PIC families have other timers more suitable for this but not this one.

It doesn't do IO processing, loops, delays etc. in a PIC interrupt routine, rather it maintains a chain of derived timers, one for each task e.g. flash an LED.

In main, the code screams around the while loop running each task in round-robin sequence.

Each task simply maintains its timer and its LED (or whatever) then return control to the scheduling loop.

Task timing can be a single bit (one systik has elapsed) OR a register a task loads with a number of systiks and waits until it goes to 0 - meaning time has elapsed.

A task is NEVER allowed to wait or delay. If its not time to do something, it returns immediately.

This is a basic example. More complex constructs can be built but even with this simple one, a 4MHz PIC has plenty of time to keep up with everything and more.

In main, the code screams around the while loop running each task in round-robin sequence.

Each task simply maintains its timer and its LED (or whatever) then return control to the scheduling loop.

Rich (BB code):
/* 
 * File:   Guichess.c
 * Author: John
 *
 * Created on February 10, 2014, 11:49 PM
 */

#pragma config FOSC = INTOSCIO // Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = ON // Power-up Timer Enable bit (PWRT enabled)
#pragma config MCLRE = OFF // MCLR Pin Function Select bit (MCLR pin function is digital input, MCLR internally tied to VDD)
#pragma config CP = OFF // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF // Brown Out Detect (BOR disabled)
#pragma config IESO = ON // Internal External Switchover bit (Internal External Switchover mode is enabled)
#pragma config FCMEN = OFF // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is enabled)


#include <xc.h>
#include <stdlib.h>


/************************************************************/
//              HARDWARE CONFIGURATION
/************************************************************/
#define _XTAL_FREQ 8000000
#define usTcyc ((_XTAL_FREQ / 1000000) / 4) // how many uS 1 Tcyc is

//*****************  CODE CONFIGURATION  ********************
#define usSysTik 10000      // 10msec systik
#define ms100PSset 10       // 10 * systik = 100ms


/************************************************************/
//              TIMERS
/************************************************************/
#if 0
    Timer 1 is used to generate a 10msec system tik. Its the
    smallest derived time available and is used to drive the
    debouncer and EE update timer.
    Timer 0 is reserved to free up the prescaler for the WDT.

    The timer runs w/o prescaler so that we can load it with
    an adjusted time without having to worry about clearing the PS
#endif

#define T1CONinit 0b00000000    // No gate, 1:1ps, Internal, OFF
#define TMR1adj 9               // Number of Tcyc it takes to stop-load-start TMR1
                                // determined by looking at disassembly.
    //Calculate reload value for timer counting up to rollover. Result is
    // number of counts based on Tcyc, adjustment, SysTik value etc.
#define TMR1setTiks (2^16-(usSysTik / usTcyc) + TMR1adj)

unsigned char  ms100PreScaler;
bit ms10_happened;      // bits get set by IRQ at the noted time interval
bit ms100_happened;

//Derived timers
// These get loaded with count by main program. They count to 00 and stay there
// When main sees they are 00, it knows to do something

unsigned char Timer10ms_A;
unsigned char Timer100ms_A;

void interrupt isr(void)
{
    //---------------- MAINTAIN SYSTIK  ---------------------
    if(TMR1IF){
        TMR1IF = 0;     // ack the IRQ

        TMR1ON = 0;     // stop the timer, reload it, restart it
        TMR1 += TMR1setTiks;  // any accumulated time + the reload value
        TMR1ON = 1;

        //------------- PROCESS SYSTIK  ------------------------
        // do 10msec stuff here
        // Flag that systik happened
        ms10_happened = 1;                 // flag 10 ms happened
        if (Timer10ms_A) Timer10ms_A--;   // count 10ms timer to 0

        //---------------- 100 ms TIMERS --------------------------
        // 10ms systik is prescaled to 100ms..
        ms100PreScaler--;
        if(ms100PreScaler == 0){
            ms100PreScaler = ms100PSset;        // reset prescaler
            ms100_happened = 1;         // flag 100ms happened
            //--------------- SERVICE 100ms TIMERS  ----------------
            // These timers run at 100ms tiks.
            if (Timer100ms_A) Timer100ms_A--; // maintain Timer100ms_A timer
        }
    } // TMR1IF
}//END OF INTERRUPT SERVICE ROUTINE

void main(void) {
TRISIO = 0b00001000;
GPIO = 0b00000000;
ANSEL = 0;
CMCON0 = 0b00000111;
OSCCON = 0b01110111;

    //--------------- INIT SYSTIK -------------------------------
    // Timer 1 is the master timer.
    // Timer 0 is not used so far.

    T1CON = T1CONinit;  // stop timer, configure it
    TMR1 = TMR1setTiks; // load it
                        // init timer chain
    ms100PreScaler = ms100PSset;

    TMR1IF = 0;         // clear IRQ
    TMR1IE = 1;         // then enable TMR1 interrupt
    PEIE = 1;           // and peripherial IRQ
    TMR1ON = 1;         // start the timer

    //--------------- FIRE UP THE SYSTEM -------------------------
    GIE = 1;            //GLOBAL INTERRUPTS ENABLED

    while(1){
        // Toggle GP1 at 500ms uning a derived timer
        if(Timer10ms_A == 0){
             GP1 = !GP1;
             Timer10ms_A = 50;   // reload timer for next time
        }

        // Toggle GP0 at 100ms using flag
        if(ms100_happened){
            ms100_happened = 0;  // reset flag for next time
            GP0 = !GP0;
        }
    }// while


}//main
EDIT: An easy way to play with this is to compile it for the simulator and set breakpoints in the two 'tasks'. Click run and observe GPIO in the SFR window.
 
Last edited:

takao21203

Joined Apr 28, 2012
3,702
something I oserved for assembler programmers- comment each line even more comment that source.

It's OK however I try to write it with variablesnames and indention so it does not need comments or just a few for the paragraphs.

for instance v_display_refresh_phase should be clear (if you know multiplex).

that said I also see sparely commented sources for Shaders (directx), and when you don't have the prerequisites, it can be baffling.

Of course I write comments, but...

Rather I tend to break up the source like in a tutorial, and write a few lines for points which are not so obvious.

The key seems to be variable names that make sense, and to break up functions, so there is not too mmuch complexity.

Even do a stupid or bad practice thing, if it is increasing readability.

For instance goto in C has some use- where it can reduce line count, reduce distances, and make source easier to read.

I say, use goto sparingly, and it helps- like MSG (monosodium glutamate).

It is not so hard to think in C when the complexity is broken up into the right size pieces.
 

Brownout

Joined Jan 10, 2012
2,390
Here's something I posted in another thread.
It doesn't do IO processing, loops, delays etc. in a PIC interrupt routine, rather it maintains a chain of derived timers, one for each task e.g. flash an LED.
Thanks for sharing. I assume using different methods to check for timeout between the two different derived timers is just to explore different coding schemes, or is there another reason?

Great post. Though I use interrupts, I still struggle with how to use them most effectively.
 

ErnieM

Joined Apr 24, 2011
8,377
Once established, the main loop has no code beyond an infinite loop, so let's ignore it. The interrupt routine does it all:
Rich (BB code):
void interrupt timer()                                             1
{                                                                  2
    PORTA=1;    // *will* turn LED on                              3
    for(int i= 0; i<16;i++)                                        4
    {                                                              5
        while(!T0IF);    // wait here until TOIF is high           6
        T0IF=0;        // clear the rollover flag                  7
        TMR0=0;        // reset the timer count (redundant?)       8
    }                                                              9
    PORTA=PORTA<<1;    // *will* turn LED off till next rollover   10
}                                                                  11
Yes, this is ugly code and demonstrates several bad practices. However, this may actually blink the LED as advertised. It is just "may" as the specific PIC is undisclosed so I cannot be sure if PORTA bit 0 is truly enabled for digital output, but let us assume it does and continue.

The LED remains off until the first timer rollover and gets turned on by line 3. Then we enter the loop, which loops (0 to 15) for a total of 16 times. The first time thru TOIF is high (it's what triggered the ISR) so we drop thru line 6, reset TOIF (line 7) and reset the timer (line 8).

Then the loop goes thru i=1, TOIF is off so we loop at line 6 till it turns back on one rollover interval later, and the same happens for 1 thru 15 (15 times) for a total delay of 15 rollovers.

Then we drop out of the for loop, and PORTA bit zero gets reset by the shift instruction, and we drop out of the interrupt routine. We loop inside main() until the next rollover happens, when the interrupt happens again.

SO... LED is on for 15 rollovers, off for 1. Very ugly code, two main objections:

1: We spend lots and lots of time inside the interrupt routine. This should be a very fast small tight routine.

2: We turn on PORTA bit 1 for no reason whatsoever.


An improved routine would look like so:

Rich (BB code):
void interrupt timer()                                   1
{                                                        2
    static i = 0;                                        3
    if (T0IF)    // test for rollover                    4
    {                                                    5
        T0IF = 0;     //reset rollover flag              6
        if (i < 15)   // see which loop count we're at   7
        {                                                8
            PORTAbits.RA0 = 1;    // turn LED on         9
        }                                               10
        else                                            11
        {                                               12
            PORTAbits.RA0 = 0;    // turn LED off       13
            i = 0;                // reset our count    14
        }                                               15
    }                                                   16
}                                                       17
First, by directly setting PORTA bit 0 (PORTAbits.RA0) we don't change port pins we do not use.

Then we keep the value of i each time we run the routine (that's what "static" does). Loops 0 to 14 we turn the LED on, and only loop 15 do we turn it off. On the outside the LED flashes the same rate, but we use a minimum of time to do this task. Most of the time we "waste" inside main(), which is fine because one day we'll want to do a whole lot more there.
 

takao21203

Joined Apr 28, 2012
3,702
it is extremely bad because once any interrupt goes off, the app will hang until timer int is raised. It may work in a specific case, but it is considerably bad.

The standard is to test if(TMR0IF),
and otherwise skip.

Eventually I did misread it so my answer was a wrong answer about wrong code...

Years ago in assembler I did put all the code in the interrupt handler and later wondered about spurious behaviour when reusing the code.
 

JohnInTX

Joined Jun 26, 2012
4,787
Thanks for sharing. I assume using different methods to check for timeout between the two different derived timers is just to explore different coding schemes, or is there another reason?

Great post. Though I use interrupts, I still struggle with how to use them most effectively.
Your assumption is correct. The code was originally written as an instructional example so different methods are explored. That's also why its heavily commented, much to the consternation of some.. In this case, the bit flags indicate that a tik has happened, sometimes that's enough - I think the original use for one was to drive a switch debouncer - tik tik tik... The countdown timers are for variable numbers of tiks - although only one value is used in the example.

As the tasks get more complex, other constructs are used, state machines etc. but the method is the same, the tasks are 'scheduled' by the 'while' loop and are not allowed to wait or delay.

FWIW, the reason to keep interrupt processing to a minimum in a PIC is that you only get 1 level (in midrange). While processing an interrupt, you can't be further interrupted (unless you are really careful how you do it) and so if you are number crunching or doing some time-intensive task or *horrors* a dumb delay, you can miss things like characters from the UART that can't wait.

My reason for not doing outputs in interrupt routines with midrange/baseline is that if you ever have to shadow the ports to fix a r-m-w problem rising from flipping individual bits on a port, you have to disable interrupts in non-interrupt code before doing shadowed outputs on the same port. Bummer.

A properly implemented interrupt-driven scheme can extend what you can do with a PICs limited resources by a great degree and as you can see from the code snippet, are not real hard to implement.

A final bonus for a scheme like this is that the code gets back to the top of the loop very often. That is a good place to add clrwdt() so you can use the watchdog without having to sprinkle clrwdt() all over the code. Its also a good place to inspect the system settings to make sure an errant task hasn't clobbered something important (like INTCON,GIE maybe - ask me how I know these things..). Inspect and make sure that the interrupts are on, timers are running, ports are set the right way, whatever is important. Fix on the fly or flag it and reset the system as req'd.

Have fun.
 
Last edited:

takao21203

Joined Apr 28, 2012
3,702
put the I2C chips serial FLASH etc. on a plugboard and see what happens.

A LEd should blink or a text be shown "error: I2C memory removed", with some fallback to a default.

One consideration really is if some regular state of the software is essential for the comfort or even survival of animals, people or valueables.

If not, like if you could simply observe the errand condition and press reset, you don't have to care that much, just test it properly.

Normally you'd have more than one CPU, another for probing a regular signal or some conditions, if the frequency goes off or it disappears, you raise an alert, record it, and reset to a default.

OP from a Chinese college. Maybe the exercize made some progress.

2

I have sometimes just disabled the interrupts if needed, just polled the INT flag, and I normally keep update values for ports in memory and then write to all ports at once from updated memory.

Depends how many external chips you drive, how much MCU time you use up, and how much you multiplex the IO.

The way of waiting for the flag in the int handler is something I'd never consider.

Build the task scheduler, and only update the flag, and exit immediately from the int handler (keep it small).

That way, when something goes wrong, you would always exit from it into the int handler.
 

spinnaker

Joined Oct 29, 2009
7,830
put the I2C chips serial FLASH etc. on a plugboard and see what happens.

A LEd should blink or a text be shown "error: I2C memory removed", with some fallback to a default.

One consideration really is if some regular state of the software is essential for the comfort or even survival of animals, people or valueables.

If not, like if you could simply observe the errand condition and press reset, you don't have to care that much, just test it properly.

Normally you'd have more than one CPU, another for probing a regular signal or some conditions, if the frequency goes off or it disappears, you raise an alert, record it, and reset to a default.

OP from a Chinese college. Maybe the exercize made some progress.

2

I have sometimes just disabled the interrupts if needed, just polled the INT flag, and I normally keep update values for ports in memory and then write to all ports at once from updated memory.

Depends how many external chips you drive, how much MCU time you use up, and how much you multiplex the IO.

The way of waiting for the flag in the int handler is something I'd never consider.

Build the task scheduler, and only update the flag, and exit immediately from the int handler (keep it small).

That way, when something goes wrong, you would always exit from it into the int handler.

Where was I2C chips mentioned in this post?

And "the comfort or even survival of animals, people or valueables." What is that all about? And the rest of it for that matter? You are doing nothing but confusing the OP. All he want to do is get a simple timer 0 interrupt working.
 

takao21203

Joined Apr 28, 2012
3,702
Where was I2C chips mentioned in this post?

And "the comfort or even survival of animals, people or valueables." What is that all about? And the rest of it for that matter? You are doing nothing but confusing the OP. All he want to do is get a simple timer 0 interrupt working.
Sure you are right. How do you know it's confusing the Chinese guy?

especially after original question was answered with enough detail for OP to go along with it, I sometimes enjoy to discuss additional, related aspects. I don't consider it hijacking of a thread.

On the one hand people using microcontrollers are expected to get along with TFTs USB and whatnot, on the other hand supposed to be the individuals are totally easy confused with some lines of explanation they have not directly asked for in a very narrow meaning of sense.
 
Top