#include // Comment below back into the code if using 16MHz crystal //#define CLK16MHZ #ifdef CLK16MHZ #define F_CPU 16000000UL // 1 MHz #define MS_SHIFT 4 #define MS_GATE 0x0f #else #define F_CPU 1000000UL // 1 MHz #define MS_SHIFT 8 #define MS_GATE 0xff #endif #include // convert from loop cycles to msecs #define _delay_ms(x) _delay_loop_2((x)*(F_CPU/4000)) /* void delay_ms(unsigned int t) _delay_loop_2() can only take a 16-bit argument. This routine repeatedly calls _delay_loop_2() in order to get the desired busy wait length. Note that there is some overhead in the loop that is not counted in the delay (so the delay is actually just a little longer) This code is also specific to the 1 MHz clock */ void delay_ms(unsigned int t) { unsigned int nloops = (unsigned short) (t >> MS_SHIFT); unsigned int i; for(i = 0; i < nloops; ++i) { _delay_ms(256); }; i = t & MS_GATE; if(i > 0) { _delay_ms(i); }; }; /* void delay_us(unsigned int t) Busy wait for a specified number of microseconds. Assumptions: - F_CPU is a multiple of 1,000,000 Note: - Maximum delay will vary with F_CPU For a 1MHz clock: - You can delay up to 65536 us - Your resolution is 4 us */ void delay_us(unsigned int t) { _delay_loop_2((t*(F_CPU/1000000)) >> 2); }; ////////////////////////////////////////////////////////////////////////////////////////// int main (void) { unsigned int counter = 0; /* Set PORTB (LEDs) to all outputs */ DDRB = 0xFF; while(1) { // Total delay: 500 ms for(counter = 0; counter < 50; ++counter) { // Delay for 10 ms delay_us(10000); }; PORTB ^= 1; } };