2

I'm trying to debug a problem and need to reduce the speed of the clock on my Arduino Mega from 16MHz to 8MHz.

I can't find any simple way of doing so, so I wanted to know if there were any gurus here who knew if this was possible, as well as how to do it.

WITHOUT PRESCALER:

long int runTime;

void setup()
{
  Serial.begin(9600);     //Setting the data transfer rate 
}

void loop()
{  
  delay(1000);
  runTime = millis();
  Serial.print("Runetime: ");
  Serial.println(runTime);
  delay(100);
  exit(0);
}

OUTPUT: 999

WITH PRESCALER:

long int runTime;

void setup()
{
  Serial.begin(19200);   //Setting the data transfer rate for when CLK Freq. is Halfed

  CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
  CLKPR = _BV(CLKPS0);  // divide frequency by 2
}

void loop()
{  
  delay(1000);
  runTime = millis();
  Serial.print("Runetime: ");
  Serial.println(runTime);
  delay(100);
  exit(0);
}

OUTPUT: 999
Isabel Alphonse
  • 203
  • 1
  • 4
  • 11

1 Answers1

5

You can set the clock prescaler for that:

void setup() {
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
}

This is explained in section 10.12 and 10.13 of the ATmega2560 datasheet.

Of course, changing the clock frequency will mess with the time-related function (millis(), delay() and co.) and the baud rate of the serial port.

Edit: Here is a small program to demonstrate the slowing of the clock:

//#define SLOW_CLOCK

void setup()
{
#ifdef SLOW_CLOCK
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();
#endif
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
}

This makes the LED flash at 1 Hz. If you uncomment the line #define SLOW_CLOCK, it instead flashes at 0.5 Hz.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81