Skip to content

Instantly share code, notes, and snippets.

@Jcardif
Created May 29, 2019 14:32
Show Gist options
  • Save Jcardif/407ded1f3014279a79a23aa846fe4795 to your computer and use it in GitHub Desktop.
Save Jcardif/407ded1f3014279a79a23aa846fe4795 to your computer and use it in GitHub Desktop.
/*
Name: BusSeat Tracker Ultrasonic Sensor
Created: 5/10/2019 17:41:54
Sensor : UltraSonic sensor => HC-SR04
Author: Joshua Ndemenge
*/
#include <SigFox.h>
#include <Arduino.h>
#include <math.h>
//init pins
const int echoPin=7;
const int triggerPin=6;
const int baudRate=9600;
float distance =0;
/*
ATTENTION - the structure we are going to send MUST
be declared "packed" otherwise we'll get padding mismatch
on the sent data - see http://www.catb.org/esr/structure-packing/#_structure_alignment_and_padding
for more details
*/
typedef struct __attribute__ ((packed)) sigfox_message {
float height;
uint8_t lastMessageStatus;
} SigfoxMessage;
// stub for message which will be sent
SigfoxMessage msg;
// put your setup code here, to run once:
void setup()
{
Serial.begin(baudRate);
while (!Serial){/* code */}
if(!SigFox.begin())
{
Serial.println("Shield error or not present");
return;
}
String version=SigFox.SigVersion();
String ID=SigFox.ID();
String PAC= SigFox.PAC();
// Display module informations
Serial.println("MKRFox1200 Sigfox first configuration");
Serial.println("SigFox FW version " + version);
Serial.println("ID = " + ID);
Serial.println("PAC = " + PAC);
delay(100);
//Send module to standby until we need to send a message
SigFox.end();
pinMode(echoPin, INPUT);
pinMode(triggerPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
// put your main code here, to run repeatedly:
void loop()
{
//clear the trigger pin
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin,HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin,LOW);
//read the echo pin
const int duration=pulseIn(echoPin,HIGH);
float newDistance=duration*0.034/2;
if(duration==0){
Serial.println("Warning : no pulse fom sensor");
}
else
{
// sendToSigfox();
//get change as absolute value
float change=fabs(newDistance - distance);
if(change > 10)
{
distance=newDistance;
sendToSigfox();
}
else
{
Serial.println("Get busy! I will scream when necessary");
}
}
delay(100);
}
//Blink the built in LED_BUILTIN
void blink()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}
//send measured distance to Sigfox
void sendToSigfox()
{
//start the module
SigFox.begin();
// Wait at least 30ms after first configuration (100ms before)
delay(100);
msg.height=distance;
SigFox.status();
delay(1);
SigFox.beginPacket();
SigFox.write((uint8_t*)&msg,12);
msg.lastMessageStatus=SigFox.endPacket();
Serial.println("status: "+ String(msg.lastMessageStatus));
Serial.println("Change occured with a new distance of " + String(msg.height));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment