Hope some one can help shed some light on a problem.
Using a button to switch an LED on and off, and trigger sound soundfiles in MaxMSP. But when uploading the code and connecting the circuit, the LED 13 keeps lighting on and off without the button being pressed. Often, it just stays lit. And, when pressing the button, it won'
This is the code:
int ledPin = 13; // choose the pin for the LED
int inPin = 7; // choose the input pin (for a pushbutton)
int val = 0; // variable for reading the pin status
void setup() {
Serial.begin(57600);
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inPin, INPUT); // declare pushbutton as input
}
void loop(){
val = digitalRead(inPin); // read input value
if (val == HIGH) { // check if the input is HIGH (button released)
digitalWrite(ledPin, LOW); // turn LED OFF
Serial.println("A");
}
else {
digitalWrite(ledPin, HIGH); // turn LED ON
Serial.println("M");
}
pinMode(inPin, INPUT); // declare pushbutton as input
Firstly this is not technically a declaration - declarations don't do things, they say things about
something. The call to pinMode changes the port/pin registers to make the pin an
input.
But a CMOS input just floats, it has near-infinite resistance, no good you unless you
have pull-up or pull-down resistor alongside the button to set the pin voltage when the
button isn't being pushed
The simplest way to achieve a button input is turn on the built-in pull-up and connect
the button from the pin to GND:
pinMode(inPin, INPUT_PULLUP); // built in pullup for the button pin.
Excellent catch, Mark! The other thing I wouldn't do is declare things that never change as "int". At the very least it is UNSIGNED. The compiler lets you do something like:
#define inPin 7 // Lets you use the pin name but doesn't waste RAM #define ledPin 13
byte val = 0; // Uses only one 8-bit location, unsigned by definition
// Don't have to worry what the other 8 bits are doing