/*
Forum: https://forum.arduino.cc/t/chair-occupancy-light-switch/1215354
Wokwi: https://wokwi.com/projects/387817499677410305
*/
// from arduino forum https://forum.arduino.cc/t/pressure-sensor/546144/4
// using sensor that looks like mine
const byte switchPin = 2; // connect the switch to pin 2, the other side to ground
const byte ledPin = 13; // use the built-in LED as an indicator
const byte LightsPin = 3; // this pin sends signal to Mosfet to turn on lights
byte SwitchRead; // variable to store value of the Seat Occupancy Switch
void setup() {
pinMode(switchPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
pinMode(LightsPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// The byte variable SwitchRead is set to HIGH or LOW depending
// on the state read by the function digitalRead(switchPin).
// The exclamation mark (!) in front of a (usually boolean) variable
// is inverting the result of digitalRead(). If the result was HIGH it becomes LOW
// or vice versa.
// As switchPin has been set to pinMode INPUT_PULLUP the return of digitalRead()
// will be HIGH if the button is not pressed (the switch is open) as an internal pullup
// resistor keeps the input state on HIGH level.
// If the button is pressed, switchPin is connected to GND. This draws the state
// to LOW.
// To make sure that the Led and the Light are switched OFF when the button is
// not pressed, the state has to be inverted:
//
// See this table of states
//
// Switch Switch state Light state
// -----------------------------------------------------------------
// not pressed HIGH LOW
// pressed LOW HIGH
//
//
// As loop() loops really quick (not to say damned quick) it is sufficient to
// read the switch state once per loop and use the variable to set ledPin
// and LightsPin.
SwitchRead = !digitalRead(switchPin);
digitalWrite(ledPin, SwitchRead );
digitalWrite(LightsPin, SwitchRead );
Serial.println(SwitchRead);
}