Skip to content

Instantly share code, notes, and snippets.

@dan-mckay
Created April 16, 2013 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-mckay/5394957 to your computer and use it in GitHub Desktop.
Save dan-mckay/5394957 to your computer and use it in GitHub Desktop.
This code queries the Cosm API for a reading from a remote sensor. This reading is used to manipulate a servo motor that is connected to an Arduino on the host machine. It is a Node.js application that uses the johnny-five module.
var http = require('http'),
five = require('johnny-five'),
feedID = 35602, //30041, //87256
apiKey = '1Og9wAmRBoWExjjN4LdksinNYIaSAKxVYVo0RHlHcHcvUT0g',
value,
oldValue,
board,
servo;
// Build get request for cosm api
var options = {
method: 'get',
host: 'api.cosm.com',
path: '/v2/feeds/' + feedID +'.json',
headers: {'X-ApiKey': apiKey}
};
// Function to execute the get request and recieve data
var callback = function(response) {
var myString = '';
var json;
response.on('error', function() {
console.log('error getting feed');
});
// Build a string of the incoming data
response.on('data', function(chunk) {
myString += chunk;
});
// When data is finished reading
response.on('end', function() {
json = JSON.parse(myString); //Create JSON object from string
value = parseFloat(json.datastreams[1].current_value); // Get reading from 1 sensor
board.emit('sensorRead', value); // Emit a custom event to Arduino, sending data
})
};
// Function to send request over the network
var makeRequest = function() {
http.request(options, callback).end();
};
// Make requests to COSM api every 2 seconds
setInterval(makeRequest, 2000);
// New Arduino instance
board = new five.Board();
// Wait for the board and serial line
// to be connected and ready
board.on('ready', function() {
// Connect servo to PWM 10 pin
servo = new five.Servo(10);
// Reset servo to 0 deg.
servo.min();
// These variables are used to compare the servo feed readings
// Initially set them to equal eachother.
oldValue = value;
var i = 0;
board.on('sensorRead', function() {
if(i === 4) {
i = 0;
servo.min();
}
// If reading changes
if(value !== oldValue) {
i++;
servo.move(i * 45);
console.log("SERVO CHANGE VAL:" + value);
}
else {
console.log("SERVO VAL:" + value);
}
oldValue = value;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment