I have the following code, which currently uses 6 output pins (pins 8 - 13) from the Arduino to my inverter circuit, which controls a BLDC motor. The code is fine and it works, however I want to add PWM using port manipulation and not analogWrite
, as this is not fast enough for this application.
I know for example I could write OCR1B = 200
, which sets the duty cycle of pin 10 to 200 and replaces the analogWrite
function, but I do not know where to put this in my code. Also, do I need 3 PWM pins as the commutation of a BLDC motor is done in 6 steps in order to do 1 full revolution, or do I only need 1 PWM pin?
void setup() {
pinMode(A0, INPUT); // sensor inputs
pinMode(A1, INPUT);
pinMode(A2, INPUT);
DDRB |= B00111111; // Sets D8, D9, D10, D11, D12 and D13 as OUTPUT
PORTB &= B11000000; // D8 to D13 LOW
}
void loop() {
switch (PINC) {
case 3:
PORTB |= _BV(PB3); // set pin 11 high
PORTB |= _BV(PB5); // set pin 13 high
PORTB &= ~_BV(PB0); //set low
PORTB &= ~_BV(PB1); //set low
PORTB &= ~_BV(PB4); //set low
PORTB &= ~_BV(PB2); //set low
break;
case 2:
PORTB |= _BV(PB3); // set pin 11 high
PORTB |= _BV(PB4); // set pin 12 high
PORTB &= ~_BV(PB5); //set low
PORTB &= ~_BV(PB2); //set low
PORTB &= ~_BV(PB1); //set low
PORTB &= ~_BV(PB0); //set low
break;
case 6:
PORTB |= _BV(PB2); // set pin 10 high
PORTB |= _BV(PB4); // set pin 12 high
PORTB &= ~_BV(PB0); //set low
PORTB &= ~_BV(PB1); //set low
PORTB &= ~_BV(PB3); //set low
PORTB &= ~_BV(PB5); //set low
break;
case 4:
PORTB |= _BV(PB2); // set pin 10 high
PORTB |= _BV(PB0); // set pin 8 high
PORTB &= ~_BV(PB1); //set low
PORTB &= ~_BV(PB5); //set low
PORTB &= ~_BV(PD3); //set low
PORTB &= ~_BV(PD4); //set low
break;
case 5:
PORTB |= _BV(PB1); // set pin 9 high
PORTB |= _BV(PB0); // set pin 8 high
PORTB &= ~_BV(PB2); //set low
PORTB &= ~_BV(PB4); //set low
PORTB &= ~_BV(PB5); //set low
PORTB &= ~_BV(PD4); //set low
break;
case 1:
PORTB |= _BV(PB1); // set pin 9 high
PORTB |= _BV(PB5); // set pin 13 high
PORTB &= ~_BV(PB0); //set low
PORTB &= ~_BV(PB4); //set low
PORTB &= ~_BV(PB3); //set low
PORTB &= ~_BV(PB2); //set low
break;
}
}