having issues with Mometary Switch and Servo control

hi i trying to make a Water Shut off… but using a momtary switch but its not working right.
i know i did a different projector for a generator using just a Toggle switch to keep it high or low but it doesnt have that feature of the software may time out in it…
i found code and it has that in there i guess the debounce and mill sec

but what i trying to do is

Press Momentary switch once… opens a Servo 90 degress. press it again goes back… and i wanted Home Assistant to also control it reason i wanted Momentary is it due able? so say Home Assistant turns on the Relay (Valve) when i press the button on the ardunio it would shut it off … u wouldnt need to hit it possibly twice as with momentary ud have to press it twice to get back to OFf state or it wouldnt…

so i wwanted to make like those shut off valves you add to water valves… u can control it from your cell phone but laos there is a button to turn on and off at the valve… so reason i wanted mometary

right now my code makes the servo back and back and forth back and forth a little…
can u see how i could do this? or if someone eles has made it?
https://www.amazon.ca/Owfeel-Control-Compatible-Application-Program/dp/B07SG48KSW/ref=sr_1_1_sspa?dchild=1&keywords=smart+water+valve&qid=1611948713&sr=8-1-spons&psc=1&smid=AICCUJ8EFJI1I&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzU1NONExFV00wWUZRJmVuY3J5cHRlZElkPUEwMDY5MTM1MjFTWDNETEdBQVRLRCZlbmNyeXB0ZWRBZElkPUEwMTQxNTMzMjMzOEdYVFdHSE8wTiZ3aWRnZXROYW1lPXNwX2F0ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=

#include <Servo.h>

Servo waterservo;
int inPin = A0;         // the number of the input pin
int outPin = 9;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin
int wateropen= 90,waterclosed=0;
int counter=0;
// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT);
  //pinMode(outPin, OUTPUT);
  waterservo.attach(outPin);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      {state = LOW;
          waterservo.write(waterclosed);
      }
    else{
      state = HIGH;
     
      if (counter >= wateropen)
 
      {
        counter=counter+1;
        waterservo.write(wateropen);
      }
    }
    time = millis();    
  }

  digitalWrite(outPin, state);

  previous = reading;
}

try this…

#include <mechButton.h>
#include <idlers.h>
#include <Servo.h>


#define BUTTON_PIN   2     // Pin we'll hook the button to. The other side hooks to ground.
#define SERVO_PIN    9
#define wateropen    90
#define waterclosed  0


mechButton  button(BUTTON_PIN);  // Set button one to pin 2.
bool        servoOpen;
Servo       waterservo;


// Your standard sketch setup()
void setup() {
   
   button.setCallback(myCallback);		// Set up our callback. (Also calls hookup() for idling.)
   servoOpen = false;
   waterservo.attach(SERVO_PIN);
}


// This is the guy that's called when the button changes state.
void myCallback(void) {

   if (!button.trueFalse()) {
      if (servoOpen) {
         closeServo90();
      } else {
         openServo90();  
      }
   }
}


//*****************************
// Call these two from wireless
void openServo90(void) {

   waterservo.write(wateropen);
   servoOpen = true;
}


void closeServo90(void) {
   
   waterservo.write(waterclosed);
   servoOpen = false;
}
//*****************************

// Your standard sketch loop()
void loop() {
      
   idle();     // Let all the idlers have time to do their thing.
   
}

Its set up to work with your button hooked to digital #2. I set up calls for your wireless dreams to call when you get that working. Test it with the button first to see if it works at all though. (Might not)

Install LC_baseTools from the library manager to compile this.

-jim lee

ok so doesnt work.. i dont know where to look for LC_basetools.. i did find the manage... im still new at this stuff bought the ardunio kit found that the DHT11 is horrible its soo out of wack lol
but ya
right now its giving me issues mechbutton.h what file do i need there?

so the Openservo90() and closeservo90() does that call a sub routine in the servo.h?

and u took out that milli sec stuff dont i need that? isnt that for when a routine gets stuck in an endless loop?

had a couple other questions but forgot at the moment lol

found how to install LCbase it had to download in the Manage.. as i also googled and downloaded a rar file..

so it works..

so how does work in the code below like the opensevevo90 if i wanna change it say only open 45 is it then openservo45
or do i still use the numbers i gave?
but least its working
and will it hang or get out of hang.. i like it that the code is alot less messy i probably can fix up my other code i wrote to make an automatic generator choking turning fuel on and ten starting engine.. never finished yet but works on tinker cad and on the board lol

i also read to use MQTT with the ardunino u gotta flash it with a different OS but if u do that how do u run this program?

id like to use it with Home Assistant so i can see it working still learning MQTT i not very good at it yet..

and i using a 1k or its 10k resistor in series of the switch is that ok.. i remember i was told i need that incase u fry it..

and what is the wireless option i need for it? since i also learning been told to try ESPHome stuff.. but i got this ardunio uno but it has no network cable like an Raspberry... whats the best to get for the arduno to run with the MQTT home assistant and is the uno good enough or do i go smaller? since this working so far (: which i greatful (:

so i modded the code… i wanted to add 2 LEDS now i remeber i supposed to need certain resistors but i forget what size i need i only have a 10k 1k and 330ohms in the kit.
Red is for for when Valve is open and Green is for the power on
i also found the open90() some reason i couldnt see all the code i in arduniop and everyime it loads it tells me hello 2004 and some issues about loading LCD problems each time the ardunino software loads…
but here is the code

#include <mechButton.h>
#include <idlers.h>
#include <Servo.h>


#define BUTTON_PIN   2     // Pin we'll hook the button to. The other side hooks to ground.
#define SERVO_PIN    9
#define wateropen    90
#define waterclosed  0
#define powerpin     13   //Ardunio On LED Green
#define waterled     14   //Water Valve Open LED Red For On

mechButton  button(BUTTON_PIN);  // Set button one to pin 2.
bool        servoOpen;
Servo       waterservo;


// Your standard sketch setup()
void setup() {
   
   button.setCallback(myCallback);    // Set up our callback. (Also calls hookup() for idling.)
   servoOpen = false;
   waterservo.attach(SERVO_PIN);
   digitalWrite(powerpin, HIGH);      // Light Up PowerPin to Show its Powered up and Running
}


// This is the guy that's called when the button changes state.
void myCallback(void) {

   if (!button.trueFalse()) {
      if (servoOpen) {
         closeServo90();
      } else {
         openServo90();        
      }
   }
}


//*****************************
// Call these two from wireless
void openServo90(void) {

   waterservo.write(wateropen);
   servoOpen = true;
   digitalWrite(waterled, HIGH);
}


void closeServo90(void) {
   
   waterservo.write(waterclosed);
   servoOpen = false;
   digitalWrite(waterled, LOW);
}
//*****************************

// Your standard sketch loop()
void loop() {
     
   idle();     // Let all the idlers have time to do their thing.
   
}

`

i had to change that pin from 14 to 12 noticed there is no pin 14

i tried Red LED and 330ohm servo its very dull is thjat because im running off USB
or i need something else i forget tranisstor i guess.
to toggle from 5volts and the servo i looking at getting runs on 6 volts i guess is that going to be too much power for the ardunino and such?

least the led comes on and off when i hit the button

what would i need if i get a 12volt power adapter to power a servo power this arduno and 2 LEDS what other components i need to see if i can get on amazon

i think i can use the expansion board to solder tthe wires to that came with the kit. or how do you secure the gpios so they dont come out

i want to use either this servo

or

You forgot to put..

pinMode(waterled,OUTPUT);

into your Setup() function.

Might make the LED work better?

Also I'd change the names of..

void openServo90(void);
void closeServo90(void);

to

void openValve(void);
void closeValve(void);

Because it seems like it matches what its doing better.

If you want to change the sero settings, just tweak these values..

#define wateropen 90
#define waterclosed 0

Good luck, seems like you're having fun with it.

-jim lee

so i wanna double check things so i added the output ya shes brighter… so is Green but green isnt that bright as red… so do i need a 100ohm resistor for green? im using both 330 i remember someone on here told me different valvue ohms i need for different colors.

2… Idler routine that is routine you built right? does it have in there the thing that stops ardunino from being in an endless loop that it cant get out of … i ad before you could try to press button but it wouldnt do anything till the sleep timer was done so couldnt break out of it…

3… is it the ESP8266 i want to add ? and is the UNO ok or should i get a smaller arduno… and is the ESPHome boards same as ardunios? so i can upload to them?

and how do you upload wireless connection and my program? wont one erase the other?

and is there a way for future if power is out it remembers the State of the valve

so right noiw i have it forces it it close as there is bug it cant detect if it was open and bugers up
but is there a way if valve open Red light on to say its open if power is lost is there a way to say valve is open flip the light Red on that its in Open state… is that possible to do like computers… to do what last state was
if power is lost and PC was on come on… if not stay off…

// Created by Mike 1/29/2021
// Shut off water Valve.
// with help from a Jim..

#include <mechButton.h>   // Mechanical Button Routin Libary
#include <idlers.h>       // Deals with Ardunio getting Stuck in endless loop
#include <Servo.h>        // Loads Servo Controls


#define BUTTON_PIN   2     // Pin we'll hook the button to. The other side hooks to ground.
#define SERVO_PIN    9     // Pin for The Servo
#define wateropen    90    // Postion Of Valve when Opened
#define waterclosed  0     // Postion Of Valve when Closed
#define powerpin     13    // Ardunio On LED Green
#define waterled     12    // Water Valve Open LED Red For On

mechButton  button(BUTTON_PIN);  // Set button one to pin 2.
bool        servoOpen;
Servo       waterservo;


// Your standard sketch setup()
void setup() {
   
   button.setCallback(myCallback);    // Set up our callback. (Also calls hookup() for idling.)
   servoOpen = false;                 // Defaults Servo Open to False So Auto Closed
   waterservo.attach(SERVO_PIN);      // Sets Servo Pin
   closeValve();                      // makes sure vavle is closed even when power is out when valve was open at time
   pinMode(waterled,OUTPUT);          // Sets Water LED ON OFF to Output
   pinMode(powerpin,OUTPUT);          // Sets Power Pin To Output
   digitalWrite(powerpin, HIGH);      // Light Up PowerPin to Show its Powered up and Running
}


// This is the guy that's called when the button changes state.
void myCallback(void) {

   if (!button.trueFalse()) {
      if (servoOpen) {          // If Servo Valve Is Open and Button Pressed Close it.
         closeValve();          // Call CloseValve Routine
      } else {
         openValve();           // If Servo Valve Is Closed and Button Pressed Open It
      }                         // Call OpenValve Routine
   }
}


//*****************************
// Call these two from wireless

// Open Valve Routine
//====================
void openValve(void) {

   waterservo.write(wateropen);         // Writes To Pin To Open Valve
   servoOpen = true;                    // Set ServOpen Value to True
   digitalWrite(waterled, HIGH);        // Turn On LED to display Water Valve is Open
}



// Close Valve Routine
//=====================
void closeValve(void) {
   
   waterservo.write(waterclosed);       // Writes To Pin To Close Valve
   servoOpen = false;                   // Sets ServoOpen Value To False to Say its not open
   digitalWrite(waterled, LOW);         // Turns Off LED to display Water Valve Is Closed
}
//*****************************

// Your standard sketch loop()
// Idles but also doesnt let Ardunino in and Endless loop if it gets stuck
void loop() {
     
   idle();     // Let all the idlers have time to do their thing.
   
}

330 is typically a fine choice for LEDs

idler(); Its a Q&D threading thing for Arduino, yes I wrote it. Basically its a way to add things that can run by themselves.

mechButton is an example of this. It just runs behind the scenes not getting in your way until you hit the button. Then, after dealing with all the debouncing nonsense, it calls the function that it's attached to letting you deal with the click as you see fit. You can create as many buttons as you like. Just create more of them.

Blink without delay? Not a problem. there's a blink object in that library that will blink an LED without you having to do more than tell it a pin number and turning it on. idle() runs that as well.

Everyone tells you that delay() is Bad. It is! But now that you have idle() you also get.. sleep(). sleep() stops your main loop() just like delay, but leaves all the background stuff running.

Think of idle() as an extension of loop(), you just can't see that part.

is it the ESP8266 i want to add ?

Sorry. I've no idea!

how do you upload wireless connection and my program? wont one erase the other?

Again, sorry no clue.

-jim lee

As for the state of the valve? I’d look into maybe putting a micro switch on the valve itself? Some way to actually let the valve give you the “real” information. Then let that control the servoOpen variable instead of just blindly deciding its a success.

-jim lee

ah ok didnt know i mentiuoned blinking but always learning.. i no pro i dabbled over the years electronics kid of 80 90s so had the 200 -in one radio shack electronics kit lol.

so i do enjoying dabling hjere least i can make a project....
so your idler takes all the work out of the delay then so if you ever wanted a certain delay what would uwant..
at this point i dont need it...

as for the state.. does the ardunino support writting to a File?
so
Status.txt
Open ==> Means Its Open
Closed===> Means its Closed

and that the program reads the text text file
If Open==> Flip Red Light On We On Set To On Mode
if Closed==>Dont Turn LED On Set To Off Mode
If File cant be read (do to a crash corrupt ) default Servo To Closed like a reset

how hard would that need to incorporate...

i also have a project likd like to do i have old Coin Operated Popcorn machine with big circuit board id like to duplcate it with an ardunio figure it is possible..

and is this code also able to work on a Raspberry Pi?
like can it be copied straight over ..

and if i cant get the wifi to work i wanted to either run couple wires from the raspberry pi to 2 pins on ardunio or run it off pi

but ill look into more of the wireless stuff.. i did look a little tells u u need a android phone to set it up i cant see why i cant just edit a config.txt file upload it and boom your done.. still learning

wish i had thius in the 80s 90s

i tried googing it only comes up with reading a text file off a computer or an SD card
i figured i could read from the ardunino itself

i wonder how my pop corn machine works then as there was no SD cards back then just a chip i guess

oh and how does the LED without a resistor damage the ardunino i didnt understand that when i was kinda explained to

isnt the LED acting like a resistor anyways.. and it only draws as much power was it needs.. or does a LED draw more then an ardunino can supply??

and if i found a 100ohm reisster that make the Green Brighter right?

and are supposed to run LEDs right off the ardunino or you supposed to run them off a Tranisistor switch? as i remember i was told i should use those too

Read up on the EEPROM of the Arduino. You can use that to store info. when the power goes off.

As for the rPi you can code the rPi in c++ its a very common language.

LED without a resistor acts like a direct short. Basically becomes a one shot colored flashbulb. Unless it fries the pin on the Arduino.

You can usually run LEDs from the pins.

-jim lee

oh ok thanks.. i had couple more questions..
are the ESP32 are they an ardunio? you can program them.. only reason i ask is can i shove my program i wrote now on the Arduino uno on a ESP32wroom? as it has the wifi built on and its smaller..
but i didnt wanna order one if it wont work

2nd.. i read about Diming LED and Fade LED and i added them in the library
but i cant figure out how to set it
i dont want run a running Fade
i wanna do like
FadeLED (12) =5 //so basiclly Fades Pin 12 to a 5th LEvel of brightness. this way i could dim Red LED to match the Green LED's brightness without needing Different LEDSs

and can i power both Servo and Ardunino off the same power supply like in the pic i have without damaging it or do i need a diode or anything tryin to figure what i need to order off amazon

so a LED is almost like an explosion or like touching Ground to Postive and you get that spark

ill look up that EEPROM stuff
and if i can write it in C++ can i just import my code here to the Raspberry Pi? or i have to re write it?
and if i need to re write it do you know how to write it there too?

which is the best way for my code?
id like Wifi or possibly network cable since network cable always better over wifi.. and work with Home Assistant

i know the ardunios are cheaper then rpi i just trying to figure whats best way ??
as i want if home assistant tells thius ardunio to activate to turn on to simulate i pressed the button
which is way is easier throught what i got now.. or a rpi?

i was thinking my water project work ok for my generator application

but i thinking ardunio cant
i also need to be able to edit Timers to come on a certain times like Outdoor Timer
so i edit the file this week it come on every hour for 15 min
and then id edit for the 2nd week it comes on every 2 hours for 15 min
i think you gotta re program the arduino each time its nothing you can ssh in and run crontab so it would run will it..

if not that that bites.. but it will work for my other project i got 3 buttons.. due to other projects had to put away but its to convert a regular generator to push button start

@jimlee do you have experience in writting in raspberry pi as id like to convert this code to raspberry pi

gonna use this current code for generator but i guess i going to raspberry pi but i know this coding works

and from raspberry pi i only seen toggle switchs not momemtary switch

unless there is a device or way to edit the ardunino when need that i can edit easily so i can change it easily without having to re program unit

some days id want the valve to turn Open 5 times next day could be 10 times but id edit it from remote computer