Skip to content

Instantly share code, notes, and snippets.

@Lauszus
Last active October 13, 2015 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lauszus/4261000 to your computer and use it in GitHub Desktop.
Save Lauszus/4261000 to your computer and use it in GitHub Desktop.
Help for Norbert Gauci
#define PWM_FREQUENCY 20000 // The motor driver can handle a pwm frequency up to 20kHz
#define PWMVALUE F_CPU/PWM_FREQUENCY/2 // Frequency is given by F_CPU/(2*N*ICR) - where N is the prescaler, we use no prescaling so frequency is given by F_CPU/(2*ICR) - ICR = F_CPU/PWM_FREQUENCY/2
const uint8_t direction1 = 9;
const uint8_t direction2 = 10;
const uint8_t pwm1 = 11;
const uint8_t pwm2 = 12;
void setup() {
Serial.begin(115200);
pinMode(direction1,OUTPUT);
pinMode(direction2,OUTPUT);
pinMode(pwm1,OUTPUT);
pinMode(pwm2,OUTPUT);
/* Set PWM frequency to 20kHz - see the datasheet http://www.atmel.com/Images/doc8025.pdf page 128-135 */
// Set up PWM, Phase and Frequency Correct on pin 11 (OC1A) & pin 12 (OC1B) with ICR1 as TOP using Timer1
TCCR1B = _BV(WGM13) | _BV(CS10); // Set PWM Phase and Frequency Correct with ICR1 as TOP and no prescaling
ICR1H = (PWMVALUE >> 8); // ICR1 is the TOP value - this is set so the frequency is equal to 20kHz
ICR1L = (PWMVALUE & 0xFF);
/* Enable PWM on pin 11 (OC1A) & pin 12 (OC1B) */
// Clear OC1A/OC1B on compare match when up-counting
// Set OC1A/OC1B on compare match when downcountin
TCCR1A = _BV(COM1A1) | _BV(COM1B1);
setPWM(pwm1,0); // Turn off pwm on both pins
setPWM(pwm2,0);
}
void loop() {
digitalWrite(direction1,!digitalRead(direction1)); // Toggle the direction pins
digitalWrite(direction2,!digitalRead(direction2));
for(uint16_t i=0;i<PWMVALUE;i++) {
setPWM(pwm1,i);
setPWM(pwm2,i);
Serial.println(i);
delay(10);
}
for(uint16_t i=PWMVALUE;i>0;i--) {
setPWM(pwm1,i);
setPWM(pwm2,i);
Serial.println(i);
delay(10);
}
}
void setPWM(uint8_t pin, int dutyCycle) { // dutyCycle is a value between 0-ICR
if(pin == pwm1) {
OCR1AH = (dutyCycle >> 8);
OCR1AL = (dutyCycle & 0xFF);
} else if (pin == pwm2) {
OCR1BH = (dutyCycle >> 8);
OCR1BL = (dutyCycle & 0xFF);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment