Float question - float from value entered from phone during wifi setup

Hi all,

I'm a bit out of my depth here. I've successfully got a NodeMCU to setup a wifi connection using WiFi manager and a great tutorial I found. The tutorial also shows how to set up additional text boxes on the Wifi setup page to user enter additional information.

I'm making an internet time based clock.

The clock sketch I'm using works, and uses the following line to set the float value used in the time zone correction.
float utcOffset = 11; //GMT 10 for AEST 11 for AEDST

this is then used in this calculation to display the correct time

void updateTime()
{
  long curEpoch = localEpoc + ((millis() - localMillisAtUpdate) / 1000);
  long epoch = round(curEpoch + 3600 * utcOffset + 86400L);
  h = ((epoch  % 86400L) / 3600) % 24;
  m = (epoch % 3600) / 60;
  s = epoch % 60;
}

I can enter a variable from the phone browser interface. I can set it as integer or string. I can serial print it in the monitor.

What I can't do is use it in the calculation.

How do I get the line
float utcOffset = 11; //GMT 10 for AEST 11 for AEDST
to accept a variable instead of entering the number in code?

What I want to do is something like
float utcOffset = timeZoneCorrection(); //GMT 10 for AEST 11 for AEDST

timeZoneCorrection is defined by
int timeZoneCorrection;

and comes from this

// Need to convert numerical input to string to display the default value.
  char convertedValue[2];
  sprintf(convertedValue, "%d", timeZoneCorrection); 
  
  // Text box (Number) - 7 characters maximum
  WiFiManagerParameter timeZoneCorrection("key_num", "Enter your time zone correction here numbers only - (AEST 10, AEDT 11)", convertedValue, 2); 

  // Add all defined parameters
  wm.addParameter(&testValue);
  wm.addParameter(&timeZoneCorrection);

Everything I need is printing in serial monitor. I just can't get the value into the UTC correction part of the sketch.

Thanks

Dave

Hello

You can't have two variables with the same name :

int timeZoneCorrection;
...
WiFiManagerParameter timeZoneCorrection( ...

You can use timeZoneCorrection.getValue(), it will return a pointer to a char array containing the actual value of the parameter, as a c-string. Then use a function to convert this c-string to an integer (you don' t need float), such as atoi.

@guix

Thankyou for replying.

In Australia we have time zones that are only out by half an hour so sometimes that value might be 9.5 - that would suggest float is required?

Dave

You can use floats if you want, then use atof, or sscanf. Or use minutes instead of hours.

And look at this example if you want to add a custom field, for example if you want to restrict the field to numbers only, or maybe a drop-down list with all the countries names.. : WiFiManager/examples/Advanced/Advanced.ino at master · tzapu/WiFiManager · GitHub

Thanks!

I've got that part working.

If I want to
printStringWithShift(custom_text_box,10);

to the 8 x MAX7219 matrix that is making up the display, why can I print a string of text if I store it as a char variable in the definitions like this
char custom_text_box[14]="To be advised";

and use
printStringWithShift(custom_text_box,10);

but not if it's returned as text from the

wm.addParameter(&testValue);
and use
printStringWithShift(testValue,10);

DJ

testValue is not a char array, it's a WiFiManagerParameter. You have to use getValue().

Thanks for your help @guix but I'm struggling. Anyone else is welcome to chime in.

I'm at the last stage of this and I can commission it without it but if I can add a text message to the LED matrix that is entered from the Wifi manager interface that would ice the cake. I'm still a bit unsure about exactly how this works.

I have two message boxes successfully created in the wifimanager interface page

using this code

// Custom elements
  // Define a text box, 50 characters maximum
  WiFiManagerParameter custom_text_box("my_text", "Enter reporting time here in h:mm pm", "default string", 50);
 
  // Add custom parameter
  wm.addParameter(&custom_text_box);

  
  // Need to convert numerical input to string to display the default value.
  char convertedValue[2];
  sprintf(convertedValue, "%d", timeZoneCorrection); 
  
  // Text box (Number) - 7 characters maximum
  WiFiManagerParameter timeZoneCorrection("key_num", "Enter your time zone correction here numbers only - (AEST 10, AEDT 11)", convertedValue, 2); 

  // Add all defined parameters

  wm.addParameter(&timeZoneCorrection);

I've successfully used the timeZoneCorrection value to perform functions on the time. That part is working.

I want to take the text from the second field custom_text_box and use that to
printStringWithShift(custom_text_box,10);
and display the string of text on the LED matrix.
If i define it early on
char custom_text_box[14]="To be advised";

That string will display to the LED matrix.
image

How do I get the information from the text field in the interface window into a format that will print to the LED matrix please.

The code won't compile if I add .getValue() to the printStringWithShift
image

I'm defeated.

Thanks

Dave

I''d also be interested to know what to use instead of printStringWithShift to get the text to scroll continuously instead of scrolling to the last character & stopping.

DJ

May also have something to do with the const char* in the printCharWithShift routine. I hadn't thought to check. But if I delete const it won't compile either.

// =======================================================================

void printCharWithShift(unsigned char c, int shiftDelay) {
  
  if (c < ' ' || c > '~'+25) return;
  c -= 32;
  int w = showChar(c, font);
  for (int i=0; i<w+1; i++) {
    delay(shiftDelay);
    scrollLeft();
    refreshAll();
  }
}

// =======================================================================

void printStringWithShift(const char* s, int shiftDelay){
  while (*s) {
    printCharWithShift(*s, shiftDelay);
    s++;
  }
}

@dkjonesau, post your complete code, not snippets.

@gfgalvo it ain't pretty so don' t laugh, but I've been a paramedic for 25 years & the internet didn't exist when I last studied any coding so I'm trying to re-learn and put this together from all those around that aren't as ancient.

/*
  ESP-01 pinout from top:
  
  GND    GP2 GP0 RX/GP3
  TX/GP1 CH  RST VCC

  MAX7219
  ESP-1 from rear
  Re Br Or Ye
  Gr -- -- --

  USB to Serial programming
  ESP-1 from rear, FF to GND, RR to GND before upload
  Gr FF -- Bl
  Wh -- RR Vi

  GPIO 2 - DataIn
  GPIO 1 - LOAD/CS
  GPIO 0 - CLK

  ------------------------
  NodeMCU 1.0 pinout:

  D8 - DataIn
  D7 - LOAD/CS
  D6 - CLK
  
*/


#include "Arduino.h"
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
//#include <SPIFFS.h>
#include <LittleFS.h>
#include <FS.h>

#define JSON_CONFIG_FILE "/test_config.json"
#define SPIFFS LittleFS

// Flag for saving data
bool shouldSaveConfig = false;

//Variables to hold data from custom text boxes
char reportingType[50] = "Ammunition / Athlete Reporting";
char reportingTime[10] = "0:00pm";

//WiFiClient client;

// Define WiFiManager Object
WiFiManager wm;

// WiFiClient client;

String date;

#define NUM_MAX 8

// for ESP-01 module
//#define DIN_PIN 2 // D4
//#define CS_PIN  3 // D9/RX
//#define CLK_PIN 0 // D3

// for NodeMCU 1.0
#define DIN_PIN 15  // D8
#define CS_PIN  13  // D7
#define CLK_PIN 12  // D6

//#define TRIGGER_PIN 0 // push button on demand

#include "max7219.h"
#include "fonts.h"

// Variables to hold data from custom textboxes
char testString[50] = "test value";
char timeZoneCorrection;
int testNumber;
char custom_text_box[14];// ="To be advised"
char reportTime[14]; 
int convertedValue;
int timeout = 120; // seconds to run for
// =======================================================================

void setup() 
{
//  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP  
  Serial.begin(115200);
  initMAX7219();
  sendCmdAll(CMD_SHUTDOWN,1);
  sendCmdAll(CMD_INTENSITY,12);
  Serial.print("Connecting WiFi ");
//  WiFi.begin(ssid, password);
  WiFiManager wm;
  
  Serial.println("\n Starting");
  printStringWithShift("Turn on phone hotspot on phone that will provide WiFi connection. Join TraptronixAU_WebClock from a second phone in wifi settings to set clock...... ",25);
//  pinMode(TRIGGER_PIN, INPUT_PULLUP);

  wm.resetSettings();
//  Define a text box, 50 char max
//  WiFiManagerParameter custom_text_box("my_text", "Enter UTC time difference here", "", 50);
//                       name of text box, html name, text to print above text box, default data in text box (value)

// Custom elements
  // Define a text box, 50 characters maximum
// 10Jan  WiFiManagerParameter custom_text_box("my_text", "Enter reporting time here in h:mm pm", "default string", 50);
 
  // Add custom parameter
// 10Jan  wm.addParameter(&custom_text_box);

  
  // Need to convert numerical input to string to display the default value.
  char convertedValue[2];
  sprintf(convertedValue, "%d", timeZoneCorrection); 
  
  // Text box (Number) - 7 characters maximum
  WiFiManagerParameter timeZoneCorrection("key_num", "Enter your time zone correction here numbers only - (AEST 10, AEDT 11)", convertedValue, 2); 

  // Add all defined parameters

  wm.addParameter(&timeZoneCorrection);



if (!wm.autoConnect("TrapTronixAU_WebClock")) {        
    // Did not connect, print error message
    Serial.println("Failed to connect & hit timeout");
    printStringWithShift("Failed to connect & hit timeout",25);
    
    //Reset & try again
    ESP.restart();
    delay(1000);
    }
// Connected
  printStringWithShift("Connecting...... ",25);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");


// Lets deal with the user config values
 
 

  }
  //Convert the number value
  testNumber = atoi(timeZoneCorrection.getValue());
  Serial.print("Test Number: ");
  Serial.println(testNumber);
  
  Serial.println("   ");
  Serial.print("          Reporting Time (testValue): ");

//  reportTime = (testValue.getValue());
  Serial.println(reportTime);

  Serial.print("          Reporting Time (custom_text_box): ");
// 10Jan  Serial.println(custom_text_box.getValue());
  Serial.println("   ");
  Serial.print("WiFi Connected: "); Serial.println(WiFi.localIP());
  Serial.print("Time zone correction value:   ");
  Serial.print(timeZoneCorrection.getValue());
    Serial.print("     ");
}
// =======================================================================
#define MAX_DIGITS 16
byte dig[MAX_DIGITS]={0};
byte digold[MAX_DIGITS]={0};
byte digtrans[MAX_DIGITS]={0};
int updCnt = 0;
int dots = 0;
long dotTime = 0;
long clkTime = 0;
int dx=0;
int dy=0;
byte del=0;
int h,m,s;
// char custom_text_box[]={"To be advised"};
// =======================================================================
void loop()
  // is configuration portal requested?

{
  if(updCnt<=0) 
  { 
    updCnt = 10;  // every 10 scrolls, ~450s=7.5m
    Serial.println("Getting data...");
    printStringWithShift("Getting data....",25);  // 25    SPEED
    getTime();
    Serial.println("Data loaded");
    clkTime = millis();
  }
 
  if(millis()-clkTime > 120000 && !del && dots) // was 120000 - clock for 40s, then scrolls 
  { 
    printStringWithShift(date.c_str(),10); // was ,75
   delay(3000);

   printStringWithShift("                     TrapTronix AU",10);
   delay(1500);
// 10Jan   printStringWithShift("           Reporting Time: ",10);
//   custom_text_box = testValue.getValue();
// 10Jan   printStringWithShift(custom_text_box,10);
   delay(2000);   
    updCnt--;
    clkTime = millis();
  }
    if(millis()-dotTime > 500) 
  {
    dotTime = millis();
    dots = !dots;
  }
  updateTime();
  showAnimClock();
  
 }

// =======================================================================

void showSimpleClock()
{
  dx=dy=0;
  clr();
  showDigit(h/10,  1, dig6x8);
  showDigit(h%10,  9, dig6x8);
  showDigit(m/10, 18, dig6x8);
  showDigit(m%10, 26, dig6x8);
  showDigit(s/10, 41, dig6x8);
  showDigit(s%10, 49, dig6x8);
  setCol(16,dots ? B00100100 : 0);
  setCol(33,dots ? B00100100 : 0);
  refreshAll();
}

// =======================================================================

void showAnimClock()
{
  byte digPos[6]={1,8,18,25,41,49};
  int digHt = 12;
  int num = 6; 
  int i;
  if(del==0) {
    del = digHt;
    for(i=0; i<num; i++) digold[i] = dig[i];
    if(h>12)
   {
    h=h-12;
    }
    dig[0] = h/10 ? h/10 : 10;
    dig[1] = h%10;
    dig[2] = m/10;
    dig[3] = m%10;
    dig[4] = s/10;
    dig[5] = s%10;
    for(i=0; i<num; i++)  digtrans[i] = (dig[i]==digold[i]) ? 0 : digHt;
  } else
    del--;
  
  clr();
  
  for(i=0; i<num; i++) {
    if(digtrans[i]==0) {
      dy=0;
      showDigit(dig[i], digPos[i], dig6x8);
    } else {
      dy = digHt-digtrans[i];
      showDigit(digold[i], digPos[i], dig6x8);
      dy = -digtrans[i];
      showDigit(dig[i], digPos[i], dig6x8);
      digtrans[i]--;
    }
  }
  dy=0;
  setCol(15,dots ? B00100100 : 0);
  setCol(16,dots ? B00100100 : 0);
  setCol(34,dots ? B00100100 : 0);
  setCol(35,dots ? B00100100 : 0);
  refreshAll();
  delay(30);
}

// =======================================================================

void showDigit(char ch, int col, const uint8_t *data)
{
  if(dy<-8 | dy>8) return;
  int len = pgm_read_byte(data);
  int w = pgm_read_byte(data + 1 + ch * len);
  col += dx;
  for (int i = 0; i < w; i++)
    if(col+i>=0 && col+i<8*NUM_MAX) {
      byte v = pgm_read_byte(data + 1 + ch * len + 1 + i);
      if(!dy) scr[col + i] = v; else scr[col + i] |= dy>0 ? v>>dy : v<<-dy;
    }
}

// =======================================================================

void setCol(int col, byte v)
{
  if(dy<-8 | dy>8) return;
  col += dx;
  if(col>=0 && col<8*NUM_MAX)
    if(!dy) scr[col] = v; else scr[col] |= dy>0 ? v>>dy : v<<-dy;
}

// =======================================================================

int showChar(char ch, const uint8_t *data)
{
  int len = pgm_read_byte(data);
  int i,w = pgm_read_byte(data + 1 + ch * len);
  for (i = 0; i < w; i++)
    scr[NUM_MAX*8 + i] = pgm_read_byte(data + 1 + ch * len + 1 + i);
  scr[NUM_MAX*8 + i] = 0;
  return w;
}

// =======================================================================

void printCharWithShift(unsigned char c, int shiftDelay) {
  
  if (c < ' ' || c > '~'+25) return;
  c -= 32;
  int w = showChar(c, font);
  for (int i=0; i<w+1; i++) {
    delay(shiftDelay);
    scrollLeft();
    refreshAll();
  }
}

// =======================================================================

void printStringWithShift(char* s, int shiftDelay){
  while (*s) {
    printCharWithShift(*s, shiftDelay);
    s++;
  }
}

// =======================================================================

float utcOffset = testNumber;  //GMT 10 for AEST 11 for AEDST

long localEpoc = 0;
long localMillisAtUpdate = 0;

void getTime()
{
  WiFiClient client;
  if (!client.connect("www.google.com", 80)) {
    Serial.println("connection to google failed");
    return;
  }

  client.print(String("GET / HTTP/1.1\r\n") +
               String("Host: www.google.com\r\n") +
               String("Connection: close\r\n\r\n"));
  int repeatCounter = 0;
  while (!client.available() && repeatCounter < 10) 
  {
    delay(500);
    //Serial.println(".");
    repeatCounter++;
    
  }

  String line;
  client.setNoDelay(false);
  while(client.connected() && client.available()) {
    line = client.readStringUntil('\n');
    line.toUpperCase();
    if (line.startsWith("DATE: ")) {
      date = "     "+line.substring(0, 22);
      h = line.substring(23, 25).toInt();
      m = line.substring(26, 28).toInt();
      s = (line.substring(29, 31).toInt())+2;
      localMillisAtUpdate = millis();
      localEpoc = (h * 60 * 60 + m * 60 + s);
      
    }
  }
  client.stop();
}

// =======================================================================

void updateTime()
{
  long curEpoch = localEpoc + ((millis() - localMillisAtUpdate) / 1000);
  long epoch = round(curEpoch + 3600 * testNumber + 86400L);
  h = ((epoch  % 86400L) / 3600) % 24;
  m = (epoch % 3600) / 60;
  s = epoch % 60;
}

// =======================================================================

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.