//ECE 476 Final Project //Cooler-Bot Mobile Unit Code //Dan Lee and Robert Zimmerman #include char mode = 2; //start in receive mode char received = 0; //pulse received flag int transleft = 0; //transmit counter signed char Ain[8]; //A/D conversion history char Ainptr = 0; //pointer to history location int ainavg = 0; //average value of history unsigned char ADReady = 0; //conversion ready flag unsigned int time1; //timeout counters #define t1 1 //short timer //Timer0 compare match ISR interrupt [TIM0_COMP] void timer0_compare(void) { char a; //loop variable time1 = t1; //reset the timer switch (mode) { //transmit mode case 1: if (transleft == 1900) //transmit for 100, then wait 1900 ticks (stabilizes speaker) { PORTC.0 = 0; //turn off MOSFET TCCR2 = 0b00001010; //turn off OC2 output } if (--transleft == 0) //at end of timeout { PORTC.0 = 0; //keep MOSFET off mode = 2; //go back to listening ainavg = 0; //reset A/D averager received = 0; //reset received flag //reset history for ( a = 0; a < 8; a++) Ain[a] = 0; //start convertin' ADCSRA = 0b11001100; } break; //receive mode case 2: //if stable pulse received if (received >= 15) { mode = 1; //go to transmit mode received = 0; //reset flag } break; } } //ADC Ready ISR interrupt [ADC_INT] void adcready() { ADReady = 1; } void main(void) { signed char read, dummy; DDRD = 0x80; //PORTD7 = OC2, PORTD2 = 23.8kHz square wave from OC0 DDRB = 0xff; //PORTB3 = OC0 DDRC = 0xff; //PORTC0 = MOSFET control PORTB = 0x00; //initilize PORTC = 0x00; //set up timer 0 and 2 TIMSK=2; //turn on cmp match ISR OCR0 = 41; //28kHz TCCR0=0b00011010; OCR2 = 41; TCCR2=0b00001010; //init the task timers time1=t1; //init the A to D converter ADMUX = 0b01101001; //enable ADC and set prescaler to 1/8 //and start a conversion ADCSRA = 0b11001011; //crank up the ISRs #asm sei #endasm // main loop while (1) { while (!ADReady) //wait for A/D conversion ; read = ADCH; //read it //update history pointer if (++Ainptr == 8) { Ainptr = 0; } //save cycles by updating average by subtracting the oldest //conversion and adding the newest ainavg -= Ain[Ainptr]; //this "multiplies" the input signal by the reference 23.8kHz signal if (PIND.2) Ain[Ainptr] = read; else Ain[Ainptr] = -read; //save the new result ainavg += Ain[Ainptr]; //correlation of 10 required for detection //use positive and negative penalties to avoid false triggering if (ainavg > 10 || ainavg < -10) { received += 3; } else if (received) { received--; } //if pulse not yet detected, keep convertin' if (received < 15) { ADCSRA = 0b11001100; } else { transleft = 2000; //start a transmission PORTC.0 = 1; //turn on MOSFET TCCR2=0b00011010; //turn on OC2 } ADReady = 0; //wait for conversion } }