#include <avr/io.h>
#include <avr/interrupt.h>
#include <Arduino.h>
void initPWM()
{
DDRB |= (1 << 5); // PORTB5 pin as output for LED 1
TCCR1A = _BV(COM1A1) | _BV(WGM10); // non-inverting mode, fast pwm with top as 0xFF
TCCR1B = _BV(CS11); // prescaler set to clk/8
DDRE |= (1 << 3); // PORTE3 pin as output for motor driver IN1
TCCR3A = _BV(COM3A1) | _BV(WGM30); // non-inverting mode, fast pwm with top as 0xFF
TCCR3B = _BV(CS31);// prescaler set to clk/8
DDRH |= (1 << 3); // PORTH3 pin as output for motor driver IN2
TCCR4A = _BV(COM4A1) | _BV(COM4A0) | _BV(WGM40); // inverting mode, fast pwm with top as 0xFF
TCCR4B = _BV(CS41); // prescaler set to clk/8
DDRL |= (1 << 3); // PORTL3 pin as output for LED2
TCCR5A = _BV(COM5A1) | _BV(COM5A0) | _BV(WGM50); // inverting mode, fast pwm with top as 0xFF
TCCR5B = _BV(CS51); // prescaler set to clk/8
}
//Set motor speed and direction with count registers using information obtained by ADC
void changeDutyCycle(int dutycycle) {
OCR1A = dutycycle; // set PWM duty cycle for LED 1
OCR3A = dutycycle; // set PWM duty cycle for motor driver IN1
OCR4A = dutycycle; // set PWM duty cycle for motor driver IN2
OCR5A = dutycycle; // set PWM duty cycle for LED 2
}
int main()
{
initPWM();// initialize PWM
sei();// initialize Interrupts
while (1)
{
if (flag == 1) {
changeDutyCycle(128); // read ADC value is 1024/4 = 256 and set motor speed accordingly
} else {
changeDutyCycle(0); // Stop PWM signals
}
}
return 0;
}
// Establish ISR using external interput on PORTD
ISR (INT0_vect) {
flag =! flag; // flag with invert command
}