Thanks guys for your quick response. Let me explain in detail, I have an arduino UNO and I have a signal generator that gives 125kHz square wave(I have attached a screenshot of it). I want to sample it such a way that I can read the value exactly in middle of the pulse, print it on the serial monitor and even save it in a buffer.
I mean for example, the 125kHz clock pulse has a time period of 8us, which is of 4us high and 4us low pulse(u can see in the screenshot below) so if we try to read it at every 4us then we should be getting 10101010101 but that's not happening.
For testing purpose, I'm using timer 1 to generate the 125kHz square pulse and using timer 2 to read it at every 4us but I don't know how to read the pulse at exactly the middle of it, so that I can get the exact value that I wanted. My code is shown below in the attachment.
#include "Timer.h"
#include "TimerOne.h"
char a[100];
int i=0;
int j=0;
void setup()
{
Serial.begin(9600);
pinMode(3, INPUT);
Timer1.initialize(8); //Timer1 period of 8us, break analogWrite() for digital pins 9&10 on Arduino
Timer1.pwm(9, 512); //generate PWM waveform (on Pin 9 and 50% duty cycle ), output pins for Timer1 are PB pins 1&2
TCCR0A=0;//set entire reg to 0
TCCR0B=0;// set entire reg to 0
TCNT0=0;//set counter to 0
OCR0A=63;//compare match register value obtained from prescaler formula
//CM reg=(clock/prescalar*desired freq)-1 = 64 for prescaler=1, desired freq=250kHz or 4usec
TCCR0A |= (1 << WGM01); //turn on CTC mode
TCCR0B |= (1 << CS00); //set prescalar to 1, thereby no prescaling
TIMSK0 |= (1 << OCIE0A); //enable timer compare INT
}
ISR(TIMER0_COMP_vect) //timer0 INT 250kHz or 4usec
//Thereby repeats at every 4usec, we can use to read data at every 4usec with this
{
if(i<100) //reading first 100 values from pin 3 and storing the buffer a[i]
{
a[i] = digitalRead(3);
}
i++;
}
void loop() {
if(i > 100)
{
for (j=0; j <100; j++)
{
Serial.println(a[j]);//print those first 100 bits on the serial monitor
}
Serial.print("The End"); //print this after we get the first 100 data bits printed on the serial monitor
}
}
Thank you and please correct me if I did anything wrong with the Timer and ISR sections of the code too.
[/code]
