Hi, I have been trying to understand how to use timer/counter manipulations in order to generate a pwm of a desired frequency. I have to output a 125kHz square wave from th arduino. Can someone show me how?
What mode to select, what values to set (ICR1 or OCR1A/OCR1B), any calculations involved? I would highly appreciate it.
Also, I need to be able to measure the duration between the consecutive pulses in the middle of the pulses rather edge to edge. I need some inputs people. ![]()
Please have a look at the code snippet.
// put your setup code here, to run once:
 //DDRB &= ~(1<<PB0);//pin 8 input //ICP1
 //DDRB &= ~(1<<PB1);
 //PORTB |= (1<<PORTB1);//PORTB Input Pullup
 //DDRB &= ~(1<<PB
 //pinMode(9, OUTPUT);//oc1a
 //DDRD &= ~(1<<PD2);//portd pin2 input
 //PORTD |= (1<<PD2);
 //pinMode(interrupt_pin,INPUT_PULLUP);
 //pinMode(dataIn,INPUT);
 pinMode(PB1,INPUT_PULLUP);
 Serial.begin(115200);
 //attachInterrupt(8, rising, RISING);
 //delayMicroseconds(1000);
 Serial.println("AVR Initialization");
 delay(50);
Â
 //Serial.print(buffer_in);
Â
 cli();
 //Timer 1 interrupt at 125kHz
 //TCCR1A = 0;
 //TCCR1B = 0;
 //TCNT1 = 0;
 ICR1 = 63;
 //turn on CTC mode
 //TCCR1A |= (0<<COM1A1)|(0<<COM1A0)|(0<<COM1B1)|(0<<COM1B0)|(0<<WGM11)|(0<<WGM10); //normal 00//toggle 01//low level 10//high level 11
 //TCCR1B |= (1<<ICNC1);
 TCCR1B |= (1<<ICNC1)|(1<<ICES1)|(1<<WGM13)|(1<<WGM12); //FAST MODE - 8 bit Mode 5
 //Set prescaler 8
 //-------> no prescaler - CS10 - 1; 64 prescaler - CS11, CS10 - 1 <-----//
 TCCR1B |= (0<<CS12)|(0<<CS11)|(1<<CS10); //256 prescaler
 //OCR1A = 127; //[(16000000/(125000*8)] - 1//top value 8 BIT
 //OCR1B = 63;
 //ICR1 = 63;
 //TCNT1 = 0;
 //enable timer compare interrupt
 //TIMSK1 |= (1<<ICIE1)|(1<<OCIE1A)|(1<<TOIE1);
 TIMSK1 |= (1<<ICIE1)|(1<<TOIE1);
 sei();