text:
Data loging while browsing a menu on LCD shield
I'm new in arduino and not particularly awaken when it comes to code ;) .
I'm developing a device SD logging Temperatures from 2 thermocouple .
Hardware works well and I'm now trying to refine use of the LCD with a menu.
I want to be able to, while logging data on the SD card (lets say every second), browsing a menu to:

See current temperatures
see the max value from the measurements
see time already elapsed
etc.

I've used a menu code from (https://www.instructables.com/id/Arduino-Uno-Menu-Template/)
The thing is when I enter a sub-menu(menuItem()), while I'm not out of this sub menu the code is not looping anymore, so data logging would be paused.
So my question is: how should I organize my code to be able to do a repetitive task in background(logging temperatures) while browsing a menu giving information and/or proposing actions (Stop datalogging, reset etc).
Here is the code from instructables modified to be used with adafruit LCD shield:
/***************************************************************************************
    Name    : LCD Button Shield Menu
    Author  : Paul Siewert
    Created : June 14, 2016
    Last Modified: June 14, 2016
    Version : 1.0
    Notes   : This code is for use with an Arduino Uno and LCD/button shield. The
              intent is for anyone to use this program to give them a starting
              program with a fully functional menu with minimal modifications
              required by the user.
    License : This program is free software. You can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
 ***************************************************************************************/
/*
   This program is designed to get you as close as possible to a finished menu for the standard Arduino Uno LCD/button shield. The only required modifications
   are to add as menu items to the master menu (menuItems array) and then modify/adjust the void functions below for each of those selections.
*/

// You can have up to 10 menu items in the menuItems[] array below without having to change the base programming at all. Name them however you'd like. Beyond 10 items, you will have to add additional "cases" in the switch/case
// section of the operateMainMenu() function below. You will also have to add additional void functions (i.e. menuItem11, menuItem12, etc.) to the program.
String menuItems[] = {"ITEM 1", "ITEM 2", "ITEM 3", "ITEM 4", "ITEM 5", "ITEM 6"};

// Navigation button variables
int readKey;

// Menu control variables
int menuPage = 0;
int maxMenuPages = round(((sizeof(menuItems) / sizeof(String)) / 2) + .5);
int cursorPosition = 0;

// Creates 3 custom characters for the menu display
byte downArrow[8] = {
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b10101, // * * *
  0b01110, //  ***
  0b00100  //   *
};

byte upArrow[8] = {
  0b00100, //   *
  0b01110, //  ***
  0b10101, // * * *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100  //   *
};

byte menuCursor[8] = {
  B01000, //  *
  B00100, //   *
  B00010, //    *
  B00001, //     *
  B00010, //    *
  B00100, //   *
  B01000, //  *
  B00000  //
};

#include <Wire.h>
#include <LiquidCrystal.h>

// Setting the LCD shields pins
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {

  // Initializes serial communication
  Serial.begin(9600);

  // Initializes and clears the LCD screen
  lcd.begin(16, 2);
  lcd.clear();

  // Creates the byte for the 3 custom characters
  lcd.createChar(0, menuCursor);
  lcd.createChar(1, upArrow);
  lcd.createChar(2, downArrow);
}
//////////////////////////////////////////////
void loop() {
  mainMenuDraw();
  drawCursor();
  operateMainMenu();

  Serial.print("Loop");
}
///////////////////////////////////////////////
// This function will generate the 2 menu items that can fit on the screen. They will change as you scroll through your menu. Up and down arrows will indicate your current menu position.
void mainMenuDraw() {
  Serial.print(menuPage);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print(menuItems[menuPage]);
  lcd.setCursor(1, 1);
  lcd.print(menuItems[menuPage + 1]);
  if (menuPage == 0) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
  } else if (menuPage > 0 and menuPage < maxMenuPages) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  } else if (menuPage == maxMenuPages) {
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  }
}

// When called, this function will erase the current cursor and redraw it based on the cursorPosition and menuPage variables.
void drawCursor() {
  for (int x = 0; x < 2; x++) {     // Erases current cursor
    lcd.setCursor(0, x);
    lcd.print(" ");
  }

  // The menu is set up to be progressive (menuPage 0 = Item 1 & Item 2, menuPage 1 = Item 2 & Item 3, menuPage 2 = Item 3 & Item 4), so
  // in order to determine where the cursor should be you need to see if you are at an odd or even menu page and an odd or even cursor position.
  if (menuPage % 2 == 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is even and the cursor position is even that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is even and the cursor position is odd that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
  }
  if (menuPage % 2 != 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is odd and the cursor position is even that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is odd and the cursor position is odd that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
  }
}

void operateMainMenu() {
  int activeButton = 0;
  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();

    switch (buttons) {
      case 0: // When button returns as 0 there is no action taken
        break;
      case 2:  // This case will execute if the "forward" button is pressed
        buttons = 0;
        switch (cursorPosition) { // The case that is selected here is dependent on which menu page you are on and where the cursor is.
          case 0:
            menuItem1();
            break;
          case 1:
            menuItem2();
            break;
          case 2:
            menuItem3();
            break;

        }
        activeButton = 2;
        mainMenuDraw();
        drawCursor();
        break;
      case 8:
        buttons = 0;
        if (menuPage == 0) {
          cursorPosition = cursorPosition - 1;
          cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        }
        if (menuPage % 2 == 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition - 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));

        mainMenuDraw();
        drawCursor();
        activeButton = 2;
        break;
      case 4:
        buttons = 0;
        if (menuPage % 2 == 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition + 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        mainMenuDraw();
        drawCursor();
        activeButton = 2;
        break;
    }
  }
}

// If there are common usage instructions on more than 1 of your menu items you can call this function from the sub
// menus to make things a little more simplified. If you don't have common instructions or verbage on multiple menus
// I would just delete this void. You must also delete the drawInstructions()function calls from your sub menu functions.
void drawInstructions() {
  lcd.setCursor(0, 1); // Set cursor to the bottom line
  lcd.print("Use ");
  lcd.print(byte(1)); // Up arrow
  lcd.print("/");
  lcd.print(byte(2)); // Down arrow
  lcd.print(" buttons");
}

void menuItem1() { // Function executes when you select the 1st item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 1");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
  }
}

void menuItem2() { // Function executes when you select the 2nd item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 2");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
  }
}

void menuItem3() { // Function executes when you select the 3rd item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Sub Menu 3");

  while (activeButton == 0) {
    int buttons;

    buttons = lcd.readButtons();
    switch (buttons) {
      case 16:  // This case will execute if the "back" button is pressed
        buttons = 0;
        activeButton = 1;
        break;
    }
    }
  }

I thank you for your help, and hope it will be helpful for others

The key is that the menu code must never wait as the operateMainMenu() function does. Instead, it has to test the buttons, do a required task, if any, quickly, and return. This means it depends on being called very frequently so it can respond to the buttons quickly, but also must return quickly when there is nothing to do. You make those calls from your loop() function, typically.
Look at the Arduino example, "BlinkWithoutDelay". In that example everything is decided by reading the time - millis(), where in your case, you'll be deciding by testing and reacting to the buttons. Just remember never to loop to wait for an input; just test for it once and act on it or just go away if it isn't there.
Your loop() function will do nothing but give each "worker" routine an opportunity to do something:
void loop(){
   menuRun();
   dataLogRun();
}

, for instance. Each of those functions gets a frequent opportunity to do one of its tasks - or not - and return, so the next one gets a chance. A loop like this one runs extremely frequently when there is nothing to do, meaning both the menu function and the data-logging function can be very responsive when something is needed.

Thanks for the answer! I didnt had the time to test but I understood the concept. I will get back at you if something is not working.

Sure - and let us know how it works out.

I've simplified the menu (no sub menu) and it is mostly working. Now I have problem regarding memory, the SD logging crash because of lack of memory(IDE warning when compiling). When  remove unnecessary code line (Serial. print), it succeed to open and write txt file, but when I try  to, read txt file in the serial monitor, it displays squares ?!! But regarding The logic of your answer, I get i and was able to apply it. Would it be interesting that I post my code?


text:
Get ESP32 Chip ID into a string variable (Arduino/C++ newbie here)
It's just a few days since I started using Arduino IDE ( programming an ESP32 ). As I learn, I am trying to write some snippets. I wanted to store the Chip ID of ESP32 into a variable (preferably string?) so that I can generate an unique device name. I looked through the ESP32 example programs and came across this program which just prints the Chip ID to the serial console.
  uint64_t chipid;

  chipid = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).
  Serial.printf("ESP32 Chip ID = %04X", (uint16_t)(chipid >> 32)); //print High 2 bytes
  Serial.printf("%08X\n", (uint32_t)chipid); //print Low 4bytes.

Now this works fine but I needed to store it into a variable in the following format "ESP32-0A1B3C4D5E6F" ( the last part of which is the Chip/MAC ID which is 6 bytes ). I went about some reading and currently reading and managed to get this far
  char ssid1[15];
  char ssid2[15];

  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  uint16_t chip = (uint16_t)(chipid >> 32);

  snprintf(ssid1, 15, "%04X", chip);
  snprintf(ssid2, 15, "%08X", (uint32_t)chipid);

  Serial.print(ssid1);
  Serial.println(ssid2);

I am trying to read this which seems to be an excellent article on handling Arduino strings but just being a few days old with Arduino/c++ I am having some difficulty in wrapping my head around some of the concepts. I come from a Python, PHP, Javascript background so I guess this is gona take a little bit of a time. I am getting the output that I want in the serial console but now I would need this in this format (MCUDEVICE-0A1B3C4D5E6F). I am sure this code can be written in a much nicer, cleaner manner but for now I need this to proceed with another snippet (which relies on device name in the above mentioned format). Can anyone provide some pointers while I try check out the different ways I could achieve this? I just want to be sure that I am not writing ugly (and dangerous code - crashes, buffer overruns etc). Greatly appreciate any pointers. I guess I am starting to get a little paranoid about handling strings ( especially on low memory devices like typical mcus ).

What is the purpose of the following line: uint16_t chip = (uint16_t)(chipid >> 32); ? Thanks

@ItamarVieira this copies the highest 16 bits from “chipid” (which is a 48-bit value in a 64-bit variable) to the “chip” variable (which is a 16-bit variable).

You can combine all your work into one single line with the snprintf. You aren't limited to just one variable, and you can add plain text:
char ssid[23];

snprintf(ssid, 23, "MCUDEVICE-%04X%08X", chip, (uint32_t)chipid);

Why don't you simply use:
char ssid[23];
snprintf(ssid, 23, "MCUDEVICE-%llX", ESP.getEfuseMac());

This way no need to bit-shift and extra middle variables...
Just watch out for capital X for uppercase result and small 'l' for type indication. (meaning use either llX or llx and not LLX).

This works on an ESP32-S3 WROOM  on Arduino 1.8.19:
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  String MCUtype = "ESP32s3" ;
  char ssid[14];
  snprintf(ssid, 14, "%llX", ESP.getEfuseMac());
  Serial.println(ssid); //
  String ssid1 = ssid ; // convert from char to String
  Serial.println(ssid1);
  int StrLen = ssid1.length();
  Serial.printf("Length of the string %i characters \r\n",StrLen);
  String MAC ="";
  int i = 0; while ( i < 6) {
    MAC = MAC + ssid1.substring(StrLen-2-2*i,StrLen-2*i)+":";
    i++ ;
  }
  MAC = MAC.substring(0,17); // remove last :
  Serial.println(MAC);
  String Serialnumber = MCUtype+"-" ;
    int j = 3; while ( j < 6) {
  Serialnumber = Serialnumber + ssid1.substring(StrLen-2-2*j,StrLen-2*j);
  j++ ;
  }
  Serial.println(Serialnumber);
}

void loop() {
  // put your main code here, to run repeatedly:

}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Why won't my code play a tone for my arduino
I have the following code that I use to try to play a melody on my Arduino, but there is no melody just a tapping noise.
I am using the built in tone() function to play on a speaker/buzzer.
I know my hardware setup is correct because running sample code online plays a nice melody.
void setup() { }
void loop() {

    noTone(6);
  // C7 in eighth
    tone(6, 2093, 250); delay(250);
    noTone(6);
    //B7 in eighth
    tone(6, 3951, 250); delay(250);
    noTone(6);
    //G7 in fourth
    tone(6, 3136, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //F7 in eighth
    tone(6, 2794, 250); delay(250);
    noTone(6);
    //E7 in eighth
    tone(6, 2637, 250); delay(250);
    noTone(6);
    //E7 in fourth
    tone(6, 2637, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //G7 in halves
    tone(6, 3136, 1000); delay(1000);
    noTone(6);
    //C6 in fourth
    tone(6, 1047, 500); delay(500);
    noTone(6);
    //B6 in eighth
    tone(6, 1976, 250); delay(250);
    noTone(6);
    //G6 in eighth
    tone(6, 1566, 250); delay(250);
    noTone(6);
    //C6 in eighth
    tone(6, 1047, 250); delay(250);
    noTone(6);

}

This is supposed to be the melody for poker face using the tone() function

you don't need noTone if you start another tone.

The sample code you link to shows pin 8 as the connection, but your code shows pin 6. If your hardware setup is "Correct" because the sample code works, you have to look at what is then different between your code and the sample code that is known to work.

I just downloaded it, and it works for me.
Hmmm.   Try downloading the other examples again, just to make sure you haven't moved a jumper.
Another way to check this out is to cut down the program to one or two lines, and see if that does or doesn't work.

What is the speaker/buzzer you are connecting to? It may need more current then the pin can support (a few tens of mA, absolute max of 40mA to prevent damaging the pin).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to read .txt file from the internet wirelessly
I am a complete beginner to Arduino, so I'm asking this moreso to see if a project will be feasible.
My ultimate goal is to have this arduino (whenever powered) check this website "https://services.swpc.noaa.gov/text/aurora-nowcast-map.txt" (every 15 minutes or something). If a specific value in the sort of array of space delimited numbers is above a threshold, it'll turn on an LED.
I want to use some WiFi shield (price is not an issue, I just don't want complicated powering) to have the Arduino read a .txt file from the internet. What will the simplest, most reliable hardware be, and how will I read this data in? An example may be very helpful!!!
I think I can handle the string-to-light part of the code, but am very unfamiliar with the wireless portion. Once I upload the script with the wireless "credentials" onto the Arduino, I would like it to just run whenever there's power/ the credentials change!
Sorry for the long mess, I know the question is a little buried and that there are similar questions, but I'm hoping by providing all the info, somebody might point me to a similar project, or have some advice with the whole project in context.
-Alex

a quick google search results in this .... https://www.arduino.cc/en/Reference/WiFi101

most reliable is Ethernet by cable, not WiFi


text:
Arduino pins vs Esp8266MOD
I had used Arduino Uno & RFID but now i want to run same code in Esp8266MOD.
i have installed all the drivers and everything else to run esp8266 in Arduino IDE but i dont know how to connect rfid in esp8266. Can someone please compare which arduino pin & esp8266 pin are similar
 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             ?
 * SPI SS      SDA(SS)      10            ?
 * SPI MOSI    MOSI         11 / ICSP-4   ?
 * SPI MISO    MISO         12 / ICSP-1   ?
 * SPI SCK     SCK          13 / ICSP-3   ?

table filled
 * Typical pin layout used:
 * ------------------------------------------------------
 *             MFRC522      Arduino       NodeMCU
 *             Reader/PCD   Uno/101       ESP8266MOD
 * Signal      Pin          Pin           Pin
 * ------------------------------------------------------
 * RST/Reset   RST          9             any, recommended 5
 * SPI SS      SDA(SS)      10            any, recommended 4, possible 15
 * SPI MOSI    MOSI         11 / ICSP-4   13
 * SPI MISO    MISO         12 / ICSP-1   12
 * SPI SCK     SCK          13 / ICSP-3   14

io 15 is SS if esp8266 is slave. but this pin must be LOW at boot. you can use it as SS if SS pin of reader doesn't pull-up.
io 4 and io 5 are untroubled pins.
io 0 and io 2 are with io 15 boot configuration pins and can be used only if they don't change the required boot state.
io 1 and io 3 are Serial interface
io 16 is RTC pin and is used for wake up from deep slepp
warning: does the reader work with 3.3 V?


text:
Testing Conditions on Port Bytes - ignoring certain bits?
Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).
For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "X - Don't Care".)
I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.
Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.
Thanks!
-Mike

You need to use boolean arithmetic.  Use the AND operator (&) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:
byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111

if ((wanted & incoming) == wanted) {
    // whatever
}

The AND operator compares each bit of the bytes in turn.  If they are BOTH 1 then the result is 1. Otherwise the result is 0.  So the above gives:
wanted:    11001110
incoming:  11011111
AND:       11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:
wanted:    11001110
incoming:  01011011
AND:       01001010

And you can see that the result doesn't match.

AH! Okay, that makes sense - I would want my 'mask' value to have bits set to '1' I care about, and '0' I don't. This would effectively force the 'don't care' bits to 0.

That is correct.

There are ways to mask off the don't care bits.
Say your example, 0b11xx1111.
Then
incomingByte = Serial.read();
incomingByte = incomingByte || 0b00110000;  // make 4, 5 high
if (incomingByte == 0b11111111){
// got all 1s, do something
}
else {
 // some 0s received, do something else
}


text:
Methodology for designing/prototyping LED patterns
Several of my projects go through this time-consuming and tedious phase:

design a LED pattern for a geometry of WS2812 LEDs
implement it with e.g. FastLED
write to Arduino and see results
goto step 1

The second step, implementing different ideas in C with FastLED (or similar) takes a lot longer than I'd like it to. How is this step usually solved? Are there higher-level software solutions? Specialised idea-testing hardware?
I'd like to easily try out ideas such as "what if these four LEDs blinked magenta every second, while a gradient was cycling around the gradient over here".

Check out https://www.bhencke.com/pixelblaze . This runs on an ESP8266 and has a web interface. Here you can create your own animations using a, somewhat custom, scripting language. You can almost instantly see the results, and tweak till you get it right.

i setup my strip to listen to sockets, and I can push about 100 RGB levels about 15 times a second before it gets choppy. I can then use JS to preview effects i think up and code quickly. I have an example at http://pagedemos.com/wcz9t2xytf76/4 ; i don't know how exportable it is, but it might give you ideas...

Pixelblaze sounds like just what I'm looking for. Just ordered one. Thank you @gerben!

For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called FadeCandy, which allows one to send various patterns to a WS2812 chain using a protocol called Open Pixel Control.
Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.
Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.

I'm not sure if there are already solutions for it (high chance there are, maybe in some DMX 'simulations'), however, it shouldn't be too difficult to make your own.
Use a programming language you like which can handle graphics, use the same data structure as you would with FastLed, and let the software program (you write) show the pixels on a screen. This means you don't need any Arduino code.
If you split the filling of the pixels and the showing of it on the screen, you can copy the resulting 'filling of the pixels' code on the Arduino.
Update
Another solution, if you want to experiment with the actual WS2812, is to program all patterns you want to check with FastLed, and let inputs (via UART or fancy knobs/buttons/menu) decide what patterns (and properties) are executed. The key is to program the patterns in a flexible way (so use functions with parameters for each property, and states for which pattern(s) are executed or executed next if you want to check some sequence).

Sorry for my unclear question! I'd like to test the pattern in real life. I'm playing around with diffusors and optical fibers for LED artwork, so I'd need it to happen on the actual hardware

The step that takes too long time for a useful design cycle is implementing these relatively simple ideas ("blue bubble starting here") in C/FastLED. I'm imagining I can't be the only one looking to find a higher-level solution for prototyping this.


text:
What is the easiest way to count how many global variables are in your sketch code?
I have a fairly complicated sketch with about 1k lines of code. I should also say that I'm not a programmer by trade...
As I go over my code and try to make it more efficient, it'd be good to know how many global variables are in my code and whether/if all of them are necessary as global. So:
1 - Is there an easy way to count how many global variables you've used (again, imagine complex code by a non-coder), and
2 - Is there an easy way in the Arduino IDE to jump to it?

You can show us the code and we tell you how to make it more efficient.

@Jot - a thousand lines?

@JaromandaX, sure, a normal sketch for a arduino Uno can be 3000 lines, 1000 lines is not a large sketch.

If you compile your code ("verify"-button) you can see the size of the program, and the amount of memory used for global variable, at the bottom of the screen.

globals aren't as evil on MCUs as they are on PCs; used right, they can save precious RAM.

all fair comments - but none answer my question: does the IDE (or any other tool) have a feature that highlights/counts your globals?

frednikgohar, you have to meet us halfway. Tell us what the compiler says about memory when you verify the sketch. It show the amount of bytes that the sketch uses (bytes and percentage) and the amount of bytes used by global variables (bytes and percentage). Show us your sketch. I don't understand what you want. If you have declared the global variables above the setup function, then that is where they are. What exactly do you want to count? variables or bytes? The compiler shows the amount of bytes when you verify the sketch.

1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.
2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.
For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.
For a Arduino Uno and larger, the optimization is done more globally.
To optimize for ram, look for the hungriest memory eaters:

For the Arduino Uno and other avr microcontrollers, the text with
Serial.println can be put in PROGMEM with the F() macro.
Many String
objects might need a lot of heap memory.
Arrays can get large
quickly.
Arrays of large elements (float, struct) can get large even
more quickly.
The SD library uses a lot of ram memory. There is a small version
of the SD library.
Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

When an integer is changed into a byte,
perhaps all the calculations are still done with integers and the
compiler needs more memory to convert from byte to integer and back.
Perhaps that integer was only used in registers and
did not use a memory location.
A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.


text:
What should I use Arduino-Mega or Rasbeery pi?
I am doing a project on Vehicle tracking and security. In my project Micro controller will sense input from sensors and at the same time it has to sense signal from user for tracking purpose and continuously checking the speed limit and boundary. so, there will be 3-4 tasks that would be executing parallel. Can anyone suggest which one is perfect for this kind of project... Arduino-Mega or Rasberry Pi?

there are many other options.

beery pi are more fun

What are the readout from sensors? If any of them is video, go for PI.

A RaspberryPi is essentially a small, low-spec computer. It is mostly an overkill for many small projects. Imagine using a super high-spec computer to play Minecraft. It's just nonsensical.
I'm assuming you'll be connecting to the car battery? Take note of the power requirements of your project. The RaspberryPi has a power requirement of 2.1A at 5V (which is a lot!), whilst an Arduino has a minimum requirement of 250mA.
Also remember: the RaspberryPi is running an operating system in the background in order to run your code. It will be working on numerous other operations and programs, not just yours. The Arduino will only run your program.
I had a similar project to what it sounds like you're doing. I used an Arduino Mega and had Bluetooth, GPS, and SD card all connected to it. The project worked absolutely fine, and I had lots of spare program space left over should I wish to expand on it. For reference, feel free to explore.

Thank you for your kind reply and suggestion. Your are absolutely right about the power requirements but the thing that I am concerned about is that can Arduino run parallel tasks like I mention there's been a request for a location at the same time sensing data from vibration sensor and check for specified boundary or speed...... so can arduino handle all tasks at same time?

In short, multithreading is not support on the Arduino. There are libraries that can supposedly do it, but all they do is slow down the program. Arduinos work synchronously (lines of code are executed one after the other, never simultaneously), so you would have to design your program to run synchronously.

you could use a dual-core ESP32 to do 2 things at once, and the ESP does them WAY WAY faster than a mega, which cuts down on opportunities for conflict. it's also cheaper and smaller.

so you mean ESP32 can run tasks(more than 2) simultaneously ?


text:
Convert normal keyboard into Bluetooth Keyboard
I am very new to the Arduino world, I am trying to convert my wired keyboard into a bluetooth keyboard. I have a few layman questions:

Is it possible to add an audio jack adapter(like PS4 joystick has), so that I can plugin my headphones to my keyboard itself to listen to the music.
Is it possible to achieve this(bluetooth keyboard + audio jack) on Arduino or do I need to use Rasberry-pi?
Is there a way to keep my current USB wire? so that I can keep working even if the battery runs out.
I want to keep all the apparatus in the keyboard casing itself, can you please suggest smallest Arduino board that will work for my use case.
I am not sure if I need a special kind of bluetooth breakout board for this(that can receive audio as input and send keystrokes to my system). Can you please guide what will be the best fit board.

Thanks in advance.

I want to keep all the apparatus in the keyboard casing itself - can you be specific about how much room you have in your keyboard casing - because if it's anything like mine, you won't find anything that will fit

@JaromandaX It's a custom made keyboard, I can fit at least something of iPhone7's height and half of it's width in my casing.


text:
Regarding running multiple functions using millis
I have been writing code for measuring when the digital signal comes and goes (ON and OFF respectively). I have done the part calculating a single system's downtime (difference in timings between ON and OFF from the system), but when I'm not able to scale up to multiple systems when I try to copy the same code which worked above. So it would be helpful if anyone could provide some insight into how it can be done plus explaining with the code would help.
My code:
unsigned long a=0, b=0, difference;
void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.print("start");
  Serial.print(",");
  Serial.print("stop");
  Serial.print(",");
  Serial.print("minutes");
  Serial.print(",");
  Serial.println("seconds");
}

void loop()
{
 //delay(1000);
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }
 if(A == HIGH)
  {
     a = millis();
     display_output();
   }
 delay(3000);
}
void display_output()
{
 int minutes, seconds, sec;
 difference = a - b;
 seconds = int(difference/1000);
 if(seconds >= 60)
 {
  //sec = seconds;
  seconds = seconds%60;
  minutes = minutes+1;
 }
 //minutes = int(seconds/60);
 Serial.print((a/1000)+1);
 Serial.print(",");
 Serial.print((b/1000)+1);
 Serial.print(",");
// Serial.print(difference);
 //Serial.print(",");
 Serial.print(minutes);
 Serial.print(",");
 Serial.println(seconds);
 //Serial.println(",");
}

The question is not very clear.  Are you trying to measure the time between two events in time?  What do you mean by "scale up to multiple systems"?  Interrupts are another way to measure the change of logic state in a signal

Yeah, I'm measuring the time difference between the time when a signal comes to the Arduino from my machine and when the signal stops. I have multiple machines working simultaneously at different stages and I have to do a project on how often and how long the machines are down. I programmed for one machine and it was working normally, but when i try to program for two or more machines ( note that two machines may go down with some error at same time), i get some random value.

First of all, you should notice there is a problem with your logic:
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }

Here you are testing the state of the pin. If it's LOW you take a
record of the time. This is wrong. What you want to record is the time
at which the inputs falls, not when it's LOW.
This is called state change detection. In order to implement
it, you have to compare the pin state that you just read with
the previous state. The correct condition is “if the pin was HIGH
last time I read it and is now LOW”:
// Global variable:
int pin_state = HIGH;

// Within loop():
int new_pin_state = digitalRead(2);
if (pin_state == HIGH && new_pin_state == LOW) {  // it just fell
    time_of_fall = millis();
    pin_state = new_pin_state;
}

Note that this assumes that the default state is HIGH. If the pin
turns out to be LOW at power-up, then the code will assume it just
fell when the program started.
Next, you have to remove any occurrence of delay() from your code.
That will only make your timings wrong. At this point you have
non-blocking code that can easily be adapted to handle multiple input
channels.
Then you have to identify the variables that are channel-specific, and
have a per-channel version of each variable (arrays are useful here).
Then your code only needs to loop through the arrays.
Instead of having multiples arrays, you can make the code cleaner by
grouping all the channel-specific data into a single data structure:
struct Channel {
    byte pin;
    byte state;
    unsigned long fell, rose;  // times of fall and rise
};

This way you can have a single array that holds all the data for all the
channels:
const int CHANNEL_COUNT = 5;

Channel channels[CHANNEL_COUNT] = {
    { 2, HIGH, 0, 0 },
    { 3, HIGH, 0, 0 },
    { 4, HIGH, 0, 0 },
    { 5, HIGH, 0, 0 },
    { 6, HIGH, 0, 0 }
};

The code now becomes quite simple: you just loop through the array and
handle one channel at a time:
void setup()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    Serial.println("pin,fell,rose,low time");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == HIGH && new_state == LOW) {  // input fell
            c.fell = millis();
        }
        else if (c.state == LOW && new_state == HIGH) {  // input rose
            c.rose = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

The function display_channel() is left as an exercise to the reader
;-) (hint: it's prototype should be
void display_channel(const Channel &c); in order to avoid
unnecessarily copying the data structure.
Next step in code modularity would be to turn the Channel structure
into a class with a proper constructor, and make display_channel() a
method of that class.

What about a link to the state-change-detection example? https://www.arduino.cc/en/Tutorial/StateChangeDetection

This code looks neat and will definitely try with this one. I don't know much about constructors and structure things. Will learn about that. I used a delay in my program so as not to have too many data points and instead the data once in two or three seconds will be enough plus its not a time critical application, so I don't know if using millis function is overkill for my application. Thank you though :)

@Jot: Good idea. I added the link.

@RajeshAnand10: 1. Learning about object-oriented programming (classes with constructors and methods) is useful, but you can live without it for simple projects like this. 2. delay() was useful in your previous version only because you got the logic wrong. Once you properly detect state changes, it serves no useful purpose. 3. What do you mean by “overkill”? Do you believe millis() is more heavyweight than delay()? It's not. For your particular problem, it's the right tool for the job.


text:
Arduino ultrasonic sensor project
I'm a newbie at Arduino, and I'm trying to make a project with ultrasonic sensor, I'm using the grove ultrasonic ranger, not the HC-SR04, and I already did test with distance and it worked very well, but now I need help with the code.
I need to create a vector that save the values of the distance to after calculate the speed using distance/time calculus, but the case of my project its to use in open places, so will be times that the distance will be "max" because there's nobody in the range, so I need a condition to exclude those values of the array (the maximum distance printed when the sensor can't feel nothing is 516 cm)
I'm not experienced with Arduino coding, so please help me, in anex is my code for basic scanning.
#include "Ultrasonic.h"

Ultrasonic ultrasonic(7);
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    long RangeInCentimeters;
    Serial.println("The distance to obstacles in front is: ");

    // two measurements should keep an interval
    RangeInCentimeters = ultrasonic.MeasureInCentimeters();
    if(RangeInCentimeters > 400)
    Serial.print ("distancia nula");
    else
    Serial.print(RangeInCentimeters);//0~400cm
    Serial.println(" cm");
    delay(1000);
}

the question is how can i do this, create a vector that save the distances above 400cm and exclude the rest

Do you need the distance up to 400 cm and ignore the rest, or over 400cm and ignore all values below 400cm?

If you don't know how many data points will be recorded, look into vectors or an external storage device. Alternatively you could use a circular array if you don't mind losing recorded data after a while.
If you know how many data points will be recorded, a basic array will suffice.
As for excluding invalid values:
// Keep trying to get a valid data point
While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
{
 delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
 RangeInCentimeters = ultrasonic.MeasureInCentimeters();
}

//... Store data to array/linked list/etc

I changed your max range to 512 because this is likely the max real value (2^9 = 512).

while?.......

why not let the loop() loop?

its for track athletes, so i did a calculus, and it will print around 10 moves every lap, my think about the memory trouble its to every lap the array placing the values, them calculating the speed and putting in another array, then reset the array, so with 2 arrays, 1 for speed and 1 for data, reseting the data array will not solute the memory trouble?

Having the while loop would let you reduce the delay value inside and pick up the next valid measurement as soon as possible, instead of waiting the full 1000ms. Other than than it's not needed.

@rokazz For only 10 data points just use an array. However I would suggest changing your delay value because in 10 seconds (the time it takes to make 10 measurements) the runner will have gone much farther than 512cm

yes, the delay time will be 100 or 200, it depends from the results of precision

i was thinking in another solution, initially i was thinking about  the sensor pointing in to the athlete running in the straight line of the field and with the data calculate the speed, but i also can make it stand by all the lap, when the runner pass it starts a time and when pass again stop and make a calculus of the distance of the field and time, giving the speed, what do you guys think about it?

@rokazz That would work as well, but if they manage to pass through the detecting range of the sensor in less than 100/200ms it won't detect them. Look at the data sheet and determine the sample rate to figure out how low you can get that delay value. The lower it is the less likely you are to miss them.


text:
convert 32 bit long to 4 bytes and back again - CAN Bus
So after 2 days attempting this I can't get my head round it.
So I am using CAN bus to transfer accelerometer data and time data (the micros() function if under 71 minutes will output data that can be an unsigned long), however I have to send the data as bytes. I have managed to bit shift a 16-bit int into 2 bytes but I am having trouble extrapolating that method (will add later) to using longs. I am having trouble understanding the union method as I am new to creating my own functions, so, how would you guys accomplish this? As simple as possible please :)

you subtract the maximum byte 3 can be from the total, and from that subtract the maximum byte 2 can be to get byte 3. byte 4 is just max byte 4 minus number minus max byte 3 +1.

You can achieve what you want by using bitshifting and bit-wise and operators.
Here is an example that lets you extract the individual bytes of your long variable. I think it should be straigtforward to extend it to variables of different length:
void loop() {
  long a=0x12345678, c=0;
  byte b[4];
  Serial.println("Original:");
  Serial.println(a,HEX);
  delay(1000);
  Serial.println("Individual bytes:");
  for (int i=0; i<4; i++)
  {
    b[i]=((a>>(i*8)) & 0xff); //extract the right-most byte of the shifted variable
    Serial.println(b[i],HEX);
    delay(1000);
  }

  for (int i=0; i<4; i++)
  {
    c+=b[i]<<(i*8);
  }
  Serial.println("Reconstructed:");
  Serial.println(c,HEX);
  delay(1000);
}

Depending on what byte ordering (big or little endian) is expected, you might need to reorder the bytes before sending or after receiving.

Very straightforward and easy to understand the principle so thankyou, however under "reconstructed" it only prints 5678?

Did you copy the code snippet from my answer? Because if I run the code on my nodemcu I get the right answer.

Yes, i copied and pasted the code, added void setup(); and Serial.begin(9600); to get the code to run on my arduino nano

by default on an 8 bit AVR, to the right hand side of the equals defaults to int arithmetic which is signed sixteen bit. So i cast the array to a uint32_t in the loop. Unsure of if that is the most efficient way, but it works! Thankyou for your help

yes right. I didn't think about the arduino controller, when I tried on the nodemcu.

I'm trying to get this with a long, but no joy
Original:
5294A
Individual bytes:
4A
29
5
0
Reconstructed:
294A

Anyone have an update to this answer?  It should work on reconstruction (I don't see anything wrong), yet it doesn't.  Am I missing something?

The union type is similar to a struct except that each of the members of the element occupy the same memory. If you define a struct so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.
union packed_long {
  long l;
  byte b[4];
};

This is the type, so you have to declare the variable to be of that type:
packed_long mydata;

Now, you have two sub-elements of mydata: l and b[].
To save your long value, write to the l part:
mydata.l = myaccel.getY();

To access each of the 4 bytes:
byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];

On the receiving end, you take each of the 4 bytes:
mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();

As long as you receive the bytes in the same order in which you sent them, you can now access your long value in mydata.l.
The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: int32_t (signed 32-bit integer) or uint32_t (unsigned 32-bit integer).

A way to send a long is to mask off and send the LSB byte (CAN standard), then shift the next one into LSB position, for 4 bytes:
uint32_t data;

// Send to CAN bus LSB-first
// This method is destructive; data should be a temp if the
// Arduino is to retain the data after sending it.
for( uint8_t b = 4; b > 0; --b ){
   sendByte(data & 0xFF);  // send curr byte
   data >>= 8;             // shift that byte away
}

// Read from CAN bus
for( uint8_t b = 4; b > 0; --b ){
   data >>= 8;                 // make room for byte
   data |= (readByte() << 8);  // read next higher byte
}
//

OK, so CAN standard is LSB first. As you have knowledge of CAN, from what i can find they send an 8 byte packet, is only one or two of those the data? So for a total of 16 bytes of information, would 8 packets be needed?

You caught me! That's about everything I know about CAN bus, and that was from Wikipedia. There is a lot of CAN bus documentation online; that article's bibliography is good start.

8 byte is the size of the data payload of a standard can-frame. so you need two standard frames to send 16 byte of information. the newer can-fd supports 64 byte data payload per frame.


text:
Print uint8_t in arduino
I'm learning esp8266 using arduino IDE. I'm still a beginner in development board programming. What I've been trying to do is use a crypto library. I am trying out AES in arduino and I chose that library because it seemed complete, and was one of the only library that used ECB. My problem is whilst calling the encrypt function, I get confused with the output.
This is what I've done so far.
#include <Crypto.h>
#include <AES.h>
#include <string.h>

AESSmall128 aes128;

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

  uint8_t key = (uint8_t)1234567654321234;

    aes128.setKey(&key, 16);

    uint8_t output = 0;

    Serial.println("before");
    Serial.print(output);

      uint8_t input = (uint8_t)9164567654321234;

    aes128.encryptBlock(&output, &input);
    Serial.println("after");
    Serial.print(output);

}

void loop()
{
}

When I print output it returns 252. What is 252? Why only 252? It seems really short looking at it. Why doesn't it output strings?

Have you seen the example? https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/examples/TestAESSmall/TestAESSmall.ino

Hey. I've tried the examples. They don't output any results from the encryption/ decryption. The test examples are for "performance checks". I've got this question done, look at Jose's answer. Thank you.

uint8_t is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.
When you typecast your long/large values to uint8_t, you basically only show the least-significant 8-bits.
However, the decryptBlock() and encryptBlock() functions expect an array of bytes, not a single byte.
The library you link to notes, right in the linked position, that the output and input parameters must be at least blockSize() bytes in length. Referencing blockSize(), it notes that this function always returns 16. So you need to pass an array of uint8_ts of at least 16 length.
When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:
uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

(When passing an array, you don't need to dereference the variable, so call aes128.setKey(key, 16);, etc. Omit the &)
Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:
uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

You can also refer to bytes with a 2-digit hexadecimal representation:
uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

UPDATE to address strings
A C-style string is a sequence of bytes, with type char to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of 0 (i.e., 0x00, not the ASCII character '0'), so you must remember that the termination byte takes up a byte of memory.
To initialize your key with a string:
const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.
char[17] output = {0}; // Initialized to all zeros
char[17] input = "iwanttoencryptme";

aes128.encryptBlock(output, input);
output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

Serial.print(output);

If the encryptBlock() function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.

Hello @jose, thanks so much for replying. Before I continue, yes I do know it's not a good key, I'm just trying out the library for fun. I have a better understanding now after you explained that it represent values between 0-255. Now my question would be, do those numbers represent ASCII values?

ASCII values are bytes, but they typically range only from 0 to 128, and even smaller for printable ASCII. If you want to start working with strings instead of arrays of numbers, you have to take extra care when reading and writing the string data.

Okay, lets say I wanted my key to be "helloareyouarehi", how would that be represented as array of uint8_t? And to output the array of uint8_t?

Oh yea, isn't it meant to be uint8_t key [] =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  syntax wise?

Array initialization can have explicit or implicit sizing. It's my preference to explicitly define the array size.

Okay Jose, Im testing it now. I will tell you in a few minutes how it goes.

I get an error:
error: invalid conversion from 'char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

What statement triggers that error?

in the encrypt function, though i casted it to (uint8_t*) but now my output is 0⸮⸮⸮⸮X⸮,O⸮e⸮ unreadable characters.

I dont have enough rep, do you mind bringing this to chat? or maybe i can contact you personally?

Let us continue this discussion in chat.

The uint8_t is exactly 8bits wide, so it can hold values from 0 to 255. Your number however is about 54bits wide.
I think you should use the array.
Also numeric literals are usually int type, so even if you do have enough space for it, it gets wrong value. Something like uint64_t value = UINT64_C(1234567654321234); must be used


text:
What is the difference using library of SoftwareSerial.h and ESP8266WiFi.h?
What is the library I should use to upload the sensor data (ultrasonic and Infrared sensor) to the localhost server.
Because I saw some of the online resources using ESP8266WiFi.h library for the ESP01 and some of resources use the softwareserial.h library. So, what is the difference between these two libraries?

one uses wifi ... the other is to create a second, software driven serial port - which is basically useless on an ESP01 because it has like 2 gpio's

The SoftwareSerial is used to communicate with the esp8266 from other MCU. The ESP8266WiFi library is for Arduino sketch running in esp8266.
The esp8266 can be used with firmware as 'network adapter' for your sketch running for example in Arduino Uno. MCU in Uno has only one hardware Serial which is used to communicate with the computer over USB (to upload and use Serial Monitor). To communicate with the esp8266 usually a second Serial interface is created with SoftwareSerial.
But esp8266 can be used as Arduino board with "esp8266 Arduino core". This 'core' contains Arduino libraries to access the WiFi functions of the esp8266 from a sketch running in esp8266.


text:
Equivalent of millis() in Atmel studio
This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.
Picture: https://imageshack.com/a/img922/3060/umtNJp.jpg
Update 2
#define F_CPU 8000000UL
#include <avr/io.h>

#include <avr/interrupt.h>

#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)
volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

volatile uint8_t count;

ISR (TIMER0_OVF_vect)

{

    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

}

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

int main (void)

{
    DDRB |= (1<<0);
    TCNT0 = 0;
    count = 0;
    TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
    TIMSK0 = (1<<TOIE0);
    sei();

    while(1)
    {
        millis() to uart.

    }

}

cross post https://stackoverflow.com/questions/53780848/using-of-millis-in-atmel-studio

The millis() function is defined in the Arduino Core for AVR architecture, specifically the wiring.c file.
You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called timer0_millis contains the number of milliseconds since the sketch started.
The millis() function basically returns that timer0_millis value.
If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.

I have found example code,but isn't same.Can you write equivalent of code in above?for being example and my learning.Of course,If is this possible?Thanks.

I will not write it for you. It's already written in wiring.c

oh sorry,I hadn't seen wiring.c file.I have added to my project.But I am not using timer0_millis.Error: 'timer0_millis' undeclared (first use in this function).
What can I add wiring.c to my project?

You will need to read all of wiring.c, understand it, and then implement it in your own project. Arduino makes very simple the things which are complex on "pain" AVR programming. What is the reason you choose to use AVR Studio?

Because I am learning atmel studio.But now,I need to this function.No need to make it so difficult.Just,I want to counter like millis() which has forward direction.I need solution.

I'm not trying to be a jerk about it, but there is A LOT of complexity and options that are simplified by Arduino. In my answer, I said that millis() basically returns timer0_millis, however, that variable gets its value from an overflow-triggered interrupt service routine. There is no "just give code" answer -- to learn AVR Studio means to learn AVR architecture. Fortunately, wiring.c and the files it includes contain all you need to be able to implement millis() in your own project.

If wiring.c is enough for millis then you can give me code.just,copy and paste bro.I promise learn how is it work.But now,I really need.And I am trying to run part of wiring.c,I don't still run.Good days.

Asking for users to just give you code isn't a good way to get anything, especially an understanding of how it should work

You already got your answer @alexjla, it is time to study now, if you want to learn

@alexjla, I gave you on SO a link to AVR forum. there is the code https://www.avrfreaks.net/comment/907712#comment-907712


text:
Connect two or more modules sharing the same pins?
I've found some separate instructions for connecting an SD reader/writer and also instructions for connecting a RFID reader and Piezo Buzzer.  I would like to use both modules and the piezo buzzer together on the same Arduino. See below for the pin wiring details from each instruction I found:
SD Reader/Writer

3.3v goes to 3.3v on the Arduino UNO (for power)
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 10 on Arduino UNO

RFID Reader

SDA - Digital 10
SCK - Digital 13
MOSI - Digital 11
MISO - Digital 12
IRQ - unconnected
GND - GND
RST - Digital 9
3.3V - 3.3V

Piezo Buzzer

Red - Pin 8
Black - GND

Is using the same pin for more that one module ok?

What RFID reader do you have / what interface does it use? SPI?

(1) I'm currently using this RFID reader, but I'm going to change to ID-20LA which has a better range
(2) I'm thinking of buying this SD module

pins 11 MOSI, 12 MISO and 13 SCK are SPI bus. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.
I recommend to wire SD reader D3 to pin 4 and in sketch use SD.begin(4).
Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus


text:
Arduino Resetting in Automotive Application
I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.
The Setup:
Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment.  Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin.  I have also tried analog LM35 sensors.  The system works outside the car just fine.
The Problem:
When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected.  There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.
What I have learned:
-When I disconnect the temperature sensors from the PCB, problem goes away.
-It makes no difference if the wires to the sensors are shielded.
-It makes no difference if I use one wire digital or analog sensors.
-It makes no difference if I connect the PCB directly to the battery
-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)
-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.
-The chance of a reset changes when the sensors are moved or the length of wire is changed.
-It only resets when the key is turned off, never when turned on.
I tried to explain the best I can without writing a novel.  I think I might need to isolate the ground to my PCB somehow.  The problem is in the ground or the long wires to the sensors.

So you are saying that peak or pulse in the GND level resets the atmega328p. That is not hard to do, I had that with a power supply. Can you show the schematic (with the reset circuit)?

There is no power spike or loss to the PCB. The car is not actually
  running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.
I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there will be spikes. Do some research on electronics for use in an automobile.
Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.
An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.
https://www.st.com/content/ccc/resource/technical/document/application_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf
https://electronics.stackexchange.com/a/40425/195251
https://en.wikipedia.org/wiki/Load_dump
https://electronics.stackexchange.com/a/163861/195251

Yes, I checked both 5v and 12v with a scope.  The problem lies in the temperature sensors, when they are disconnected, the problem goes away.  Most of the car has been disconnected, fuel pump, injectors, coils etc there is basically nothing left to interfere.

@user1113986 A battery that can give a lot of amps and wires of some length, that is all that is needed for spikes. If a relay is still in the car and turns on or off then there will be spikes. Can you tell what kind of scope it is? Even with a expensive scope an experienced engineer has still some guessing to do when it comes to spikes.

Snap-on Modis scope.  Interference is on the ground to the temperature sensors.  With the ground disconnected, no problem, but then the system won't work...

What I would try is to use twisted conductors with an external shield. Connect the shield only at the PCB. If possible have the sensor shielded. Use the twisted conductors for the sensor. Do not use the shield for the sensor. If you can't get it to work then you might want to consider a sensor that is measured, then converted to digital, and the digital signal goes to the Arduino and an optocoupler is used to provide electrical isolation.


text:
Arduino esp8266 interferes with analog sensors
UPDATE: I tried CNY70 sensor and the same error is valid for it too. Even outputs of CNY70 and LDR is the same while ESP8266 plugged in. I think ESP8266 interferes with all analog sensors
I connected my esp8266 and ldr sensor to my seeediuno (clon of arduino by seeedstudio) and ldr returns values like 70 110 105 120 etc. When I directly pointed light to ldr, return values don't change, value scatter randomly between 50-130. When I disconnect esp8266 and switch to arduino diecimila from ardunio ide, ldr sensor works fine. I think esp8266 somehow interferes with ldr sensor. How can I fix this problem?
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
[![#define SSID "myssşd"
#define PASS "mypass"
#define BID 000001

const char *host = "api.host.com";

void setup() {
  //start serial connection
  Serial.begin(115200);
  //configure pin 2 as an input and enable the internal pull-up resistor
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
  pinMode(A0, INPUT);

  WiFi.begin(SSID, PASS);

  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Connecting...");
  }
  //If connection successful show IP address in serial monitor
  Serial.print("Connected to ");
  Serial.println(SSID);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
}

void loop() {
  //read the pushbutton value into a variable
  int sensorValMeal = analogRead(A0);
  Serial.println(sensorValMeal);
  delay(1000);
}

This is how my serial prints looks like. You can see the anomally, I added my events as well.
Connecting...
Connecting...
Connecting...
Connecting...
Connected to Anaconda
IP address: 192.168.1.21
42 <- This is start
41
41
41
41
41
41
41
40
40
151 <- I turned my phones light to ldr
78
85
84
89
92
69
97
99
100
96
104 <- I switched of my phone's light
63
103
103
108
108
109
109
114
111
112
111
103
112
113
114
112
116
104
116
116
101
117
118
118
108
122
80
109
118
123
124
125
124
114
127
127
127
98
126
127
124
114
125
127
125
124
127
98
127
126
104
127
127
126
118
128
127
92
123
126
127
128
127
111
130

esp8266 takes power from 3.3 V pin?

I followed a tutorial at youtube. In the video it was connected to 3.3v pin and I did so. I connected analog sensor to 5v pin as I have seen in online tutorial of LDR and CNY70 sensors. I tried to power sensors via 3.3 V pin but nothing changed.

the current draw of esp8266 causes voltage drops

I connected 9v battery through Vin but the result is the same. Even 9v is not enough? I don't have any 12v battery.

You aren't using the Seeduino Arduino clone. You're using (as in writing software for, and programming) the ESP8266.  Every instruction you write affects only the ESP8266. The Arduino is nothing more than a power supply (and maybe a USB to Serial adaptor if you use it as such).
To access the analog pins on the Arduino you will need to:

Design a communication protocol between the two boards
Implement that communication protocol for both boards
Program both boards with their own unique sketches that use the protocol to communicate between them.

The Arduino will gather the data using its sketch, then send the results to the ESP8266 for sending through the internet.
Alternatively put the standard AT firmware on the ESP8266 and use that as the protocol above - then you only have to implement it on the Arduino.

You read the analog pin of the esp8266, not the analog pin of the Seeeduino.

how can I correct that? I connected analog sensor to A0 of seeeduino.

you have two MCU. you need two sketches

How can I do that? I can create 2 sketch and upload them but I need to transfer variables to ESP8266. Will I transfer variables over rx tx?


text:
how can i split string data in arduino?
im sending string data via serial with following format ex. :45:60 or such as ":120:57".i got the data shown in Serial.println (secondValue) Serial.println (thirdValue); but i cant convert it to int
String myString;
char c;
int Index1,Index2,Index3, azi;
String secondValue, thirdValue;
void setup(){
Serial.begin(9600);}
void loop(){
while (Serial.available()>0)
{
delay(10);
c = Serial.read();
 myString += c;
}
 if (myString.length()>0)
{
Index1 = myString.indexOf(':');
Index2 = myString.indexOf(':', Index1+1);
Index3 = myString.indexOf(':', Index2+1);

secondValue = myString.substring(Index1+1, Index2);
thirdValue = myString.substring(Index2+1, Index3);

Serial.println(secondValue);
Serial.println(thirdValue);

myString="";
}
delay(1000);
}

Hint: Try String.toInt(), https://www.arduino.cc/en/Tutorial.StringToIntExample

https://majenko.co.uk/blog/evils-arduino-strings

https://majenko.co.uk/blog/splitting-text-c

https://majenko.co.uk/blog/reading-serial-arduino

All numbers are integers?
If yes, you can use toInt() function.
int secondValueInt, thirdValueInt;

secondValueInt = secondValueInt.toInt();
thirdValueInt = thirdValue.toInt();

thx a lot bro, you are a life saver (Y)


text:
Why does using ESP8266 in deep sleep mode still drain the battery quickly?
I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to this post it should last at least a year.
I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid     = "xxxx";
const char* password = "xxxx";

const char* host = "xxxx";

void setup() {
  Serial.begin(115200);
  dht.begin();
  delay(10);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  readSensorsAndPost();
  ESP.deepSleep(18e8); //30 minutes
}

void readSensorsAndPost() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  char charVal[10];
  dtostrf(t, 5, 2, charVal);
  makeAnHttpRequest(charVal);
}

bool makeAnHttpRequest(String msg) {
  //send the value
}

void loop() {

}

First do measurments

The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).
I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.
Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?

I haven't done any measurements yet but when I have I will post the result. Will also change the setup as per your suggestion.

You are also powering the USB interface chip, which never goes to sleep.

@Majenko is there an easy way to disable powering the USB interface chip?

Migrate to a standalone module without all the extra junk and use an external USB adapter.


text:
is there any real arduino emulators (so I can upload and run machine code on it)
I play with Arduino Micro. I write my programs in directly in machine code, in binary editors (yes, I know that there are more easy ways to program an Arduino, I do it for fun and learning). Often my programs work, but if not, then I would like to run them on an emulator to understand what's exactly going on under the hood. Is there any Arduino emulator that accepts hex files with compiled program and can execute it? I already looked at tools mentioned at Can I program for Arduino without having a real board? , but as far as I see, they are simulators rather than emulators and I can't use compiled binary programs in them.

Are you sure you are not writing Opcode?  As machine code is literally typing in numbers.  For example, there are no "labels" let alone "goto labels".  When writing in machine code, generally all branches need to be calculated to either a relative or absolute memory address.

Yes, I am sure that I am not writing opcodes, I am writing in machine code - this is why I mentioned that I use binary editor (I tried to be clear about it).

Ok, understood.  Going on, I answered your question generically.  But I see you were asking about the ATmega32U4.  If I were Microchip, I wouldn't publish how my processor worked.  That's intellectual property.  So it would be surprising to find a working software emulator available for this specific processor.  As I send in the answer, most developers simply work with the actual processor using its JTAG interface.

Hint: Search github, here is an example of a simulator that you could continue working on: https://github.com/buserror/simavr

Disclaimer: I have no affiliation with Wokwi (based on opensource AVR8js engine) except that I have learnt a lot from it.
I just tried it on the free Wokwi Arduino simulator(my favourite Arduino simulator for learning) and it worked in a blink!
Here is what I did to load the hex file into the Arduino simulator

Go to the Arduino IDE and open the basic blink example
Change the ON time delay to 100ms (to make sure, the hex file is really loaded into the Arduino simulator and to verify it's working.
Once the modified example is compiled go to the %temp% folder
Search for *.hex files and find the one which is just the latest one (this is the only way I found to grab the hex file needed)
Go to Wokwi Arduino Simulator with any Arduino example
Click on the editor tab in the left
Press function key F1
Select the option Load HEX file and START simulation
Done - the simulation should run like expected.

I have created a short GIF and I hope you like it (lazy to show step by step)

What is your affiliation with Wokwi?

Hello @starCat I have been following this Simulator for my Arduino learning but not involved in developing. I have got a lot of help as training and tutorials form Wokwi while I learn and develop other projects.

I have seen this Simulator growing from simple blink to complex projects and is closely knowing all the updates happening. Let me know if I should do something

There are many different processors used in making many different types of Arduino boards.  So there is no one way to write Arduino machine code.
There are emulator for simpler processors available for the asking.  But, while they work, it is not believe they claim to be totally accurate.
At one point in processor development history, ICE machines were widely used.  This is where a real processor is modified to allow access to internal controls and registers.  (This actually sounds like the answer to your question.)  However, as processors grew in speed and complexity, this approach grew out of favor.
Currently, most processors are built with extra internal circuitry and interface to break program execution for debugging purposes.  JTAG is one such industry standard / example.
So, while the question has merit, the common practice is likely not to run code on an emulator, but to run it on the processor using the JTAG interface and an IDE running on a host-computer / work-station.

The in-circuit-emulators were very expensive and never 100% accurate (for example different timing for external signals), while the JTAG is already in the microcontroller for free.

Good points @Jot.  And I can attest to the timing difficulties.


text:
Is there any working analogue to the pair std::function and std::bind in Arduino?
Both ArduinoSTL and StandardCplusplus don't support them. They implement the version that is compatible with c++03 (not c++11).
This functionality is handy when you design libraries that work with callbacks. And you do need them, if your Arduino does more than one thing simultaneously.
I tried also several other options, but none was enough. Most complete thing I found, Passing capturing lambda as function pointer, does not support plain function pointers and does not allow me to hold the function object as a member of the structure, because the type of the object depends on the lambda (not only its signature, like in std::function).
In particular, I need a functor that

can store both capturing lambdas and plain function wrappers
has a type that depends only on the signature of the function, so I can store it as a class member.

Well, ARM compilers with C++11 support usually have working functional library and other STL stuff. For the AVR's you can try to implement something own, or copy something like in mbed (its online compiler doesn't support c++11 so they have some not very good wrapper classes for callbacks)

@KIIV Writing a proper substitution of std::function seems very intimidating to me. Do you know something that is already written, that I can use to store both capturing lambdas and function pointers?

It can do just function pointers and as a bonus even method pointers, but it's not for the c++11 so no lambdas.

Storing capturing lambdas and function pointers will require implementing some kind of type-erasure. And that is exactly what std::function is. You will have to implement some version of std::function. You can make a simplified implementation, but there's no way around it. Although it is not clear why you claim that you need callbacks to do "more than one thing simultaneously".

I mean the event driven execution, i.e. cooperative multitasking. I suppose you are not aware if anyone wrote such library?

This is not on the whole an unreasonable thing to want to do. I've just been asked to port a framework I wrote on the ESP8266 over to vanilla Arduino and guess what - I've made extensive use of std::function for callback registration because of the elegance and modularity it enables. In a thin-and-light environment this is an extremely useful thing to be able to do.

We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function_objects.
Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.

I've changed the address of the repository - by mistake I pointed you to an old and defunct one. The proper address is https://github.com/fopeczek/function_objects


text:
Taking String Input from NodeMCU Webpage and Printing it on Serial Monitor
I've started working with NodeMCU recently. I've very little knowledge about this device and how a website works. I'm trying to take a long string input from a website hosted by NodeMCU, store it on a variable and then print in on NodeMCU Serial Monitor.
I've got the following program. Here I only have created a text box for typing. But I don't know how to take that input inside a variable and use it later for serial printing.
#include <ESP8266WiFi.h>

const char* ssid = "****";
const char* password = "*************";

WiFiServer server(80);

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

WiFi.begin(ssid, password);

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

void loop() {
    WiFiClient client = server.available();
    if (!client) {
    return;
    }

    Serial.println("new client");
    while(!client.available()){
    delay(1);
    }

    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("");

    client.println("<!DOCTYPE HTML>");
    client.println("");

    client.println("Serial Printer (Put Text here: ): ");
    client.println("

");
    client.println("<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>");
    client.println("");

    delay(1);
    Serial.println("Client disonnected");
    Serial.println("");

}

You first need to learn about HTML forms. You need more than just an input tag.

use ESP8266WebServer and see the SimpleAuthentification example

Try this. It uses the webserver library. I thought it was cleaner code. I also have a nicer way to include the pure html code.
For your original form go to yourIPaddress/single
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "MTS61752";
const char* password = "6900979039";

ESP8266WebServer webserver(80);

//------------------------------------------------
static const char PROGMEM singleLine[] = R"rawliteral(
<!DOCTYPE html>

<title>Single Line Input</title>

<form method="post" action="/save" >
Serial Printer (Put Text here: ):

<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>
<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>

<title>Clock Settings</title>

<form method="post" action="/save" >
Turn on time:
<input name="onTime" type="text" size="16" value="" >

Turn off time:
<input name="offTime" type="text" size="16" value="" >

<input type="submit" name="clk_action" value="accept">
</form>

)rawliteral";

//------------------------------------------------
void handleRoot() {
  webserver.send(200, "text/html", INDEX_HTML);
}

//------------------------------------------------
void handleNotFound() {
  webserver.send(404, "text/plain", "Page not found ...");
}

//------------------------------------------------
void handleSave() {
  String str = "Settings Saved ...\r\n";

  Serial.print("number of arguments ");
  Serial.println(webserver.args());                    // number of arguments

  if (webserver.args() > 0 ) {
    for ( uint8_t i = 0; i < webserver.args(); i++ ) {
      str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

      Serial.println("Arg "+ String(i)+"="+ webserver.argName(i));
      Serial.println("Arg "+ String(i)+"="+ webserver.arg(i));
    }
  }
  webserver.send(200, "text/plain", str.c_str());
}

//------------------------------------------------
void handleSingleLine() {
  webserver.send(200, "text/html", singleLine);
}

//------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  webserver.on("/", handleRoot);
  webserver.on("/save", handleSave);
  webserver.onNotFound(handleNotFound);
  webserver.on("/single", handleSingleLine);

  webserver.begin();
  Serial.println("Web server has started");
}

//------------------------------------------------
void loop() {
  webserver.handleClient();

}

[pedant]You need to close your tags properly.[/pedant]

Can you be more specific. I can't see anything missing closing tags.

Inputs and BR tags.

<input .... /> and

  https://stackoverflow.com/a/13232170/6544572 --- These are void elements. This means they aren't designed to contain text or other elements, and as such do not need — and in fact, cannot have — a closing tag in HTML. -----  I did some searching and it seems that XHTML uses  but I have found any documentation that specifies its use in HTML. (note, my HTML knowledge is limited) On   http://w3c.github.io/html-reference/br.html#br

I always work in XHTML. HTML is so nineties. I take the view that XHTML is a flavour of XML, so must be treated as such. Makes it simpler to switch from one to another: the same set of rules apply to both, since they are both just XML.


text:
Why does the program size increase so drastically with these switch-cases?
EDIT: The problem is my op-code catch is op >= 0x20 || op <= 0x2F rather than op >= 0x20 && op <= 0x2F and so most of the switch-case was being optimised away!
This is a really difficult question to ask, because I cannot make a minimal-verifiable version of it as its own sketch.
For fun, I'm writing an ATtiny85 byte-code interpreter. It reads op codes from EEPROM and executes them. Keeping my eye on the program size, I've been completely stumped by what's happening in the following.
I really must stress though - I could not recreate this in a minimal sketch :(
//_mem[] is a uint8_t[] for RAM allocation
//_pMem is a moveable pointer to _mem[]
//NextByte() retreives the next byte from EEPROM

//Before this is if-else statements catching ranges of similar op codes
  ...
//This one catches similar math functions (mem op= num1):
  } else if (op >= 0x20 || op <= 0x2F) {
    uint8_t num1 = _mem[NextByte()];
    if      (op == 0x20) *_pMem += num1; //1A
    else if (op == 0x21) *_pMem -= num1; //1S

//For all other op codes:
  } else {

//These can mostly be ignored

    switch (op) {
      case 0x00: J(*_pMem);                                break; //J_
      case 0x01: _o = NextWord();                          break; //JA
      case 0x0A: ++_pMem;                                  break; //MI
      case 0x0B: --_pMem;                                  break; //MD
      case 0x0C: _pMem += NextByte();                      break; //MA
      case 0x0D: _pMem -= NextByte();                      break; //MS
      case 0x10: *_pMem = NextByte();                      break; //S_
      case 0x11: _mem[NextByte()] = _mem[NextByte()];      break; //CP
      case 0x12: *_pMem = _mem[NextByte()];                break; //V_
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x80: SV();                                     break; //SV
      case 0xFF: noHalt = false;                           break; //HT
    }

The program in total, when in this configuration, is 2030 bytes.
However, when I instead put just the two op codes, 0x20 and 0x21, into the switch-case, the program balloons to 2680 bytes! Code:
      //the if-else statement for 0x20 and 0x21 is completely removed
      ...
      case 0x13: _mem[NextByte()] = *_pMem;                break; //_V
      case 0x20: *_pMem += _mem[NextByte()];               break; //1A
      case 0x21: *_pMem -= _mem[NextByte()];               break; //1S
      case 0x80: SV();                                     break; //SV
      ...

Immediately, I thought "it must be something to do with replacing num1 with _mem[NextByte()] each time", but when I tried the same thing in the if-else configuration, it was only 2044 bytes.
Obviously there's waaay more code besides this out-of-context slice, and I'd be happy to share the whole sketch, but why does it even matter? I cannot imagine why there is a 600+ byte jump, other than maybe the logic behind the switch(). Hence I'm asking!
It's not as if it's suddenly using floating point or any other gotcha...
While trying to make a minimal sketch, the if-else and switch statement configurations were only several bytes different in size, even while propping up various parts with unoptimisable code.
Thank you for all your time.

I can only guess, but my guess is that those two lines break the optimization (perhaps a number of optimizations). Perhaps not just the switch-case but the memory pointers as well. The switch-case can be efficient and it can be not efficient. Therefor, you can only get this behaviour with the switch-case statement. Perhaps there are compiler options that can be useful, but I don't know any for the switch-case. What was the size with a if-else chain with and without those two lines?

@Jot, it's one of 3 until the unconditional else - it's the 2nd one to use a range match.

I meant, if you convert the complete switch-case to a if-else-if chain, then what is the difference in code size with and without those two lines? That should be normal. A if-else-if chain is compiled in a normal way, the switch-case is known to cause such things, although 600 bytes is really a lot. I can't believe that the compiler generates a full table (or two tables) with a jump table for 256 16-bit addresses. If removing the switch-case helps, then stay away from it. You could have a look at the binary code with avr-objdump.

don"t you need break in cases of the switch?

@Jot, I believe converting that whole switch-case into an if-else was smaller by 2 bytes, so I decided to keep it as a switch-case for readability. This 600+ byte problem isn't actually affecting me for now, but I'd just like to know what's going on :)

@Juraj, the breaks are aligned just before the comments

Smaller by 2 bytes? You mean after the size increased to 2680, turning the complete switch-case into a if-else-if chain reduced the size to 2678? What was the size with and without those two lines?

sorry, I didn't see them on phone

Sorry to waste everybody's time! We can see exactly what's happened... my op-code catch is op >= 0x20 || op <= 0x2F rather than op >= 0x20 && op <= 0x2F, so the whole switch-case was being optimised away.

Compilers can be smart that way. Too smart for us humans to understand why.

Sorry that I didn't see that. There is a warning for unused variables. Is there a warning for unused code? Sometimes I put this pragma at the beginning of sketch: #pragma GCC diagnostic warning "-pedantic"


text:
Stepper Motor button control with A4988 Driver
So I'm quite new to programming and have inevitably worked myself into a corner. What I am trying to accomplish is to allow for a stepper motor, (powered by an A4988 driver) to move with the push of a button. The schematic is as follows:

And the code to try and make the motor move with a button is:
const int = buttonPin = 2;
const int = stepPin = 3;
const int = dirPin = 4;

int buttonState = 0;

void setup(){
    pinMode(stepPin,OUTPUT);
    pinMode(dirPin,OUTPUT);
    pinMode(buttonPin,INPUT);
}

void loop(){
    buttonState = digitalRead(buttonPin);

    if (buttonState = HIGH){
       digitalWrite(dirPin,HIGH);{
           digitalWrite(stepPin,HIGH);
           delayMicroseconds(500);
           digitalWrite(stepPin,LOW);
           delayMicroseconds(500);
           }
    }}

What am I doing wrong?

Seperate each code part and test each part. First check if you can detect a push on the button by turning on a led or sending a message to the serial monitor. Then create for example 100 steps for the stepper mode in code. Then you can put the two things together. Please add extra information to your question: which stepper motor is is?

Please edit the question to include a description of the problem. I can see one definite problem with your code and one thing which probably isn't what you want, but it would be useful to know how it doesn't work.

Sometimes microstepping doesn't work with particular motors. I suggest configuring the driver board for full step operation until you get your code working properly.


text:
HTTPS POST method fails in esp32
I was trying to connect with server but, I was unable to post the data. I have added the SSL key to connect with server that is happening but HTTPS POST is not. I tried the same method with http, I am able to connect with server in that case.
/* set SSL/TLS certificate */
    client.setCACert(ca_cert);
//////////////////////////////// try to connect to server again and POST the data on the cloud //////////////////////////
  if (!client.connect(host, httpsPort)) {
     Serial.println("Connection failed!");
  } else {
     Serial.println("Connected to server!");
     client.println("POST /devices/deviceData HTTP/1.1");
     client.println("Host: api.thi***i.io");
     client.println("cache-control: no-cache");
     client.println("Content-Type: application/json");
     client.println("Authorization: Bearer eyJ0e***");
     client.println("Postman-Token: b1f4e147-8d13-4a27-a1a9-b****");
     client.print("Content-Length: ");
     client.println(PostValue.length());
     client.println();
     client.println(PostValue);
  }
  Serial.print("Waiting for response ");
  while (client.available() == 0) {
     if (millis() - timeout > 50000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
     }
  }

  Serial.println("Response From Server");
  while(client.available()) {
     char c = client.read();
     Serial.write(c);
  }

It should connect from my logic but I am getting server error 400.
Can I know, what can be issue here?

Still, I am getting the same issue. Bad Response  400

Is there any other method to resolve this issue?

I have fixed in my code. But, still I am getting the same issue.

I have edited into the question. I have removed client.println() and in my code also. But, still I am getting BAD response from the servre. Is there any space or next line I am missing into the code?

this does not say if you were able to connect to the server .... I was trying to connect with server. But, I was unable to post the data. ....  please clarify you post

try adding another client.println(); after client.println(PostValue);

what is the actual host name? api.thi***i.io