/****************************************** PURPOSE: Running a stepper motor with the Arduino with LEDs and a Proximity sensor Created by Rudy Schlaf after a sketch by Sam Leong Edited for the purpose of my project and added LED incorporation and a proximity sensor by Evan Crall DATE: 11/2015 *******************************************/ #define echoPin 7 //these are the 2 pins connected to the prox. sensor #define triggerPin 6 #define pin1 10 //these are the Arduino pins that we use to activate coils 1-4 of the stepper motor #define pin2 11 #define pin3 12 #define pin4 13 #define LEDpin4 4 //pin that controls LEDs #define delaytime 20 //delay time in ms to control the stepper motor delaytime. //Our tests showed that 8 is about the fastest that can yield reliable operation w/o missing steps void setup() { Serial.begin(115200);//start serial communication pinMode(echoPin, INPUT);//set pinmodes for prox sensor pinMode(triggerPin, OUTPUT); pinMode(pin1, OUTPUT); //define the pins for the stepper as an output pinMode(pin2, OUTPUT); pinMode(pin3, OUTPUT); pinMode(pin4, OUTPUT); pinMode(LEDpin4, OUTPUT); //define the LED pin as an output } void loop(){ Serial.print("The distance is : "); digitalWrite(triggerPin, HIGH); // make a 10usec pulse delayMicroseconds(10); digitalWrite(triggerPin, LOW); int distance = pulseIn(echoPin,HIGH); //now read the pulse that is sent back by the sensor //pulseIn returns the pulse length in usec distance= distance/58; //the distance in [cm] is calculated by pulselength[usec]/58 Serial.print(distance,DEC);// send the measurement to the serial monitor Serial.println(" cm"); delay(10); if (distance>15) { //here is the part where the distance reading determines if the motor runs or not digitalWrite(LEDpin4, LOW); } else { //within 15cm causes the LEDs to light up and the stepper to begin its movement digitalWrite(LEDpin4, HIGH); int numberOfSteps = 50; step_OFF(); //turning all coils off while(numberOfSteps>0){ forward(); //going forward numberOfSteps -- ;//counting down the number of steps } delay(10); step_OFF(); //turning all coils off numberOfSteps = 50; while(numberOfSteps>0){ backward(); //going backward numberOfSteps -- ;//counting down the number of steps } } }