-->

GeeKee CeeBee

Welcome to GeeKee CeeBee's Page: House of Mechatronics Projects & Lessons.
Contact Email: Ceebee1108@gmail.com
Follow me on Youtube
__________________________________________________________________________________________________________________________________

Hi-Freq Square Wave Generator

Simple practical guide to using Arduino for generating high-frequency square wave.
Use of 16bit Timer with simple calculations.
Arduino code provided below.

Components List

Arduino Uno
Jumper Wires

Simple Steps

1) Figure out OCR1A value for desired frequency using following equation.


2) Simply comment/uncomment out the lines in the code to set TCCR1B bits according to the prescalar selected in step(1)



__________________________________________________________________________________________________________________________________

Arduino Code

PID Controller for DC Motor Speed Tracking
    
//GeeKee CeeBee
volatile byte state = 0;
void setup(){

DDRD = B00100000;   //pin5 as output
Serial.begin(9600);
cli();//disable interrupts
  //timer 1:
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  //set compare match register- change this to generate different frequencies
  //  (16Mhz clock/ (prescalar * (2 * desired frequency)))-1
  OCR1A = 79; // = (16 000 000 / (1*2*100000hz) - 1 = 79
  //turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS10 bit for 1 prescaler
  TCCR1B |= (1 << CS10);

 // Set CS11 bit for 8 prescaler (uncomment below line to activate)
  // TCCR1B |= (1 << CS11);

 // Set CS11 CS10 bit for 64 prescaler (uncomment below line to activate)
  // TCCR1B |= (1 << CS11) | (1 << CS10) ;

 // Set CS10 bit for 256 prescaler (uncomment below line to activate)
  // TCCR1B |= (1 << CS12);

 // Set CS12 CS10 bit for 1024 prescaler (uncomment below line to activate)
  // TCCR1B |= (1 << CS12) | (1 << CS10) ;

  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei();//enable interrupts

}

void loop()
{
}


//timer 1 interrupt
ISR(TIMER1_COMPA_vect){
    PORTD ^= B00100000; // toggle pin5 state every timer event to generate sqaure wave
}