I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.

Can someone help me with the code? Any help is very much appreciated.

Here is my code.

int Pwmpin=9;//Pwm Output Pin
int Fchange= A0;//Frequency change through Potentiometer

void setup() {
  pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
  TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
  TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8

void loop(){
  float freq=0;
  float count=10000,countt=0,Pinput=0;
    ICR1=count;//variable Frequency
    freq= int(16000000/countt);
    Serial.print("Pwm Freq =");
    Pinput=analogRead(A0);//Read input value
    Serial.print("adc value is:");
    Serial.print("pwm value is:");
    if(count>=100000) {
  • And the question is? – Edgar Bonet Jul 10 '17 at 13:36
  • It is difficult to help when we do not how the ADC value should relate to the PWM output. However, keep in mind that ADC conversions are normally noisy and likely should employ techniques to reduce the noise. Also, you might want to look at the micro processor's specifications for the specific processor on your specific Arduino (there are many different types). The PWM values you stated may not be obtainable due to the granularity of the processor's PWM hardware. – st2000 Jul 10 '17 at 14:15
  • You could get 41.6̅% duty cycle with a 12 MHz Arduino (do these even exist?). The closest you can get with a 16 MHz Arduino is 41.875%. – Edgar Bonet Jul 10 '17 at 14:46
  • You appear to be trying to model an analog PWM generator circuit with an MCU - this is probably a bad idea, and would need a higher performance ADC at least. If it all possible, simply using the internal timer to generate PWM digitally would be best. – Chris Stratton Jul 10 '17 at 15:36
  1. Read the datasheet.
  2. Figure out which pen mode works for you and which prescaler and top you need.
  3. Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.

For your application leave the top value alone.

Your code is far from that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.