text:
Solution to interrupt Arduino every n seconds
I'm a very beginner with electronics and of course with Arduino. Actually I've been in the software field (.NET) for the past 12 years. I am trying to develop a simple system to run for longer using Arduino Nano. Longer means roughly it could be for years continuously, expecting normal wear and tear.
So what I understood is Arduino loop always executes based on any values from sensors while in the loop. And also Arduino has some interrupt mechanism too.
But since the looping system feels pretty awkward for some situations, I tried to stop the loop using exit(0); inside the loop. So loop will stop  after the first execution.
I am trying to build an external simple interrupt hardware system (like any timer object in software) which interrupts Arduino in a specified interval, say 20 sec. So when that interrupt on that particular pin occurred we can call some function there to do the job and that's all from Arduino side and it can go back to sleep.
So I believe this will reduce the load on Arduino and of course since no looping it will not get heated at all. How can we make such a system (external timer) to interrupt Arduino in specific intervals? This is just a theory in mine, not an idea how to implement it in electronics.
How can I achieve this above scenario?

You can implement sleep timers in code. No need for external circuits

You can refer below links once for understanding sleep concept on Arduino.
1) http://playground.arduino.cc/Learning/ArduinoSleepCode
2) http://www.gammon.com.au/power

You wrote:

I'm a very beginner with electronics [...] the looping system feels
  pretty awkward

I think these two statements are highly correlated. It feels awkward to
you simply because you are not used to it.

So what I understood is Arduino loop always executes based on any
  values from sensors while in the loop.

This sounds like a misunderstanding. The Arduino loop() is a function
you write, and whether its behavior is “based on any values from
sensors” or not is up to you. The main() function provided by the
Arduino core library will just call your loop() repeatedly.

I tried to stop the loop using exit(0);

As explained by Tom L. in his answer, there is nowhere to exit to. In
this kind of embedded system, exit() essentially means “stop doing any
useful work”. On AVR microcontrollers (like in the Nano), exit() is
implemented as an empty infinite loop running with interrupts disabled.

I believe [sleeping] will reduce the load on Arduino and of course
  since no looping it will not get heated at all.

Heat? What heat? The CPU core of the Arduino does not generate heat. Not
at any significant level. Think about this: it's clocked at 16 MHz.
Yes, those are megahertz: snail pace! The MCU can get hot if you
have it source or sink too much current, but this is completely
unrelated to CPU load.

I am trying to build an external simple interrupt hardware system
  [...] which interrupts Arduino in a specified interval, say 20 sec.

Since you come from the software world, you probably know about
“premature optimization”: this is exactly what you are doing here. I
recommend you stop right now. Do not build into your system complexity
that may not be useful. Instead, start simple: read the Blink without
delay[] Arduino tutorial, and apply this technique to solve your
problem. In a nutshell, you will put, inside your loop(), something
like:
if (millis() - previousMillis >= JOB_PERIOD) {
    do_the_job();
    previousMillis += JOB_PERIOD;
}

Note that the tutorial I mentioned would instead do something like
previousMillis = millis();, which is fine if you want to ensure that
JOB_PERIOD is the minimum time between the jobs. The code above,
instead, assumes you want to enforce an average period.
Once you have this working, test it, and see whether you do need to
optimize it. There are two aspects that could be optimized: current
consumption and period accuracy. Either may be useful for your
particular application. Or none. Or both. It all depends on your
specific requirements.
Current consumption
There is a low hanging fruit here. You can put the CPU to sleep on every
loop iteration, simply by calling sleep_mode():
#include <avr/sleep.h>

const uint32_t JOB_PERIOD = 20000;  // 20 seconds

void do_the_job()
{
    // The stuff you have to do every 20 seconds.
}

void loop()
{
    static uint32_t previousMillis;
    if (millis() - previousMillis >= JOB_PERIOD) {
        do_the_job();
        previousMillis += JOB_PERIOD;
    }
    sleep_mode();
}

The Arduino core library has a timer interrupt triggered every
1024 µs. This is the interrupt responsible of updating the variable
that millis() returns, and it will wake you up. With the code above,
the Arduino will be awake for only a few CPU cycles per iteration
(update millis(), subtract, compare) and spend most of its time
sleeping. In the default sleep mode, only the CPU does sleep. But it is
also the only mode in which the timer does not sleep, and is thus the
appropriate mode here.
The trick above should suppress most of the power consumption of the
CPU. If it's still consuming too much for your liking (i.e. if you want
your Nano to run for years on a couple of AA cells), you should know
there are ways to push the microcontroller into the ultra-low power
realm. But it is not so simple, and you will have to tune not only the
software, but also the hardware. Your journey into microamp hunting
should start by reading Power saving techniques for
microprocessors, by Nick Gammon. The link has already been
mentioned in Chirag Patel's answer.
Period accuracy
The Arduino Nano being clocked from a ceramic resonator, you should
expect its timing accuracy to be pretty poor. The standard solution for
when you need accurate timings is to use an RTC. You could query the RTC
periodically to ask for the current time or, better yet, you can choose
an RTC with “alarm” capability. This is not unlike an alarm clock: you
program it to send you an interrupt signal at a time of your choosing.
Read the manual of your RTC for details.


text:
POST to server using ESP8266 module- Arduino Uno- AT+ commands
I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken
The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.
I do not understand why my server does not receive data
Thank you a lot in advance for your help.
I have used the following code:

#include "Arduino.h"
#include "ESP8266.h"
#include "SoftwareSerial.h"
#include "ArduinoJson.h"

#define ssid "mySSID"
#define pw "myPW"
#define IP "xxx.xxx.xxx.xxx"
#define URL "http://myurl.com/myaccesstoken"

int incomingByte;

void setup() {//I connect to wifi
  Serial.begin(115200);
  Serial.println("AT");
  delay(5000);
  analogReference(INTERNAL);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=3");
    delay(1000);
    String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
    Serial.println(WF);
    delay(5000);}
}

void loop() {
  //JSON data creation
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["flow"] = 2.54;
root["measured"] = "2017-08-14T06:16:03.418Z";
root.printTo(Serial);
delay(5000);
 // I start communication with server
 Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
 delay(5000);
 Serial.println("AT+CPSTATUS");
 // I use HTTP protocol to POST the data
    Serial.println("AT+HTTPINIT");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"CID\",\"1");
    delay(2000);
    Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
    delay(2000);
    Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
    delay(2000);
    Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
    delay(2000);
    Serial.println("AT+HTTPACTION=1");
    delay(2000);
    Serial.println("AT+HTTPREAD");
    delay(2000);
    if(Serial.available() > 0)
        {
                // read the incoming byte:
                incomingByte = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte);
    }
    Serial.println();
    Serial.println("AT+HTTPTERM");

    delay(5000);
  }

Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"
I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.

Ok. Can you suggest tutorials? Because I used a similar code (at least in the first part) to send data on thingspeak without problem and I did not find any useful tutorials on web.

@Wolf Do you have sample thingspeak code im having trouble with ESP8622

@jason Yes.Anyway you can start from the code above, removing all the "http+xxxx". The example is too long for this chat...where I can share with you it?

I suggest you use computer based tools to start communication with ESP8266 module and test out sending and receiving data before you connect the module with Arduino.
If you are looking for tutorials for the same then I suggest you visit this link maybe it will solve your problem or give you a direction to work on

source: Stack Exchange

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

sort: votes


text:
Error Compiling to Board Teensy LC
I wrote a simple switch program using a teensy LC and transistors, but the Arduino compiler will not compile for the Teensy LC. And not for just my program, but any program, including the example programs included in the Arduino. I have tried compiling for other boards and they all compile fine. This problem was also replicated on another computer running Windows 10, I am running Windows 7, with the same error message. The error message and associated code is below, for reference.
int led1 = 0;
int led2 = 1;
int led3 = 2;

int input1 = 5;
int input2 = 7;
int input3 = 9;

int bypass1 = 23; //output 1
int toneStack1_1 = 22; //output 2
int toneStack1_2 = 21; //output 3
int bypass2 = 20; //output 4
int toneStack2_1 = 19; //output 5
int toneStack2_2 = 18; //output 6
int bypass3 = 17; //output 7
int toneStack3_1 = 16; //output 8
int toneStack3_2 = 15; //output 9

boolean bypass = true;        //idicators for which mode is active
boolean toneStack1 = false;
boolean toneStack2 = false;
boolean toneStack3 = false;

void setup()
{
  pinMode(input1, INPUT);    //setting inputs
  pinMode(input2, INPUT);
  pinMode(input3, INPUT);

  pinMode(led1, OUTPUT);    //setting outputs
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  pinMode(bypass1, OUTPUT);
  pinMode(toneStack1_1, OUTPUT);
  pinMode(toneStack1_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack2_1, OUTPUT);
  pinMode(toneStack2_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);

  digitalWrite(bypass1, HIGH);   //sets to bypass mode
  digitalWrite(bypass2, HIGH);
  digitalWrite(bypass3, HIGH);

}

void loop()
{
  input1 = digitalRead(input1);    //reads inputs from pushbuttons
  input2 = digitalRead(input2);
  input3 = digitalRead(input3);

  if(input1 == HIGH && bypass == true) //Bypass to tonestack 1
  {
    digitalWrite(bypass1, LOW);   //turns off bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    bypass = false;
    toneStack1 = true;
  }

if(input2 == HIGH && bypass == true) //Bypass to tonestack 2
  {
    digitalWrite(bypass2, LOW);   //turns off bypass transistors
    digitalWrite(bypass3, LOW);

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2

    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    bypass = false;
    toneStack2 = true;
  }

  if(input3 == HIGH && bypass == true) //Bypass to tonestack 3
  {

    digitalWrite(bypass3, LOW); //turns off bypass transistor

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2
    digitalWrite(bypass2, HIGH);

    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    bypass = false;
    toneStack3 = true;
  }

  if(input1 == HIGH && toneStack1 == true) //tonestack 1 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    bypass = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tone stack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH); //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack2 = true;
    toneStack1 = false;
  }

  if(input3 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tone stack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);    //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack3 = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack2 == true) //tonestack 2 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    bypass = true;
    toneStack2 = false;
  }

  if(input1 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack1 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack3 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack3 == true) //tonestack 3 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    bypass = true;
    toneStack3 = false;
  }

  if(input1 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack1 = true;
    toneStack3 = false;
  }

  if(input2 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack2 = true;
    toneStack3 = false;
  }
}

And the error message:
Arduino: 1.8.4 (Windows 7), TD: 1.38, Board: "Teensy LC, Serial, 48 MHz, Smallest Code, US English"

In file included from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.h:34:0,

                 from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:31:

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp: In member function 'void IntervalTimer::end()':

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:87:20: error: 'IRQ_PIT_CH0' was not declared in this scope

   NVIC_DISABLE_IRQ(IRQ_PIT_CH0 + index);

                    ^

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\kinetis.h:5627:68: note: in definition of macro 'NVIC_DISABLE_IRQ'

 #define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + ((n) >> 5)) = (1 << ((n) & 31)))

                                                                    ^

Error compiling for board Teensy LC.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I'm at my wits end trying to figure this out. I have reinstalled the Arduino 1.8.4, reinstalled Teensyduino, installed previous version of Arduino, and rebooting my system. Nothing so far has worked. I feel like there is something I am missing with this, as it seems no one else has my problem, from what I could find. Any help would be appreciated.

I was able to do a very hacky fix that seemed to work. In the directory Arduino > hardware > teensy > avr > cores > teensy3 there is a .H file called kinetis. This seems to be where some of the timers addresses are stored, and under Teensy LC, the infamous IRQ_PIT_CH0 from the error message is missing. I added it in defining it as 4 and everything seems to be working now. I haven't tested my code yet, aside from compiling it, but the blink program does work. I don't know if this will cause issues down the line, but it has seemingly fixed my current problem.

I experienced a similar error.  Upon further research it seems to be a known issue.  I was able to compile using 1.8.2 and Teensyduino 1.36  I accessed 1.36 from downloading the zip file of the pjrc website in the upper right corner.  The Link was download website.  Then the path was pjrc_2017_04_04\teensy\td_136

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


text:
How to use ESP8266 wifi shield as a hotspot?
I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?
Thanks......

What examples have you tried? Are you trying to get internet access onto your phone by going through the WiFi shield and Arduino? Where is the Arduino getting access to the Interent that it could then provide that to your phone?

Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.
However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.


text:
Is there a way to send a String via a Webserver Textbox without the use of the SD card?
Since my last post, I've been trying to do some extra things with my Stranger Things Wall Project.
I connected a LCD Screen (16x2) that will take any text being processed to the wall and show what is being written (So we can read the full message even if we lost the first chars being flashed)
The original example I followed used a Bluetooth App to send the message, however I want to use a Web Server with Ethernet.
My current challenge is if it is possible to make a WebServer to feed text to arduino, without the use of a SD card. I did manage to find an example that sends a simple command, but in my case, I need to call a function and sends a string.
My knowledge is limited on the areas of HTML and JS, so any help is welcome. If it matters, the Ethernet Shield I am using currently is the W5100.
The schematic is the same as the last post, however, here is the updated code:
#include <Wire.h> //INCLUSÃO DE BIBLIOTECA
#include <LiquidCrystal_I2C.h> //INCLUSÃO DE BIBLIOTECA
#include <SPI.h> //INCLUSÃO DE BIBLIOTECA
#include <Ethernet.h> //INCLUSÃO DE BIBLIOTECA

//Pin connected to ST_CP of 74HC595
#define latchPin 5
//Pin connected to SH_CP of 74HC595
#define clockPin 7
////Pin connected to DS of 74HC595
#define dataPin 6
// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   90
// size of buffer that stores a line of text for the LCD + null terminator
#define LCD_BUF_SZ   17
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
LiquidCrystal_I2C lcd(0x27,16,2);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //ATRIBUIÇÃO DE ENDEREÇO MAC AO ETHERNET SHIELD W5100 - ETIQUETINHA
EthernetServer server(80);
String text;                                                    //Variável do tipo string que receberá o texto

void setup() {
  Serial.begin(9600);                                           //Velocidade de comunicação
  for (int i = 2; i < 7; i++) {
    if (i != 4) {
      pinMode(i, OUTPUT);                                   //Declarando o pino como saída
    }
  }
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  lcd.init();
  lcd.setBacklight(HIGH);
  lcd.setCursor(0,0);
  lcd.print("Iniciando");
  if (Ethernet.begin(mac) == 0) {
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("FALHA AO PEGAR");
    lcd.setCursor(7,1);
    lcd.print("IP");
  // no point in carrying on, so do nothing forevermore:
    delay(5000);
    return;
  }
  // print your local IP address:
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("PRONTO");
  lcd.setCursor(0,1);
  lcd.print(Ethernet.localIP());
  server.begin();
  brilho(255);
  inicializationEffect();                                       //Chamada da Função responsável pelo efeito inicial
}
void loop() {
   EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          client.println("
Stranger Things

");
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }

  //receiveText();                                               //Chamada da função responsável por receber o texto digitado
}
//Função que recebe o texto diitado
void receiveText() {
  while (Serial.available() > 0) {                              //Verifica se existe alguma informação na Serial
    char c = Serial.read();                                     //atribui cada caractere a variável c que é do tipo char
    if (c != '\n') text.concat(c) ;                              //verifica se a variável do tipo char recebeu uma quebra de linha que indica o fim da palavra ou frase e concatena todos os caracteres na String text
    delay(10);                                                  //aguarda 10 milissegundos
  }
  if (text.length() > 0) {                                      //verifica se a string text tem tamanho maior que 0
    text.toUpperCase();                                       //transforma tudo que estiver na string text para maiúsculo
    if (text[0]=='#'){
      waveEffect();
    }else if(text[0]=='!'){
      blink();
    }else {
      executeEffect(text);                                        //chama a função executeEffect passando a string text como parâmetro
    }
  }
  text = "";                                                    //limpa a string text
}
//Função responsável por ativar linha que recebe como parâmetro o número da linha
void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      if (i == 4) { i = 8; } //porta 4 usada pelo SD do Ethernet
      digitalWrite(i, LOW);
    }
  }
  if (line >= 1 && line <=3){
    if (line == 3) { line = 7; } //porta 4 usada pelo SD do Ethernet
    digitalWrite(line+1, HIGH);                               //coloca a linha 1 em estado lógico alto
  }
}

void activateLetter(char letter, int on, int off) {
  int lt;
  brilho(255);
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);                                                //mantém o pino em nível lógico alto durante o tempo que foi determinado no parâmetro da função
  }
  if (off) {
    callCol(0);
    delay(off);                                               //mantém o pino em nível lógico baixo durante o tempo que foi determinado no parâmetro da função
  }

}

void callCol(int col){
  digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));
  digitalWrite(latchPin, HIGH);

}
void executeEffect(String text) {
  for (int i = 0; i < text.length(); i++) {
    if (text[i] == ' ') {
      delay(1000);
    } else if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      activateLetter(text[i], 1000, 200);
    }
  }
}

void inicializationEffect() {
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);                          //ativa a linha
    activateLetter(char(64 + i), 100, 10);                   //ativa a letra
  }
}
void waveEffect() {
  Serial.println("Wave");
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
    lineActivation(0, 0);                          //ativa a linha

}
void blink() {
  Serial.println("Blink");
  callCol(511);
  lineActivation(1,1);
  lineActivation(2,1);
  lineActivation(3,1);
  for (int i = 0; i < 256; i++){
    brilho(i);
    delay(1);
  }
  delay(100);
  for (int i = 255; i >= 0; i--){
    brilho(i);
    delay(1);
  }
}

void brilho(byte brt) { // 0 to 255
  analogWrite(9, 255-brt);
}

your code has no SD card functions ... it is unclear what you are asking

Yes. I do not have SD card functions and I am not looking to use them. I would like to know if it is possible to do the "On press send process code" without an SD card. Every example I've found so far requires the SD card and uses Ajax/js or something related.

You can build a simple webserver for the Arduino, and create an HTML page as the user interface to send commands to the Arduino from a webbrowser. If you want to go all the way, you can even have the Arduino host that webpage and communicate over a websocket, if you can get all of that to fit in the memory of an Arduino Uno. I have implemented such a thing, so it is doable, but it was on an Arduino Nano 33 IoT. BTW I don't get what the SD card has to do with it.

i am certain that you can find minimal ajax code that does not store javascript files locally .... your problem is that you are searching in the arduino realm ... the answers are in the html/javascript/ajax realm ... your question is not really about an arduino

I see, so this is the wrong place to ask such a question. Should I delete it or keep it up and wait for the vote to close?  The SD thing is just because I can only find examples that work on the SD directly

Well, you need to run a webserver on the Arduino, that bit belongs here, and questions about building a webinterface to control an Arduino don't bother me that much, but the opinions of the powers-that-be may differ.

Well, for now I will keep it up then, and if somehow I get a solution I'll self-answer it it remains open.

Yes, and it's not too hard, but do you do need to do string parsing in C to achieve it.
In your code you read the header of the HTTP request byte by byte and send it to serial, essentially discarding it.
Instead you need to read the header line by line (at least the first line) and parse the URL parameters.
The format of the first line should be something like:
GET / HTTP/1.1

or:
GET /?text=This+will+be+displayed HTTP/1.1

You need to parse that to get everything between = and the the space if they exist. You can then display it as you wish.
Next you also need to alter the code that is sending the web page content to also include a simple HTML form with the GET method and the destination of /, which contains a text field called text.

I followed your idea and, while googling on how to deal with the resulting strings, found your examples on how to use a Char array instead of a string. It worked pretty well! Thanks! I also followed your answer to convert the %20 to space and so on, but got stuck on the accented letter problem, because some chars are over the 127 (like Ã), but I guess I'll just remember not to use them.

@Feeds Accents are a nasty subject. There's no standard for how to fit them into 8 bit values and each language has its own arrangement. That's why UTF was created. And that gets really nasty to parse since there's multiple UTF standards...

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


text:
Cant make the second 74HC595 to start counting
I'm doing my first project with Arduino, however I got in a block and cannot figure out what I am doing wrong.
This project is 'simple'. It's that Stranger Thing's Wall.
However, I want to use the 74HC595 to leave pins free on the arduino for maybe expand and do something else with that too, so, I tried doing the arduino tutorial (https://www.arduino.cc/en/Tutorial/Foundations/ShiftOut)
So my current schematic is this one below

My code, however, is kind of a frankenstein. I used the shiftOut from the tutorials, however I must confess I do not know how it works (And I think its where the error may lie). I do know VBA and Python, but I know nothing of C (Or whichever this language is)
    //Pin connected to ST_CP of 74HC595
#define latchPin 5
//Pin connected to SH_CP of 74HC595
#define clockPin 7
////Pin connected to DS of 74HC595
#define dataPin 6
String text;                                                    //Variável do tipo string que receberá o texto
void setup() {
  Serial.begin(9600);                                           //Velocidade de comunicação
  for (int i = 2; i < 7; i++) {
    pinMode(i, OUTPUT);                                   //Declarando o pino como saída
  }
  Serial.println("Iniciando");
  inicializationEffect();                                       //Chamada da Função responsável pelo efeito inicial
  //basicTest();
}
void loop() {

  receiveText();                                               //Chamada da função responsável por receber o texto digitado
}
//Função que recebe o texto diitado
void receiveText() {
  while (Serial.available() > 0) {                              //Verifica se existe alguma informação na Serial
    char c = Serial.read();                                     //atribui cada caractere a variável c que é do tipo char
    if (c != '\n') text.concat(c) ;                              //verifica se a variável do tipo char recebeu uma quebra de linha que indica o fim da palavra ou frase e concatena todos os caracteres na String text
    delay(10);                                                  //aguarda 10 milissegundos
  }
  if (text.length() > 0) {                                      //verifica se a string text tem tamanho maior que 0
    text.toUpperCase();                                       //transforma tudo que estiver na string text para maiúsculo
    if (text[0] == '#'){
      waveEffect();
    }else {
      executeEffect(text);                                        //chama a função executeEffect passando a string text como parâmetro
    }
  }
  text = "";                                                    //limpa a string text
}
//Função responsável por ativar linha que recebe como parâmetro o número da linha
void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      digitalWrite(i, LOW);
    }
  }
    digitalWrite(line+1, HIGH);                               //coloca a linha 1 em estado lógico alto
}

void activateLetter(char letter, int on, int off) {
  int lt;
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);                                                //mantém o pino em nível lógico alto durante o tempo que foi determinado no parâmetro da função
  }
  if (off) {
    callCol(0);
    delay(off);                                               //mantém o pino em nível lógico baixo durante o tempo que foi determinado no parâmetro da função
  }

}

void callCol(int col){
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, 0);
  shiftOut(dataPin, clockPin, col);
  digitalWrite(latchPin, HIGH);

}
void executeEffect(String text) {
  for (int i = 0; i < text.length(); i++) {
    if (text[i] == ' ') {
      delay(1000);
    } else if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      activateLetter(text[i], 1000, 200);
    }
  }
}

void inicializationEffect() {
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);                          //ativa a linha
    activateLetter(char(64 + i), 1000, 10);                   //ativa a letra
  }
}
void waveEffect() {
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);                          //ativa a linha
  }
}

void basicTest() {
  lineActivation(2,1);
    for (int i = 0; 1 < 500; i++) {
    callCol(255-i);
    delay(100);
    }

}

void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
int i=0;
int pinState;
pinMode(myClockPin, OUTPUT);
pinMode(myDataPin, OUTPUT);
//clear everything out just in case to
//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);
//for each bit in the byte myDataOut�
//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--)  {
digitalWrite(myClockPin, 0);
//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}
//Sets the pin to HIGH or LOW depending on pinState
digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}

If I understood right (Which I may not) theoretically, when I send a value over 255, it should "overflow" to the next 74HC595, which would be used to light the ninth column.

why shiftOut(dataPin, clockPin, 0);?

To ensure its clear, however I removed that line for the solution I posted

where did you get that idea?

I mean, I was wrong. But the point was to always set the Binary value to 0 before setting it to the correct value. Just as a Failsafe, however the more I deal with this I realize the less I know. It doesnt need a failsafe, right?

Solved using https://arduino.stackexchange.com/a/17093/37827
By removing the custom shiftOut function and changing my
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, col);

with
shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));

Works like a charm
PS: Feel free to suggest something else, but this way it fixed my problem

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


text:
Sending letter by letter to LCD, however the LCD knows the full string?
I think this is my last post about this specific project, but I got a really weird curveball right now
I managed to do the webpage I wanted, and pass the string along. Now, when a LED lights up, it sends the corresponding letter to the LCD.
The problem now is that somehow, when I send a long string, the LCD somehow "knows" and display the overflow on the second row, which makes no sense to me. All I can think of is that the Ethernet Shield is using the same connections as my I2C that connects to the LCD.
That being said, here is my code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <Ethernet.h>
#define latchPin 5
#define clockPin 7
#define dataPin 6

LiquidCrystal_I2C lcd(0x27,16,2);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server(80);
String text;
char readHttp[100];
int i;
boolean temtexto;
char lcdtext[16];
void setup() {
  Serial.begin(9600);
  for (int i = 2; i < 7; i++) {
    if (i != 4) {
      pinMode(i, OUTPUT);
    }
   }
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  lcd.init();
  lcd.setBacklight(HIGH);
  lcd.setCursor(0,0);
  lcd.print("INICIANDO");
  Serial.println("Iniciando");
  if (Ethernet.begin(mac) == 0) {
    lcd.clear();
    lcd.setCursor(1,0);
    lcd.print("FALHA AO PEGAR");
    Serial.println("FALHA");
    lcd.setCursor(7,1);
    lcd.print("IP");
    delay(5000);
    return;
  }

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("PRONTO");
  lcd.setCursor(0,1);
  lcd.print(Ethernet.localIP());
  lcd.setCursor(0,0);
  Serial.println(Ethernet.localIP());
  server.begin();
  brilho(255);
  inicializationEffect();
}

void loop(){
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        lcd.setBacklight(LOW);
        lcd.clear();
        char c = client.read();
        if (c == ';') { temtexto = false; readHttp[i] = '\n';}
        if (temtexto) {
          if(i < 100) {
            readHttp[i] = toupper(c);
            i++;
          }
        }
        if (c == '?') { temtexto = true; }
        if (c == '\n') {
          client.println("HTTP/1.1 200 OK"); // Envia nova pagina
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          client.println("");
          client.println("");
          client.println("<TITLE>Parede Stranger Things</TITLE>");
          client.println("");
          client.println("");
          client.println("
Qual texto deseja enviar?
");
          client.println("<input type=text id=texto style=width:295px  maxlength=50>
");
          client.println("<input type=submit value='Enviar' style=width:150px;height:45px onClick=location.href='/?'+document.getElementById('texto').value+';'>");
          client.println("");
          client.println("");
          client.println("<string>");

          client.println("</string>");
          delay(1);
          client.stop();
          char *leader = readHttp;
          char *follower = leader;

          // While we're not at the end of the string (current character not NULL)
          while (*leader) {
              // Check to see if the current character is a %
              if (*leader == '%') {

                  // Grab the next two characters and move leader forwards
                  leader++;
                  char high = *leader;
                  leader++;
                  char low = *leader;

                  // Convert ASCII 0-9A-F to a value 0-15
                  if (high > 0x39) high -= 7;
                  high &= 0x0f;

                  // Same again for the low byte:
                  if (low > 0x39) low -= 7;
                  low &= 0x0f;

                  // Combine the two into a single byte and store in follower:
                  *follower = (high << 4) | low;
              } else {
                  // All other characters copy verbatim
                  *follower = *leader;
              }

              // Move both pointers to the next character:
              leader++;
              follower++;
          }
          // Terminate the new string with a NULL character to trim it off
          *follower = 0;
          lcd.clear();
          executeEffect(readHttp);
          memset(readHttp, 0, sizeof readHttp);
          i = 0;
        }
      }
    }
  }
}

void lineActivation(int line, int keepalive) {
  if (keepalive == 0) {
    for (int i = 2; i <= 4; i++) {
      if (i == 4) { i = 8; } //porta 4 usada pelo SD do Ethernet
      digitalWrite(i, LOW);
    }
  }
  if (line >= 1 && line <=3){
    if (line == 3) { line = 7; } //porta 4 usada pelo SD do Ethernet
    digitalWrite(line+1, HIGH); //coloca a linha 1 em estado lógico alto
  }
}

void activateLetter(char letter, int on, int off) {
  int lt;
  lt = (((int)letter - 64) % 9);
  if (((int)letter - 64) > 8) {
    lt = lt + 1;
  }
  if (on) {
    callCol(1<<lt-1);
    delay(on);
  }
  if (off) {
    callCol(0);
    delay(off);
  }
}

void callCol(int col){
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, highByte(col));
  shiftOut(dataPin, clockPin, MSBFIRST, lowByte(col));
  digitalWrite(latchPin, HIGH);
}

void executeEffect(char text[]) {
  if (strlen(text) > 0) {
    brilho(255);
    lcd.setBacklight(HIGH);
    memset(lcdtext, ' ', sizeof lcdtext);
  }
  for (int i = 0; i < strlen(text); i++) {
    if (text[i] == ' ') {
      lcdScreen(' ');
      delay(1000);
    } else if (((int)text[i] < -58 && (int)text[i] > -65) || ((int)text[i] < -28 && (int)text[i] > -33)) {
      text[i] = 'A';
    } else if (((int)text[i] < -47 && (int)text[i] > -41) || ((int)text[i] < -9 && (int)text[i] > -14)) {
      text[i] = 'O';
    } else if (((int)text[i] < -52 && (int)text[i] > -57) || ((int)text[i] < -20 && (int)text[i] > -25)) {
      text[i] = 'E';
    } else if (((int)text[i] < -49 && (int)text[i] > -53) || ((int)text[i] < -16 && (int)text[i] > -21)) {
      text[i] = 'I';
    } else if (((int)text[i] < -35 && (int)text[i] > -40) || ((int)text[i] < -3 && (int)text[i] > -8)) {
      text[i] = 'U';
    } else if (((int)text[i] == -25 || (int)text[i] == -57)) {
      text[i] = 'C';
    }
    if ((int)text[i] < 65 or (int)text[i] > 90) {
    } else {
      lineActivation(int(((int)text[i] - 64) / 9) + 1, 0);
      //Serial.println(text[i]);
      lcdScreen(text[i]);
      activateLetter(text[i], 1000, 200);
    }
  }
  for (int i = 0; i < 16; i++){
    lcdScreen(' ');
    delay(500);
  }
  lcd.setBacklight(LOW);
  lcd.clear();
}

void lcdScreen(char ltc) {
  Serial.println(ltc);
  memcpy(lcdtext, &lcdtext[1], sizeof(lcdtext) - sizeof(char));
  lcdtext[15] =  ltc;
  lcd.setCursor(0,0);
  lcd.print(lcdtext);
}

void inicializationEffect() {
  Serial.println("LineByLine");
  for (int i = 1; i < 27; i++) {
    lineActivation(int(i / 9) + 1, 0);//ativa a linha
    activateLetter(char(64 + i), 100, 10); //ativa a letra
  }
}

void waveEffect() {
  Serial.println("Wave");
  for (int i = 1; i < 4; i++) {
    lineActivation(i, 1);//ativa a linha
  }
  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 100, 0);
  }

  for (int i = 1; i < 10; i++) {
    activateLetter(char(72 + i), 0, 100);
  }
  lineActivation(0, 0);
}

void blink() {
  Serial.println("Blink");
  callCol(511);
  lineActivation(1,1);
  lineActivation(2,1);
  lineActivation(3,1);
  for (int i = 0; i < 256; i++){
    brilho(i);
    delay(1);
  }
  delay(100);
  for (int i = 255; i >= 0; i--){
    brilho(i);
    delay(1);
  }
}

void brilho(byte brt) {
  analogWrite(9, 255-brt);
}

I am using a W5100 Ethernet Shield, a I2C to LCD adapter and a 16x2 LCD. The I2C is connected to the pins A4(SDA) and A5(SCL).
Here is a picture of how the LCD appears when I send "This is a really long string":

On the first line the text scrolls, one character at a time, as intended. However, on the second line there is an overflow of the text that, as far as I can tell, I never sent to the LCD in the first place. Even if I try to lcd.clear() after every character sent, it still persists with the end of the string on the second line.

I think what you're seeing is the result of:
lcd.print(lcdtext);

and the fact that lcdtext is not null-terminated.  print() is expecting
a string, that is some sequence of zero or more non-'\0' characters followed by a '\0' character.  Not having null-terminated it yourself, in practice it will continue reading memory after your the location of lcdtext in memory until it finds a '\0'.  Somewhere in there it is probably finding the extra character(s) that you're seeing.
You could make a point of having '\0' at the end of it always, making lcdtext one character larger if necessary in order to do that.  Or you could:
lcd.write(lcdtext, sizeof lcdtext);

In this form with the length/size as a second argument, write doesn't expect a string, just an arbitrary chunk of characters whether they contain '\0' or not and knows to stop at whatever count of characters was specified.
As an aside memmove should be used rather than memcpy when the input and output destinations overlap.  What happens with memcpy when they do overlap is undefined:
memmove(lcdtext, &lcdtext[1], sizeof(lcdtext) - 1);

memmove is outwardly the same thing, only designed for this scenario.  The difference between them is a matter of which optimizations are enabled by the knowledge that the source and destination may or may not overlap. It may not be a source of a problem on your current platform, depending on how memcpy was written, but it may later or when you switch platforms.

I replaced memcpy with memmove and it worked the same way as before. The lcd.write is not a function on <LiquidCrystal_I2C.h>, which is the library I am using for I2C to communicate with led. Adding a '\0' to the end just removed the 4 lines at the end. The RING still appeared

@Feeds, I'm not surprised memmove() made no difference on an AVR.  I am sort of surprised you're not able to use that form of write() though, since it is part of the Print class which provides print() and println() among others.  Do you have a link to the exact rendition of LiquidCrystal_I2C library you're using?

Now that I think about it, the problem may reside on the lcdtext not being a string, but a char array. The library I am using is the one on sketch https://github.com/johnrickman/LiquidCrystal_I2C, version 1.1.2

At https://github.com/johnrickman/LiquidCrystal_I2C/blob/master/LiquidCrystal_I2C.h#L55 you can see where Print inherited.  At https://github.com/johnrickman/LiquidCrystal_I2C/blob/master/LiquidCrystal_I2C.cpp#L10 single character write() is implemented.  https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/Print.cpp#L34 where the default implementation is for the two-parameter version of write() mentioned uses the single character write().

In other words, it should work fine.  If that's a sticking point, take some time with it and if still stuck maybe start a new question with a cut-down code example asking about that one aspect.

I am away from my arduino right now, but I will test as soon as I get home to report my findings. I am still weirded out how the LCD works

Huh, I kinda solved it, but I still dont get it how the lcdtext was getting the full string.
I replaced the lcdScreen function with this:
void lcdScreen(char ltc) {
  Serial.println(ltc);
  Serial.print(lcdtext);
  memmove(lcdtext, &lcdtext[1], sizeof(lcdtext) - 1);
  lcdtext[15] =  ltc;
  lcd.setCursor(0,0);
  for (int i = 0; i < 16; i++){
    lcd.print(lcdtext[i]);
  }
}

It works, but I still dont understand why I had the full text when I am just calling this function with a single char each time


text:
What does display.setSegments(&segto, 1, 1); do?
I am using a TM1637 display for my Arduino Uno. The goal was to just light up one point of the colon in the middle - what seems to be kind of impossible to accomplish. During research I stumbled over the following snippet, which I dont fully understand:
  uint8_t segto;
  int value = 1244;
  segto = 0x80 | display.encodeDigit((value/100)%10);
  display.setSegments(&segto, 1, 1);

Ok line 1 seems to declare s.th. like a char, an unsigned 8bit integer. Line 2 should be clear.
Line 3: The pipe symbol seems to do a kind of addition - never seen this before. The rest here is also not clear to me - why these strange calculation to pass a value (here 2) to .encodeDigit() ?
Finally line 4: Why is the adress of 'segto' passed to the function instead of just the value?
This all ends up showing a "2:" on the display. I got the snippet from this 'manual': https://robojax.com/learn/arduino/robojax-TM1637_display_manual.pdf
Maybe s.o. can help to light things up a bit

Let's take the hardest line first.  We'll start from the "inside" outwards.
segto = 0x80 | display.encodeDigit((value/100)%10);

The innermost bit is:
value/100

That gives you 12 from 1244.
Then there's modulus 10.
12%10

That gives you 2 (divide by 10 and return the remainder - 12/10 = 1.2, or 1 remainder 2)
That is then passed through a function that calculates what segments need to be turned on to represent the digit 2. Let's say that's 00110111 in binary, where each bit represents a segment to display.
To that you want to add the colon, which is in the most significant bit's place.  So you set that bit. That's done with the OR operator, which in C is |. 0x80 is 10000000 in binary.
OR the two values together:
00110111
10000000
========
10110111

That value is then assigned to the segto variable.
I am not familiar with that library, but I would assume that the setSegments function is expecting an array of segment settings, a number of digits to apply it to, and maybe a digit offset in the display (at a guess).
In C there is no real difference between using a 1 element array and using a variable and taking its address.
You could just as well have used:
uint8_t segto[1];
int value = 1244;
segto[0] = 0x80 | display.encodeDigit((value/100)%10);
display.setSegments(segto, 1, 1);

If you were doing more than one digit you'd be wanting to use an array anyway.


text:
Is there any way or command to do the double reset of the esp8266 through CODE(sketch)?
I just want to do the double reset of the ESP8266 through code (sketch) .Is there any command or function for this ?is it possible??

Double reset? What's that?

Why would you want to? If the device is already under your control, couldn’t you just run the code you would otherwise run after a double reset (like reconfiguring Wifi)?

you have an esp8266 module wired to Arduino and you want to reset it from the sketch in Arduino?

In node mcu we have one double reset button .when we press that button it will re start the wifi .

yes sir ,how do i go for that???@Juraj

I think we are all confused with the term you are using: "double reset button".  We have no idea what you are talking about as none of us use this term.  If all you want is to restart the WIFI, look at any code that uses the WIFI radio and study how it starts the WIFI radio.  Chances are if you run that code again the WIFI radio will be re-initialized.

Of course then there is this project at github.

@kiran, there is no "double reset button". There is a procedure that involves pressing reset twice, which tells the NodeMCU to enter Wifi reconfiguration mode (or whatever), but only if it's configured to detect a double reset and act on it. If you want to generate a double reset programatically, I presume you could also just run the piece of code that you'd run upon detecting a (manually generated) double reset.

wire a pin of Arduino to reset pin of the esp8266. in setup set the pin as INPUT. if you want to reset the esp8266, set the pin as OUTPUT, then write it LOW, then set it again as INPUT. don't write it HIGH. for double reset repeat the reset.

There are not enough details in the question so we need to guess the goal of the project.  Assuming the goal is to have alternative behaviors depending on pressing the reset button once or twice with in a given span of time.
This project at github likely uses the RTC and some of the RTC flash memory in an ESP8266 to determine if the reset button has been pressed once or twice in a given span of time.
From that project:

PURPOSE: Detects a double reset so that an alternative start-up mode
can be used. One example use is to allow re-configuration of a
device's wifi.

This does not answer the question. The question is about generating a double reset programatically, not detecting it.

I am not sure generating a double reset (what ever this turns out to be) is the end goal.  Let us hear a response from the person (@kiran) posting the question.  I had hoped he would respond to this answer and by doing so would give us enough information to make a better question and answer.

I agree. The question and the underlying reasons for it are far from clear.


text:
Can't read PWM signal from 2-pin fan header
I'm trying to get PWM values from a 2-pin fan header on DuetWifi board (it is a 3D Printer Controller Board). Here is some info about the fan connection on that board.
From their forum, I got to know that fan output is open-drain and can operate with frequency up to 65535 Hz (frequency for each fan is configurable).
First of all, I connected Duet FAN- to Arduino D7 and tried that code:
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT_PULLUP);
}

void loop() {
  duration = pulseIn(pin, HIGH);
  Serial.println(duration);
}

But it shows constant readings between 6-7 in Serial Monitor:
7
6
7
7
7
7
7
6
6
7

Also, any fan speed adjustment in the Duet UI doesn't affect those readings as well.
After that, I have tried a lot of different libraries and codding approaches from Arduino forum to get suitable PWM readings from FAN- pin, but have no luck.

Please show us how you connected the Arduino to the fan.

Your picture shows that you have only connected one line to the Arduino.  You do not have a common ground between the Arduino and the fan controller.  You need to connect the grounds together.
Voltage is like height, it requires two points to measure.  If I point at a hill and I say, "How high is that hill?" that seems like a pretty easy question to answer at first.  But it becomes ambiguous quickly.  Do we want to say how high it is compared to the ground around it?  Or how high from sea level?  Or how high from where we are standing?  You simply can't say how high a hill is unless you agree on where to measure from.
It's the same with voltage.  You can't measure a voltage unless you have a potential that you can consider the 0 point to measure from.  That 0 point is the ground wire.  And as you have drawn the circuit the two boards don't agree on where they will consider 0 volts.

Thank you for such a detailed explanation.


text:
How to convert Unicode char to “Unicode HEX Position” in Arduino
How to convert Unicode char to "Unicode HEX Position" in Arduino or C
i will share a picture here :

for example in JavaScript you can do that with charCodeAt(); ! this function will return exactly the char-code and then you can convert it to hex!
for example in JavaScript i can do that like this to return exact table value
 var inpString = 'س';
    var myChar=0;
    var output = 0;
    myChar = inpString.charCodeAt(0);
    output = (ToHex((myChar&0xff00)>>8 )) + (ToHex( myChar&0xff ));

    function ToHex(i)
    {
        var sHex = "0123456789ABCDEF";
        var Out = "";
        Out = sHex.charAt(i&0xf);
        i>>=4;
        Out = sHex.charAt(i&0xf) + Out;
        return Out;
    }
 alert(output);

So how can i do that in Arduino ? its using to send unicode char in PDU mode in Arduino
i just need to convert unicode char like this -> 'س' to correct Unicode HEX Position that i shared in the picture above
for example 'س' is 0633 or 'A' is 0041 or 'ب' is 067E

Or simply console.log("س".charCodeAt(0).toString(16)).

please do not post at multiple locations ... https://stackoverflow.com/questions/62878287/how-to-convert-unicode-char-to-unicode-hex-position-in-arduino-or-c

Unlike JavaScript, C++ makes no difference between a character and its
code point. Thus, 'A', 0x41 and 65 are just different ways of
writing the same number.
Note, however, that the char type is intended to hold ASCII only. For
everything else, you may try using wide characters. For example, the
program
void setup() {
    Serial.begin(9600);
    wchar_t c = L'س';
    Serial.println(c, 16);
}

void loop() {}

outputs 633 on the serial port. Note the second argument to
Serial.println() which specifies base 16. Default is to print
numbers in decimal.
Beware that the representation of wide characters is implementation
defined, and the avr-libc doesn't provide support for manipulating them
or strings made with them. If you want to transmit them, you will also
have to decide for yourself how to break them down into a sequence of
bytes, as that's the only thing a serial port (or I2C, or SPI for that
matter) can transmit. UTF-8 is the most popular choice. I doubt wide
characters are popular in embedded systems at all.

its working, you are amazing thank you so much

so the difference to the sketch in my answer is the encoding of the source code versus the encoding of Serial Monitor.

@Juraj: The encoding of the source code is irrelevant to my answer as long as the dev environment is consistent (same encoding used by the editor and assumed by the compiler): the compiler initializes c with the code point of the character the editor shows between the quotes. It is basically equivalent to writing wchar_t c = 0x633, but in a way that hopefully makes more sense to the programmer. As soon as the program does I/O with non-ASCII characters, it will have to make a decision about the character encoding it is going to use.

This will read and print unicode characters from/to Serial Monitor and print their HEX codes. Please set the line ending in Serial Monitor to NL and confirm the entered character with Enter.
void setup() {
  Serial.begin(115200);
}

void loop() {
  if (Serial.available()) {
    char buff[4];
    int l = Serial.readBytesUntil('\n', buff, sizeof(buff) - 1);
    if (l > 0) {
      buff[l] = 0;
      Serial.println(buff);
      Serial.print(buff[0], HEX);
      if (l > 1) {
        Serial.print(buff[1], HEX);
      }
      Serial.println();
    }
  }
}

thank you for the answer , this code print -> D8B3 for -> 'س' , Not 0633 !
but its working correct for ascii character

If buff[0] is less than 16, you would have to zero pad. 2. This program assumes the serial monitor sends characters as UCS-2BE, which is not the case. Like almost everything nowadays, it uses UTF-8 for input and output.

@EdgarBonet, my sketch doesn't assume anything. it prints the hex values and I know it is UTF-8. and visible characters have codes > 0x10

The question is about printing the code point (not the code units!) of a character in hex. Your sketch prints the hex values of pairs of bytes, concatenated. The way they are concatenated embeds the implicit assumption that these bytes represent 16-bit numbers transmitted in big endian order. Considering these 16-bit numbers as equivalent to code points is only valid if the characters are transmitted as UCS-2.

A reliable way to output Unicode chars is to use Octal equivalents in the string you are printing.
e.g.
Serial.print("\342\204\211");

will output ℉ provided the receiver has  font for that unicode.
Using Non-ASCII chars in Arduino
has a .jar file that converts between Unicode chars, \u... strings and Octal
Hex \x.. is not used because C compilers can get confused if the next character after the two hex digits is 'a' to 'f'. Using octal avoids this problem. The GCC compiler used by Arduino also does not accept all unicode sequences such as \u0020


text:
How to check if the MQTT connection is still active?
I am wondering if there is a way to check and see if the MQTT connection is still active.
The reason for this is that I am having trouble with the connection dropping after a short while and not seeming to reconnect.
/*
  ArduinoMqttClient - WiFi Simple Sender

  This example connects to a MQTT broker and publishes a message to
  a topic once a second.

  The circuit:
  - Arduino MKR 1000, MKR 1010 or Uno WiFi Rev2 board

  This example code is in the public domain.
*/

#include <ArduinoMqttClient.h>
#include <MKRGSM.h>

#include "arduino_secrets.h"
// Please enter your sensitive data in the Secret tab or arduino_secrets.h
// PIN Number
const char PINNUMBER[]     = SECRET_PINNUMBER;
// APN data
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;

GSMClient client;
GPRS gprs;
GSM gsmAccess;
MqttClient mqttClient(client);

const char broker[] = "*****";
int        port     = 1883;
const char topic[]  = "Tempdata";

const long interval = 500000;
unsigned long previousMillis = 0;

float SERIESRESISTOR = 9.87;
float TEMPERATURENOMINAL = 25.0;
float BCOEFFICIENT = 3540.0;
float thermistor = 0.0;
float THERMISTORNOMINAL = 10;

int count = 0;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);

  Serial.println("Starting Arduino web client.");
  // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("You're connected to the network");
  Serial.println();

  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
  mqttClient.setId("pump-house-gsm");

  // You can provide a username and password for authentication
  //mqttClient.setUsernamePassword("****", "****");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

  // set analog resulotion to 12
  analogReadResolution(12);
}

void loop() {
  // call poll() regularly to allow the library to send MQTT keep alives which
  // avoids being disconnected by the broker
  mqttClient.poll();

  // to avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
  // see: File -> Examples -> 02.Digital -> BlinkWithoutDelay for more info
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    /*Read analog outputof NTC module,
     i.e the voltage across the thermistor */
    float average = ((float)analogRead(A0) / 4095.0) * 3.3;

    average = (average * SERIESRESISTOR) / (3.3 - average);

    float steinhart;
    steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
    steinhart = log(steinhart);                  // ln(R/Ro)
    steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
    steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
    steinhart = 1.0 / steinhart;                 // Invert
    steinhart -= 273.15;                         // convert absolute temp to C

    // save the last time a message was sent
    previousMillis = currentMillis;

    // Keep track of times a message was sent
    // this is to reconnect every hour.
    count = count + 1;

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    mqttClient.print("The temperature is ");
    mqttClient.print(steinhart);
    mqttClient.endMessage();
  }
}

Maybe endMessage, beginMessage, or poll has a return that says it has failed to send a message?
I've looked at endMessage and beginMessage and it does not seem like it to me, but poll is much more complicated and I can't really tell.

I found the solution with the connected function included in the ArduinoMqttClient (found it browsing the library code).
Here is a code snippet showing what I added:
...
...
if (currentMillis - previousMillis >= interval) {
  if (!mqttClient.connected()) {
    if (mqttClient.connect(broker, port)) {
        Serial.println("reconnected");
    }
  }

  /*Read analog outputof NTC module,
  i.e the voltage across the thermistor */
  float average = ((float)analogRead(A0) / 4095.0) * 3.3;
...
...

It is working so far!


text:
What's wrong with this code..?
I want to make an 8*8 led matrix. I found this code on the web:

    int latchPin = 12;  //Pin connected to ST_CP of 1st 74595
    int clockPin = 13;  //Pin connected to SH_CP of 1st 74595
    int dataPin = 11;   //Pin connected to DS of 1st 74595

    int latchPin2 = 6;  //Pin connected to ST_CP of 2nd 74595
    int clockPin2 = 7;  //Pin connected to SH_CP of 2nd 74595
    int dataPin2 = 5;   //Pin connected to DS of 2nd 74595

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);

      pinMode(latchPin2, OUTPUT);
      pinMode(clockPin2, OUTPUT);
      pinMode(dataPin2, OUTPUT);
    }

    void loop() {
      /************** Send HIGH to first Anode pin (16th pin) and LOW to all
      other anode pins (15, 11, 3, 10, 5, 6, 13) of LED matrix *************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin, LOW);
      //Send 0 0 0 0 0 0 0 1 (1) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 1st 74595
      shiftOut(dataPin, clockPin, MSBFIRST, 1);
      // shift out the bits:
      digitalWrite(latchPin, HIGH);

      /**************** Send LOW to the first cathode pin (4th pin) and HIGH to all
        other cathode pins (7, 2, 8, 12, 1, 14 and 9) of LED matrix *****************/

      // take the latchPin low so the LEDs don't change while you're sending in bits:
      digitalWrite(latchPin2, LOW);
      // Send 1 1 1 1 1 1 1 0 (254) to Q7 Q6 Q5 Q4 Q3 Q2 Q1 Q0 of 2nd 74595
      shiftOut(dataPin2, clockPin2, MSBFIRST, 254);
      // shift out the bits:
      digitalWrite(latchPin2, HIGH);
    }

I expected this code to turn on the first LED, but when I uploaded this code nothing lights up. I checked my rows and colum connections.
Also, I want to ask if a 74hc595 can output sink current?

what's a first LED? ... what is it connected to?

In reverse order, yes about 20ma or so sink and source. If you look on the data sheet it will give you the answer. As far as the first part simple connect this to that and that should fix it. That is about as helpful as the schematic, not a frizzy drawing, you included. You have both hardware and software and knowledge of both is normally required to solve the problem. Show all power and ground connections on the schematic.

Have you connected the 5V from the schematic to an external power supply? If yes, did you connect the GND of the power supply to the GND shown in the schematic too?

Did saprate power supply needed for this...

I can't add comment to your question so I post as an answer even though this is not much an answer. This is just a hint to solve your problem.
8x8 led matrix and 595s are pretty low-level stuff, so I assume you have some knowledge about electronics and programming in general.
I think your wiring is OK but I also think you misunderstand how 595 works.
Here is the flow taken from a library (ESP32) for 64x64 RBG LED panel using bunch of 595s:
uint8_t data[8]; // data for one row

digitalWrite(OE_PIN, HIGH); // disable output, 595 outputs go into high impedance state

for (int i=0; i<8; i++)
  shiftOut(DATA_PIN, CLOCK_PIN, MSBFIRST, data[i]);  // dump data out

digitalWrite(LATCH_PIN, LOW);  // pulse 1 clock
delayMicroseconds(1); // note 2*
digitalWrite(LATCH_PIN, HIGH); // latch is active high

digitalWrite(OE_PIN, LOW); // Enable output

I think now you know how to fix your code.
Note 1: I find those names SER, SRCLK, RCLK (on TI's datasheet) are confusing. I prefer the names SERIAL DATA INPUT, SHIFT CLOCK, LATCH CLOCK (on ONSEMI MC74HC595 datasheet) or better DATA, CLK, LATCH, OE, RESET.
Note 2: Check 74HC595 datasheet to see clock pulse width limit and speed limit. And if you are using UNO or MEGA (@16MHz), you are good without stretching the clock (data clock and latch clock). If you use higher speed MCU, e.g: ESP32@240MHz or STM32@72MHz, you have to consider clock stretching there and also inside shiftOut() function.
To improve your circuit, you should wire both OE of 595s to a Digital pin. You can also connect both latch pin into one digital pin. Every time you latch, botch 595 latch, and every time you enable output, both enable output.
So with your configuration, just shiftOut data normally for the 595 on the left and invert data for the 595 on the right, like this
#define DATA_COL_PIN 11
#define DATA_ROW_PIN 5
#define CLOCK_COL_PIN 13
#define CLOCK_ROW_PIN 7

#define OE_PIN 4 //use digital pin 4 to enable output on both 595s
#define LATCH_PIN 6 // or 12, but you must connect both latch inputs of both 595s together

uint8_t col = 0b00000001; // for the left 595
uint8_t row = 0b00000001; // for the right 595

digitalWrite(OE_PIN, HIGH);
shiftOut(DATA_COL_PIN, CLOCK_COL_PIN, MSBFIRST, col);
shiftOut(DATA_ROW_PIN, CLOCK_ROW_PIN, MSBFIRST, ~row); // ~row = 0b11111110 = invert_bits(row)
digitalWrite(LATCH_PIN, LOW);
digitalWrite(LATCH_PIN, HIGH);
digitalWrite(OE_PIN, LOW);

The code above is just for you to understand how it works. Normally, they would work on a buffer such as
uint8_t row[8]; // each byte is one row

And they do row scanning, turn one row ON at a time and just flip each column ON and OFF following the byte data of that row.
I stop here as this is going off-topic. You just ask what is wrong with your code right?
BTW, 595 can sink/source 35mA on each pin (70mA in total). So if you want to light up one row at a time with your setup, you should choose each current limiter carefully so that not to exceed 70mA in total.

70mA / 8xLED = 8.75mA for each LED (assume red LED)
(5v - 1v7) / 8.75mA = 377R

It's likely the resistors should be at least 377 ohm or 470 ohm for safety.

Sry i didn't get it... Are u trying to say instead of putting 8bit value in decimal... I have to make array for it...

I'm probably ahead of myself on how people do write a graphic driver for these LED panel by answering like that. It's doesn't matter if a number is written in binary or decimal or hexadecimal. I just use binary because it's straight forward reflecting each bit as a single LED on the matrix. The array of eight 8-bit number has 8x 8-bit = 64-bit, which represents all 64 LEDs on your 8x8 led panel. So you have 2 functions, one to read this array and spit out data to 595s, the other function to modify this array so you have visual effect or animation or changing a static image after some time.


text:
AT command validation does not appear on the serial monitor
I can't validate an AT command. Would anyone have any suggestions as to what I might be doing wrong? It should be printing "Sending successful! or "Sending failed!", but it doesn't show any text.
if (httpReadResponse.indexOf("OK") != -1) {
  Serial.println("Envio bem-sucedido!");
} else {
  Serial.println("Falha no envio!");
}

My serial monitor is printing this:

AT+HTTPDATA=192,5000\
DOWNLOAD\
OK\
AT+HTTPACTION=0\
OK\
AT+HTTPREAD

Full function:
void sendHttpRequest(int distance_cm) {
  gsm_send_serial("AT+HTTPINIT");
  gsm_send_serial("AT+HTTPPARA=CID,1");
  gsm_send_serial("AT+HTTPSSL=1");
  gsm_send_serial("AT+HTTPPARA=URL," + url2 + "/" + distance_cm + "/" + id_cliente + "/" + id_caixa + "/" + ipadd1 + "/" + sinal + "/" + totalMilliLitres + "/" + vazao_atual + "/" + apikey);
  gsm_send_serial("AT+HTTPPARA=CONTENT,application/x-www-form-urlencoded");
  gsm_send_serial("AT+HTTPDATA=192,5000");
  gsm_send_serial("param=Aqualizar");
  gsm_send_serial("AT+HTTPACTION=0");

  String httpReadResponse = gsm_send_serial("AT+HTTPREAD");

  gsm_send_serial("AT+HTTPTERM");

  if (httpReadResponse.indexOf("OK") != -1) {
    Serial.println("Sending successful!");
  } else {
    Serial.println("Sending failed!");
  }
}

The declaration of url2 may be important to interpreting gsm_send_serial("AT+HTTPPARA=URL," + url2... It would be better to provide all the variable declaration involved, if not compilable and testable code.

what is the value  of httpReadResponse.indexOf("OK")?

THE VALUE IS "OK" IN THE SERIAL

Print the value of the response,  ie. Serial.println(httpReadResponse);

String httpReadResponse = gsm_send_serial ("AT+HTTPREAD"); How is function gsm_send_serial() defined ? You are clearly expecting it to return a String under the circumstances that you are using it. Also, which Serial instance is connected to the serial monitor? Does, for example, Serial.println("Hello World") work? Which serial instance is connected to the GSM device?

It would help, if you provide a minimal compilable example code, that demonstrates your problem. How is the SIM800 connected, that the Serial Monitor and the Arduino both see the modules AT answer?

AT+HTTPACTION=0

AT+HTTPACTION=0 starts a GET session. Based on your code, you are supposed to create a POST session, which should be AT+HTTPACTION=1.
Read SIM800 Series_IP_Application Note which provides the examples for both GET and POST request based on the SIMCOM HTTP AT-command set. The application note can be found at SIMCOM's website (requires registration for free download) or simply google "SIM800 Series_IP_Application Note" as there are many sites that have the document available without the need for registration.


text:
Menu with switch case not behaving correctly
I hope this the right place to post this question :)
I'm trying to display a menu on a SSD1351 OLED display, to which I communicate with U8glib. I'm trying to obtain an Init screen, then, with a long press on a button (Menu), get in to a menu with 3 options (let's say option1, option2 and back). I got it working this way:
#include <Button.h>  // https://github.com/JChristensen/Button.git
#include "U8glib.h"
#include <Wire.h>

#define PULLUP true
#define INVERT true
#define DEBOUNCE_MS 20

Button ok(2, PULLUP, INVERT, DEBOUNCE_MS);
Button menu(5, PULLUP, INVERT, DEBOUNCE_MS);
Button down(3, PULLUP, INVERT, DEBOUNCE_MS);
Button up(4, PULLUP, INVERT, DEBOUNCE_MS);
U8GLIB_SSD1351_128X128_332 u8g(8, 9, 7);
uint8_t screen = 0;
uint8_t menu_current = 0;
void setup() {
  u8g.setFont(u8g_font_unifont);
  u8g.setDefaultForegroundColor();
  drawScreen();
}

void loop() {
  ok.read();
  menu.read();
  up.read();
  down.read();
  if (menu.pressedFor(1000) && screen == 0) {
    screen = 1;
    menu_current = 0;
    drawScreen();
  }
  if (screen == 1) {
    if (up.wasReleased()) {
      if (menu_current > 0) {
        menu_current--;
        drawScreen();
      }
    }
    if (down.wasReleased()) {
      if (menu_current < 2) {
        menu_current++;
        drawScreen();
      }
    }
    if (ok.wasReleased()) {
      switch (menu_current) {
        case 0:
          screen = 2;
          break;
        case 1:
          screen = 3;
          break;
        case 2:
          screen = 0;
          break;
          break;
      }
      drawScreen();
    }
  }
  if (screen == 2 || screen == 3) {
    if (menu.wasReleased()) {
      screen = 1;
      menu_current = 0;
      drawScreen();
    }
  }
}

void drawScreen() {
  u8g.firstPage();
  do {
    whatToDraw();
  } while (u8g.nextPage());
}

void whatToDraw() {
  switch (screen) {
    case 0: {
        u8g.drawStr(0, u8g.getFontLineSpacing(), F("Init"));
      } break;
    case 1: {
      const char *menu_strings[3] = { "option1", "option2", "Back" };
      uint8_t i, h;
      u8g_uint_t w, d;
      u8g.setFontRefHeightText();
      u8g.setFontPosTop();
      h = u8g.getFontAscent() - u8g.getFontDescent();
      w = u8g.getWidth();
      for ( i = 0; i < 3; i++ ) {
        d = (w - u8g.getStrWidth(menu_strings[i])) / 2;
        u8g.setDefaultForegroundColor();
        if ( i == menu_current ) {
          u8g.drawBox(0, i * h + 1, w, h);
          u8g.setDefaultBackgroundColor();
        }
        u8g.drawStr(d, i * h, menu_strings[i]);
      }
    }
    break;
    case 2: {
      u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option1"));
    }
    break;
    case 3: {
      u8g.drawStr(0, u8g.getFontLineSpacing(), F("Option2"));
    }
    break;
    break;
  }
}

Everything seems to be working except the back option: when I select it, the display gets blanked instead of visualizing screen 0 ("Init"). Variables seem to be set correctly. Does anybody have an idea why this isn't working?
Thank you :)
Dario
EDIT: copied the whole sketch as requested :)

I didn't define a back back physical button. "Back" is one of the options visualized in the menu. I'd like to be able to select it (highlight it with up and down buttons) and click the Ok button, to revert to Init screen :)

Yes, that's exactly my test case :) if I try to print the variables in serial monitor, everything seems to be working fine, but the display blanks out...

@LookAlterno I tried to remove the 'F()' caption but nothing changed.. I also tried to remove the 'u8g.getFontLineSpacing()' but nothing changed too :(
Then I tried to print on serial the 'screen' variable and, in the test case, it correctly prints '0' but I keep having this problem. I'd like to solve it, but a workaround would be cool too.. Thank you :)

You can consider using one of the existing menu libraries, there are some available on github. Just pick the one that best fits your needs
https://github.com/search?utf8=%E2%9C%93&q=arduino+menu&type=


text:
Help adding 3 more on/off switches so that I can control 4 LEDs
This code is working fine to switch on/off one LED. Can anyone help me add 3 more on/off buttons so that I can control 4 LEDs?
#include <String.h>
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {
  0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED
};
byte ip[] = {
  192 , 168 , 2 , 20
};
byte gateway[] = {
  192 , 168 , 2 , 1
};
byte subnet[] = {
  255 , 255 , 255, 0
};
EthernetServer server(80);
String richiesta;
int pinLed = 9;

void setup() {
  Ethernet.begin(mac,ip,gateway,subnet);
  pinMode(pinLed,OUTPUT);
  Serial.begin(9600);
  richiesta = "";
}

void loop() {
  EthernetClient client = server.available();
  if(client) {
    Serial.println("Tujse na ho payega");
    while(client.connected()) {
      if(client.available()) {
        char c = client.read();
        richiesta.concat(c);
        if(c == '\n') {
          Serial.print(richiesta);
          if(richiesta.indexOf("Led=1")>0) {
            Serial.println("Pin will be high");
            digitalWrite(pinLed,HIGH);
          } else {
            Serial.println("Pin will be low");
            digitalWrite(pinLed,LOW);
          }
          client.println("HTTP/1.1 200 ok");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<title> Home Automation</title>");
          client.print(" ButtonOn  Buttonoff ");
          client.stop();
          richiesta = "";
        }
      }
    }
  }
}

Just use an array, int pinMode[4] and then use loops to access it, you will be able to add as many leds as you want (pins allowing).

The html you send must be changes to add the buttons:
client.print(" Button1On  Button1off ");
client.print("Button2On  Button2off ");
client.print("Button3On  Button3off ");
client.print("Button4On  Button4off ");

Then you need to add some ifs:
  if(richiesta.indexOf("Led1=1")>0) {
    Serial.println("Pin1 will be high");
    digitalWrite(pin1Led,HIGH);
  } else if(richiesta.indexOf("Led1=0")>0){
    Serial.println("Pin1 will be low");
    digitalWrite(pin1Led,LOW);
  }
  if(richiesta.indexOf("Led2=1")>0) {
    Serial.println("Pin2 will be high");
    digitalWrite(pin2Led,HIGH);
  } else if(richiesta.indexOf("Led2=0")>0){
    Serial.println("Pin2 will be low");
    digitalWrite(pin2Led,LOW);
  }
  //etc.

you can use arrays and loops to avoid the repeated code each time.

I'm not saying that this solution is wrong, it isn't, but using loops and case statements would make this solution much better.

Use arrays, one for switches, one for leds. I don't see the code for leds in your code.
Note that you need 8 pins (4 for switches, 4 for leds).
Initialize them, e.g.
int switchPins[] = { 2, 3, 4, 5 };
Same for leds
int ledPins[] = {6, 7, 8, 9};

To access them, use a for loop:
for (int iLed = 0; iLed < 4; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

Because 4 might be used a lot, consider them making const or define:
#define NR_OF_LEDS 4

for (int iLed = 0; iLed < NR_OF_LEDS; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

or use the length of the array
for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

I think the switches are on the web page.

Than add 3 more switches on the web page.


text:
Arduino Nano: MAX30102 and memory problems
We are making a simple pulse oximeter device with an Arduino Nano and a MAX30102 sensor.
The problem is the SpO2 reading and processing algorithm of the MAX30102 library literally does signal processing on the Arduino with large arrays of data and because of that, when you do BPM and SpO2, the 2kb memory of the Arduino is already full.
Can you guys give me some advice to overcome this problem?

If you mean large lookup tables / reference data, you should say, because that's definitely something worth knowing.  More details in any case.

Are you saying it doesn't work with just that library, or are you saying there are other libraries also that make it not work (like an OLED library)?

I meant the arrays that saves data. It takes 4 second of data and process it. That beginning data alone takes 400 bytes of 2k. And it hits %90 of 2kb at spo2,bpm and oled but i still need to add bluetooth.

Which specific library? The linked datasheet does not make any reference to a library.

Arduino UNO is not recommended for MAX30102 as it requires a lot of processing and RAM. Consider shifting to Arduino Mega or the ESP32.

In the question they acknowledge the library they're using uses a lot of ram. I think the question is how do they do it on their hardware despite that.  If it's fundamentally not doable in less ram, then explaining that might be useful.


text:
How can I use multiple 7-segment displays in Tinkercad
I need to connect five 7-segment displays using Tinkercad.
We know that Tinkercad doesn't have an Arduino Mega to use its pins.
How can I do this without the Arduino Mega?

Multiplexing? No idea what tinkercad has / does.

use a display module with a control chip

It sounds like you will need to multiplex them.
Assuming common cathode LEDs:
Set up a transistor for each digit that activates the ground for that digit. (Lighting all the segments of a digit will probably exceed the max current sink of one of your digital pins.) You may be able to drive a single segment directly from an output pin, assuming it's current draw is ≤20 mA. If the segments draw > 20 mA then you will likely need transistors for the segment drivers as well. (The max output of a pin on most Arduinos is actually 40 mA, and if the average current when multiplexed across 5 digits is < 20 mA, you might get away with drawing up to 40 mA per segment. I'd ask somebody with more electronics experience than me to confirm this.)
Write your code to switch one digit's ground on at a time, after turning on the desired anode (segment) pins. Cycle through the digits rapidly and they will all appear to be on at the same time.
The pseudo-code:
setup {
   digit index = 0
   turn all pins (segment anodes and digit cathodes) to open state
}

loop {
   set up segments pins for digit[index]
   Turn on cathode for that digit
   short delay to allow segments of current digit to glow
   turn off cathode (ground) of current digit
   digit index = (digit index + 1) % num_digits
}

The above would require a digital pin for each segment, and a pin for the ground of each digit. (7 + 5 = 12 digital pins total.) Without multiplexing, you'd need 7x5 = 35 digital pins, and would still have to make sure you didn't exceed the total current output limits of the Arduino. (35 segments x 20 mA/segment would be 700 mA total.) Most Arduinos have a total current output of no more than 200 mA across all pins, so you could not light up all the segments of more than 2 digits at once, assuming 20 mA/segment.)
Note that it might be easier to ignore all of the above and get a serial LED display driver like a MAX7219. You just need 2 digital lines to drive that, and it will control 8  8-segment digits (7 segments plus a decimal point at each position)


text:
Wemos D1 mini won't connect to WiFi: status code 6
So I have a Wemos D1 mini which I want to connect to my WiFI in order to let is push sensor data to my server. But I cannot connect it with my WiFi as I get a code 6.
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

The Serial.print(WiFi.status()); prints 6 which is WL_CONNECT_FAILED if I'm right.
I checked the router and it uses WPA/WPA2, the ssid and password are correct. The router is using 2.4 GHz with WiFi 802.11b and 802.11g.
I used the board to scan, with the example code provided by the esp8266 board manager library thing, and it found my SSID with the ones of my neighbors.
Can somebody tell me what is going wrong?
I already checked solutions like: This one , github answers, etc.
Edit: It can connect to a mobile phone hotspot. It gives code 6 1 time and then it connects. Any one an idea how I connect to the WiFi the router is providing ?

6 is WL_DISCONNECTED. what is while while?

@Juraj I see I copied a code I tried. One solution was to take WiFi.waitForConnectResult instead of WiFi.status(). It is fixed now. Where did you find that 6 is WL_DISCONNECTED?

in the source code of esp8266 Arduino 2.7.4 in libraries/ESP8266WiFi/src/include/wl_definitions.h

run a sketch with WiFi.disconnect() only. run it only once.

@Juraj that did not fix it

@dandavis Yes it is, it is a requirement by the router

i always start my wifi section with   WiFi.disconnect();delay(24);  WiFi.mode(WIFI_STA);, which fixes a few problems for me.

@dandavis I tried it but the code 6 still remains

Apparently, something went wrong with connecting to the router. The router was casting 802.11 g + n, which for some reason, made the esp8266 give a code 6. I have tried 802.11 b, 802.11 b+g+n, 802.11 n, which work all fine.
So I updated the settings that the router now uses 802.11n and the esp8266 can now connect to the internet!

If you can later say more definitively what it was, you can edit your answer for future readers.  In a little over a day, I think, you'll be able to accept your own answer, and probably should.

For me, the solution was manually setting the mode to 802.11g as explained here: https://github.com/esp8266/Arduino/issues/8412
Add the following code before connecting the WiFi:
WiFi.setPhyMode(WIFI_PHY_MODE_11G);


text:
Weird char on a 20X4 LCD
I'm trying to make an RC controller.
I have a problem with my LCD.

I have already double-checked the wiring and the connections are great.
I made a PCB with Kicad and order it to JLCPCB. I have some mistake, you can see the soldered wire.

Before the PCB, I did my project with a breadboard and it worked fine.
const String menuElem[4] = {"Models", "Trims", "Reverse command", "Channel"};

const int rs = 3, en = 4, d4 = 5, d5 = 6, d6 = 7, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void menu() {
  lcd.clear();
  //lcd.setCursor(0,0);
  //byte pos = 0;
  //int sizeOfanArray = *(&array + 1) - array;
  byte menuElemLength = *(&menuElem + 1) - menuElem;
  for (byte i = 0; i < menuElemLength; i++) {
    lcd.setCursor(2, i);
    lcd.println(menuElem[i]);
  }
  showMenuNav(currentMenuPos);
}

try const char* menuElem[4] = {"Models", "Trims", "Reverse command", "Channel"};

The pictures of your custom board and wiring job don't really tell us anything. It looks to me like you have a bug in your code. You're getting SOME characters from your strings, which tells me that the LCD is working. It looks to me like your strings are being sent with the wrong lengths.

Thank you @Juraj it solves the problem. I understand my mistake. I replaced String by char* in my code and in every class. I use strcat to concatenate my char* but I don't know if this is the best solution.
@DuncanC Yes, at start i believed that I have bad connection or something like that.

Your code to calculate the length of your Strings does not make sense. The String type is an object type. The addresses of your String objects will not match the length of the charcters in those strings. You should use an array of C strings as suggested by Juraj, and then you should use strlen() to get the length of those strings (C strings have a null terminating byte, and strlen() uses that null to calculate the length. Note that C strings can't handle Unicode.)
The String type is best avoided on Arduino anyway, as String objects tend to fragment the extremely limited heap memory on Arduino devices and cause out-of-memory crashes.

Yes, my mistake is to use a String object like a char* pointer.
I would use ``char*pointer instead ofString` object in my future code.
Thank you for your reply!


text:
Servo starts rotating whenever it is plugged
I am making a fish feeder using an Arduino Mega 2560, a servo motor SG90 and an RTC DS3231. I want to make it rotate twice a day, i.e. morning and 9 o'clock evening.
Whenever I plug my Arduino board to my laptop for the first time it rotates correctly during specified time 9 o'clock and I change the time to 9 o'clock 10 mins to check again and it rotates after I plug it to my laptop for 180 degrees and then rotates during the specified time.
What should I do to avoid that initial rotation?
Here is my code:
#include<Wire.h>
#include<LiquidCrystal.h>
#include "RTClib.h"
#include <Servo.h>

Servo myservo;

int pos = 0;
RTC_DS3231 rtc;
DateTime now;
const int OnHour = 9;
const int OnMin = 15;

void setup() {
  Serial.begin(9600);
  rtc.begin();
  myservo.attach(9);
  rtc.adjust(__DATE__,__TIME__));
}

void loop() {
  now = rtc.now();
  Serial.print(now.hour);
  Serial.print(" hour(s), ");
  Serial.print(now.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay(1000);
  if (now.hour == OnHour && now.min == OnMin) {
    Serial.println("feeder ON");
    myservo.write(90);
    delay(1000);
    myservo.write(180);
  } else {
    Serial.println("feeder OFF");
    delay(10);
  }
}

Hint: What is the initial setting of the Servo?

@user52610 ... did you try my solution?

I'm not fully understanding the problem, but I assume you want it on for 9:00 / 9AM and 21:00 / 9 PM on for 15 minutes.
const int onTime1 =  9 * 60 +  0; // 9:00 AM
const int onTime2 = 21 * 60 + 30; // 9:30 PM
const int onMinutes   = 15; // Minutes

void loop()
{
  now = rtc.now();
  int nowTime = now.hour * 60 + now.min; // Minutes from current day

  if (((onTime1 <= nowTime) && (nowTime < onTime1 + onMinutes)) ||
      ((onTime2 <= nowTime) && (nowTime < onTime2 + onMinutes)))
  {
     myservo.write(90); // On
  }
  else
  {
     myservo.write(180); // Off
  }
  delay(1000); // 1 s delay
}

You can make the above if statement easier by:
  mysesrvo.write(180 - 90 * (int) (
   ((onTime1 <= nowTime) && (nowTime < onTime1 + onMinutes)) ||
   ((onTime2 <= nowTime) && (nowTime < onTime2 + onMinutes))));


text:
strtok() command with Serial communicaton
After I take a char* variable from serial communication, I use strtok to split variables with " ". But when I do that it acts like there is a " " after every character. I dont know why. How can I fix this ?
void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  char* a = "The quick brown fox jumped over the lazy dog.";
  char* c = a3;
  char* b;
  b = strtok(c, " ");
  while (b != NULL) {
    Serial.println(b);
    b = strtok(NULL, " ");
  }
}

void loop() {
}

outcome:
The
quick
brown
...

This parsing code works perfectly, until I take it from serial ports. Serial code here, like this:
#include <SoftwareSerial.h>
#define bRSerial 9600
#define bRmY 9600

char vD[45];
int i = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(bRSerial);
  while (!Serial) {
    ;
  }
  mySerial.begin(bRmY);
}

void loop() {
  if (mySerial.available()) {
    //Serial.write(mySerial.read());
    vD[i]=mySerial.read();
    i++;
    if (i = 46) {
      char* a = vD;
      char* b;

      b = strtok(a, " ");
      while (b != NULL) {
        Serial.println(b);
        b = strtok(NULL, " ");
      }
      i=0;
    }
  }
}

outcome:
T
h
e
q
u
i
c
k
b
r
o
w
...

Is there a way to fix this? i need to get it from serial and split on " ".

if ( i == 46 ) {

yep that was it.  :D simply 1 mistake that i couldnt see thanks.

is this how you plan to use it or only a test? it would be simpler to detect the delimiter when it is read

i dont know how to use it simplier.

if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0 else vD[i] = c

and I do not see where you set the terminating 0 of vD a.k.a. a

only a syntax typo. the condition should be if ( i == 46 ) {
if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0
and I do not see where you set the terminating 0 of vD a.k.a. a

As @Juraz mentioned, in the case you have a typo. Also I'd have suggestions as one who had spent a while coding reading process in terminal. When you need to read something from a serial port it is good to use the while() loop, instead of if(), so I recommend changing:
while (mySerial.available()) {
  //Serial.write(mySerial.read());
  vD[i]=mySerial.read();
  i++;
  if (i == 46) {
    char* a = vD;
    char* b;

    b = strtok(a, " ");
    while(b != NULL) {
      Serial.println(b);
      b = strtok(NULL, " ");
    }
    i=0;
  }
}

the if is in loop()