codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
//3 leds on pin 2, 4, 6 int a = 2; int b = 4; int c = 6; //the ultrasonic sensors trig and echo are connected to pin 12 and 13 #define trigPin 12 #define echoPin 13 //run only once at the beginning. Define pinMode-s depending on we gonna send or recive data from that void setup() { //LEDs pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); //distance sensor pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } // the loop routine runs over and over again forever: void loop() { int duration, distance; //send the sound digitalWrite(trigPin, HIGH); delayMicroseconds(1000); //wait a little bit digitalWrite(trigPin, LOW); //turn off the sound //perceive when it come back duration = pulseIn(echoPin, HIGH); //convert from time to distance (in cm) distance = (duration/2) / 29.1; //first turn off all the leds digitalWrite(a, LOW); digitalWrite(b, LOW); digitalWrite(c, LOW); if(distance<10) //if very close: 3 leds on { digitalWrite(a, HIGH); digitalWrite(b, HIGH); digitalWrite(c, HIGH); } else if(distance<20) //if close: 2 leds on { digitalWrite(a, HIGH); digitalWrite(b, HIGH); } else if(distance<30) //if not so far: only 1 led on { digitalWrite(a, HIGH); } }
Private
[
?
]
Run code
Submit