As the title says, I need 1khz frequency signal with 10-bit resolution. But I am not good with uControllers and complicated programming.

I need a simple code for this task.

I tried using this Interactive PWM from arduinoslovakia.eu but I dont know what the frequency is at 10-bit resolution and how to set frequency in this code.

  • Are you talking about a square wave? In what way would it have 10-bit resolution? Either it is 1 kHz or not, yes? Are you talking about an error factor? Like, 1 kHz +/- 5% ? – Nick Gammon Aug 17 '19 at 8:33
  • @NickGammon The "10-bit resolution" will refer to the resolution of the duty cycle parameter. i.e., a duty cycle between 0 and 1023 instead of the normal 0 to 255. – Majenko Aug 17 '19 at 12:12
  • Perhaps but the rather brief question does not mention duty cycles. – Nick Gammon Aug 17 '19 at 12:21
  • @NickGammon No, but it does mention PWM, and PWM has a duty cycle (which is what makes it PWM). – Majenko Aug 17 '19 at 14:39

I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.

Assuming you are using a Uno this code will do it:

// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

void setup() 
  pinMode (outputPin, OUTPUT);

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()

You can change the 1000 in the calculation for timer1_OCR1A_Setting, within reason, to get other frequencies.

See my page about timers for more background information.

| improve this answer | |
  • On a 16Mhz Arduino you'd get around 14 bits of resolution, using this code. It is however impossible to get exactly 14-bit (or 10-bit) of resolution without changing the frequency (to around 0.9765kHz). – Gerben Aug 17 '19 at 13:32
  • 1
    To explain that comment, OCR1A would be set to 16000 using the above code, and that is log(16000)/log(2) bits, namely 13.97 bits roughly. Therefore your duty cycle (OCR1B) could be in the range 0 to 15999 giving at least 10 bits of resolution. – Nick Gammon Aug 17 '19 at 21:21
  • Thanks for the answer. – Vikas Kumar Aug 18 '19 at 13:18

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.