Hello,
I have a small DC motor (20mA), which only needs to run in one direction.
It's speed shall be regulated via back-EMF. Thus the motor is directly connected between Pin11 and GND. Diode to GND is there.
Using analogWrite(11, dutycycle); works.
However, when I want to measure the back-EMF, then I have to do it at the falling edge of the dutycycle.
Obviously, I could feed pin 11 to pin 1 and have a falling edge IRQ do the job.
Stupid as I am, I thought, it should however also work with T2 as fast PWM generator. IRQ generated on the compare. In the ISR I can then do the motor regulation. That however is a later topic right now.
I don't even get the PWM to work and I'm at my wits end.
What is wrong?
This the important part of the sketch:
void start_motor(void)
{
//digitalWrite(motor_drv,HIGH);
//analogWrite(motor_drv,start_rev);
//TIMSK2 &= _BV(OCIE1B); // disable T1 compare A interrupt
OCR2A = start_rev;
OCR2B = start_rev;
delay(start_time);
OCR2B = mid_rev;
OCR2A = mid_rev;
//TIMSK2 |= _BV(OCIE1B); // enable T1 compare A interrupt
Serial.println("Motor started");
}
void setup() {
// put your setup code here, to run once:
pinMode(motor_drv, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(stall_ind, OUTPUT);
pinMode(shunt, INPUT);
pinMode(motor_pos, INPUT);
k=0;
//PRR &= _BV(PRTIM2); // enable T2
TCCR2B = _BV(CS22); // T2 clk = sysclk/64,
//TCCR2B = _BV(WGM22) | _BV(CS22); // T2 clk = sysclk/64,
//TCCR2B = _BV(WGM22) | _BV(CS20); // T2 clk = sysclk
//TCCR2A = B01100011; // T2 = fast PWM w/ end of duty cycle at OCRA match, output on D11
//TIMSK2 |= _BV(OCIE1A); // enable T1 compare A interrupt
//TIMSK1 |= _BV(OCIE1B); // enable T1 compare B interrupt
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
//TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
Serial.begin(115200);
start_motor();
}
I have uncommented everything in loop() regarding the motor. So it should just run with one straight PWM. Impossible. It either does not run at all or it runs full speed.
Like I said, I don't understand how this should be made to work. The Atmega328p DS and code examples in the Internet do not run the motor with a PWM. Full speed or stop, that's all I get.
Thanks for your help in advance.
BR