Random numbers

Hi all!

Im working on a project where in some part of the code i need to make a random number and concatenate it with a pre-defined string.

Sorry if im not well explained, the thing goes like this...

The code:

... outside the SETUP void i have this variable:

int randomNumber;

...then inside the SETUP void i have this:

randomNumber = random(1,100);
  Serial.print("numero aleatorio: ");
  Serial.println (randomNumber);      <----- i can see correctly a random number on the serial monitor
  if (!wifiManager.autoConnect("SensorPlanta" + randomNumber)) {
    Serial.println("Fallô al conectar WiFi :( ");
    delay(3000);
}

This works ok, but i cannot see the SSID correctly and it shows like "config...", so i missing something here.

The idea is to randomly generate the SensorPlanta name and following that string a random number and see it correctly on my SSID networks so i can connect to.

What data type does the wifiManager.autoConnect() function take for its argument(s)?

randomNumber = random(1,100);

Please be aware that this will always return the same "random" number unless you take steps to avoid it

Thanks for the answers!.

Now im facing another problem. I have an array of elements, lets say the Alphabetics letters...and i want to make a random string so i can use as SSID name. So the story is like this...:

.... OUTSIDE SETUP........

char *sensorName[] = {"A", "B", "C", "D", "E"}
char sensorNameComplete

.... INSIDE SETUP ......

sensorsNameComplete = random(sizeof(sensorsName) / sizeof(char*));
Serial.println(sensorsName[sensorsNameComplete];

if (!wifiManager.autoconnect((const char)sensorNameComplete()) {
Serial.println("wifi connection fail");
}

.....OUTPUT......

exit status 1
'sensorsNameComplete' cannot be used as a function

So my thoughs are that i cannot pass a variable to the wifimanager.autoconnect function.

Any help?

Thanks a lot!

sensorNameComplete is not a function, it is a (char) variable. Lose the parenthesis.

sizeof(char*)

Did you mean just char. char* is a pointer so it will not be 1 byte.

uhm weird..
Do you mean:
sensorsNameComplete = random(sizeof(sensorsName) / sizeof(char*);

I get:

expected ')' before ';' token

Thanks!!

You are confusing character strings, characters and numbers.

random() is an integer number, 16 bit binary on an Arduino Uno.
'A' is an ASCII character
"A" is a zero terminated ASCII character string.
char name[n] is an array of n bytes, which could contain ASCII characters.

Please explain exactly what it is that you want to do, and give an example of a desired result.

Uhm ok, let me explain the best i can.

I want to publish SSID name randomly so every device have a different one at the moment i want to connect them to wifi. Let's say if you publish "PlantSensor", what happend if i connect two devices at the same time?, how do i have to do to make a difference among them?.

So the idea is to have an Alphabetic array and let the program to decide ramdomly 5 or 6 letters, any of them. The main idea was to have an static String like "SensorPlant" and add this random array at the end of the line like "SensorPlant-oziwq".

My approach without the array works ok, but the complex part comes when i want to add this String coming from an Array.

I think something like this:

  • Declare the array
  • Declare a variable
  • Let the array to choose 6 random letters and pass the result to the variable
  • Use that variable to the SSID wifimanager.autoconnect() so i can make it visible.

Hoooooppppe that helps!

Thanks a lot!

Marty1982:
uhm weird..
Do you mean:
sensorsNameComplete = random(sizeof(sensorsName) / sizeof(char*);

I get:

expected ')' before ';' token

Thanks!!

In an expression, the number of ( must equal the number of )

Does this do part of what you want? It chooses 6 random characters from an array, adds them to a string and adds that randomized string (sensorNameRandom) to a literal string (filename). Result in newSensorName.

char sensorName[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'};
char sensorNameRandom[7];
char fileName[] = "filename";
char newSensorName[20];

void setup()
{
   Serial.begin(115200);
   randomSeed (analogRead(0));
}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 1000;
   if (millis() - timer >= interval)
   {
      timer = millis();
      buildSensorName();
   }
}

void buildSensorName()
{
   for (unsigned int n = 0; n < 6; n++) // leave room for the '\0'
   {
      sensorNameRandom[n] = sensorName[random(sizeof(sensorName))];
   }
   sensorNameRandom[6] = '\0';  // make the character array into a string
   //Serial.println(sensorNameRandom);
   snprintf(newSensorName, 18, "%s %s",  fileName, sensorNameRandom);
   Serial.println(newSensorName);
}

Result:

filename HAGHHG
filename IHFGBC
filename IAGFIE
filename BEHBBG
filename FBIBEB
filename DDICHG
filename CAEHCE

Now you have a string to add to the wifiManager.autoconnect() function. Which brings us back to the unanswered question in reply #1.

Reference for snprintf() function.

To make a filename like PlantSensorABCDEF (with random characters for ABCDEF), you could change groundFungus' example to this:

  ...
   snprintf(newSensorName, 18, "PlantSensor%s",  sensorNameRandom);
   Serial.println(newSensorName);
  ...

Ok, thanks a lot for taking the time to be so kind and upload some code. I only understood some lines, so whenever you can, you can do a step by step explanation so everyone can understand that and enjoy it.

So, i will share the whole for you in order to understand it and make a solution out of it.
I also accept some fix, refactor and pices of advise.

The code has added the part groundFungus added.

It only need to make the new variable to make it work inside the wifimanager.autoconnect () function like he said. Im trully honest, i dont understand too much and i will fail trying to make it work.

Thanks again!!

// Auth blynk Token xxxxxxxxxxxxxxxxxxxxxxxx

int red = D3;
int green = D4;
int blue = D5;

char sensorName[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
char sensorNameRandom[10];
char fileName[] = "SensorPlanta";
char newSensorName [20];

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#include <FS.h>   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <DHT.h>

//needed for WiFiManager library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>

#include <ArduinoJson.h>

#include <BlynkSimpleEsp8266.h>

#define DHTTYPE DHT11
#define DHTPIN D6     // D2 fisical pin

DHT dht(DHTPIN, DHTTYPE);
BlynkTimer timer;

//char mqtt_server[40] = "ingrese server mqtt";
//char mqtt_port[6] = "ingrese puerto mqtt";
char blynk_token[33] = "Ingrese Token de Blynk";
char plant_name[33] = "Ingrese nombre de la planta";

//flag for saving data
bool shouldSaveConfig = false;

void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

void buildSsidName () {
  for (unsigned int n = 0; n < 6; n++) // leave room for the '\0'
  {
    sensorNameRandom[n] = sensorName[random(sizeof(sensorName))]; 
  }
  sensorNameRandom[6] = '\0'; //make the character array into a string
  //Serial.println(sensorNameRandom);
  snprintf(newSensorName, 18, "%s %s", fileName, sensorNameRandom);
  Serial.println(newSensorName);
}

const int sensorValue = A0;

void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.println("Publishing to Blynk...");
  Blynk.virtualWrite(V0, sensorValue);
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);

  if (sensorValue >= 1000) {
    // Blynk.email("mailexample@gmail.com", "ESP8266 Alert", "Temperature over 28C!");
    Blynk.notify(plant_name);
  }
}

void setup()
{
  Serial.begin(115200);

  randomSeed (analogRead(0));

  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);

  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

  dht.begin();

  timer.setInterval(1000L, sendSensor);

  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          //strcpy(mqtt_server, json["mqtt_server"]);
          //strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(blynk_token, json["blynk_token"]);
          strcpy(plant_name, json["plant_name"]);

        } else {
          Serial.println("failed to load json config");
        }
        configFile.close();
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  //WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  //WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 33);
  WiFiManagerParameter custom_plant_name("plant name", "plant name", plant_name, 33);

  WiFiManager wifiManager;

  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  //wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  //wifiManager.addParameter(&custom_mqtt_server);
  //wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);
  wifiManager.addParameter(&custom_plant_name);

  //reset settings - for testing
  //wifiManager.resetSettings();

  //wifiManager.setMinimumSignalQuality(30);

  //wifiManager.setTimeout(120)
  static unsigned long timer = 0;
  unsigned long interval = 1000;
  if (millis() - timer >= interval) {
    timer = millis();
    buildSsidName();
  }

// THIS PART IS THE ONE TO WORK IT OUT !!
  if (!wifiManager.autoConnect((const char)newSensorName()); {
  Serial.println("Fallô al conectar WiFi");
  }

  //if you get here you have connected to the WiFi
  Serial.println("Wifi Conectado!: ");
  digitalWrite(blue, HIGH);


  //read updated parameters
  //strcpy(mqtt_server, custom_mqtt_server.getValue());
  //strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(blynk_token, custom_blynk_token.getValue());
  strcpy(plant_name, custom_plant_name.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
  Serial.println("saving config...");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    //json["mqtt_server"] = mqtt_server;
    //json["mqtt_port"] = mqtt_port;
    json["blynk_token"] = blynk_token;
    json["plant_name"] = plant_name;

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }

  while (WiFi.status() != WL_CONNECTED) {
  int mytimeout = 5;
  delay(500);
    Serial.print(".");
    if ((millis() / 1000) > mytimeout ) { // try for less than 6 seconds to connect to WiFi router
      Serial.println(" ");
      break;
    }
  }

  if (WiFi.status() == WL_CONNECTED) {
  Serial.println(" ");
    Serial.println("connected to WiFi!! yay :)");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    Blynk.config(blynk_token);
    bool result = Blynk.connect();

    if (result != true)
    {
      Serial.println("BLYNK Connection Fail");
      Serial.println(blynk_token);
      wifiManager.resetSettings();
      ESP.reset();
      //delay (5000);
    }
    else
    {
      Serial.println("BLYNK Connected!! Yay again");
    }
  }
  else if (WiFi.status() != WL_CONNECTED) {
  Serial.println("WiFi Connection Fail");
  }

  Serial.println(plant_name);

  Blynk.run();

  //timer.run();

  //reset and try again, or maybe put it to deep sleep
  Serial.println("********************");
  Serial.println("DEEP SLEEP");
  Serial.println("Deep Sleep on...");
  Serial.println("********************");
  //ESP.deepSleep(60e6); // 60 segs
  //ESP.deepSleep(1.08e+10); // 3 horas
  //ESP.deepSleep(2.16e+10); // 6 horas
  delay(100);

}

void loop()
{
  timer.run();
}

Anyone?

i dont understand too much and i will fail trying to make it work

Lack of knowledge and that attitude are easily fixed by self-directed study.

Start with the basics, go over some language tutorials (free on the web!) and work through some of the examples that are provided with Arduino. Study examples of Arduino code on the forum. If you have specific questions, post those.

Learn to crawl before trying to run. Otherwise, post on the Gigs and Collaborations forum section. You may be asked to pay for the help.

@Marty1982

Other posts/duplicates DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you also take a few moments to Learn How To Use The Forum.
It will help you get the best out of the forum in the future.
Other general help and troubleshooting advice can be found here.

Thanks all you guys!