Hardware Reference
In-Depth Information
Listing 7-3: Bar Graph Distance Control—bargraph.ino
//A bar graph that responds to how close you are
const int SER =8; //Serial output to shift register
const int LATCH =9; //Shift register latch pin
const int CLK =10; //Shift register clock pin
const int DIST =0; //Distance sensor on analog pin 0
//Possible LED settings
int vals[9] = {0,1,3,7,15,31,63,127,255};
//Maximum value provided by sensor
int maxVal = 500;
//Minimum value provided by sensor
int minVal = 0;
void setup()
{
//Set pins as outputs
pinMode(SER, OUTPUT);
pinMode(LATCH, OUTPUT);
pinMode(CLK, OUTPUT);
}
void loop()
{
int distance = analogRead(DIST);
distance = map(distance, minVal, maxVal, 0, 8);
distance = constrain(distance,0,8);
digitalWrite(LATCH, LOW); //Latch low - start sending
shiftOut(SER, CLK, MSBFIRST, vals[distance]); //Send data, MSB first
digitalWrite(LATCH, HIGH); //Latch high - stop sending
delay(10); //Animation speed
}
Load the above program on to your Arduino, and move your hand back and
forth in front of the distance sensor—you should see the bar graph respond
by going up and down in parallel with your hand. If you find that the graph
hovers too much at “all on” or “all off”, try adjusting the maxVal and minVal
values to better fit the readings from your distance sensor. To test the values
you are getting at various distances, you can initialize a serial connection in
the setup() and call Serial.println(distance); right after you perform the
analogRead(DIST); step.
Search WWH ::




Custom Search