Introduction: Atmega128A Proportional Motor Driving - ATMEL ICE AVR Timer UART PWM Control

About: Computer engineer

In this instructable, I'll explain you how to

  • control a DC motor with PWM
  • communicate via UART
  • handle timer interrupts

First of all, we'll use an AVR Core system Development board which you can find on Aliexpress around 4 USD.
The Development board link is here. We'll also use Atmel ICE Debugger and Atmel Studio to program&debug our software.

Step 1: Deep Diving Into Datasheet & Source Code - Clock Speed

In 1. the bullet we define our crystal frequency where we can see on the development board

Attachments

Step 2: Setting UART Registers

In order to communicate with UART you have to set USART Baud Rate Registers – UBRRnL and UBRRnH correctly you can calculate it yourself or you can use online calculator to get correct values easily

Online Calculator

http://ruemohr.org/~ircjunk/avr/baudcalc/avrbaudca...

So MYUBBR value is calculated then,
In register UCSR0B we enable RXEN0(recv enable) TXEN0 (transmit enable) and RXCIE0 (RX for interrupt).
In register UCSR0C we select 8 bit char size.

After we set RX interrupt bit, we should add ISR function for USART0_RX_vect

ISR(USART0_RX_vect){
char rcvChar = UDR0;
if(rcvChar != '\n') {
buffer[bufferIndex] = rcvChar;
bufferIndex++;
}
}

You shouldn't do any business logic in your interrupt service routine. You have to make the function return asap.

Step 3: PWM Settings

In function initPWM we set our CPU clock scaler , Timer/Counter mode as Fast PWM and set Its behaviour with COM bits

We also should connect the DC motor to OC2 pin which is specified in Table 66. Compare Output Mode, Fast PWM Mode in our datasheet, you will also see that OC2 pin is (OC2/OC1C) PB7

Step 4: Result

When you upload the source code in the attachment.

You can enter a new PWM value (0-255) from UART (you can use arduino serial port terminal) to set the DC Motor speed.

Attachments