Hi all,
I'm hoping I've got this right and it seems to work on TinkerCad but just want someone to confirm as I'm new to Arduino and Solenoids.
Here's the setup. Apologies TinkerCad doesn't have a solenoid so I used a DC Motor instead. The idea is I have a third-party controller that acts like a relay so I want to feed an input in/out and then when the inputPin reads either High or Low it triggers the solenoid for a period of time only once. On the board, I added an LED to do the same.
The mini breadboard illustrates the third-party controller and in this picture the input would be high. Will probably play around and create a relay/switch on the mini breadboard to make it more accurate.
Here's the code which works.
// Constants:
const int ledPin = 13; // the pin that the LED is attached to
const int relayPin = 2; // the pin that the third-party controller is attached to
// Variables:
int relayState = 0; // current state of the relay
int lastrelayState = 0; // last state of the relay
void setup()
{
// initialize the relay pin as a input:
pinMode(relayPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop()
{
// read the relay input pin:
relayState = digitalRead(relayPin);
// compare the relayState to its previous state
if (relayState != lastrelayState) {
if (relayState == HIGH) {
// if the current state is HIGH then the button went from off to on:
digitalWrite(ledPin, HIGH);
delay(1500);
digitalWrite(ledPin, LOW);
Serial.println("Relay State is ON");
lastrelayState = relayState;
} else if (relayState == LOW) {
// if the current state is LOW then the button went from on to off:
digitalWrite(ledPin, HIGH);
delay(1500);
digitalWrite(ledPin, LOW);
Serial.println("Relay State is OFF");
lastrelayState = relayState;
}
delay(50);
}
if (relayState == 0) {
Serial.println("Relay State is OFF");
}
delay(50);
}
Any suggestions or comments on what's right and wrong with this?
Thanks in advance for helping.





