Mega PWM Pin 13: momentary high frequency pwm upon code compile

Hi, I was wondering if someone could help with this. I have a simple program, using Timer 4 to pull PWM Pin 13 high/low alternating every second. This is attached to a relay. When I compile the code, pin 13 outputs PWM - I hear the relay run at like at least 10Hz. However, when I power down and power up, I don't get the same thing, which is why I think it cant be the Setup(). I've attached the code. Quick note: I have recently discovered that Serial inside an ISR is a no-no; however I have left it in because maybe thats the cause? If anyone knows why this is happening, I would appreciate the advice.

#include "Arduino.h"
#define RelayPin 13
#define PIN_OUTPUT 3
//Initialise Pins 
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
int volts[9]={0,0,0,0,0,0,0,0,0};
static const int analog_pins[] = {A5,A6,A7,A8,A9,A10,A11,A12,A13};

boolean toggle4 = LOW;

void setup(){

 //set pins as outputs
 pinMode(RelayPin, OUTPUT);
 cli();//stop interrupts

//set timer4 interrupt at 1Hz
 TCCR4A = 0;// set entire TCCR1A register to 0
 TCCR4B = 0;// same for TCCR1B
 TCNT4  = 0;//initialize counter value to 0
 // set compare match register for 1hz increments
 OCR4A = 15624/1;// = (16*10^6) / (1*1024) - 1 (must be <65536)
 // turn on CTC mode
 TCCR4B |= (1 << WGM12);
 // Set CS12 and CS10 bits for 1024 prescaler
 TCCR4B |= (1 << CS12) | (1 << CS10);  
 // enable timer compare interrupt
 TIMSK4 |= (1 << OCIE4A);

sei();//allow interrupts

}//end setup

ISR(TIMER4_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)


 toggle4 = !toggle4;
 for(int i=0; i<9; i++){

void loop(){
 //do other things here

What you are seeing is the bootloader toggling pin13 as an indicator.

1 Like