Hi,
I want to create a WIFI enabled Socket, to control TV, Coffee Maker etc. Spark core work fine. But always use Smartphone to ON or OFF Electrical Appliance. I want a manual over ride such as a momentary touch switch to ON or OFF Product with out SmartPhone. I need help here
If you can post your current code, we can help you add that in. You need only a pushbutton wired from a digital pin and you will add to your code something like this:
#define BUTTON_PIN 2
byte lastButtonState = HIGH;
unsigned long timer = 0;
void setup()
{
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop()
{
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState && timer > 100UL)
{
if (buttonState == LOW)
{
//do something here!
Serial.println("Pressed!!");
timer = millis();
}
}
lastButtonState = buttonState;
//
// do your other stuff here
}
@BulldogLowell, the tip is great, but just some notes on your code.
Please try to use D2 rather than the Arduino way to only use numbers (e.g. 2).
And for your timer I guess you rather want to do something like (millis() - timer > 100UL).
And @Sam, you’d need to wire the button between GND and D2 in order to use this code (just to fill in the gaps, if you didn’t know already).
you are on the right track Try this, I have tested and it works like this:
Button press Toggles led
use curl commands in the code to turn it off, on, or toggle it with a 0, 1, or 2 respectively
const int buttonPin = D2;
const int ledPin = D7;
int ledState = HIGH;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup()
{
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
Spark.function("toggleLed", toggleLed);
}
void loop()
{
// this block is your run-of-the-mill pin state change with a debounce
int buttonState = digitalRead(buttonPin);
if ((buttonState != lastButtonState) && (millis() - lastDebounceTime > debounceDelay))
{
if (buttonState == LOW)
{
Serial.println("Pressed!!!");
ledState = !ledState; // Toggle the led wth the button press
lastDebounceTime = millis();
}
}
lastButtonState = buttonState;
// you can leave this here....
digitalWrite(ledPin, ledState);
}
// add this block to control via curl
// * To turn on/off
// * curl -k https://api.spark.io/v1/devices/<yourSparkID>/toggleLed -d access_token=<yourAccessToken> -d params=<0 or 1> // or send a '2' and Toggle the led
//
int toggleLed(String command)
{
int value = command.charAt(0) - '0';
if (value == 0 || value == 1)
{
ledState = value;
return value;
}
else if (value == 2)
{
ledState = !ledState;
return ledState;
}
else return -1;
}
@Sam, use a single Spark.function() but pass it a string indicating the plug number and the action like: “4,OFF”. It is just a matter of parsing the “command” string. If you search the forum you will find others who have asked the same question complete with recommended code