Arduino vs Avr Studio (solved)

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

    Hi everybody,

 

    I just tried to get an LED ON for one second and OFF for another second. I chose the "L" LED since it is already there (Arduino Uno).

    And I wrote this:

    byte byteSeconds = 0; // this increments to 200 which means one second

    void setup()
    {
      // put your setup code here, to run once:
    DDRB = (1 << 5); // pin 5 becomes an output

    TCNT1 = 0;
    TCCR1B = (1 << WGM12 | 1 << CS11 | 1 << CS10); // start timer1, prescaler = 64, CTC mode

    OCR1A = 1250;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if ((TIFR1 & (1 << OCIE1A)) > 0)
        {
          TIFR1 = (1 << OCIE1A);

          byteSeconds++;
          if (byteSeconds == 200)
          {
            byteSeconds = 0;
            PINB = (1 << 5); // toggle pin 5 in port B register which is marked on the board as SCK
          }
       }
    }

 

    It does not work properly. It blinks faster, about 410ms ON, 410ms OFF.

 

    Not being able to figure out what's the problem, I went to Avr Studio and tried the same thing, slightly different:

#include <avr/io.h>

static uint8_t byteSeconds = 0;

int main(void)
{
    /* Replace with your application code */
  DDRB = (1 << 5);

  TCNT1 = 0;
  TCCR1B = (1 << WGM12 | 1 << CS11 | 1 << CS10);

  OCR1A = 1250;

  while (1)
  {
    if ((TIFR1 & (1 << OCIE1A)) > 0)
    {
      TIFR1 = (1 << OCIE1A);

      byteSeconds++;
      if (byteSeconds == 200)
      {
        byteSeconds = 0;
        PINB = (1 << 5);
      }
    }
  }
}

 

    This one works perfect (although I am not sure OCRA1  should be set to 1250 or 1249).

    I am not looking for "better" ways to do this, I am looking for the reason the Arduino code doesn't work.

    Thank you.

 

edit: how I can delete an empty Quote block ?

Last Edited: Sun. May 21, 2017 - 02:59 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I guess it depends on your clock frequency? Arduino default to 16MHz I think.

John Samperi

Ampertronics Pty. Ltd.

www.ampertronics.com.au

* Electronic Design * Custom Products * Contract Assembly

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Arduino might use timer 1, so you need to fully initialise the timer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

 

Arduino might use timer 1, so you need to fully initialise the timer.

    Right, "TCCR1A = 0;" was missing, thank you.