Hi! I'm making an art installation and this code will be a crucial part of my project!
I would like to have ultrasonic sensor input to detect human, and make the motor run.
I hope the motor stops, when no one is approaching.
Closer human interation = motor runs faster.
(*Hopefully I would like to put two ultrasonic sensors.)
I've tried to alter the existing codes.
Please help me
Here is my code:
int smDirectionPin = 8; //Direction pin
int smStepPin = 9; //Stepper pin
int smEnablePin = 13; //Motor enable pin
int trigPin = 11; //sensor
int echoPin = 10; //sensor
void setup(){
 /*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
 Serial.begin(9600);
 pinMode(smDirectionPin, OUTPUT);
 pinMode(smStepPin, OUTPUT);
 pinMode(smEnablePin, OUTPUT);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 digitalWrite(smEnablePin, HIGH); //Disbales the motor, so it can rest untill it is called uppond
}
/*The rotate function turns the stepper motor. Tt accepts two arguments: 'steps' and 'speed'*/
void rotate(int steps, float speed){
 digitalWrite(smEnablePin, LOW); //Enabling the motor, so it will move when asked to
 /*This section looks at the 'steps' argument and stores 'HIGH' in the 'direction' variable if */
 /*'steps' contains a positive number and 'LOW' if it contains a negative.*/
 int direction;
 if (steps > 0){
  direction = HIGH;
 }else{
  direction = LOW;
 }
 speed = 1/speed * 70; //Calculating speed
 steps = abs(steps); //Stores the absolute value of the content in 'steps' back into the 'steps' variable
 digitalWrite(smDirectionPin, direction); //Writes the direction (from our if statement above), to the EasyDriver DIR pin
 /*Steppin'*/
 for (int i = 0; i < steps; i++){
  digitalWrite(smStepPin, HIGH);
  delayMicroseconds(speed);
  digitalWrite(smStepPin, LOW);
  delayMicroseconds(speed);
 }
 digitalWrite(smEnablePin, HIGH); //Disbales the motor, so it can rest untill the next time it is called uppond
}
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)
 {
 rotate(800, 0.1); //The motor rotates 800 steps clockwise with a speed of 0.1 (slow)
 }
 else if(20 <= distance < 30)
 {
 rotate(-1600, 0.5); //The motor rotates 1600 steps clockwise with a speed of 0.5 (medium)Â
 }
  else if(30 <= distance < 50)
 {
 digitalWrite(smStepPin, LOW);
 }
 else;
 {
 digitalWrite(smStepPin, LOW);
 }
 Serial.print (distance);
 Serial.println (" cm");
 delay(500);
}