Hey all!
First of all let me introduce myself. My name is Stan. I'm studying Industrial Product Design. And I'm new to this forum.
I'm not completely new to arduino but really experienced neither.
Since a couple of weeks I am working on a project for school where I need to control a DC motor with PWM, read out the speed and need to control a Z-axis (with stepper motor) by reading out the distance with a ultrasonic meter. By pushing a button I can control the Z-axis, and depending on what is measured the stepper will move to the left or right (and so the Z-axis).
The first part of the project is already finished, I can control a DC motor with PWM and read it out with a infrared reflective sensor.
At the end I need to merge the two codes (DC motor PWM, reading speed and Z-Axis) so it all works together.
At this moment I succeeded in making move the stepper motor to the left or right (if measured >60 or <60) by pushing the button. But if I push the button it will keep on measuring.
What I want it to do is by pushing the button it will measure one or two times and based on that measurement move it to a certain direction.
I've did my homework on google before posting it here. But did not get any (good) results compared to my project.
Can please somebody help me?
so, here is the code...
#include <NewPing.h>
#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 6, 7);
int triq = 3;
int echo = 2;
int stepCount = 0; // number of steps the motor has taken
int motorSpeed = 2;
int time = 0;
int timeWait = 500;
int maxDelay = 500;
long pulse, inches, cm;
//int distance = cm;
boolean distance = false;
const int buttonPin = 8;
int buttonState = 0;
NewPing sonar (3, 2);
int readDistance(){
//code to read distance
return distance;
}
void setup() {
Serial.begin(9600);
time = millis();
pinMode(triq, OUTPUT);
pinMode(echo, INPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin); // read input value
if(buttonState == HIGH){
long duration, distance;
digitalWrite(triq, LOW);
delayMicroseconds(2);
digitalWrite(triq, HIGH);
delayMicroseconds(5);
digitalWrite(triq, LOW);
delayMicroseconds(10);
duration = pulseIn(echo, HIGH);
distance = (duration/2) / 2.91;
Serial.print ("mm ");
Serial.print (distance);
Serial.println();
if (distance > 60){
if (motorSpeed > 0)
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(2);
} else {
if (motorSpeed > 0)
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(-2);
}
// put your main code here, to run repeatedly:
}
}