0

I am learning to use avr-gcc, but I have no idea, how to solve the following task:

The 8 bits from Port B should alternately set from 0 to 1 with an interval of 500 mili seconds.

I appreciate your help.

Daniel Zemljic
  • 443
  • 1
  • 4
  • 8

3 Answers3

2

You can use #include <util/delay.h> , and if you write : _delay_loop_2(1000); you will have a delay of 1 ms; You could use this function:

void delay()
{

    for(int i=0;i<500;i++) 

        _delay_loop_2(1000);
}
mbinette
  • 5,094
  • 3
  • 24
  • 32
Alex
  • 81
  • 5
1

Have a look at this example. This a very basic code for timer0:

#include<avr/io.h>
#include<avr/interrupt.h>
#define F_CPU 1000000UL
unsigned int t=0;
main()
{
    DDRD=0xFF;
    TCCR0=(1<<CS00);
    TCNT0=0;
    TIMSK=(1<<TOIE0);
    sei();
    while(1);
}
ISR(TIMER0_OVF_vect)
{
    t++;
    if(t==40000)
    {
        PORTD=~PORTD;
        t=0;
    }

}
Anthon
  • 69,918
  • 32
  • 186
  • 246
  • Even when you find it to be very basic, its best to add some comments to help others – Mike Apr 07 '13 at 14:11
  • FTR: If you want to make the ISR smaller, you can replace the `PORTD = ~PORTD;` with `PIND = 0xff;`, and make the `t` counter count **down** from `40000` down to `0` instead of up. Or switch to a 16 bit timer and get rid of `t` altogether. – ndim Aug 10 '17 at 23:52
0

As @Alex said you can #include <util/delay.h>, but instant of using the provided code (by @Alex) you can simple use _delay_ms(500);

This will provide you a delay of 500ms.

The choice is yours, just keep in mind that in both cases the frequency of your clock must be defined properly to your compiler:

Example for 16MHz:#define F_CPU 16000000UL

ChrisB
  • 498
  • 3
  • 10