//Var declaration
int usI0 = 0; //Unscaled value of Analog Input O
float sI0 = 0; //Scaled value of Analog Input O
int y0 = 0; //Minimum scaled value, intercept
int y1 = 10; //Maximum scaled value
float m; //gradient
boolean toggle_timer1 = 0; //storage variable
void setup() {
Serial.begin(9600);
m = y1 - y0;
m = m / 1023;
//Timer1 configuration
//Adapted from: https://www.instructables.com/Arduino-Timer-Interrupts/
cli();//stop interrupts
//set timer1 interrupt at 20 Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 10hz increments
OCR1A = 781;// = (16*10^6) / (20*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}//end setup
ISR(TIMER1_COMPA_vect){//timer1 interrupt 10 Hz toggles a boolean variable
//generates pulse wave of frequency 20Hz/2 = 10 kHz (takes two cycles for full wave- toggle high then toggle low)
if (toggle_timer1){
usI0 = analogRead(A0); //Read from Analog Input O
sI0 = m*usI0;
sI0 = sI0 + y0;
toggle_timer1 = 0;
}
else{
toggle_timer1 = 1;
}
}
void loop() {
//Serial.println();
Serial.println(sI0);
//delay(2000);
}