Code for creating PWM with Baby Orangutan 328p

i purchased a Baby Orangutan 328p to power a small robot for a university project, but managed to fry the H bridge due to a dodgey motor that was pulling over 1.6A constant jst to get it turning. so i have resorted to buying a higher power H bus, but would like to know if there is an easy way to create a pulse width modulation using the internal clock of the chips processor. if someone could point me in the right direction it would be greatly appreciated. i could probably work out a round about way of creating one with a load of while, for and if statements, but as i am relatively new to programming my code would be long and cumbersome. any pre-made code would be awesome.

Thanks for any help.

I am using the Atmega328p baby-o in combination with the 18V25CS motor driver.

The original code comes from the pololu resources of the 168LV controller and is called demo3

I use timer 2 for generating pwm

Setting up the timer:

TCCR2A = 0xF3; // set OCxx on compare match, clear at TOP with WGM02=0, select fast PWM, TOP=0xFF
TCCR2B = 0x02; // WGM02=0, timer clock = IO clk / 8 => PMW freq = 20MHz/8/256 = 9.77 kHz
OCR2A = 0; OCR2B = 0; // set duty cycles initially for brake

Setting up the outputs:

DDRB  |=  (1 << DDB3); // drive pin high, motor output M2A 
PORTB |=  (1 << DDB3); // Set pin as output
DDRD  |=  (1 << DDD3); // Set pin as output 
PORTD |=  (1 << DDD3); // drive pin high, motor output M2B

Giving the output a value:

OCR2A = pwm; // give pwm a value between 0 and 255 and there you have your pwm

awesome! thanks heaps. i’ll give this a go :slight_smile:

okay, so after a while of trying to understand this code, i have no idea :P. sorry i’m a noob when it comes to this. i sorta understand the setting up the timer part. but i have no clue when it comes to setting up the outputs. what code would i put in if i want to make PB1 and PB2 pins the outputs which go into the H bridge for motor 1 and PB4 and PB5 the outputs for the H bridge that drives motor 2? (note: i have completely fried the board’s h bridge, so i cant use pins M1A, M1B or M2A, M2B)

thanks again for any help.

also, if its easier, is there a way to change wat pin outputs the PWM goes through in the pololu header files?
which file would that be? and wat would need to be changed? (this is if its possible at all)

I have fried two ATmega48 boards in the learning process, I would accept the loss and replace the baby-O.

You can set up timer1 for delivering a pwm signal. In order to do this you have to understand how timers work. I found this excellent tutorial on avrfreaks.

To my understanding the Atmega328p has 6 pwm outputs, chapter7 in the baby-O user guide, timer 1 can still be used.