Page 129 - Programming the Photon Getting Started With the Internet of Things
P. 129
void setup() {
Spark.variable("analog", &reading, INT);
Spark.variable("volts", &volts, DOUBLE);
}
void loop() {
reading = analogRead(analogPin);
volts = reading * 3.3 / 4096.0;
}
Looking at the code, we can see it is similar to the previous experiment’s code, with
the exception that we are now going to use two variables in our program. The first variable
is the same as in the previous example and returns the same value when reading analog
pin A0. The second variable will be used to return the actual voltage value at analog pin
A0. There is a simple mathematical equation that we can used in the loop function to
calculate the voltage. The value from the reading is multiplied by 3.3 V and then is
divided by 4,095, which is the maximum value that can be read on the analog pin.
You may remember we used a bit of HTML to turn an LED on or off. The biggest
issue with this is that the code can been seen in plain text by a user and, as such, causes
some security concerns for those who want to host the webpage on the Internet. Using
HTML on a local server or your own desktop computer is fine if you are testing out the
functions and you are the only person able to access those files. However, in order to be
safer and more secure, we can use a programming script language within HTML that hides
all our code—more importantly, it hides our token and device IDs. We have also added a
nice little graphical user interface, which gives a nice feel to the data that is being
presented; this is done using a simple JavaScript plugin courtesy of www.justgauge.com.
The HTML code for this experiment is as follows:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.j
s" type="text/javascript" charset="utf-8"></script>
<script src="raphael.2.1.0.min.js"></script>
<script src="justgage.1.0.1.min.js"></script>
<script>
var accessToken = "your access token here";
var deviceID = "your device id here"
var url = "https://api.spark.io/v1/devices/" + deviceID + "/volts";
function callback(data, status){
if (status == "success") {
volts = parseFloat(data.result);
volts = volts.toFixed(2);