Serial Communication freezes with BMP180 and Arduino Mega - c++

I recently bought an ELEGO Mega 2560, or in other words an Arduino Mega. I bought a bmp180 sensor as well. I connected the bmp in this fashion, VCC - 3.3v, GND - GND, SCL - 21, SDA - 20. I uploaded a simple code which just displayes altitude. When I go to the Serial Monitor to view the results, nothing pops up. It is suppose to say BMP init success if it connects, and fail if it doesn't. When I go to the monitor, it just doens't say anything. When I disconnect the sensor, it says fail. It appears as if the Serial Monitor just freezes. Also a headsup, my code is very messy, I'm sorry if it's hard to keep up.
#include <Wire.h>
#include <SFE_BMP180.h>
SFE_BMP180 bmp180;
float Po = 1014.9;
#define ledPin 7
#define TransmitPin 5
//int Altitude = 5;
int sendValue;
String incomingString;
unsigned long lastTransmission;
const int interval = 1000;
void setup() {
Wire.begin();
pinMode(ledPin, OUTPUT);
pinMode(2, INPUT);
pinMode(10, OUTPUT);
pinMode(TransmitPin, OUTPUT);
bool success = bmp180.begin();
Serial.begin(115200);
if (success) {
Serial.println("BMP180 init success");
}
else
Serial.println("fail");
}
void loop() {
sendValue = digitalRead(29);
if (sendValue == HIGH) {
if (millis() > lastTransmission + interval) {
Serial.println("AT+SEND=1,8,Return");
digitalWrite(TransmitPin, HIGH);
delay(100);
digitalWrite(TransmitPin, LOW);
lastTransmission = millis();
}
}
if (Serial.available()) {
incomingString = Serial.readString();
if (incomingString.indexOf("Testing!") > 0) {
digitalWrite(10, HIGH);
delay(100);
digitalWrite(10, LOW);
}
}
char status;
double T, P, alt;
bool success = false;
status = bmp180.startTemperature();
if (status != 0) {
delay(1000);
status = bmp180.getTemperature(T);
if (status != 0) {
status = bmp180.startPressure(3);
if (status != 0) {
delay(status);
status = bmp180.getPressure(P, T);
if (status != 0) {
if (millis() > lastTransmission + interval) {
alt = bmp180.altitude(P, Po);
Serial.print("AT+SEND=1,8,");
int altAsFoot = alt * 3.281;
Serial.println(altAsFoot);
digitalWrite(TransmitPin, HIGH);
delay(100);
digitalWrite(TransmitPin, LOW);
}
for (int i = 0; i < 1800; i++) {
delay(1);
if (Serial.available()) {
incomingString = Serial.readString();
if (incomingString.indexOf("+OK") > 0) {
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
}
if (incomingString.indexOf("Testing!") > 0) {
digitalWrite(10, HIGH);
delay(100);
digitalWrite(10, LOW);
}
}
}
}
}
}
}
}

Turns out it was a hardware issue. I had ground shorted to SDA. I'm assuming the same will happen if it's shorted to SCL. Make sure both SDA and SCL aren't shorted to each other or ground.

Related

Trying to make pushbutton to a toggle switch, when pressed it's going to run sensors and pressed again nothing is going to happen

So i have a dht11 sensor connected to show the temperature and a HC-SR04 sensor to make a LED light up when the distance is under 15cm. I also have photoresistor to light up when it's dark and not ligh up when it's day.
I can do this on my own but the thing is i am trying to make the pushbutton as a toggle switch. When pressed once the sensors should stop printing data to the seriall monitor and the lights to turn off. When pressed again it shoul go back to printing the temperature, HC sensor and photoresistor should also work. When pressed again it should go back to stopping everything and so on.
The # is in norwegian don't mind that just explains the code
// #Include tar med en biblotek
// #define betyr at du gir navn til en constant integer
#include "DHT.h"
#define DHTTYPE DHT11
const int DHTPIN = 7; // fyll inn: digital pin sensoren er koblet til
DHT dht(DHTPIN, DHTTYPE);
const int trig = 10;
const int echo = 11;
int bstate = 1;
int led = 2; //En variabel for led pin.
float tid, avstand, t; // "t" en variabel for temperaturen
int led1 = 8;
int bpin = 5;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
dht.begin();
pinMode(led1, OUTPUT);
pinMode(led, OUTPUT);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(bpin, INPUT);
}
void loop() {
if(digitalRead(bpin) == LOW){
Serial.println("System on!");
bpin = 1;
while(bstate == 1){
//Temperatur Sensor kode:
t = dht.readTemperature(); //leser av temp verdier fra sensor og legger verdi inn i "t" variabelen.
Serial.print("Temperature: ");
Serial.println(t);
delay(2000);
return;
//Photoresistor LED
int verdi = analogRead(A1);
Serial.print("Verdi: ");
Serial.println(verdi);
if (verdi > 400){
digitalWrite(led1, HIGH);
}
else {
digitalWrite(led1, LOW);
}
if(digitalRead(bpin) == LOW)
{
bstate = 0;
Serial.println("System off!");
delay(1000);
}
//Ultralyd sensor kode:
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
tid = pulseIn(echo, HIGH);
avstand = (tid*0.034)/2;
if (avstand < 15){
digitalWrite(led, HIGH);
delay(10000);
}
else {
digitalWrite(led, LOW);
}
delay(500);
if(digitalRead(bpin) == LOW)
{
bstate = 0;
Serial.println("System off!");
delay(1000);
}
}
}
}
Another code with toggle switch:
#include "DHT.h"
#define DHTTYPE DHT11
const int DHTPIN = 7; // fyll inn: digital pin sensoren er koblet til
DHT dht(DHTPIN, DHTTYPE);
const int trig = 10;
const int echo = 11;
int ledstate = 0;
int bstate = 0;
int led = 2;
int led1 = 8;
int bpin = 5;
int bnew;
int bold = 1;
float tid, avstand, t;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(bpin, INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(bnew);
bnew = digitalRead(bpin);
if(bold == 0 && bnew == 1){
if(bstate == 0){
Serial.println("System on");
//Temperatur Sensor kode:
t = dht.readTemperature(); //leser av temp verdier fra sensor og legger verdi inn i "t" variabelen.
Serial.print("Temperature: ");
Serial.println(t);
delay(2000);
return;
//Photoresistor LED
int verdi = analogRead(A1);
Serial.print("Verdi: ");
Serial.println(verdi);
if (verdi > 400){
digitalWrite(led1, HIGH);
}
else {
digitalWrite(led1, LOW);
}
//Ultralyd sensor kode:
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
tid = pulseIn(echo, HIGH);
avstand = (tid*0.034)/2;
if (avstand < 15){
digitalWrite(led, HIGH);
delay(10000);
}
else {
digitalWrite(led, LOW);
}
delay(500);
bstate = 1;
}
else if(bstate == 1 && bnew == 1){
Serial.println("System off");
bstate = 0;
}
delay(1000);
}
bold = bnew;
delay(1000);
}
Code without if (Not toggle switch):
// C++ code
//
#include "DHT.h"
#define DHTTYPE DHT11
const int DHTPIN = 7; // fyll inn: digital pin sensoren er koblet til
DHT dht(DHTPIN, DHTTYPE);
const int trig = 10;
const int echo = 11;
int led = 2;
int led1 = 8;
float tid, avstand, t;
void setup()
{
pinMode(led, OUTPUT);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
}
void loop()
{
//Ultralyd sensor kode:
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
tid = pulseIn(echo, HIGH);
avstand = (tid*0.034)/2;
if (avstand < 15){
digitalWrite(led, HIGH);
delay(10000);
}
else {
digitalWrite(led, LOW);
}
delay(1500);
//Temperatur Sensor kode:
t = dht.readTemperature(); //leser av temp verdier fra sensor og legger verdi inn i "t" variabelen.
Serial.print("Temperature: ");
Serial.println(t);
delay(2000);
return;
//Photoresistor LED
int verdi = analogRead(A1);
Serial.print("Verdi: ");
Serial.println(verdi);
if (verdi > 400){
digitalWrite(led1, HIGH);
}
else {
digitalWrite(led1, LOW);
}
}
The connections are correct but when ii run these codes almost nothing happens. the first code i can turn system on but not off and just dht11 sensor is working, syste turned off automatic. The second code the temperature printed nan or - all the time and system on to other sensors did not work. The third code temperature kinda worked and HC-SR04 sensor worked but not the photoresistor.
Circuit drawing of curcuit
Scematic view of circuit
Anything would help thanks

C++ Assignment - Why isn't the push button working?

I am trying to do the following on an Arduino:
Task: Create a toggle switch that controls when 3 LEDs switch on (at the same time). In a toggle switch, when the button is pressed, the LEDs switch on. When it is pressed again, the LEDs switch off.
My pushbutton isn't turning on to turn on the LEDs
The code is:
// C++ code
//Declare
int ledPin13 = 13;
int ledPin12 = 12;
int ledPin11 = 11;
int buttonPin = 1;
int buttonState;
//State if input or output
void setup() {
pinMode(buttonPin , INPUT);
pinMode(ledPin13 , OUTPUT);
pinMode(ledPin12 , OUTPUT);
pinMode(ledPin11 , OUTPUT);
}
//Stage 3 - Code what you want to do (according to psuedocode)
void loop() {
buttonState = digitalRead(buttonPin);
if(buttonState == HIGH) {
digitalWrite(ledPin13 , HIGH);
digitalWrite(ledPin12 , HIGH);
digitalWrite(ledPin11 , HIGH);
}
else {
digitalWrite(ledPin13 , LOW);
digitalWrite(ledPin12 , LOW);
digitalWrite(ledPin11 , LOW);
}
}
It is because your program continuously reads a state. It means the time of pressing the button in compare with the checking of the state by MCU is too mush . for fixing this problem you have two options:
Checking the button. You have to check the state but It is better
to use debouncing which means adding delay between two reads.
bool LEDstate = false;
void loop()
{
if (digitalRead(buttonPin) == HIGH)
{
delay(500); // to be stable
if (digitalRead(buttonPin) == HIGH)
{
if (LEDstate == false)
{
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin12, HIGH);
digitalWrite(ledPin11, HIGH);
LEDstate = true;
}
else
{
digitalWrite(ledPin13, LOW);
digitalWrite(ledPin12, LOW);
digitalWrite(ledPin11, LOW);
LEDstate = false;
}
while (digitalRead(buttonPin) == HIGH); // wait to release
}
}
}
Inverse reading, which means you have to read the pressing and then wait to release to change the state of LEDs
bool LEDstate = false;
void loop()
{
if (digitalRead(buttonPin) == HIGH)
{
delay(100); // to be stable
while (digitalRead(buttonPin) == HIGH); // wait to release
if (LEDstate == false)
{
digitalWrite(ledPin13, HIGH);
digitalWrite(ledPin12, HIGH);
digitalWrite(ledPin11, HIGH);
LEDstate = true;
}
else
{
digitalWrite(ledPin13, LOW);
digitalWrite(ledPin12, LOW);
digitalWrite(ledPin11, LOW);
LEDstate = false;
}
}
}
bool toggleState = 0;
buttonState = digitalRead(buttonPin);
delay(100);
if( buttonState == 1)
{
if(toggleState)
toggleState = 0;
else
toggleState = 1;
}
if(toggleState)
{
digitalWrite(ledPin13 , HIGH);
digitalWrite(ledPin12 , HIGH);
digitalWrite(ledPin11 , HIGH);
}
else
{
digitalWrite(ledPin13 , LOW);
digitalWrite(ledPin12 , LOW);
digitalWrite(ledPin11 , LOW);
}

Turn relay on from Bluetooth for certain amount of seconds

I am working on two way communication between arduino and android phone. Currently everything is working, however I have couple of issues I have been trying to solve recently.
How I can ignite ignition for 5 seconds? I mean if IgnitionPin is on HIGH, run it for 5 seconds then automatically turn off? There is an easy way with delay, but it will not work in my case as don't want any other delays to slow up my script.
I am using Arduino Uno. I want to start my Arduino with pin in OFF position. Why pin 10 always turns ON then shuts down, even with digitalWrite(IgnitionPin, HIGH); I have tried other pins and they work fine -> turned OFF on start.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
const long ignitionInterval = 5000;
int ignitionState = HIGH;
unsigned long previousMillis = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
ignitionState = HIGH;
digitalWrite(IgnitionPin, ignitionState);
ignitionCountTime = millis();
}
if (ignitionCountTime - previousMillis >= ignitionInterval) {
previousMillis = ignitionCountTime;
if (ignitionState == HIGH)
{
ignitionState = LOW;
}
digitalWrite(IgnitionPin, ignitionState);
}
delay(loopDelay);
}
EDIT:
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
unsigned long startTime;
unsigned long ignitionInterval = 30000;
unsigned long ignitionCountTime = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
digitalWrite(IgnitionPin, HIGH);
ignitionCountTime = millis();
}
if (ignitionCountTime - startTime >= ignitionInterval)
{
digitalWrite(IgnitionPin, LOW);
}
delay(loopDelay);
}
#1
Use the TimerOne library or setup an ISR.
Run the ISR at, 5 times per second.
uint32_t timeout = 5 * 60;
uint8_t flag = 1;
digitalWrite (myPin, HIGH);
if (timeout && flag) {
timeout--;
} else {
digitalWrite (myPin, LOW);
flag = 0;
}
OR
by checking time elapsed since some specific point in time.
unsigned long startTime;
unsigned long interval = 60000;
const byte aPin = 13;
void setup()
{
pinMode(aPin, OUTPUT);
digitalWrite(aPin, HIGH);
}
void loop()
{
if (millis() - startTime >= interval)
{
digitalWrite(aPin, LOW);
}
}
EDIT
Arduino is a microcontroller, it can do only one thing at once.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
uint32_t timeout = 5 * 60;
uint8_t flag = 0;
void setup()
{
BTserial.begin(115200);
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if (choice == "m")
{
timeout = 5 * 60; //modify this timeout.
flag = 1;
digitalWrite(IgnitionPin, HIGH);
}
else if ((timeout > 0) && (flag == 1))
{
timeout--;
}
else
{
digitalWrite(IgnitionPin, LOW);
flag = 0;
}
delay(loopDelay);
}
#2 - In setup you are running 'digitalWrite(IgnitionPin, HIGH);' this will make it high
just use pinMode(IgnitionPin, OUTPUT); for setting pin as output pin
void setup()
{
Serial.begin(115200);
Serial.println("Enter AT commands:");
BTserial.begin(115200);
sensors.begin();
// Set Pin as an output pin
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
If you want IgnitionPin as LOW at each restart - use 'digitalWrite(IgnitionPin, LOW);' in setup() after pinMode call.

Problem in arduino if run system how to fix

Hello i have problem :
state sensor = sensor steps "IF" anyone "steps now = impulse " = all code run"perfect good work im happy" but if sensor LOW a did not detect any motion while loading the code = broke stop all , even if it is at the end close or halfway, it will stop when there is no traffic "" (stage_sensor == HIGH)"", i dont have idea how to fix this//
Please help or sugestion
EDIT : There may be syntax errors (is not consistent), but just wanted to present a problem, the system only works under "if" and this is problem, i dont know how to fix
#include <AccelStepper.h> //accelstepper library
// #define light
// #define move_sensor
// #define pump_water
// #define fan_blowing
// #define fan_extractor
// #define blue
// #define red
// #define green
const byte limitSwitch_1 = 26;
const byte limitSwitch_2 = 25;
bool switchFlipped = false;
bool previousFlip = true;
int switchCounter;
int newSpeed;
int state_sensor = 0; // <--- stage sensor //
int light = 2;
int blue = 3;
int red = 4;
int green = 5;
int fan_blowing = 6;
int water_pump = 8;
int move_sensor = 9;
int fan_extractor = 10;
AccelStepper stepper(1, 22, 23);
void setup()
{
pinMode(water_pump, OUTPUT);
pinMode(light, OUTPUT);
pinMode(fan_blowing, OUTPUT);
pinMode(fan_extractor, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(move_sensor, INPUT);
pinMode(limitSwitch_1, INPUT_PULLUP); //pin 1 engine (IF touch)
pinMode(limitSwitch_2, INPUT_PULLUP); //pin 2 engine (IF touch)
Serial.begin(9600);
stepper.setMaxSpeed(1000);
stepper.setAcceleration(100);
stepper.setSpeed(1000);
delay(500);
}
void loop()
{
digitalWrite(light, HIGH);
digitalWrite(blue, HIGH);
state_sensor = digitalRead(sensor_move);
if (state_sensor == HIGH) // <--- stage sensor IF anyone move = all code run but if sensor LOW did not detect movement all code broke stop all //
{
digitalWrite(blue, LOW);
digitalWrite(red, HIGH);
stepper.runSpeed();
engine();
}
}
void engine()
{
if(digitalRead(limitSwitch_1) == LOW)
{
switchCounter++;
delay(1000);
newSpeed = -1 * (1000 + (switchCounter * 200));
stepper.setSpeed(newSpeed);
}
if(digitalRead(limitSwitch_2) == LOW)
{
switchCounter++;
delay(1000);
newSpeed = -1 * (1000 + (switchCounter * 200));
stepper.stop();
fans();
}
}
void fans()
{
digitalWrite(red, HIGH);
{
digitalWrite(fan_blowing, HIGH);
digitalWrite(fan_extractor, HIGH);
delay(1000);
digitalWrite(water_pump, HIGH);
}
delay(1000);
digitalWrite(red, LOW);
digitalWrite(water_pump, LOW);
digitalWrite(green, HIGH);
delay(1000);
digitalWrite(fan_blowing, LOW);
digitalWrite(fan_extractor, LOW);
digitalWrite(green, LOW);
digitalWrite(blue, HIGH); //this blue RGB light "ON" but if sensor_steps "ON" = active cycle , blue light led off
delay(1000);
}
What you could do is set up a global "stage" variable:
#include <AccelStepper.h> //accelstepper library
const byte limitSwitch_1 = 26;
const byte limitSwitch_2 = 25;
bool switchFlipped = false;
bool previousFlip = true;
int switchCounter;
int newSpeed;
int stage;
AccelStepper stepper(1, 22, 23);
void setup()
{
pinMode(limitSwitch_1, INPUT_PULLUP);
pinMode(limitSwitch_2, INPUT_PULLUP);
Serial.begin(9600);
stepper.setMaxSpeed(1000);
stepper.setAcceleration(100);
stepper.setSpeed(1000);
delay(500);
stage = 0;
}
void loop()
{
stepper.runSpeed();
runner();
}
void runner()
{
if(stage == 0 && digitalRead(limitSwitch_1) == LOW)
{
switchCounter++;
delay(5000);
newSpeed = -1 * (1000 + (switchCounter * 200));
stepper.setSpeed(newSpeed);
++stage;
}
if(stage == 1 && digitalRead(limitSwitch_2) == LOW)
{
stepper.setSpeed(1000);
delay(1000);
stepper.setSpeed(0);
++stage;
}
if (stage == 2) {
// do next thing, then ++stage;, etc.
}
}

Issue with while loop

For my project I am trying to messure the distance between my sensor and an object to trigger an alarm. If the alarm goes off, a message will be sent to my Telegram account with a library (UniversalTelegramBot). For messuring th distance, I'm using a loop to the distance between the sensor and the object, but to check if I get any messages through I also need to use a loop. I want to make it so that with the comment "/off" the distance get messured again, but when you type something else it waits till the comment "/off" gets used again. While the alarm is on and it's checking for messages, I want to use "/start" as comment to see which other comments to use and how to use it, without going to the messure loop again.
My main problem is that when the alarm goes off and I type anything, it doesn't matter what, the loop starts messuring again, but I only want it to go back to messuring when I type "/off" in telegram.
My code:
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
UniversalTelegramBot bot(TELEGRAM_BOT_TOKEN, client);
int delayBetweenChecks = 250;
unsigned long lastTimeChecked;
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
if (from_name == "")
from_name = "Gast";
Serial.print("De volgende knop is ingedrukt: ");
Serial.println(text);
if (text == F("/off")) {
digitalWrite(LED_PIN, LOW);
alarmStatus = 0;
noTone(buzzer);
}
if (text == "/start") {
String welcome = "Welkom bij jouw alarmsysteem, " + from_name + ".\n";
welcome += "/off : om het alarm uit te zetten\n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
}
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration / 2) / 29.1; // Divide by 29.1 or multiply by 0.0343
inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
while (cm <= 9) {
Serial.println("ALARM!");
digitalWrite(LED_PIN, HIGH);
tone(buzzer, 250);
alarmStatus = 1;
if (alarmStatus = 1) {
if (millis() > lastTimeChecked + delayBetweenChecks) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
handleNewMess ages(numNewMessages);
if (numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
}
lastTimeChecked = millis();
}
}
break;
}
delay(250);
}
If I understand it correctly, you could keep two separate state variables. One for turning the alarm on and off when you leave/return home and one for when triggering the alarm.
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
const int delayBetweenChecks = 250;
bool alarmStatus = false; // off by default
bool alarmTriggered = false; // off by default
UniversalTelegramBot bot(TELEGRAM_BOT_TOKEN, client);
double measure_distance_in_cm() {
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
unsigned long duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
return static_cast<double>(duration) / (29.1 * 2.);
}
void trigger_on() {
digitalWrite(LED_PIN, HIGH);
alarmTriggered = true;
}
void trigger_off() {
digitalWrite(LED_PIN, LOW);
alarmTriggered = false;
}
void handleNewMessages() {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
for (int i = 0; i < numNewMessages; i++) {
String text = bot.messages[i].text;
Serial.println(text);
if (text == "/start") { // when you're leaving home
alarmStatus = true;
trigger_off();
}
else if (text == "/stop") { // when you're returning home
alarmStatus = false;
trigger_off();
}
else if (text == "/off") { // turn off a triggered alarm
trigger_off();
}
else if (test == "/on") { // force triggering of the alarm
trigger_on();
}
}
}
void loop() {
static unsigned long lastTimeChecked = millis();
handleNewMessages();
if(alarmStatus) { // you only need to do this if the alarm is on
if(alarmTriggered == false) { // only measure if the alarm isn't already triggered
double cm = measure_distance_in_cm();
if(cm <= 9.) {
Serial.println("ALARM!");
trigger_on();
}
}
// If it's triggered: Sound the alarm in 200ms bursts until /off or /stop is received
if(alarmTriggered) tone(buzzer, delayBetweenChecks-50);
}
// try to keep the polling at a steady pace
lastTimeChecked += delayBetweenChecks;
unsigned long now = millis();
if(lastTimeChecked > now) delay(lastTimeChecked - now);
}
Disclaimer: I don't have an Arduino so I can't test it myself.