Photon / Ubidots Code for Switch monitoring

Hi all,

Help! Started using the Ubidots service which seems like a great place for monitoring your IOT devices.

I can get the Photon running with the light sensor demo fine but cant seem to merge my code into it The Code is below, all I am looking to do is detect a microswitch button press and then send that to Ubidots:

// This #include statement was automatically added by the Particle IDE.
#include "HttpClient/HttpClient.h"

// This code is based on the original Http Example by nmattisson, see https://github.com/nmattisson/HttpClient

#include "HttpClient/HttpClient.h"
#include "application.h"

#define VARIABLE_ID "56b89034762542395061c3f1"
#define TOKEN "hvfS6EgvocbmvcyL8bU21KR46IfxTT"

HttpClient http;
int switchPin = D2; // MicroSwitch is connected to D2
int val; //variable for reading the pin status
int buttonState; //variable to hold the button state
unsigned int  counter = 0;
char          msg[1024];
unsigned int nextTime = 0;    // Next time to contact the server

// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
  { "Content-Type", "application/json" },
  { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup() {
  pinMode(switchPin, INPUT); // Initialize D2 pin as input
  buttonState = digitalRead (switchPin); // read the intial state
  request.hostname = "things.ubidots.com";
  request.port = 80;
  request.path = "/api/v1.6/variables/"VARIABLE_ID"/values?token="TOKEN;
  Serial.begin(9600);
}

void loop() {
  if (nextTime > millis()) {
    return;
  }
  // Read sensor value
  {
    val = digitalRead(switchPin); //read input value and store it in val
    if (val != buttonState); {       //the button state has changed!
      if (val == LOW) {              //check if the button is pressed
        counter++;             //increment the button presses variable

        Serial.println("Sending data ...");

        request.body = "{\"value\":" + String(switchPin) + "}";

        // Post request
        http.post(request, response, headers);
        Serial.println(response.status);
        Serial.println(response.body);

        buttonState = val;               //save the new state in our variable

        nextTime = millis() + 1000;
      }
    }
  }
}

The code compiles and flashes OK.
Thanks for the help all.
N

Does your code ever go inside the “Read sensor value” part of loop() - it looks like your missing an else.

This semicolon if (val != buttonState);<---- is a typo and means your program will not flow as you expect.

Your posting switchPin, did you mean to post val?

I’m not sure what the point of counter is?

I am not sure exactly what your trying to achieve but I think the logic between buttonState and val needs to be looked at again. Mainly whether buttonState = val; should be inside your if clause.

Can you let us know what your desired behaviour is? i.e. notification every time button state changes/notification every time every time button is pressed/notification every time button is released etc.

Maybe something like this:

void loop() {
  if (nextTime <= millis()) 
  {
    val = digitalRead(switchPin); //read input value and store it in val
    if (val != buttonState) //the button state has changed!
    {       
      if (val == LOW)
      {              //check if the button is pressed
        counter++;             //increment the button presses variable

        Serial.println("Sending data ...");

        request.body = "{\"value\":" + String(val) + "}";

        // Post request
        http.post(request, response, headers);
        Serial.println(response.status);
        Serial.println(response.body);
      }
    }
    buttonState = val;               //save the new state in our variable
    nextTime = millis() + 1000;
  }
}
1 Like

If you have no external pull-resistor you'd need to use INPUT_PULLUP or INPUT_PULLDOWN to prevent your pin from floating when the switch is open.

And of course the above :wink:

1 Like

This might seems silly, but how are you supplying current to the button that you are reading?

pinMode(somePin, OUTPUT);
digitalWrite(somePin, HIGH);

Needless to say, if the pin you are reading has no supply current it won’t change states when pressed and therefore won’t send the update to Ubidots.

I have a push button connected to D5.

The code below work for me.

// This #include statement was automatically added by the Particle IDE.
#include "HttpClient/HttpClient.h"
#include "application.h"


#define VARIABLE_ID "yourVAR_ID"
#define TOKEN "yourToken"


HttpClient http;
//boolean buttonPush = false;
int buttonValue1 = 0;
int buttonValue2 = 0;
unsigned int nextTime = 0;    // Next time to contact the server

// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
    { "Content-Type", "application/json" },
    { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup() {
    pinMode(D0, INPUT);
    pinMode(D5, OUTPUT);
    digitalWrite(D5, HIGH);
    request.hostname = "things.ubidots.com";
    request.port = 80;
    request.path = "/api/v1.6/variables/"VARIABLE_ID"/values?token="TOKEN;
    Serial.begin(9600);
}

void loop() {
    
    buttonValue1 = digitalRead(D0);
    
    
    if (buttonValue1 != buttonValue2) {
            Serial.println("Sending data ...");
            request.body = "{\"value\":" + String(buttonValue1) + "}";
            buttonValue2 = buttonValue1;
            // Post request
            http.post(request, response, headers);
            Serial.println(response.status);
            Serial.println(response.body);
            
                return;
    }
    

    nextTime = millis() + 1000;
    
    
}
1 Like

You either hard wire it to 3V3 or GND or use a seperate supplyPin, but usually option one is the easiest and common one and most likely the option the OP has chosen.

2 Likes

Yes I hardwired to 3v3 and then the other to GND

Thanks for the advice

I had it all working with the particle dashboard (using a different version of code) using particle.publish which was great.

Thanks all for the advice I will give it a try and let you know if it all works

Thanks. Yes your right I’m wanting to get a notification each time the button is pressed, will give your example a go

Thanks a lot for the code example.

Struggling to get it to verify though - keep getting the error message:

???

You need to import that library from the Libraries drawer (bookmark icon)
https://docs.particle.io/guide/getting-started/build/photon/#using-libraries

2 Likes

Silly me, thanks.

1 Like