1. 超声波测距离
void setup ( ) {
Serial. begin ( 9600 ) ;
pinMode ( TrigPin, OUTPUT) ;
pinMode ( EchoPin, INPUT) ;
}
void loop ( ) {
int TrigPin = 2 ;
int EchoPin = 3 ;
float distance;
digitalWrite ( TrigPin, LOW) ;
delayMicroseconds ( 2 ) ;
digitalWrite ( TrigPin, HIGH) ;
delayMicroseconds ( 10 ) ;
digitalWrite ( TrigPin, LOW) ;
distance = pulseIn ( EchoPin, HIGH) / 58.00 ;
Serial. print ( distance) ;
Serial. print ( "cm" ) ;
Serial. println ( ) ;
delay ( 1000 ) ;
}
2. 超声波控灯(可以写多范围)
int TrigPin = 2 ;
int EchoPin = 3 ;
float distance;
void setup ( ) {
Serial. begin ( 9600 ) ;
pinMode ( TrigPin, OUTPUT) ;
pinMode ( EchoPin, INPUT) ;
pinMode ( 4 , OUTPUT) ;
}
void loop ( ) {
digitalWrite ( TrigPin, LOW) ;
delayMicroseconds ( 2 ) ;
digitalWrite ( TrigPin, HIGH) ;
delayMicroseconds ( 10 ) ;
digitalWrite ( TrigPin, LOW) ;
distance = pulseIn ( EchoPin, HIGH) / 58.00 ;
Serial. print ( distance) ;
Serial. print ( "cm" ) ;
Serial. println ( ) ;
if ( distance > 10 ) {
digitalWrite ( 4 , HIGH) ;
} else {
digitalWrite ( 4 , LOW) ;
}
delay ( 1000 ) ;
}
3. 超声波控灯(映射)
int trig = 2 ;
int echo = 3 ;
int s = 0 ;
int n = 0 ;
void setup ( ) {
Serial. begin ( 9600 ) ;
pinMode ( trig, OUTPUT) ;
pinMode ( echo, INPUT) ;
}
void loop ( ) {
digitalWrite ( trig, LOW) ;
delayMicroseconds ( 2 ) ;
digitalWrite ( trig, HIGH) ;
delayMicroseconds ( 10 ) ;
digitalWrite ( trig, LOW) ;
s = pulseIn ( echo, HIGH) / 58.00 ;
Serial. println ( s) ;
if ( s < 50 ) {
n = map ( s, 0 , 50 , 255 , 0 ) ;
analogWrite ( 7 , n) ;
}
else {
analogWrite ( 7 , 0 ) ;
}
}
4. 超声波控制舵机
# include <Servo.h>
Servo servo;
float s ( ) {
float distance;
digitalWrite ( 2 , LOW) ;
delayMicroseconds ( 2 ) ;
digitalWrite ( 2 , HIGH) ;
delayMicroseconds ( 10 ) ;
digitalWrite ( 2 , LOW) ;
distance = pulseIn ( 3 , HIGH) / 58.00 ;
return distance;
}
void setup ( ) {
pinMode ( 2 , OUTPUT) ;
pinMode ( 3 , INPUT) ;
pinMode ( 8 , OUTPUT) ;
servo. attach ( 8 ) ;
servo. write ( 0 ) ;
delay ( 10 ) ;
}
void loop ( ) {
float s2 = s ( ) ;
if ( s2 < 14 ) {
servo. write ( 90 ) ;
delay ( 1000 ) ;
} else {
servo. write ( 0 ) ;
delay ( 10 ) ;
}
}