Hello programmers,
I made a program to sweep a dc motor back and forth when i press the start button.
I also have a stop button which stops teh program. Yet it only stops the program when i hold this button till the if-loop ends. I would like it to stop instantly.
This is the current code:
#define CW 7 //CW is defined as pin #7//
#define CCW 8 //CCW is defined as pin #8//
const int buttonPin = 2;
const int buttonPin1 = 12;
int buttonState = 0;
int buttonState1 = 0;
int run;
void setup() { //Setup runs once//
Serial.begin(9600);
run = 0; //starts stopped
pinMode(CW, OUTPUT); //Set CW as an output//
pinMode(CCW, OUTPUT); //Set CCW as an output//
pinMode(buttonPin, INPUT);
pinMode(buttonPin1, INPUT);
}
void loop() { //Loop runs forever//
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
if(run == 0)
{
run = 255;
}
else
{
run = 0;
}
}
if(run > 0)
{
digitalWrite(CW,HIGH); //Motor runs clockwise//
delay(5000); //for 1 second//
digitalWrite(CW, LOW); //Motor stops//
digitalWrite(CCW, HIGH);//Motor runs counter-clockwise//
delay(5000); //For 1 second//
digitalWrite(CCW, LOW); //Motor stops//
//code you only run if button was pressed, stops running when button pressed again, so forth...
}
buttonState1 = digitalRead(buttonPin1);
if (buttonState1 == HIGH) {
run = 0;
}
}
//end of code//
With this i want to install 1 photoresistor. it will read the light level in the setup of the program. lets call this startvalue". i want the same resistor to read the light level while the program runs. If the light level is below the startvalue i want the program to stop. I now use this code for the resistor:
int value;
const byte resistorpin = A1;
int lightCal;
Void setup(){
lightCal = analogRead(resistorpin);
}
Void loop(){
if (value < lightCal - 100){
[the code....]
}
I cant get it to work. Sometimes it does stop but only after the loop ends. Does anyone know how i can fix this?
So i need a button to be pressed once and stop my program instantly. And i need a program that uses a resistor to stop the program instantly but for as long as the light level is below the value read in the setup.