- #define motor1 5
- #define motor2 6
- int ultra_sonic(int trigger, int echo){
- digitalWrite(trigger, LOW);
- delayMicroseconds(2);
- digitalWrite(trigger, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigger, LOW);
- int duration = pulseIn(echo, HIGH, 50000);
- int distance = duration * 0.034 / 2;
- return distance;
- }
- void setup() {
- Serial.begin(9600);
- pinMode(9, OUTPUT);
- pinMode(10, INPUT);
- pinMode(3, OUTPUT);
- pinMode(5, OUTPUT);
- }
- void loop(){
- int distance = ultra_sonic(9, 10);
- if (distance > 30){
- for (int i = 0; i<=255; i++){
- analogWrite(motor2, i);
- digitalWrite(motor1, 0);
- if(distance < 30){
- break;
- }
- delay(10);
- distance = ultra_sonic(9, 10);
- Serial.print("distance1: ");
- Serial.println(distance);
- while(i == 255){
- digitalWrite(motor2, HIGH);
- digitalWrite(motor1, LOW);
- distance = ultra_sonic(9, 10);
- if(distance < 30){
- break;
- }
- Serial.print("distance: ");
- Serial.println(distance);
- }
- }
- }
- else{
- analogWrite(motor1, 0);
- analogWrite(motor2, 0);
- }
- }
Recent Pastes