Go Down

Topic: Code only works when serial monitor is open ! (Read 2382 times) previous topic - next topic

psmelakt

I know that the problem is with ( while Serial) but I'm not sure how to fix it!
Code: [Select]
#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;
}

Robin2

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
Two or three hours spent thinking and reading documentation solves most programming problems.

sterretje

Code: [Select]
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):
Code: [Select]
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)


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 you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.

AWOL

Code: [Select]
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.

psmelakt

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.

psmelakt

Code: [Select]
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):
Code: [Select]
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.

Danois90

You are calling "while(!Serial);" before "Serial.begin()" - that may be an issue.
Instead of mocking what's wrong, teach what's right! ;)
When you get help, remember to thank the helper and give some karma!
Please, do NOT send me any private messages!!

Delta_G


Code: [Select]
if ( 8734<val_x<14169)

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:

Code: [Select]
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. 
|| | ||| | || | ||  ~Woodstock

Please do not PM with technical questions or comments.  Keep Arduino stuff out on the boards where it belongs.

psmelakt

Code: [Select]
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:

Code: [Select]
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)

Whandall

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 )
Code: [Select]
  while (!Serial && (millis() < 30000));
Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

Delta_G

#10
Aug 04, 2018, 09:05 pm Last Edit: Aug 04, 2018, 09:05 pm by Delta_G
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.

Code: [Select]
if ( 8734<val_x<14169)

|| | ||| | || | ||  ~Woodstock

Please do not PM with technical questions or comments.  Keep Arduino stuff out on the boards where it belongs.

psmelakt

Code: [Select]
  while (!Serial && (millis() < 30000));

that did it :) now the code works.

sterretje

You just as well leave the test out. Lot simpler ;)
If you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.

psmelakt

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.

bidouilleelec

Hello psmelakt

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

    Code: [Select]

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


that did it :) 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

Go Up