2019年11月15日 星期五

變更組裝,加入超音波測距模組





https://hackmd.io/@yoyostudy/ByGowUKIO


先讓它動起來:

int M1 = 10; //enable right whell
int E1 =12;  //high;forward
int M2 =11;  //enable left whell                    
int E2 = 13; //high:forward

int BUZZER =4;

int TRIGGER_OUT=7;
int ECHO_IN=8;


long ultrasonic_rangefinder()
{
  digitalWrite(TRIGGER_OUT, HIGH);     // 給 Trig 高電位,持續 10微秒
  delayMicroseconds(10);
  digitalWrite(TRIGGER_OUT, LOW);

  long duration = pulseIn(ECHO_IN, HIGH);  

  long cm = (duration/2) / 29.1;        
  return(cm);
}



void motor_forward()
{
  digitalWrite(M1,HIGH);
  digitalWrite(E1,HIGH);
  digitalWrite(M2,HIGH);
  digitalWrite(E2,HIGH);
}

void motor_stop()
{
  digitalWrite(M1,LOW);
  digitalWrite(M2,LOW);
}


void motor_backward()
{
  digitalWrite(M1,HIGH);
  digitalWrite(E1,LOW);
  digitalWrite(M2,HIGH);
  digitalWrite(E2,LOW);
}

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  //initial motor
  pinMode(M1, OUTPUT);
  pinMode(E1, OUTPUT);
  pinMode(M2, OUTPUT);
  pinMode(E2, OUTPUT);

  //initial buzzer
  pinMode(BUZZER,OUTPUT);

  //initial ultrasonic rangefinder
  pinMode(TRIGGER_OUT,OUTPUT);
  pinMode(ECHO_IN,INPUT);

  //motor stop
  digitalWrite(M1,LOW);
  digitalWrite(M2,LOW);

  //buzzer off
  digitalWrite(BUZZER,LOW);

  //ultrasonic rangefinder off
  digitalWrite(TRIGGER_OUT,LOW);
 
}

void loop() {
  // put your main code here, to run repeatedly:
 
  long dist,dist1,dist2;

  delay(50);
 
  dist1=ultrasonic_rangefinder();
  dist2=ultrasonic_rangefinder();
  dist=(dist1+dist2)/2;
 
  Serial.print(dist);
  Serial.print(" ");
  if(dist>50)
  {
    motor_forward();
    digitalWrite(BUZZER,LOW);
  }
  else if(dist<20)
  {
    motor_backward();
    digitalWrite(BUZZER,HIGH);
  }

}


成功....YA!! YA!!

跑得好慢.....Zzzz



沒有留言:

張貼留言