Re: Controlling a DC motor with Ultrasonic sensor

Code for a micromotor:

#define trigPin A1
#define echoPin A2
#define m1a 11
#define m1b 3
#define m2a 5
#define m2b 6

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(m1a, OUTPUT);
  pinMode(m1b, OUTPUT);
  pinMode(m2a, OUTPUT);
  pinMode(m2b, OUTPUT);

void loop () {
  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (1000);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration / 2) / 29.1;

  if (distance < 20) {
    analogWrite( m1a, LOW);
    digitalWrite(m1b, 200);
    analogWrite(m2a,  LOW);
    digitalWrite(m2b, 200);
  else {
    analogWrite( m1a, 200);
    digitalWrite(m1b, LOW);
    analogWrite(m2a,  200);
    digitalWrite(m2b, LOW);
  if  (distance > 20) {
    Serial.println("Out of range");
  else {
    Serial.println(" cm");

Moderator edit:
</mark> <mark>[code]</mark> <mark>

</mark> <mark>[/code]</mark> <mark>
tags added.

Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.,148850.0.html

You will get better response if you started your own thread.
I have asked the moderator to see if he/she can give you a new thread for your post.

Tom... :slight_smile:

@edytech, please do not hijack. Thread split.