This week, I wanted to experiment with using magnetic snaps as a switch. The magnetic snaps were purchased from Mood, a fabric store in the Garment District. Using a sewing machine, I created a soft light switch using cloth and polyester filling, attached jumper wires to the magnetic snaps (no soldering necessary) and connected the wires to the Arduino. When the magnets snapped into place, the four yellow LEDs on the Arduino would light up.
Code:
// declare variables:
int switchPin = 8; // digital input pin for a switch
int yellowLedPin1 = 4; // digital output pin for yellow LEDs
int yellowLedPin2 = 5;
int yellowLedPin3 = 6;
int yellowLedPin4 = 7;
int switchState = 0; // the state of the switch
void setup() {
pinMode(switchPin, INPUT); // set the switch pin to be an input
pinMode(yellowLedPin1, OUTPUT); // set the yellow LED pins to be outputs
pinMode(yellowLedPin2, OUTPUT);
pinMode(yellowLedPin3, OUTPUT);
pinMode(yellowLedPin4, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the switch input
switchState = digitalRead(switchPin);
Serial.println(switchState);
if (switchState == 1) {
// if the switch is closed:
digitalWrite(yellowLedPin1, HIGH); // turn on the yellow LEDs
digitalWrite(yellowLedPin2, HIGH);
digitalWrite(yellowLedPin3, HIGH);
digitalWrite(yellowLedPin4, HIGH);
}
else {
// if the switch is open:
digitalWrite(yellowLedPin1, LOW); // turn off the yellow LED
digitalWrite(yellowLedPin2, LOW);
digitalWrite(yellowLedPin3, LOW);
digitalWrite(yellowLedPin4, LOW);
}
}



