I got a Maxsonar ez-2 (I think, Might be 4). I wired is as follows +5V to pin 1 GRND to pin 0 and signal to pin 3 Analog.
I wrote the following program to make it go. What I want to happen is see the LED turn off and on depending on how far away it is measuring.
All I get is the Infinite distance LED flashing.
Code: Select all
/* ---------------------------------------------------------
* | Arduino Experimentation |
* | Distance Sensor using Maxsonar.
* ---------------------------------------------------------
*
*
*/
const int sensorPin = A0; //sensor on analog 0
//LED Pin Variables
int ledPins[] = {2,3,4,5}; //An array to hold the pin each LED is connected to
//i.e. LED #0 is connected to pin 2, LED #1, 3 and so on
//to address an array use ledPins[0] this would equal 2
//and ledPins[7] would equal 9
/*
* setup() - this function runs once when you turn your Arduino on
* We the three control pins to outputs
*/
void setup()
{
//Set each pin connected to an LED to output mode (pulling high (on) or low (off)
for(int i = 0; i < 5; i++){ //this is a loop and will repeat eight times
pinMode(ledPins[i],OUTPUT); //we use this to set each LED pin to output
} //the code this replaces is below
/* (commented code will not run)
* these are the lines replaced by the for loop above they do exactly the
* same thing the one above just uses less typing
pinMode(ledPins[0],OUTPUT);
pinMode(ledPins[1],OUTPUT);
pinMode(ledPins[2],OUTPUT);
pinMode(ledPins[3],OUTPUT);
*/
}
/*
* loop() - this function will start after setup finishes and then repeat
* we call a function called oneAfterAnother(). if you would like a different behaviour
* uncomment (delete the two slashes) one of the other lines
*/
void loop() // run over and over again
{
int distsensor = 0;
for (int i =0 ; i< 5 ; i++ ) {
digitalWrite(ledPins[i], LOW);
}
delay(50);
distsensor += analogRead(sensorPin);
distsensor /= 8;
if (distsensor > 500) {
digitalWrite(ledPins[0], HIGH);
digitalWrite(ledPins[1], LOW);
digitalWrite(ledPins[2], LOW);
digitalWrite(ledPins[3], LOW);
delay(50);
}
else if (distsensor <= 500) {
digitalWrite(ledPins[3], HIGH);
digitalWrite(ledPins[0], LOW);
digitalWrite(ledPins[2], LOW);
digitalWrite(ledPins[1], LOW);
delay(50);
}
else if (distsensor <= 300) {
digitalWrite(ledPins[2], HIGH);
digitalWrite(ledPins[0], LOW);
digitalWrite(ledPins[3], LOW);
digitalWrite(ledPins[1], LOW);
delay(50);
}
else if (distsensor <= 200) {
digitalWrite(ledPins[1], HIGH);
delay(50);
}
}