Clean up code and fix setup

Hi,

I have the code below and could be more than I need. I’m new to C/C++, Arduino and electronics too :slight_smile:

Anyway, these are my problems:

  • code length; what can I remove?
  • the setup runs only I open the serial monitor. I want the code start when the battery powers the device.
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_)
  #include <SoftwareSerial.h>
#endif
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"

#include "BluefruitConfig.h"

#define SEALEVELPRESSURE_HPA (1013.25)

#define PIN            6
#define NUMPIXELS      4

#define FACTORYRESET_ENABLE         0
#define MINIMUM_FIRMWARE_VERSION    "0.6.6"
#define MODE_LED_BEHAVIOUR          "MODE"

int initialStart = 0;
/*=========================================================================*/

// Create the bluefruit object
Adafruit_BluefruitLE_UART ble(Serial1, -1);

// Create bme object
Adafruit_BME280 bme; // I2C

// Create Neopixels
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

// A small helper
void error(const __FlashStringHelper*err) {
  Serial.println(err);
  while (1);
}

/**************************************************************************/
/*!
    @brief  Sets up the HW an the BLE module (this function is called
            automatically on startup)
*/
/**************************************************************************/
void setup(void)
{
  while (!Serial);  // required for Flora & Micro
  delay(500);

  Serial.begin(115200);

  Serial.println(F("Checking BME280 sensor"));
  if (!bme.begin()) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
  Serial.println(F("Checking Bluefruit Command Mode"));
  
 
  if ( !ble.begin(VERBOSE_MODE) ){
    error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
  }

  //Serial.println(F("Checking Neopixels"));
    pixels.begin();
    pixels.setPixelColor(0, pixels.Color(255,255,255));
    pixels.setPixelColor(1, pixels.Color(255,255,255));
    pixels.setPixelColor(2, pixels.Color(255,255,255));
    pixels.setPixelColor(3, pixels.Color(255,255,255));
    pixels.show();

  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(001);
  
  ble.verbose(false);  // debug info is a little annoying after this point!

  /* Wait for connection */
  while (! ble.isConnected()) {
      delay(500);
  }

  // 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 loop(void){
  //checkStatsForPixels();
  // 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?"));
    }
  }

  // Check for incoming characters from Bluefruit
  ble.println("AT+BLEUARTRX");
  ble.readline();
  if (strcmp(ble.buffer, "OK") == 0) {
    // no data
    return;
  }
  // Some data was found, its in the buffer
  Serial.print(F("[Recv] ")); Serial.println(ble.buffer);

  //if(ble.buffer == "getStats"){
    
    
    float temperature = bme.readTemperature();
    float humidity = bme.readHumidity();
    float pressure = bme.readPressure() / 100.0F * 0.7500616827;
    float altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);
    
    char valSize[10];
    String temperatureAsString;
    String humidityAsString;
    String pressureAsString;
    String altitudeAsString;
    String d_stats;
    
    dtostrf(temperature,1,2,valSize);
    temperatureAsString = String(valSize);
    dtostrf(humidity,1,2,valSize);
    humidityAsString = String(valSize);
    dtostrf(pressure,1,2,valSize);
    pressureAsString = String(valSize);
    dtostrf(altitude,1,2,valSize);    
    altitudeAsString = String(valSize);
    
    d_stats = "{'d_stats':[{'t':'" + temperatureAsString + "','h':'"+humidityAsString+"','p':'"+pressureAsString+"','a':'"+altitudeAsString+"'}]}\n";
    ble.print("AT+BLEUARTTX=");
    ble.println(d_stats);
    if(initialStart == 0){
      initialStart = 1;
      checkStatsForPixels();
    }
    
    Serial.println(d_stats);
    
  //}
  ble.waitForOK();
}

/****************/
// biostats
uint32_t redColor = pixels.Color(255,0,0);
uint32_t blueColor = pixels.Color(0,0,255);
uint32_t greenColor = pixels.Color(0,255,0);
int checkStatsForPixels(){
   for(int i = 0; i < 10000000; i++) {
    float t = bme.readTemperature();
    float h = bme.readHumidity();
    float p = bme.readPressure() / 100.0F * 0.7500616827;
    float a = bme.readAltitude(SEALEVELPRESSURE_HPA);

    uint32_t tempColor = redColor;
     if(t < 12){
        tempColor = blueColor;
      }else
      if(t > 12 && t < 20){
        tempColor = greenColor;
      }else
      if(t > 20){
        tempColor = redColor;
      }
      pixels.setPixelColor(0, tempColor);
      pixels.show();
      Serial.println(t);
      ble.print("AT+BLEUARTTX=");            
      ble.println(t);
     delay(1000);
   }
}

/**************************************************************************/
/*!
    @brief  Checks for user input (via the Serial Monitor)
*/
/**************************************************************************/
bool getUserInput(char buffer[], uint8_t maxSize)
{
  // timeout in 100 milliseconds
  TimeoutTimer timeout(100);

  memset(buffer, 0, maxSize);
  while( (Serial.peek() < 0) && !timeout.expired() ) {}

  if ( timeout.expired() ) return false;

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

  return true;
}

I want the code start when the battery powers the device.

What evidence do you have that setup() does not run when power is applied ?

Which Arduino are you using ?

I'm using Adafruit Flora.

If I don't open the serial monitor, the Bluetooth doesn't communicate with the Android app. If I power the device with a battery, I can connect, but no data is transmitted to the Android app.

george_i: I'm using Adafruit Flora.

If I don't open the serial monitor, the Bluetooth doesn't communicate with the Android app. If I power the device with a battery, I can connect, but no data is transmitted to the Android app.

This is a "busy waiting loop":

 while (!Serial);

On certain boards this line will "wait until Serial port on the PC is opened".

Typically you include that line if you want to see all output from the start of the program on.

Whe using a board with Atmega32U4 controller and do not want to open Serial, you better comment out that line before compiling.

Thanks jurs. Have a karma point from me (I don't know what's that).