Skip to content

Instantly share code, notes, and snippets.

@GregoryHlavac
Created May 6, 2017 01:15
Show Gist options
  • Save GregoryHlavac/ba9a245870f6680993a3cedf5d9496ad to your computer and use it in GitHub Desktop.
Save GregoryHlavac/ba9a245870f6680993a3cedf5d9496ad to your computer and use it in GitHub Desktop.
// This #include statement was automatically added by the Particle IDE.
#include <MCP9808.h>
int MAX_DISTANCE = 200;
int PING = D6;
int RED = A2;
int GREEN = A3;
MCP9808 mcp = MCP9808();
double temperatureF = 0;
double temperatureC = 0;
long distanceC = 0;
long distanceI = 0;
void setup()
{
Particle.variable("temperatureF", temperatureF);
Particle.variable("temperatureC", temperatureC);
Particle.variable("distanceC", distanceC);
Particle.variable("distanceI", distanceI);
while(!mcp.begin())
{
Particle.publish("Failure", "Could not find Temperature/Humidity Sensor.");
delay(1000);
}
mcp.setResolution(MCP9808_SLOWEST);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
}
void updateTemperature()
{
temperatureC = mcp.getTemperature();
temperatureF = (temperatureC * 9 / 5) + 32;
}
long microsecondsToInches(long microseconds) {
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
void updateDistance()
{
long duration;
pinMode(PING, OUTPUT);
digitalWrite(PING, LOW);
delayMicroseconds(2);
digitalWrite(PING, HIGH);
delayMicroseconds(5);
digitalWrite(PING, LOW);
pinMode(PING, INPUT);
duration = pulseIn(PING, HIGH);
distanceC = microsecondsToCentimeters(duration);
distanceI = microsecondsToInches(duration);
}
void loop()
{
updateTemperature();
delay(5000);
updateDistance();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment