views:

322

answers:

4

I'm supposed to write a program that will send some values to registers, then wait one second, then change the values. The thing is, I'm unable to find the instruction that will halt operations for one second.

+7  A: 

How about setting up a timer interrupt ?

Some useful hints and code snippets in this Keil 8051 application note.

Paul R
The IDL bit in the PCON register will put the CPU into the idle state if you need that. The timer interrupt will wake it back up.
mocj
Good point - no sense in sucking up CPU cycles and possibly battery life too, if you're just idling while you wait for a timer interrupt
Paul R
+4  A: 

I would setup a timer so that it interrupts every 10ms. In that interrupt, increment a variable.

You will also need to write a function to disable interrupts and read that variable.

In your main program, you will read the timer variable and then wait until it is 10100 more than it is when you started.

Don't forget to watch out for the timer variable rolling over.

Robert
wait until it is 100 more than it is when you started, perhaps.
Craig McQueen
Craig - you are correct. Those basic math operations get me every time.
Robert
+2  A: 

There is no such 'instruction'. There is however no doubt at least one hardware timer peripheral (the exact peripheral set depends on the exact part you are using). Get out the datasheet/user manual for the part you are using and figure out how to program the timer; you can then poll it or use interrupts. Typically you'd configure the timer to generate a periodic interrupt that then increments a counter variable.

Two things you must know about timer interrupts: Firstly, if your counter variable is greater than 8-bit, access to it will not be atomic, so outside of the interrupt context you must either temporarily disable interrupts to read it, or read it twice in succession with the same value to validate it. Secondly, the timer counter variable must be declared volatile to prevent the compiler optimising out access to it; this is true of all variables shared between interrupts and threads.

Another alternative is to use a low power 'sleep' mode if supported; you set up a timer to wake the processor after the desired period, and issue the necessary sleep instruction (this may be provided as an 'intrinsic' by your compiler, or you may be controlled by a peripheral register. This is general advice, not 8051 specific; I don't know if your part even supports a sleep mode.

Either way you need to wade through the part specific documentation. If you could tell us the exact part, you may get help with that.

A third solution is to use an 8051 specific RTOS kernel which will provide exactly the periodic delay function you are looking for, as well as multi-threading and IPC.

Clifford