Search code examples
carduino-unoatmega

Control motors' speed using C in Arduino results in different speed despite having the same value


I'm trying to using C on the Arduino board to control the speed of the 2 motors. However, when uploading the code, each motor runs at different speed despite having the same OCR value. Can you give it a check for the reasons, I would be very appreciate if you do so. The two motors is the same. The board I use is Arduino Uno

#include <avr/io.h>
#include <util/delay.h>

void setup() {
    DDRB = B11111100; 
    DDRD = B00000000;
    TCCR2A = TCCR1A =  B10100011; 
    TCCR2B = B00000001;           
    TCCR1B = B00000100;           
    OCR2A = 0;
    OCR1B = 0;
}

void loop() {
    OCR1B = 255;
    OCR2A = 255;
    PORTB |= _BV(PORTB4);
    PORTB |= _BV(PORTB5);

}

Solution

  • Timer 2 is 8 bit wide, but Timer 1 is 16 bit wide. The motor connected to the OCR1B output gets 255/65535=0.3% PWM, while OCR2A gives 255/255 = 100% PWM to the other motor.

    You can

    • use the CTC (clear timer on compare match) mode
    • use two timers of the same width, like timer 0 and timer 2
    • use two output compare units of the same timer (e.g. OCR1A/OCR1B)