int value=0; // analog value
int index=1;
byte sntmsg[6]; // vector to send
/* sntmsg
sntmsg is a 6 bytes vector:
1st byte is always 0xFF and it is used as a check
2nd to 6th bytes contain 4 analog values read form the arduino input A0 and converted into 10 bit numbers:
2nd byte: most significant 8 bits of the 1st analog value
3rd byte: least significant 2 bits of the 1st analog value + most significant 6 bits of the 2nd analog value
4th byte: least significant 4 bits of the 2nd analog value + most significant 4 bits of the 3rd analog value
5th byte: least significant 6 bits of the 3rd analog value + most significant 2 bits of the 4th analog value
6th byte: least significant 8 bits of the 4th analog value
*/
void setup() {
sntmsg[0] = 0xFF; // byte1: check
Serial.begin(9600); // initialization serial
noInterrupts(); // interrupts OFF
//set timer1 interrupt at 600 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 1hz increments
OCR1A = 416; // = [(16*10^6) / (600*64)]- 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 64 prescaler
TCCR1B |= (1 << CS11) | (1 << CS10);;
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
interrupts(); // interrupts ON
}
ISR(TIMER1_COMPA_vect){ //timer1 interrupt 600Hz
// read analog value
value = analogRead(A0); // read analog value
switch (index) {
case 1:
sntmsg[1]= (byte) (value >> 2); // most significant 8 bits of the 1st analog value
sntmsg[2]= (byte) (value << 6); // least significant 2 bits of the 1st analog value
++index;
break;
case 2:
//most significant 6 bits of the 2nd analog value
bitWrite(sntmsg[2], 5, bitRead(value, 9));
bitWrite(sntmsg[2], 4, bitRead(value, 8));
bitWrite(sntmsg[2], 3, bitRead(value, 7));
bitWrite(sntmsg[2], 2, bitRead(value, 6));
bitWrite(sntmsg[2], 1, bitRead(value, 5));
bitWrite(sntmsg[2], 0, bitRead(value, 4));
sntmsg[3]= (byte) (value << 4); // least significant 4 bits of the 2nd analog value
++index;
break;
case 3:
// most significant 4 bits of the 3rd analog value
bitWrite(sntmsg[3], 3, bitRead(value, 9));
bitWrite(sntmsg[3], 2, bitRead(value, 8));
bitWrite(sntmsg[3], 1, bitRead(value, 7));
bitWrite(sntmsg[3], 0, bitRead(value, 6));
sntmsg[4]= (byte) (value << 2); // least significant 6 bits of the 3rd analog value
++index;
break;
case 4:
// most significant 2 bits of the 4th analog value
bitWrite(sntmsg[4], 1, bitRead(value, 9));
bitWrite(sntmsg[4], 0, bitRead(value, 8));
sntmsg[5]= (byte) (value); // least significant 8 bits of the 4th analog value
index=1;
Serial.write(sntmsg,6); // send value
break;
} // end switch
} // end timer1 interrupt 600Hz
void loop() {
}
Comments