Last active
April 12, 2025 14:42
-
-
Save chendy/69454f6ec77b54f9a710 to your computer and use it in GitHub Desktop.
Arduino code to create a 38.4 Khz (or other frequency) square wave (or other pwm) signal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Code to pulse pin 3 with a (38.4 Khz) modulated signal | |
| * Tested on Arduino Uno | |
| * Mike Cook Nov 2011 - Released under the Open Source licence | |
| * modifications by Senthil Seveelavanan 2015 | |
| */ | |
| volatile byte pulse = 0; | |
| /* Interrupt service routine to pulse the modulated pin 3 | |
| */ | |
| ISR(TIMER2_COMPB_vect){ | |
| pulse++; | |
| // change number for number of modulation cycles in a pulse | |
| if(pulse >= 8) { | |
| pulse =0; | |
| // toggle pin 3 enable, turning the pin on and off | |
| TCCR2A ^= _BV(COM2B1); | |
| } | |
| } | |
| /* sets pin 3 going at the IR modulation rate | |
| */ | |
| void setIrModOutput(){ | |
| pinMode(3, OUTPUT); | |
| // Just enable output on Pin 3 and disable it on Pin 11 | |
| TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20); | |
| TCCR2B = _BV(WGM22) | _BV(CS22); | |
| // defines the frequency 51 = 38.4 KHz, 54 = 36.2 KHz, 58 = 34 KHz, 62 = 32 KHz | |
| OCR2A = 51; | |
| // defines the duty cycle - Half the OCR2A value for 50% | |
| OCR2B = 25; | |
| // select a prescale value of 8:1 of the system clock | |
| TCCR2B = TCCR2B & 0b00111000 | 0x2; | |
| } | |
| void setup(){ | |
| setIrModOutput(); | |
| // Output Compare Match B Interrupt Enable | |
| TIMSK2 = _BV(OCIE2B); | |
| } | |
| void loop(){ | |
| // change the duty cycle to prove working (use oscilliscope) | |
| for (int i=0; i<=51; ++i) { | |
| delay(500); | |
| OCR2B = i; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment