Code only works when serial monitor is open !

I know that the problem is with ( while Serial) but I’m not sure how to fix it!

#include <MKRGSM.h>
#include<math.h>
#include<stdio.h>
#include "arduino_secrets.h"
#include <SPI.h>
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"
#include <Wire.h>
#include <Adafruit_LSM9DS0.h>
#include <Adafruit_Sensor.h>




#define BLUEFRUIT_HWSERIAL_NAME      Serial1

int val_x,val_y,val_z;
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;
    #define FACTORYRESET_ENABLE         1
    #define MINIMUM_FIRMWARE_VERSION    "0.6.6"
    #define MODE_LED_BEHAVIOUR          "MODE"
    Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);


#define PINNUMBER  "" 
GSM gsmAccess;
GSM_SMS sms;
GSMLocation location;
GPRS gprs;
Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();
 

// char array of the message
char remoteNumber[20]= "00442030954971"; 
char txtMsg[200]="run";
// A small helper
void error(const __FlashStringHelper*err) {
  Serial.println(err);
  while (1);
}

void setup() 
{
  while (!Serial);     // will pause Zero, Leonardo, etc until serial console opens
  delay(500);

  Serial.begin(115200);
  Serial.println("LSM raw read demo");
  // Try to initialise and warn if we couldn't detect the chip
  if (!lsm.begin())
  {
    Serial.println("Oops ... unable to initialize the LSM9DS0. Check your wiring!");
    while (1);
  }
  Serial.println("Found LSM9DS0 9DOF");
  Serial.println("");
  Serial.println("");
  Serial.println(F("Adafruit Bluefruit Command Mode Example"));
  Serial.println(F("---------------------------------------"));
  Serial.println("SMS Messages Sender");
 
   boolean connected = false;
   
   while(!connected){
    if((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true ; 
    }
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
    location.begin();
    Serial.print(F("Initialising the Bluefruit LE module: "));

  if ( !ble.begin(VERBOSE_MODE) )
  {
    error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
  }
  Serial.println( F("OK!") );

   if ( FACTORYRESET_ENABLE )
  {
    /* Perform a factory reset to make sure everything is in a known state */
    Serial.println(F("Performing a factory reset: "));
    if ( ! ble.factoryReset() ){
      error(F("Couldn't factory reset"));
    }
  }

  /* Disable command echo from Bluefruit */
  ble.echo(false);

  Serial.println("Requesting Bluefruit info:");
  /* Print Bluefruit information */
  ble.info();

  Serial.println(F("Please use Adafruit Bluefruit LE app to connect in UART mode"));
  Serial.println(F("Then Enter characters to send to Bluefruit"));
  Serial.println();

  ble.verbose(false);  // debug info is a little annoying after this point!

  // LED Activity command is only supported from 0.6.6
  if ( ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION) )
  {
    // Change Mode LED Activity
    Serial.println(F("******************************"));
    Serial.println(F("Change LED activity to " MODE_LED_BEHAVIOUR));
    ble.sendCommandCheckOK("AT+HWModeLED=" MODE_LED_BEHAVIOUR);
    Serial.println(F("******************************"));
  }
}

void locationcheck()
{
  if (location.available()) {
    Serial.print("Location: ");
    Serial.print(location.latitude(), 7);
    Serial.print(", ");
    Serial.println(location.longitude(), 7);

    Serial.print("Altitude: ");
    Serial.print(location.altitude());
    Serial.print(" started");
    Serial.println("m");

    Serial.print("Accuracy: +/- ");
    Serial.print(location.accuracy());
    Serial.println("m");

    Serial.println();
  }
}

void loop() 
{
  float a;
 
   for (int i=0;i<10;i++)
 {
  lsm.read();
  Serial.print("sensor");
  val_x = (lsm.accelData.x);
  val_y = (lsm.accelData.y);
  val_z = (lsm.accelData.z);
  Serial.print("sensor");
  delay(500);
  // Check for user input
  char inputs[BUFSIZE+1];

  if ( getUserInput(inputs, BUFSIZE) )
  {
    // Send characters to Bluefruit
    Serial.print("[Send] ");
    Serial.println(inputs);

    ble.print("AT+BLEUARTTX=");
    ble.println(inputs);

    // check response stastus
    if (! ble.waitForOK() ) {
      Serial.println(F("Failed to send?"));
    }
  }
  locationcheck();

 

  if (!ble.isConnected()) {

   if ( 8734<val_x<14169)
   {  
   sendSMS();
   Serial.print("Right shift");
   delay(500);
   
   }
   if ( -17902<val_x<-8750)
   {  
   sendSMS();
   Serial.print("right shift");
 
   delay(500);
  
   }
  }
 }
 }

 void setupSensor()
{
  
  lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G);


}
 void sendSMS(){

  float lat = location.latitude();
  float lon = location.longitude();

  String txt;
  txt += String(lat, 7);
  txt += F(":");
  txt += String(lon, 7);
  
  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(lat, 7);
  Serial.println();
  Serial.println(lon, 7);
  Serial.println();

  
  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txt);
  sms.endSMS(); 
  Serial.println("\nCOMPLETE!\n");  

}
bool getUserInput(char buffer[], uint8_t maxSize)
{
  // timeout in 100 milliseconds
  TimeoutTimer timeout(100);

  memset(buffer, 0, maxSize);
  while( (!Serial.available()) && !timeout.expired() ) { delay(1); }

  if ( timeout.expired() ) return false;

  delay(2);
  uint8_t count=0;
  do
  {
    count += Serial.readBytes(buffer+count, maxSize);
    delay(2);
  } while( (count < maxSize) && (Serial.available()) );
return true;
}

psmelakt:
I know that the problem is with ( while Serial) but I'm not sure how to fix it!

You have not told us what Arduino board you are using.

What happens if you comment out line 47?

...R

if ( 8734<val_x<14169)

I wonder if this does what you think it does.
This is the warning I get (compiling for a 328P based board):

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_955932\sketch_aug03b.ino: In function 'void setup()':

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_955932\sketch_aug03b.ino:5:13: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]

   if ( 8734 < val_x < 14169)

Robin2:
You have not told us what Arduino board you are using.

The first line of the code contains something possibly related to a MKR; so possibly that.

OP might have to take precautions. You can bring a Leonardo (using external power) to a grinding halt within a few minutes if you send data after you opened the serial monitor and next disconnect the cable; this might be the same for the MKR.

if ( 8734<val_x<14169)Evaluate left to right.
Is val_x greater than 8734?
This give is a result true or false, aka one or zero.
Is one or zero less than 14169?
True.

Robin2:
You have not told us what Arduino board you are using.

What happens if you comment out line 47?

...R

I'm using an Arduino MKRGSM 1400 the code works fine when the serial monitor is open.
i think the problem is only with while serial part and solution should be by adding a time limit next to it for example ( wait 30 seconds and check if there is a serial connection if not run the code ) but i'm not good in programming and i'm not sure how to do it.

sterretje:

if ( 8734<val_x<14169)

I wonder if this does what you think it does.
This is the warning I get (compiling for a 328P based board):

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_955932\sketch_aug03b.ino: In function 'void setup()':

C:\Users\sterretje\AppData\Local\Temp\arduino_modified_sketch_955932\sketch_aug03b.ino:5:13: warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning [-Wparentheses]

if ( 8734 < val_x < 14169)



The first line of the code contains something possibly related to a MKR; so possibly that.


OP might have to take precautions. You can bring a Leonardo (using external power) to a grinding halt within a few minutes if you send data after you opened the serial monitor and next disconnect the cable; this might be the same for the MKR.

It should be working fine because these values are from the sensor i’m just telling it to send a SMS when the values are in this range.
also i tried connecting the usb and the battery in the same time and run the code then i disconnected the usb but the code still wasn’t working.

You are calling "while(!Serial);" before "Serial.begin()" - that may be an issue.

if ( 8734<val_x<14169)

psmelakt:
It should be working fine because these values are from the sensor i’m just telling it to send a SMS when the values are in this range.

No, that’s not what you are saying with that line. You think that line says when val_x is in this range, but you’re not using good syntax. That line is equivalent to:

if (true)

and it says to do something all the time. It’s already been explained why it means that. If you want to compare to a range, then you have to do that in two comparisons and use AND. You can’t just make up your own syntax and expect it to work.

Delta_G:

if ( 8734<val_x<14169)

No, that’s not what you are saying with that line. You think that line says when val_x is in this range, but you’re not using good syntax. That line is equivalent to:

if (true)

and it says to do something all the time. It’s already been explained why it means that. If you want to compare to a range, then you have to do that in two comparisons and use AND. You can’t just make up your own syntax and expect it to work.

in my original code i used this if statement and it worked fine!
if (val_z<=665 && val_x<365)

psmelakt:
i think the problem is only with while serial part and solution should be by adding a time limit next to it for example ( wait 30 seconds and check if there is a serial connection if not run the code )

  while (!Serial && (millis() < 30000));

psmelakt:
in my original code i used this if statement and it worked fine!
if (val_z<=665 && val_x<365)

Yes, doing it that way will work. But you have to have the AND in it. You can’t have it like the one I pointed out earlier.

This one is legal and compiles but doesn’t do what you think it does.

if ( 8734<val_x<14169)

Whandall:

  while (!Serial && (millis() < 30000));

that did it :slight_smile: now the code works.

You just as well leave the test out. Lot simpler :wink:

hey guys, Just a quick question!
my laptop can't read my arduino any more ! it happened after connecting a battery and the usb in the same time; However, this wasn't the first time that i did that.

Hello psmelakt

Quote from: Whandall on Aug 04, 2018, 06:46 pm

Code: [Select]

while (!Serial && (millis() < 30000));

that did it :slight_smile: now the code works.

“now the code works.” : sure, one day or another you will have millis() >= 30000.

Have you read post #6 ?

Regards,
bidouillelec

bidouilleelec:
Hello psmelakt

"now the code works." : sure, one day or another you will have millis() >= 30000.

Crap. This is in setup, millis starts with zero and counts up, so "one day or another" happens after 30 seconds.

bidouilleelec:
Have you read post #6 ?

which is

Danois90:
You are calling "while(!Serial);" before "Serial.begin()" - that may be an issue.

Why should anyone read that irrelevant superstitious post anyway?

Hello Wandall

Posted by Whandall

  • Today at 05:23 pm

Quote

Quote from: bidouilleelec on Today at 05:17 pm

Hello psmelakt

“now the code works.” : sure, one day or another you will have millis() >= 30000.

Crap. This is in setup, millis starts with zero and counts up, so “one day or another” happens after 30 seconds.

Quote from: bidouilleelec on Today at 05:17 pm

Have you read post #6 ?

which is
Quote from: Danois90 on Aug 03, 2018, 01:53 pm

You are calling “while(!Serial);” before “Serial.begin()” - that may be an issue.

Why should anyone read that irrelevant superstitious post anyway?

Are you sure? Did you test it?
I did.

Regards,
bidouilleelec

bidouilleelec:
Hello Wandall

Are you sure? Did you test it?
I did.

Regards,
bidouilleelec

And what was the result?

I did test it numerous times in the past (and now again) and it does not make a difference as far as I can see.

Hello Sterretje

And what was the result?

The result is :

Post #6 is right.

Post #9 is just adding a delay and testing !Serial is unusefull as Serial.begin is after the test. (sure one day comes after 30ms)

Regards,
bidouilleelec

bidouilleelec:
Post #9 is just adding a delay and testing !Serial is unusefull as Serial.begin is after the test. (sure one day comes after 30ms)

You realize that the sketch works if there is a serial connection?
And that devices without native USB return true always?

That's what while (!Serial); is waiting for.

Adding a timeout to the endless wait makes the sketch work even if there is no serial connection.

The connection test (operator bool) does not need a begin before it can be used.