Pages: [1]   Go Down
Author Topic: Introducing delay using timers in arduino  (Read 468 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm doing register level programming in arduino.The goal is to write my own delay logic using timers.Here is the code
Code:
#include<avr/io.h>

int main()
{
  DDRB=(1<<PORTB5);
  TCCR1B=(1<<CS12);
  while(1)
  {
    if(TCNT1>=31250)
    {
      PORTB^=(1<<PORTB5);
      TCNT1=0;
    }
  }
  return 0;
}
The above program is for arduino to introduce delay without using delay function and its working alright.But have a look at the code below.
Code:
#include<avr/io.h>

void setup()
{
   DDRB=(1<<PORTB5);
   TCCR1B=(1<<CS12);
}

void loop()
{
   if(TCNT1>=31250)
   {
      PORTB^=(1<<PORTB5);
      TCNT1=0;
   }
}
When I write it this way,the program is getting compiled but there is no blinking in arduino. What might be the problem?

Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 212
Posts: 8966
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Could it be that the PWM output code (analogWrite()) is configuring Timer1?  Perhaps you have to initialize more than one of the Timer1 registers.

You may also want to try:
Code:
      PINB = (1<<PORTB5);
That toggles the pin without needing the XOR operator.  The PINx register will toggle any bits written as 1.
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The arduino's main function calls "init()" before setup(). init() is defined in your arduino directory under:
{arduino}/hardware/arduino/cores/arduino/wiring.c

See if it is messing with any of the same registers that you are.
Logged

Pages: [1]   Go Up
Jump to: