[chbot] AVR external interrupt and Makefile example

Charles Manning manningc2 at actrix.gen.nz
Thu Nov 12 07:31:47 GMT 2009


... and any variable you change in an interrupt but read elsewhere should be 
volatile

eg.
volatile uint16_t count4ms;


See http://en.wikipedia.org/wiki/Volatile_variable

In CPUs like AVR which can disable/enable interrupts quickly then Col's 
approach is fine.

On some other CPU architectures it is cheaper to read the value twice and 
re-read if the value changed. ie something like

 do {
	temp = count4ms;
	tempx = count4ms;
 } while (temp!=tempx);

That's why you publish code. It helps point out your foibles and everyone 
learns... even us old dogs. 

[Don't worry.. today I made a **huge** blunder in the Google Android kernel 
and I learnt a lot!]

-- Charles


On Thursday 12 November 2009 17:40:15 Col wrote:
> Hi Richard
>
> In the interest of the group I would like to point out your supplied
> code contains a race condition.
>
> Basically the count4ms is 16 bit variable on an eight bit micro. If an
> interrupt occurs 1/2 way through reading the variable you could get
> unexpected results.
>
> My suggestion is something like
>
>
> #include <util/atomic.h>
>
> ATOMIC_BLOCK( ATOMIC_FORCEON )
> {
> 	temp = count4ms;
> }
> if ( temp >= 305 ) {
>
>
> This is outlined in the libc user manual.
> http://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html
>
>
> Cheers
> Col.
>
> _______________________________________________
> Chchrobotics mailing list Chchrobotics at lists.linuxnut.co.nz
> http://lists.ourshack.com/mailman/listinfo/chchrobotics
> Mail Archives: http://lists.ourshack.com/pipermail/chchrobotics/
> Web site: http://kiwibots.org
> Meeting Dates:
> Tue 15 December 2009 6.30pm
> Tue 16 February 2010 6.30pm
> When replying, please edit your Subject line to reflect new content.





More information about the Chchrobotics mailing list