Hello, can someone check my code and let me know if it's right? I am making a spot welder using a car battery for my project and using arduino to control the solenoid. Basically, the solenoid acts as a switch when pushbutton is pressed and lets the current pass for 30 milliseconds. I got the debounce code from some user from this forum couple of months ago and found the code for solenoid on a different site. For convenience I have attached my schematics, too.
Not seeing why you need debouncing on the switch. Just start the current flow when you see a high-to-low transition on the switch input. Your 20 (should be 30 as PaulS hinted) ms of delay letting the current flow will more than cover any switch bounce time.
Once the 30 ms cycle is done, don't start another until you see the next high-to-low transitions.
I need some guidance regarding my code. I used oscilloscope to observe how my solenoid would behave and I found that it has 17ms closing delay and 12 ms opening delay. I haven't carried out my experiment yet because I don't want to overheat (possibly expulsion due to high current for extended period of time) my metal specimens. Do I need to change my codes or does this code work just fine?
int solenoid_pin = 5;
const byte ButtonPin = 2;
const unsigned long DebounceTime = 30;
pinMode (ButtonPin, INPUT_PULLUP); // Button between Pin and Ground
unsigned long currentTime = millis();
boolean buttonPressed = digitalRead(ButtonPin) == LOW; // Active LOW
static boolean buttonAlreadyPressed = false;
static unsigned long buttonStateChangeTime = 0;
// Check for button change and do debounce
if (buttonPressed != buttonAlreadyPressed &&
currentTime - buttonStateChangeTime > DebounceTime)
// Button state has changed
buttonStateChangeTime = currentTime;
buttonAlreadyPressed = buttonPressed;
// Button was just pressed