Counting micro switch

Hi all.

I am a complete newbie when it comes to programming and photon but so far I love what I see, seems like a great system.

I have managed to connect a microswitch which when pressed sends a signal to the dashboard log to say it’s been pressed (using spark.publish) but I can’t work out how to count the number of presses and also have this published on the dashboard.

Any help very greatfully received.

Create a variable and increment its value whenever the switch is actuated. Add the value of the variable to the string that is published in the Particle.publish() call. There are a lot of ways of doing this but something like this might give you some ideas:

unsigned int  counter = 0;
char          msg[1024];

digitalRead(...)               // code reading switch actuation
counter++;                     // increment counter variable for each switch actuation

sprintf(msg, "switch actuated, count = %d", counter);
Particle.publish(msg);

Thanks that worked great, appreciate the help.

One thing I cant work out though is how to get the count data into the data section on the dashboard. It just comes up null?

Cheers

Nick

Well, I don’t know either. I’ve only used the Particle.Publish() function to display debugging information. So perusing the reference documentation for the Firmware and looking at the section on Cloud Functions, sub-section on Particle.Publish(). It specifies the Cloud events properties including the optional data that you want to use. In there you’ll see that there are optional arguments to Particle.Publish() that allow one to specifically set the ‘data’ and it gives some examples of doing that. So instead of writing the information into a string buffer as I did in my code fragment, you’d pass the counter variable in as the second argument of the Particle.Publish() function call. You should look over the Cloud Function part of the reference documentation, its pretty well explained there.

There are several overloads of Particle.publish() - the docs would tell, that’s what they are for after all :sunglasses:

Try

Particle.publish("YourEventName", msg);