makerbotspace
There are lots of tutorials on the web for Arduino, and Digispark is one flavour.
The tutorial suggested will get you started but doesn't toggle the output.
This compiles but is NOT tested.
Its not the prettiest code, but also isn't complicated. (sorry to all you programmers out there)
/*
Button Toggle with debounce..
Pin connections for Digispark
P0 =
P1 = On board LED (Rev A)
P2 = pushbutton (P4 to +5v) use an external pulldown resistor to GND
P3 =
P4 =
P5 = output to transistor (also works for relay shield) ...don't forget the series resistor to the base
M.Beckett Feb 2013
*/
//inputs
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 1; // the number of the LED pin ver A
//const int ledPin = 0; // the number of the LED pin ver B
const int OutputPin = 5; // this is the same as the relay shield
//Settings
boolean OutputState = false; //sets output to off
boolean lastButtonState = LOW; // note the last button read to ensure it is released.
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(OutputPin, OUTPUT);
digitalWrite (OutputPin, LOW); //turn it OFF
//digitalWrite(buttonPin, HIGH); //this sets the internal pullup and isn't really necessary for this
}
void loop()
{
//read the button pin and if HIGH AND doesn't equal last time then next line
if (digitalRead(buttonPin) == HIGH && digitalRead(buttonPin) != lastButtonState)
{
delay(50); // Wait 50mS for debounce and then check again
if (digitalRead(buttonPin) == HIGH) // If it's still HIGH then change the outlet state
{
OutletControl(); // Executes the OutletControl() routine below and then returns
}
}
// ** this needs the button to restore before checking again **
}
void OutletControl()
{
if (OutputState == false) // If it is OFF (note the double equals in an 'if' statement)
{
digitalWrite(ledPin, HIGH); // turn LED ON
OutputState = true; // set the 'flag' for ON
lastButtonState = HIGH; // set the button state HIGH so we don't keep toggling it while its held
digitalWrite (OutputPin, HIGH); // turn it OFF
}
else // It must be already ON
{
digitalWrite(ledPin, LOW); // turn LED OFF
OutputState = false; // set the 'flag' for OFF
lastButtonState = LOW; // set the button state LOW so we don't keep toggling it while its held
digitalWrite (OutputPin, LOW); // turn it OFF
}
// 'returns' back to the line immediately after it was called.
}
The lastButtonState is needed because there are no delays anywhere, it would switch ON and OFF as long as the button was held.
You can also digitalRead an output pin to see if its HIGH or LOW. Useful if more than one process can change it.
All mechanical switches have bounce (think of dropping a tennis ball onto a hard surface), and the cheaper switches are around 25mS ...hence the 50mS delay.
If the sketch is time critical there are other ways of doing this without the delay.
Mark