I am trying to build a dog treadmill which keeps him centered, by detecting his position using an ultrasound sensor and altering the speed of the treadmill accordingly: a) When he is centered, the speed is at a set point b) As he begins to tire and fall back, the speed of the treadmill will slow c) When he disappears from the treadmill, it will stop completely
Pls kindly advise: 1. For controlling the stepper motor, is it better to use a dedicated Stepper Motor Driver (like the EasyDriver from SaprkFun), or to drive it directly from Arduino through a transistor?
If it is the latter, is it better to use the the Stepper Motor Library , or use the analogWrite(9,ldr) PWM command or similar?
Do you think the following sketch will work? Driving stepper motor speed according to ultrasound distance
include
int ledPin 13; int v = 0; const int pingPin = 7; // Pin no. of the ultrasound sensor's output Stepper myStepper(200, 8,9,10,11); // initialize the Stepper library
void setup() { Serial.begin(9600); // Initialize the Serial port pinMode(ledPin, OUTPUT); // set up the LED pin }
void loop() { long duration, inches, cm; // establish variables for duration of the ping, and the distance result in inches and centimeters
pinMode(pingPin, OUTPUT); digitalWrite(pingPin, LOW); // The PING))) is triggered by a HIGH pulse of >=2 ms. Give a short LOW pulse beforehand to ensure a clean HIGH pulse delayMicroseconds(2);
digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin, LOW); pinMode(pingPin, INPUT); // The same pin reads the signal from the PING))) duration = pulseIn(pingPin, HIGH); // a HIGH pulse, whose duration = time (ms) from sending of the ping to the reception of its echo off an object cm = microsecondsToCentimeters(duration); // convert the time into a distance Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); if (cm < 50) v = v+10;
if (cm > 70) v = v-10;
if (cm > 80) v = 0;
myStepper.setSpeed(v); // set the motor speed at v RPMS }
// PING))) Datasheet : Speed of sound = 340 m/s (29ms/s) or 73.746ms/in (113’/s); /2 to get distance of obstacle.
long microsecondsToCentimeters(long microseconds) // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf { return microseconds / 29 / 2; // divide by 2 to get the distance of object }
Thanks for your kind assistance, in advance.
Wei