simple arduino DC/DC buck converter

I needed Arduino to switch MQ-7 CO sensor which needs 5V/0,150mA and 1.4V. 150mA is too much for ATmega, so I needed transistor, but I wanted to supply 5V instead of 4.3V, so I had to make this simple DC/DC buck converter. It uses opamp in comparator mode for boosting Arduino's 5V PWM to something near external 12V supply, and NPN voltage follower for handling quit high current. 
Arduino's PWM is quite slow (default for Timer0 and Timer2 is something like 1kHz), so I had to speed it up:
void setup() {
  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  TCCR2A = 0b10100011; //OC2A - D11 and OC2B -D3, enabled; fast pwm 
  TCCR2B = 0b001; // prescaler =1
  // CPU_CLK=16MHz; Timer2 > 8bit > 256 values; fpwm=16MHZ/256=62.5kHz
    Serial.begin(115200);
}


TCCR2A = 0b10100011; enables PWM on Timer2 and outputs it on Arduino's pins 11 and 3.
TCCR2B = 0b001; sets Timer2 prescaler to 1, which means timer will step every time CPU clock makes step and PWM freq will be 256 times (Timer2 is 8bit) slower than CPU clock. 16MHz/8bit=16MHz/256=62,5kHz.
Timer2 doesn't control time functions, so it's safe to change it's frequency: micros, millis and delays will work as they should. 

So now it's time to put circuit together:


Now there are two ways:
1. Manually adjust PWM value.
2. Do it automatically.

First option would require using potentiometer on A1 and modified AnalogInOutSerial example sketch. Noting down PWM value and then hardcoding it in target sketch.
Second needs calibrating function called in the beginning of program. Function should be something like this:

void PWMcalibration(uint16_t rawvalue){
  uint8_t i=0;
  while((analogRead(A0)<rawvalue){
    analogWrite(3, i);
    delay(100);
    i++;
  }
  Serial.print("PWM = ");
  Serial.print(i);
  Serial.print("\t, A0 = ");
  Serial.print(map(analogRead(A0), 0, 1023, 0, 10000));
  Serial.println("mV");
}

It's safe to use 1/2 voltage divider to sense RL voltage on A0 pin (5V max) as long as opamp/comparator have voltage range: Vcc-1.5V and transistor is silicon one, which clips 0,7V, because this will clip 2,2V from 12V supply and maximum voltage on RL will be 9,8V for 255 PWM value.

Comments