- Tue Oct 10, 2006 1:09 pm
#20274
Been playing with the MaxSonar-EZ1 module for the past day or so, and figured I'd post my include for it. It's using ADC on an ATMega32 currently, but should work with any AVR that has ADC. It is not the prettiest or most "proper" code, but it works. Here's a shot of it in action:
Code: Select all
Questions/comments always appreciated.// sonar_maxez1.h
//
// Include for MaxSonar-EZ1 sonar ranging module using ADC. Tested on
// ATMega32 under avr-libc/avr-gcc on Linux. Thanks to Paul Daniels
// for the example I ripped the ADC stuff out of.
//
// nihil[at]nihil.rchomepage.com
//
// ADC input (ADC0 by default)
#define ADC_INPUT _BV(REFS0)
// 2.048 = inches, 0.806 = cm
#define SONAR_SCALER 2.048
// Initialize ADC for the module, call once before reading
void sonar_init() {
ADCSRA = _BV(ADEN)|_BV(ADPS1)|_BV(ADPS0);
ADMUX = ADC_INPUT;
}
// Read from the module, returns distance scaled by SONAR_SCALER
unsigned int sonardata;
int sonar_read() {
ADCSRA |= _BV(ADSC);
while(ADCSRA & _BV(ADSC));
sonardata = (ADC/SONAR_SCALER);
return sonardata;
}
// _EOF_