text:
Problem in using COZIR W-100 with arduino
I was using the COZIR W-100 carbon dioxide sensor with an Arduino Mega 2560 with the example code from this site.
But the measured value of carbon dioxide by sensor was 90 ppm in fresh air and that is not correct. Please help me find the cause and a solution.

You're right. 90ppm is too low.

Since that is a  20% CO2 sensor, should you multiply by 5?


text:
How to delay outside loop
I am using a function outside loop(), which is called after an interrupt. Inside this function, I am setting several relays that need to change after a second or two, depending on my setting. I tried the delay, it doesn't work. millis() isn't working as well; I found out it stops counting when I exit the loop function.
My code looks something like this:
const long on_interval = 2000;
unsigned long currentMillis = millis();
bool hv_bool = false;

void hv_switch() {
    if (digitalRead(hv_pin)==HIGH){
        hv_startup();
    }
}

void hv_startup() {
    unsigned long previousMillis = 0;
    digitalWrite(pre_charge, HIGH);
    digitalWrite(main_charge, LOW);
    //Wait interval
    previousMillis = currentMillis;
    while (currentMillis - previousMillis < on_interval) {
        Serial.println(millis());
        //Wait
    }
    digitalWrite(pre_charge, LOW);
    digitalWrite(main_charge, HIGH);
    hv_bool = true;
    loop();
}

void setup(){
    //Set some ports

    //Initiate interrupt
    attachInterrupt(digitalPinToInterrupt(hv_pin), hv_switch, RISING);
}

void loop() {
    //Low voltage loop after startup, high voltage off
    while (hv_bool == false) {
        Serial.println("Waiting on high voltage");
        digitalWrite(hv_led, LOW);
        digitalWrite(pre_charge, LOW);
        digitalWrite(main_charge, LOW);
    }
}

millis() works fine in any function, except in interrupt context, where it doesn't increment.

@EdgarBonet has it - hv_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.
But a bigger problem is that loop() is called from hv_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.
So I'd suggest several fixes:

Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.
Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

In loop(), test the flag. If it is set, clear it and call another function to handle the less urgent processing required by the interrupt.

source: Stack Exchange

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

sort: votes


text:
Modbus RTU slave library
I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found a library. When I try using the library, I get a timeout error.
Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?

Please provide additional details. What is the master device? Check whether baud rate, parity bit, data bit are set properly. And if possible provide the git repository of the library you are using.

http://www.electronhacks.com/2014/04/arduino-modbus-plc-rtu/

i find library from this

as master i am using simulator and simulator's name is modbus poll

so i edited code your as below
    #define mySerial Serial1
byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

int data_count = 5;

void setup() {

mySerial.begin(9600);
Serial.begin(9600);
delay(1000);

}
int count = 0;
void loop() {

  if(count%10 == 0) {
    Serial.println();
    send_data();
  }

  count++;

  while(mySerial.available()>0)
  {
    byte b=mySerial.read();
    delay(1);
    Serial.print(b,HEX);
    Serial.print(" ");
  }
  //Serial.println(count);
  while(Serial.available())
  {

    byte a=Serial.read();
    delay(1);
    mySerial.print(a);

  }

  delay(1000);

}

void send_data() {
  Serial.println("send data");

  delay(1);
  for(char i=0;i<8;i++){
    mySerial.write(test_data[i]);
    delay(1);
    Serial.print(test_data[i],HEX);
    Serial.print(" ");
  }

  Serial.println();

  delay(1);

beside in slave library, which i have uploaded. i replace 'Serial' with 'Serial1' as i am using genuino zero.

but still i am not getting any response

Hey do you have any actual Modbus device?

you can use modscan32 software to retrieve data from slave device also. The software acts as a master device and you have slave device.

i have not any actual modbus device

yes, i have used modbus flow software which is working like master

but i am getting timeout error. so i asked question to check that my slave code is correct or not...!

Then you might conclude as so.

do you hav any working slave library??

no, I tested with my device as modbus master.

You can check out https://github.com/andresarmento/modbus-arduino/blob/master/README.md

He has used it as Modbus slave

connection is working fine. i am not getting any error. i used their lamp example to read coil. in that example, they set status of coil 1. but i am getting response "zero"

I am unable to simulate and see the result right now; I hope if the library functions properly this might be a communication issue. I can add a one step debug for you to check and see what is happening.
Your device is acting as a Modbus RTU slave, So take another Arduino, make it act it like a master device, and see what response is coming from the slave device.
Here is a glimpse of code I used to make arduino as a master and see the response coming in Serial terminal.
    #include <SoftwareSerial.h>
    #define rxPin 2
    #define txPin 3

    #define RS485_pin 10
    //SoftwareSerial mySerial(rxPin, txPin);
    #define mySerial Serial1

    byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

    int data_count = 5;
    byte rcvdata[15];
    int param_value_int[7];

    void setup() {
      // put your setup code here, to run once:
    //mySerial.begin(19200,SERIAL_8E1);
    mySerial.begin(9600);
    Serial.begin(9600);
    delay(1000);
    pinMode(RS485_pin, OUTPUT);
    digitalWrite(RS485_pin,LOW);
    delay(100);
    }
    int count = 0;
    void loop() {

      if(count%10 == 0) {
        Serial.println();
        send_data();
      }

      count++;

      while(mySerial.available()>0)
      {
        byte b=mySerial.read();
        delay(1);
        Serial.print(b,HEX);
        Serial.print(" ");
      }
      //Serial.println(count);
      while(Serial.available())
      {
        digitalWrite(RS485_pin,HIGH);
        byte a=Serial.read();
        delay(1);
        mySerial.print(a);
        digitalWrite(RS485_pin,LOW);
       // Serial.print(a);
      }

      delay(1000);
      //while(1);
    }

    void send_data() {
      Serial.println("send data");

      digitalWrite(RS485_pin,HIGH);
      delay(1);
      for(char i=0;i<8;i++){
        mySerial.write(test_data[i]);
        delay(1);
        Serial.print(test_data[i],HEX);
        Serial.print(" ");
      }

      Serial.println();
      digitalWrite(RS485_pin,LOW);
      delay(1);
    }

Here you can use Software Serial or normal Serial1 or Serial2 on devices like Mega. Make sure if it is RS485 based you have to toggle the RS485 read-write pin each time to enable and disable one feature at a time as RS 485 uses half-duplex communication.
In this case test_data[] uses Function code FC03 Read holding register. You can make your custom data. I am assuming you are familiar with all the types available.Still there is a great site [   link ] to look up to if you don't know the basics. The last two bytes are checksum. And there is an online checksum calculator available if you need also
 https://www.lammertbies.nl/comm/info/crc-calculation.html
In this way you can at least debug and share the result, so that we can help more.

Comments are not for extended discussion; this conversation has been moved to chat.

This isn't a forum. Comments on the question are for clarification of the question, not for experimenting with different ways of solving the problem.

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


text:
Where can i get touch sensitive buttons with RGB-LED like in Ableton Push
I am searching for this component: a touch sensitive button with LEDs like in the Ableton Push or in other Launchpads. Does anyone have an idea about where I can buy something like this? The best would be an RGB LED.
This is what I've found so far. It has no RGB LED though.
Thanks!

https://www.adafruit.com/products/1929 ?

Touch-sensitive? As in, an on/off switch? I've seen kits (such as the ones mentioned in comments and answers), but none that are pressure-sensitive

Just a little more searching would have led you to this, along with its associated breakout board, bezels, and LEDs.

The specific buttons you link to are custom made. They're not something you can buy off the shelf. In fact they aren't even buttons.
What they are is a translucent moulded silicone rubber sheet with conductive pads behind (typically in a ring shape) with an LED mounted on a PCB behind them.  The pad is pressed, which flexes the silicone rubber, to press the conductive portion against exposed tracks on the PCB behind.
There are some similar products around, such as the Sparkfun one Ignacio points to but it is highly unlikely you will find anything off-the-shelf that does exactly what you want.  Coupling a pre-moulded translucent rubber keypad membrane (if you can find one somewhere) with your own custom designed PCB to take the RGB LEDs you want (preferably surface mount to keep the size small enough) and provide the exposed tracks is probably the only way you can get exactly what you want.
You may be able to create your own sheet by first making a suitable mould, maybe with wood or modelling clay or something like that, then filling it with silicone (translucent bathroom sealant) and then impress on the back of that a second mould to provide the contact points and indents etc. Then, after a few days when it's all dry, add to the contact points some self-adhesive copper foil, or paint them with conductive paint. Don't quote me on that though, I haven't tried it ;)

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


text:
Trouble uploading code to ESP12 with CH340g
I have a programming circuit for the esp12(see attached) enter image description here
I have produced a pcb using this circuit. Upon plugging the pcb into my pc via the micro usb, the pc immediately recognizes the device.
The problem comes when I hit the upload button in the Arduino IDE. I get the following error:
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "NodeMCU 0.9 (ESP-12 Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Sketch uses 265572 bytes (25%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26984 bytes (32%) of dynamic memory, leaving 54936 bytes for local variables. Maximum is 81920 bytes.
C:\Users\XXXX\Documents\ArduinoData\packages\esp8266\tools\esptool\2.5.0-3-20ed2b9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\XXXX\AppData\Local\Temp\arduino_build_988997/WiFiScan.ino.bin
esptool v0.4.13-1-gf80ae31 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
An error occurred while uploading the sketch
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

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

Where is the error in my design that is preventing the successful upload in the Arduino IDE.
Edit: So I changed the CH340G to a CH340C and removed the 12MHz Crystal and the two 22pf caps connected the the 12MHz. It works perfectly now. I uploaded the code even at 921600 baud.
I guess the issue might have been which crystal I used or maybe the caps. Didn't think it would matter as long as the crystal is 12MHz, but maybe there is something else to account for.
Anyway...the new design will include the CH340C instead of the CH340G, but to be honest I will probably redesign it to use the CP2102.
Thank you for the quick responses. I really do appreciate it.

Well, the schematic seems OK and correct - have you tried putting the ESP into programming mode manually (tie GPIO0 to ground)

iirc, nodemcu 0.9 was a little funky. i would try other board profiles, including the generic.

Jaramanda X I did try to manually boot the ESP into flashing mode. I desoldered the auto-reset/auto-program components and just hooked it up to a breadboard with some push buttons. No success until I replaced the CH340G with a CH340C and removed the 12MHz and both 22pf caps. Programmed perfectly on the first try after that. Thank you for the quick response. Now I am going to go get drunk

So, I guess that means there's a difference in functionality between the CH340G and CH340C such that the former doesn't work with the nodemcu style reset circuit

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


text:
Arduino only works properly when I'm touching it
I'm working on a arduino proyect, but I encountered a problem that I dont know how to solve.
The only thing I have done in the hardware part is connect the arduino nano to a power source (phone charger) through the 5v and Ground pins, but the built-in leds tell me that the code isn't running as it should be.
The TX led (Serial output) should be constantly on (because the code is always printing out things to the monitor), but instead it turns on and off in a longer interval of time, the code is running slower than it should be.
This stops when I touch ground with my finger or when the arduino is connected to a computer.
When I searched for a solution I found that most of the time this problem was related to missing connections to ground, and here seems to be the same, but the only thing I have connected is the arduino.
Any idea of what's happening and how to solve it?
To give more context, what I'm trying to do is a thermostat that can take a value of temperature and time, and turn on or off a relay. This relay is the one that opens or closes the electrical circuit of the lab's stove depending on the temperature and the time.
There are 4 buttons:
AUMENTAR ("increase" in english): increases the value selected in 5 (when pressed has a delay of 0.5 seconds).
DISMINUIR ("decrease"): decreases the value selected in 5 (when pressed has a delay of 0.5 seconds).
SIGUIENTE ("next"): changes the value you are editing (has no delay).
INI_DET ("start/stop"): starts or stops the machine (has no delay).
Code:
#include <max6675.h>
#include <LiquidCrystal.h>

//
// VARIABLES
//

// Machine's phisical state
int temperatura = 0; // en °C
int temperatura_prev;
// int humedad;
bool maquina_en_funcionamiento = false;

// User's variables (con la maquina no funcionando)
int array_de_valores[] = {20,10};     // valores editables por el usuario
int valor_seleccionado = 0;             // valor que se esta editando (por defecto, temperatura): 0=Temperatura, 1=Tiempo, 2=Humedad
// Variables visibles para el usuario (con la maquina funcionando)
int array_de_opciones[] = {0, 0};       // opciones visibles para el usuario
int opcion_seleccionada = 0;            // opcion visible (por defecto, maquina): 0=Maquina, 1=Operacion

// Process' variables
int temp_bus, tiempo_bus, hum_bus;  // copias de array_de_valores que se mantendran fijas hasta el final del proceso
int reloj = 0;                      // tiempo transcurrido en minutos desde que comenzo el proceso
int reloj_prev;
unsigned long reloj_milis;          // tiempo transcurrido en milisegundos desde que comenzo el proceso
unsigned long inicio_milis;         // milisegundos al comienzo de la operacion
int tiempo_restante;
bool resistencia_en_funcionamiento = false; // estado actual de la resistencia (por defecto, apagada)

// Phisical components
LiquidCrystal lcd(6,7, 2,3,4,5);
MAX6675 sensor_temp(16,15,14);
#define RELE 13
  // botones
#define AUMENTAR 8 // Aumentar valor
#define DISMINUIR 9 // Disminuir valor
#define SIGUIENTE 10 // Cambiar valor
bool sig_pres = false;
#define INI_DET 11 // Iniciar o Detener maquina
bool ini_det_pres = false;

//
// FUNCTIONS
//

// Funciones para control de lcd
void actualizarLCD() {
  if (!maquina_en_funcionamiento) { // si la maquina no esta en funcionamiento
    switch (valor_seleccionado){
      case 0: // temperatura
        lcd.home();
        lcd.print("»TEMP TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[0]);
        lcd.setCursor(8,1);
        lcd.print("°C");
        break;
      case 1: // tiempo
        lcd.home();
        lcd.print(" TEMP»TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[1]);
        lcd.setCursor(8,1);
        lcd.print("min");
        break;
      case 2: // humedad
        lcd.home();
        lcd.print(" TEMP TIEMPO»HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[2]);
        lcd.setCursor(8,1);
        lcd.print("%");
        break;
    }
  }
  else { // si la maquina esta en funcionamiento
    switch (opcion_seleccionada){
      case 0:
        lcd.home();
        lcd.print("»MAQUINA  OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temperatura);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_restante);
        break;
      case 1:
        lcd.home();
        lcd.print(" MAQUINA »OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temp_bus);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_bus);
        break;
    }
  }
}

// Funciones de variables editables por el usuario
void aumentarValor(int cantidad) {
  array_de_valores[valor_seleccionado] += cantidad;
  actualizarLCD();
}
void cambiarValor(){
  switch (valor_seleccionado){
    case 0:
      valor_seleccionado = 1;
      break;
    case 1:
      valor_seleccionado = 2;
      break;
    case 2:
      valor_seleccionado = 0;
      break;
  }
  actualizarLCD();
}

// Funciones de control de proceso
void iniciarResistencia() {
  digitalWrite(RELE, HIGH);
  resistencia_en_funcionamiento = true;
}
void detenerResistencia() {
  digitalWrite(RELE, LOW);
  resistencia_en_funcionamiento = false;
}

void iniciarProc() {
  // realizar una copia de los valores en array_de_valores
  temp_bus = array_de_valores[0];
  tiempo_bus = array_de_valores[1];
  inicio_milis = millis();

  // iniciar la maquina (cuando continue el ciclo)
  maquina_en_funcionamiento = true;

  actualizarLCD();
}
void detenerProc() {
  detenerResistencia();

  // borrar variables
  temp_bus = 0;
  tiempo_bus = 0;
  reloj_prev = 0;
  reloj_milis = 0;
  inicio_milis = 0;
  tiempo_restante = 0;

  maquina_en_funcionamiento = false;

  actualizarLCD();
}

//
// MAIN PROGRAM
//

void setup() {
  // codigo que se ejecuta una unica vez:
  Serial.begin(9600);
  Serial.println("INICIANDO PROGRAMA");

  // relay
  pinMode(RELE, OUTPUT);
  detenerResistencia();

  // buttons
  pinMode(AUMENTAR, INPUT);
  pinMode(DISMINUIR, INPUT);
  pinMode(SIGUIENTE, INPUT);
  pinMode(INI_DET, INPUT);

  //iniciar lcd
  lcd.begin(16,2);
  actualizarLCD();
}

void loop() { // codigo que se ejecuta en bucle:
  // buttons
  if (digitalRead(AUMENTAR) == HIGH) { // if button AUMENTAR is pressed
    if (!maquina_en_funcionamiento) {  // and the machine is not working
      aumentarValor(5);                // increase the value
      delay(500);                      // and wait
    }
  }
  else if (digitalRead(DISMINUIR) == HIGH) { // si se presiona el boton DISMINUIR
    if (!maquina_en_funcionamiento) {        // IDEM AUMENTAR
      aumentarValor(-5);
      delay(500);
    }
  }
  else if (digitalRead(SIGUIENTE) == HIGH) { // si se presiona el boton SIGUIENTE
    if (!sig_pres) {                         // verificar si no se lo presiono antes
      sig_pres = true;                       // poner la var sig_pres en true para bloquear el boton
      cambiarValor();                        // y cambiar la variable
    }
  }
  else if (digitalRead(INI_DET) == HIGH) {   // si se presiona el boton INI_DET
    if (!ini_det_pres) {                     // verificar si no se lo presiono antes
      ini_det_pres = true;                   // poner la var ini_det_pres en true para bloquear el boton
      if (!maquina_en_funcionamiento) {
        iniciarProc();
      }
      else {
        detenerProc();
      }
    }
  }

  if (digitalRead(SIGUIENTE) == LOW) {    // si el boton SIGUIENTE no esta siendo presionado
    if (sig_pres) {
      sig_pres = false;                   // desbloquear el boton
    }
  }
  if (digitalRead(INI_DET) == LOW) { // si el boton INI_DET no esta siendo presionado
    if (ini_det_pres) {
      ini_det_pres = false;               // desbloquear el boton
    }
  }

  // Some output of data to the Serial monitor
  Serial.print("Valor seleccionado: ");
  Serial.println(valor_seleccionado);
  Serial.print(array_de_valores[0]);
  Serial.print(", ");
  Serial.println(array_de_valores[1]);
  Serial.print("Maquina en funcionamiento: ");
  Serial.println(maquina_en_funcionamiento);

  // PROCESS CONTROL
  if(maquina_en_funcionamiento) {

    // TEMPERATURE CONTROL
    temperatura_prev = temperatura;
    temperatura = sensor_temp.readCelsius();

    if (temperatura >= temp_bus) { // si la temperatura es igual o exede la deseada
      detenerResistencia(); // apagar la resistencia
    }
    else { // si la temperatura es menor que la deseada
      if (!resistencia_en_funcionamiento) { // y la resistencia esta apagada
        iniciarResistencia();
      }
    }

    if (temperatura_prev != temperatura) {
      actualizarLCD();
    }

    // TIME CONTROL
    unsigned long milis_ahora = millis();
    milis_ahora -= inicio_milis;
    if ( (milis_ahora - reloj_milis) >= 1000){
      reloj_milis = reloj_milis + 1000;
    }

    reloj_prev = reloj;
    reloj = reloj_milis/60000;

    tiempo_restante = tiempo_bus - reloj;
    /*
    Serial.print("Reloj de milisegundos=");
    Serial.println(reloj_milis);
    Serial.print("Reloj=");
    Serial.println(reloj);
    Serial.print("Tiempo restante=");
    Serial.println(tiempo_restante);
    */
    if (reloj >= tiempo_bus) { // si se llego al tiempo deseado
      detenerProc(); // detener
    }

    if (reloj_prev != reloj) {
      actualizarLCD();
    }

  }
}

Thanks in advance.

Have you tried powering through the USB jack? And can you try the Blink sketch from the Arduino IDE? If that sketch works, there must be something wrong with the code, in which case you need to add it to your question.

if you read your post carefully, you will find out that you used a lot of words to say nothing more than that you have an arduino nano powered by a phone charger, running some unknown code, and that you think that the code execution is affected when you touch the arduino .... first thing that you need to do is to verify that you actually are affecting the program execution and not affecting the LEDs only

@chrisl The USB jack has the same problem, it only works when its connected to the PC. The Blink sketch works fine. I'll add the code to the post.

@jsotola The execution is definetly getting affected, it runs slower than it should.

You can check this link https://store.arduino.cc/usa/arduino-uno-rev3. Open Documentation tab. 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

@AmitRay so I should be powering the arduino through the Vin pin with a power supply higher than 7V?

@FacundoBarrera Yes that may solve this problem. Did you try that?

@AmitRay I did try, but was the same. Though I know now what is happening, the phone charger is making some noise that is interfiering with the arduino, and when I touch ground it discharges on me. I'll post that as the answer when I clarify some doubts that I have. Thank you for helping!

This stops when I touch ground with my finger or when the arduino is
  connected via USB to a computer.

It sure sounds like a grounding problem, probably between the PC and the Arduino. Try connecting the Arduino ground and the PC ground - my guess is that the problem goes away.
All of the electrical components in a system need to share the same ground for any communication to take place. It sounds like one of them might not.
Is either the PC or the charger plugged into the wall with an adapter that only carries two of the three wires? Usually each one will connect to ground side of the house circuit but if one of them doesn't ...

When the arduino is connected to the computer works as expected, but I can't depend on the computer like this. And I don't know what you mean with two or three wires, there are only two wires (5v and ground).

JRobert, did you read the question? or event the part you quote?


text:
Multiple libraries were found for "WiFiClient.h" using nodemcu
I am trying to send HTTP requests from nodemcu so I started by uploading the esp8266 library but when I run the following code
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(115200);                                  //Serial connection
  WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://localhost:8080/getallcadres/getnbpassage/5");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("5");   //Send the request
   String payload = http.getString();                  //Get the response payload

   Serial.println(httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(30000);  //Send a request every 30 seconds

}

i got this error
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Build options changed, rebuilding all
In file included from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecure.h:41:0,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiServerSecure.h:20,

                 from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/ESP8266WiFi.h:41,

                 from C:\Users\ELA_HIDRI\Desktop\PFE_ING\nodemcu\nodemcu.ino:2:

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:38:5: error: 'BearSSL::WiFiClientSecure::~WiFiClientSecure()' marked override, but does not override

     ~WiFiClientSecure() override;

     ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:41:9: error: 'int BearSSL::WiFiClientSecure::connect(const String&, uint16_t)' marked override, but does not override

     int connect(const String& host, uint16_t port) override;

         ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:46:12: error: 'size_t BearSSL::WiFiClientSecure::write_P(const char*, size_t)' marked override, but does not override

     size_t write_P(PGM_P buf, size_t size) override;

            ^

C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:58:12: error: 'size_t BearSSL::WiFiClientSecure::peekBytes(uint8_t*, size_t)' marked override, but does not override

     size_t peekBytes(uint8_t *buffer, size_t length) override;

            ^

Multiple libraries were found for "WiFiClient.h"
 Used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi
 Not used: C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
exit status 1
Error compiling for board Generic ESP8266 Module.

so what is this error why i am getting it
Edit
i switched to an other version of arduino ide 1.6.5 the error is gone but it looks like it is not connection i got

delete folder C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi. it is the WiFi library for the retired Arduino WiFi Shield

i could not acces to windowsApps

@Juraj please check my update

better answer to this question https://forum.arduino.cc/index.php?topic=623460.msg4223849#msg4223849

relevant issue.  UPVOTED

Simply Switch
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

to
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

really?  that simple?  will test to see if i can reproduce issue on ubuntu as well.  tks!!

I am new to nodemcu. When I was using ESP8266WiFi.h, I got the error "Error compiling for board NodeMCU 1.0 (ESP-12E Module)" which said that Multiple libraries were found for ESP8266WiFi.h. I solved by simply put the void loop(){} empty function at the end of my code. Now It's working...


text:
ESP8266-01 is not working and it's hot
it has been so long since I tried to connect the esp8266 through Arduino Uno and get it to work my goal is to send data from the Arduino Uno to web site, I have tried everything and a lot of codes but none worked at first I could get a response  but sometimes it does and sometimes it does not I even bought an other one but the new one did not respond at all so I flashed the old one following the instructions in here and I got response the next day I tried to reuse it and it does not respond at all not even when I put the serial on 115200 and both NR&CR and tried AT but nothing showed in return .i found this tutorial
and I tried to get it to work using a mobile app but as usual, it does not work
AT
AT+RST
ATE0
AT+CWMODE=1
AT+CWQAP
AT+CWDHCP=1,1
AT+CWJAP="RemoteXY","12345678"

but i did not get hte name of it wifi in my wifi list
this is the code
// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__ESP8266_HARDSERIAL

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL Serial
#define REMOTEXY_SERIAL_SPEED 115200
#define REMOTEXY_WIFI_SSID "RemoteXY"
#define REMOTEXY_WIFI_PASSWORD "12345678"
#define REMOTEXY_SERVER_PORT 6377

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,30,0,8,13,0,
  2,0,70,25,22,11,2,26,31,31,
  79,78,0,79,70,70,0,1,0,10,
  26,12,12,2,31,88,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  uint8_t switch_1; // =1 if switch ON and =0 if OFF
  uint8_t button_1; // =1 if button pressed, else =0

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_SWITCH_1 2
#define PIN_BUTTON_1 12

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_SWITCH_1, OUTPUT);
  pinMode (PIN_BUTTON_1, OUTPUT);

  // TODO you setup code

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);
  digitalWrite(PIN_BUTTON_1, (RemoteXY.button_1==0)?LOW:HIGH);

  // TODO you loop code
  // use the RemoteXY structure for data transfer

}

i wired it like this

one last thing is it gets hot every time so what could be the problem what's wrong with is what should I do

Sounds like it's dead, Jim.

both, even the new one ?

Hit is not good. Maybe there is something fundamentally wrong that you are doing to them.

like what i connected the RX -> RX /TX-> TX/ CH_en and vcc to 3.3 v of the arduino / gnd ->gnd

Well yes, that's something fundamentally wrong. Connect RX to TX and TX to RX instead.

I tried that too I even tried to connect them to other arduino pins

It's probably already dead. It's too late to try changing things now.

Also you omitted the resistors for your LEDs. You're well on the way to killing the Arduino too.

but i tried to flash it and tried the at and responded yes then i tried at+rst and responded error but then i tried AT+UART_DEF=9600,8,1,0,0 i  then it does not respond at all again .i did not put the leds was trying it with without

when a chip gets hot as soon as the VCC/GND is connected, it means :

The VCC/GND are internally connected due to a previous failure (it
gets hot AFTER the accident).
An output pin, is connected to a supply rail through a very low resistance load (or short circuited). pins usually sink or
source as low as 20mA of current. so if you connect them to a load
less than (3.3/20)*1000 ~= 150 ohms (in your case with 3.3v supply),
you are going to fry the output driver. always be sure that a pin, even if it's defined as an input, has a little resistor (a 220 ohms res).
this accident happens between output/supply or output/output pins.

you may have misconnected TX pin to a wrong pin.

i have connected to tx the TX of the arduino in this example .how do i know if it is working

@ElaHidri you mean TX to RX right ? TX line connects to RX line of the other end

yes I even tried other Arduino pins .do I need to add level shifter?

no you don't need a level shifter for ESP8266 and Arduino as the esp pins are 5v tolerant. but it you connect TX to another "output" pin you may have damaged them. TX pin is an output, idle high pin. another output pin with idle low, short circuits the pins @ElaHidri

@ElaHidri even though people seem to successfully do so, by the official specs the esp8266 is not 5V tolerant. You supply the esp with 3.3V at vcc, so connecting any pin to a 5v logic level directly is incorrect.


text:
Arduino Uno Issue: No output power
I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.
I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab
I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.
I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.

I don't see an Arduino in that circuit diagram.

Hi, the Arduino board is powering the circuit above. The 5V is being sourced from the Arduino board.

Did you measure or calculate the 22.72 mA? If not, measure it (maybe the resistor is working) 22.72 mA is just a bit above recommended (20 mA), but I doubt it should give a problem.

It was calculated. I didn't really get time to measure it since the board got damaged right away. I've ordered a few more boards, so I'll keep that in mind.

It sounds like you might have let the Magic Smoke escape! If you remove your circuit, does the arduino still work? Normally, you would use the digital I/O pins to power a 7 segment led. Also, the fact that you connected a whole bunch of the "segments" to ground and another whole bunch to +5 (with maybe a resistor) might be a contributing factor.

Check out this tutorial for how to connect a 7 segment led to arduino. You will note that it says (about 1/3 of the way down):
"Single digit seven segment displays typically have 10 pins. Two pins connect to ground, and the other 8 connect to each of the segments."

I think the whole schematic would help. You are right that, as shown, even with a direct short through the LEDs, that would only draw 22 mA from the power rail which it should easily cope with. I don't see how the Arduino is being used here, and that undisclosed information might be germane to your problem. Are you using manual switches here? Why is the Arduino even involved in this design?

@GMc Even if I remove the circuit, it still won't work. I hastily assumed that the pins above the 7 segment display was the input pins and the pins below it were ground pins. I've built the same circuit with a new Arduino board and the correct configuration (this time I limited the current with a 1K resistor). It works fine now.

LOL when it comes to electronics, haste often makes smoke. Smoke usually means Arduino broke! Follow the tutorial i linked above and check everything at least twice! :-)

You need to have a current limiting resistor for each of the LED segments. Sharing one resistor between them all is a very bad idea, as multiple lit LEDs (in parallel) will be using the same resistor - see this excellent answer to Why exactly can't a single resistor be used for many parallel LEDs?:

The main reason is because you can't safely connect diodes in
  parallel.
So when we use one resistor, we have a current limit for the whole
  diode section. After that it's up to each diode to control the current
  that goes through it.
The problem is that real world diodes don't have same characteristics
  and therefore there's a danger that one diode will start conducting
  while others won't.

I would hazard a guess that you've drawn too much current, or, in your case, tried to sink too much through the PWM pin.
Also, it would (probably) be better to use individual data pins, not PWM pins, to turn on each segment, rather than connecting all of the segments to just one pin. It just seems a bit odd to do it that way.

The schematic you have drawn is completely safe to connect to an Arduino PWM pin. It may not be an optimal choice (closing multiple switches will change the brightness of segments), but it's not dangerous. As you said yourself, the current is limited to a safe value even if there's a dead short in the 7-segment display.
Typically, you burn your board when you connect/disconnect stuff while your Arduino is powered (because intermediate circuits may be unsafe even if the final result is OK), or when you built a circuit which is different from what you think you have built.


text:
Connecting a 5v dc fan to ultrasonic sensor
I am currently doing a simple uni project where i want the distance read by an ultrasonic sensor to control the speed of a dc 5v fan. I have attached a schematic of how i think i can link the ultrasonic sensor and fan components in order to achieve my main goal. Please tell me if this circuit is right or wrong and give some helpful feedback, thank you!

It's wrong.
A fan is a motor. A motor is a power hungry inductive device.
Just like any other motor or similar device (such as a relay or solenoid) you cannot drive it directly from the Arduino. Instead you need (at the very least) a transistor to switch a higher current and a diode to absorb back EMF.

Thank you for telling me it was wrong. Would like to know where i could possibly plop this transistor and diode.

The same way as you would for any other inductive device such as a relay (like I am sure I mentioned). There's a billion and one tutorials telling you how (and that's not an overstatement).


text:
Arduino clone changing its serial port on slight physical displacement, even during an ongoing serial communication
I'm using an Arduino clone for serial communication. However, as soon as I even touch the board, it resets, and the serial communication stops. When I view the serial port using the 'Tools' menu of Arduino IDE, I observe that it has changed. Sometimes, opening the serial monitor crashes Arduino IDE. I was using MATLAB as well, and observed that it crashed too whenever I initiated serial communication. The setup was working well for a week, when suddenly I encountered this problem.
Do you think that there is a problem with Arduino clone? Any help would be appreciated.

Is it a CH340G USB chip?

If the board is resetting when you touch it you might have a bad connection.  It could be worth checking you USB lead is plugged in properly, changing the USB cable and looking at the socket on the board for bad soldering.

Apologies for posting so late. I figured out that it was the problem with the board itself. As Matt suggested, it was bad soldering on the board. I replaced it with Arduino Uno, and it is working fine. Thanks.


text:
GSM GPRS for sending an sms
I want to know if it is possible to send an SMS from a SIM900 using Arduinos to another SIM900.
Problem: When the gsm is connected to the network, it does not send an sms; my airtime balance remains the same.
Here is the code I used:
#include <SoftwareSerial.h>
SoftwareSerial SIM900 (9,10);

void setup()
{
   serial.begin(9600);
   SIM900.begin(9600);
   delay(5000);
}

void loop()
{
   sendSMS();

   while(SIM900.available()!=0)
     {
        Serial.println(SIM900.read());
     }
}

void sendSMS()
{
    SIM900.println("AT+CMGF=1\r");
    delay(100);
    SIM900.println("AT+CMGS=\"+27769384488"\r");
    delay(100);
    SIM900.println("Hello");
    delay(100);
    SIM900.println((char)26);
    delay(100);
    SIM900.println();
    delay(5000);

}

I had worked on GSM long back ago and sometimes it becomes very difficult to debug the problem. However u need to just check whether the AT commands are being sent properly to the GSM module. I had tried using Software Serial but it did not work for me but when I switched to the usual Serial port it worked like a charm. Few things that you need to check are:

Check the baud rate of GSM module. Does it match with the baud rate of Software Serial.
Do a if-else check to see whether the commands are actually being sent to the GSM module. The println() returns the number of bytes written so you can do like this in your sendSMS() function.

  int a; //To store the number of bytes written
  a=SIM900.println("AT command to be sent");
  if(a)
  {
  Serial.println("Command sent");
  }
  else
  {
  Serial.println("Command not sent");
  }

Now upload the code and open the serial monitor to see whether the command is actually being sent to the GSM module or not.

You also need to check whether the format of your AT command is correct. Because you need to send \n(newline) and\r(carriage return) at the end of every AT command to ensure proper operation. For this you need to read the response sent back by the GSM module after every command. This can be done by reading the Software serial port and the printing the response onto the Serial monitor.
You also need to check whether your GSM module has detected the SIM card. Usually this is indicated by an onboard LED that blinks after every 3 seconds.

I think your code is pretty much correct but try to ensure that everything is setup properly as I said.
Here is my code but I used Serial port instead:

  void setup()
  {
    Serial.begin(9600);
    delay(10000);  \\For initialization purpose
  }
  void sendSMS()
  {
    Serial.println("AT+CMGF=1");
    delay(5000);
    Serial.println("AT+CMGS=\"Phone number with international code\"");
    delay(5000);
    Serial.print("Hello");
    delay(5000);
    Serial.println((char)26);
    delay(5000);
  }
  void loop()
  {
    sendSMS();
    do
    {
    }while(1);
  }

This code will send the SMS once so you need to reset the board for sending another SMS or you can remove the do while loop for continuous operation.You can adjust the delay accordingly.

Yes, it is possible.
Your code doesn't show any sign of board powering on and initialization.
SIM900 has some LED that show status - make sure you are connected to GSM network.
Please check this tutorial: https://www.youtube.com/watch?v=RUGV_64lQX8

Thanks for respond, I have used Hash include SoftwareSerial.h   #include <SoftwareSerial.h> but the website refused to display it, i was powering it using the button in it.  Is this the only initialization used?


text:
Will I be able to control stuff from anywhere in the world if I use a wifi shield like ESP8266?
Currently, I am using a Bluetooth shield, HC-05, which is working perfectly but there are two problems:

Only one person can connect to Bluetooth  at a time.
I have to be in a specific place to be able to control the lights.

I want to be able to control everything from anywhere in the world. I've thought about using an Ethernet Shield, but I'd prefer using a Wifi Shield if it can do the task.

Yes, but realistically only with the help of a well-engineered and maintained intermediate server on the publically visible Internet - drilling holes in your firewall to expose an esp8266 to incomming connection is a bit dicey even if you work around your ISP's likely attempts to prevent it, so you are better off having both the ESP8266 and the controllers be clients which make outgoing connections to a real server which passes messages between them.

answer on your comment on Majenko's answer:
(cannot comment due to reputation)

build a simple web server on your device and make sure it is accessible from a local network node (e.g. a PC).To do this open from a web browser the page ip:port where ip is the ip assigned to arduino (usually from your router's DHCP service) and port is the port which your web server listens to. This is configured in your arduino code. For an arduino Wifi shield you can find a tutorial for this step here
Now you have to set up port forwarding. This means that when somebody from the internet sends a request on your router, the router will forward this request on your arduino and not on another node on your local network. The nodes on your local network are individually recognized by their IP address. Port forwarding is configured per port, so you must set up port forwarding from a specific in-port to a specific ip,local-port combination. For example if your arduino has been assigned ip 192.168.2.10 and your web server listens on port 80, you can forward all requests from port 8080 to 192.168.2.10:80. This means that every request comes from the internet on port 8080 on your router (internet side) will be forwarded on your local node on ip 192.168.2.10 and port 80. Note that for simplicity in-port and out-port can be the same and they usually are. Port forwarding is configured in your router's menu and the exact procedure is different for every modem. Your best bet is to search google for your modem's model + port forwarding. If you succesfully configure this, then you will be able to load web server's page from a node outside your local network by visiting ip:port where ip is your router's internet ip and port is the aforementioned in-port. A simple page to see your internet ip is this.

These are basically the main steps to have access from internet. Further improvements could be:

solving dynamic IP issue (in order to access your arduino, you have to know your router's internet ip which can change by your ISP anytime. Buying a static IP or setting up a dynamic DNS solves this issue)
turning your web server to non web server (more advanced topic).

If you haven't already, take a look at Blynk.cc's website. Blynk provides a (drag-and-drop configurable!) smartphone/tablet app and a number of skeleton programs for many platforms and interfaces including, of course, the Arduinos.
In brief, your Arduino program can report data to their server, and the smartphone app can read and display that, as well as send control signals back to your board. They make it simple to accomplish basic things and quite easy to expand it to do more. The ESP8266 is a good choice for a web interface, especially if you're using an Arduino Uno or other Atmega328p-based platform, because it takes about the least amount of the MCU's limited resources of any of the compatible network interfaces.
Because your Arduino program will be configured as a network client you will avoid the hassles and potential security issues of configuring your local network to allow access to internal server from outside. The Arduino sketch opens an outboud connection to their server, just as a web-browser would, so you won't need to "poke holes" in your router's firewall to let in your client and anyone else that wants to mess with your stuff.
(Note: I have no connection with them, but I think they have a strong platform for Internet of Things hobbyists and I use their stuff.)
Update:
Blynk supports Arduino WiFi, WiFi 101, CC3000, and ESP8266 w/original (AT) firmware. This device (Atmega328p with ESP8266) is logging temperatures from 3 DS18b20 thermo sensors to Blynk as I type this:

I have actually heard of Blynk. But I don't think they support wifi shield yet.

The WiFi shield connects your Arduino to your local network. What you then do with that network is entirely up to you.
Yes, it is possible.
Is it easy, though? Well, if you have to ask the question then for you it won't be easy. You have to know how networks work for a start. Routing, port forwarding, client-server models, etc.

Can you put me in the right direction?

It is definitely possible to control anywhere from the World where internet is available.
As @forivaras noted, there are a few accidental complexities involved in the network setup. It is nothing specific to Arduino, these come from the fact how Internet works nowadays.
For start, I suggest using an ESP8266 module (instead of any other solution), which is connecting to a readily available 3rd party server (such as dweet.io and visualize with freeboard.io, or Adafruit IO, or IFTTT).
In fact, you don't need the Arduino at all. The ESP8266 is a way more powerful than an Arduino, and yuu can program it as if it would be an Arduino plus Wifi.
So the hardware comes for less than $10, and you can find ready made howtos on the web such as:
https://learn.adafruit.com/home-automation-in-the-cloud-with-the-esp8266-and-adafruit-io/introduction
This ensures a smooth start! Have fun :)


text:
STPM10 using Arduino SPI communication
I am working with STPM10 energy metering chip (evaluation board) and I want to read the data from 8 internal registers of the chip each containing 32 bits.
The datasheet of the STPM10 chip suggested to have a simplex synchronous SPI where the MOSI of the Arduino is not connected to any pin on the energy chip. Instead they provided a timing diagram to switch from reading and writing on the energy chip.

After the t5, datasheet stated that we should apply 32 serial clocks per data record and up to 8 data records can be read this way. My problem is how to apply 32 serial clocks to the chip.  Is the Serial clock on the Arduino SPI automatically activated after SPI.begin() ? If not, how can I start the serial clock? By the way, this is the code I've written:
#include <SPI.h>

SPISettings settingA(32000000, LSBFIRST, SPI_MODE0);
const byte SYN = 8;
void setup() {
  Serial.begin(9600);
  pinMode(SYN,OUTPUT);
 /*Initializes the SPI bus by setting SCK, MOSI and SS to outputs
  Pulling SCK, and MOSI low, and SS high */
  SPI.begin();
  SPI.beginTransaction(settingA);

  }

void loop() {
  //0----->t1
  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(500);
  //t1----->t2
  digitalWrite(SYN,LOW);
  delayMicroseconds(1000);
  //t2----->t3
  digitalWrite(SYN,HIGH);
   delayMicroseconds(0.035);
  //t3----->t4
  digitalWrite(SS, LOW);
  delayMicroseconds(0.035);
  //t4----->t5
  digitalWrite(SYN, LOW);
  delayMicroseconds(0.035);
  //t5---->t6
  digitalWrite(SYN, HIGH);
  delayMicroseconds(0.035);

  byte d1 = SPI.transfer(0x00);
  byte d2 = SPI.transfer(0x00);
  byte d3 = SPI.transfer(0x00);
  byte d4 = SPI.transfer(0x00);
  byte d5 = SPI.transfer(0x00);
  byte d6 = SPI.transfer(0x00);
  byte d7 = SPI.transfer(0x00);
  byte d8 = SPI.transfer(0x00);
  byte d9 = SPI.transfer(0x00);
  byte d10 = SPI.transfer(0x00);
  byte d11 = SPI.transfer(0x00);
  byte d12 = SPI.transfer(0x00);
  byte d13 = SPI.transfer(0x00);
  byte d14 = SPI.transfer(0x00);
  byte d15 = SPI.transfer(0x00);
  byte d16 = SPI.transfer(0x00);
  byte d17 = SPI.transfer(0x00);
  byte d18 = SPI.transfer(0x00);
  byte d19 = SPI.transfer(0x00);
  byte d20 = SPI.transfer(0x00);
  byte d21 = SPI.transfer(0x00);
  byte d22 = SPI.transfer(0x00);
  byte d23 = SPI.transfer(0x00);
  byte d24 = SPI.transfer(0x00);
  byte d25 = SPI.transfer(0x00);
  byte d26 = SPI.transfer(0x00);
  byte d27 = SPI.transfer(0x00);
  byte d28 = SPI.transfer(0x00);
  byte d29 = SPI.transfer(0x00);
  byte d30 = SPI.transfer(0x00);
  byte d31 = SPI.transfer(0x00);
  byte d32 = SPI.transfer(0x00);

  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(499);

  Serial.println(String(d4,BIN) + " " + String(d3,BIN) + " " +  String(d2,BIN) + " " +  String(d1,DEC));
  Serial.println(String(d8,BIN) + " " + String(d7,BIN) + " " +  String(d6,BIN) + " " +  String(d5,BIN));
  Serial.println(String(d12,BIN) + " " + String(d11,BIN) + " " +  String(d10,BIN) + " " +  String(d9,BIN));
  Serial.println(String(d16,BIN) + " " + String(d15,BIN) + " " +  String(d14,BIN) + " " +  String(d13,BIN));
  Serial.println(String(d20,BIN) + " " + String(d19,BIN) + " " +  String(d18,BIN) + " " +  String(d17,BIN));
  Serial.println(String(d24,BIN) + " " + String(d23,BIN) + " " +  String(d22,BIN) + " " +  String(d21,BIN));
  Serial.println(String(d28,BIN) + " " + String(d27,BIN) + " " +  String(d26,BIN) + " " +  String(d25,BIN));
  Serial.println(String(d32,BIN) + " " + String(d31,BIN) + " " +  String(d30,BIN) + " " +  String(d29,BIN));
  Serial.println(" ");

The timing diagram posted does not look like a standard SPI transaction.  I am inclined to say you can not use the Arduino SPI library.  Instead, you may need to bit-bang this out totally in software.  For instance, I do not believe there is a "SYN" line in the standard SPI bus.  And I don't believe the Chip Select line should go high before the end of the SPI transaction.

This is basically a bidirectional SPI (which many of ST's MCUs support) plus a mode/latch pin - SYN which one would drive with a GPIO.  I don't believe there is any requirement that the chip select go high early, especially as some of the timing diagrams in the data sheet show it low during the whole transfer.

The STPM10 specification describes a SPI bus unlike any I have seen.  Apparently the STPM10 "SYN" line controls the direction of the "SDA" line.  As far as I know, there is no "SYN" line in a SPI bus.  As such I do not think a normal Arduino SPI library will talk to an STPM10.
A normal single port (MOSI and MISO combined) SPI slave would automatically switch between reading and writing bits.  When interfacing with a two port master (such as an Arduino) a resistor is used between the MISO and MOSI nets.
This is the best image I could find.  Ignore the chip names.  And substitute MOSI for SDO and MISO for SDI.  Note there is no "SYN" line in this SPI bus.

I'm showing this diagram as it appears the STPM10 is using a single line for both input and output data.
Because of the missing "SYN" line I do not think you can even use the SPI hardware in the Arduino's Atmel processor.  I think your only option is to create a SPI driver from scratch only using software.
I see where STMicroelectronics offers an evaluation software package that talks to the STPM10.  Guessing, it looks like they wrote it in National Instruments Lab View.  If you could get the source code for that it may provide hints on writing your own STPM10 driver.

Like the datasheet says, its best if you implement writing in software and use the hardware SPI for reading. The steps for writing to the registers are as follows:

disable the SPI peripheral;
set MISO, SCLK and SS to be output;
set the pin which is connected to SYN to be output high;
activate SCS first and then SYN;
activate SCL;
apply a bit value to SDA and deactivate SCL;
repeat the last two steps seven times to complete one byte transfer;
repeat the last three steps for any remaining byte transfer;
deactivate SYN and the SCS;
enable again the SPI module;

In Arduino-speak:
#define SCS 4  // define your own CS to have better control

void setup(){
  pinMode(SS, OUTPUT);  //needed to use the SPI

  pinMode(SCS, OUTPUT);  // set SCS and SYN as output
  pinMode(SYN, OUTPUT);
  digitalWrite(SCS, HIGH);  // idle state
  digitalWrite(SYN, HIGH);
  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)) // mode 3, max read clock is 32mhz
}

void write_reg(byte addr, byte val){
  val = (val << 7) | (addr << 1);  // 6-bit addresses!
  SPI.end();  // disable SPI
  pinMode(MISO, OUTPUT);
  digitalWrite(SYN, HIGH);
  delayMicroseconds(10);

  digitalWrite(SCS, LOW);  // assert SCS and SYN
  digitalWrite(SYN, LOW);
  for (int i = 0; i < 8; i++){  // shift out a byte
    delayMicroseconds(10);
    digitalWrite(SCK, LOW);  // max clock is 100kHz
    digitalWrite(MISO, (val & 0x80) ? HIGH : LOW);
    delayMicroseconds(10);
    digitalWrite(SCK, HIGH);
    val <<= 1;
  }

  digitalWrite(SYN, HIGH); // deassert SCS and SYN
  digitalWrite(SCS, HIGH);

  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)); //restart SPI
}

For reading, you use the hardware SPI like this:
void read_regs(uint32_t data[], uint8_t len){  // an array to hold register data is passed
  digitalWrite(SYN, LOW);  // latching operation
  digitalWrite(SCS, LOW);
  digitalWrite(SYN, HIGH);

  uint32_t val = 0;
  for (int i = 0; i < len; i++){  // read the 8 32-bit registers into the array
    val = SPI.transfer(0);  // your 32 serial clocks
    val |= (uint32_t)SPI.transfer(0) << 8;
    val |= (uint32_t)SPI.transfer(0) << 16;
    val |= (uint32_t)SPI.transfer(0) << 24;
    data[i] = val;
  }

  digitalWrite(SCS, HIGH);  // deassert SCS
}

// Use the functions this way:

uint32_t reg_data[8];  // array to hold read data, max is 8

void loop(){
  write_reg(47, 1);  // set config bit 47
  read_regs(reg_data, 8);  // read all reg data into array

  for (int i = 0; i < 8; i++)
    Serial.println(reg_data[i], HEX);
}

The connections are:
Arduino MISO = SDA
Arduino SCK = SCL
Arduino D4 = SCS
Arduino D5 = SYN

Each call of SPI.transfer() yields 8 serial clocks i.e. a clock for each bit, so 32 serial clocks is merely 4 SPI.transfer() calls. Your code is actually producing 32 x 8 = 256 serial clocks. I suggest you read up on SPI.
I didn't include some of the delays in the datasheet because digitalWrite() on an Uno takes about 5us which is more than enough for this case. Of course, the code is untested so...I've done most of your work already, almost feels like I should be getting paid or something...

Will definitely test this once I have a breakout for the module. Will donate some cash to you when it works. 80% done on this non-SPI , SPI.


text:
Arduino relay module working in a wrong way
I have an Arduino Mega and a 4-channel relay module.
This is the relay module.
When the Arduino digital output is LOW, the relay is energized.  When the Arduino output is HIGH, the relay coil is de-energized.
How can I fix this?

Hiii brother, yes all relays has this problem exept keystudio relay modules, you can fix it about using a trasintor npn 2a2222 and connect gnd to collector, pin x to base and relay pin to emetor,

That's how they're designed to work energized is LOW de-energized is HIGH you just need to take this into account when writing your Arduino code

Indeed, while not particularly relevant with an ATmega, historically low-side outputs have been stronger than high-side ones, so when driving an LED (in this case probably one inside an optocoupler on the relay board) it has been conventional to use the I/O pin to drive the LED cathode, while wiring the Anode to the supply.  (It doesn't really matter which side the current limit resistor goes on, since the same current flows in the entirety of the path).

If you read the documentation or watch/read any tutorials on the mechanical relay you are using you will learn that LOW is active and HIGH is inactive for these devices. There is no way to change that behavior, that is how they are built. (Well, you can, but it's not worth the effort)
This design is intentional to prevent relay activation on power-up or system reset. And be sure to put this code in your setup routine to ensure proper system initialization.
digitalWrite(Relay, HIGH);
pinMode(Relay, OUTPUT);

Where Relay is the pin variable you defined for your relay.
Just code your routine using LOW to activate the relay when necessary.
Try this tutorial 4 channel relay tutorial

I would first set it to output, and then set it high? Not sure if it makes a difference though.

Yes. some boards are working in wrong way. I suggest you to build the relay board your self. . Its better to plan your project according to your requirement.

The board is not "working in wrong way". It was designed to operate this way, and the user "Bra1n" gives the correct answer.

You can purchase relay boards that are active high or active low or selectable, your choice. You need to read the description to determine what type it is. Here is a link for one that is selectable high or low active: "https://www.rajguruelectronics.com/Product/1730/1%20channel%20relay%20board%20with%20high%20low%20level%20trigger.pdf" This is an example not a recommendation. These are very popular with the Arduino crowd.


text:
800l v1 Baud rate is not fixing at 115200, How fix it for 115200 for lifelong
I am trying t change the baud rate of sim800l v1. But not successfully happening, every power cycle again going to AT+IPR= 0. I am using the following AT commands for changing the baud rate.
1.AT
2.AT+IPR?
3.AT+IPR=115200
4.AT&W
after power rebooting of sim800L going it is going AT+IPR=0.
Thank you

Your mistake is using AT&W to save the parameter, for some reason you have to add the profile number which is only 0 and use AT&W0 on a sim800l a sim800c with newer firmware accepts AT&W. I've learnt this the hard way.

From a quick scan of its AT command manual, I think you want to look at section 1.7.1, "Parameter Saving Mode". There are several modes, and while the description isn't quite clear, it looks like one command causes all subsequent parameter changes to be saved into NVRAM (so they will survive over a power-down), while another one causes the most recently changed parameter into NVRAM. I'm not sure which mode would best serve your needs, but the latter one would appear to answer your immediate need, retaining the baud rate.


text:
Can I Control My Android Game with Arduino Gamepad
I have a project that I need to make a game(guitar hero like rhythm game) on unity for android and develop a custom controller for it that works on mobile game. I decide to use Arduino and hc05 module for communication via bluetooth. But every tutorial that I watched on internet that phone used as a controller, I want to make it reverse. I want to use Arduino as a gamepad on Adnroid. Is that possible?

Not with a HC-05, unless you want to write your game to use serial communication specifically (i.e., be 100% custom with the control interface). HC-05 cannot be a game controller. Only serial.

Majenko is right, though there are other bluetooth boards, that support the HID protocol. You could search or them. Or you need to implement serial communication into your game for it working with the HC-05

So ESP32 can be a solution?


text:
Can ESP32 used for mobile game controller?
I have a term project: I need to develop a mobile game(Guitar Hero Like rhythm game) probably on Unity  and I need to develop a custom controller for this game that works on android device. There will be 3 buttons for notes and Bluetooth connections between android device and controller. My question is can I use ESP32 as a mobile game controller. If it's yes, which model that you suggest me?

Yes you can, Pick the most inexpensive one that supports Bluetooth, you only need 3 inputs.

Anything that supports BT/BLE could be used.


text:
DFRobot GSM / GPS shield with UNO init error
Apologies, but I have little experience of Arduino etc. Has the "Sim808 init error" been resolved anywhere please? I have tried every example I can find including the ones on these StackExchange pages without success. I started with the GPS test code from:
https://wiki.dfrobot.com/SIM808_GPS_GPRS_GSM_Shield_SKU__TEL0097
Parancey, Marcello, Pooya and Arslan and others have suggested mods to this code so I have tried all of them I think - none working.
Then I watched this video:
https://www.youtube.com/watch?v=fN8fwX3KmsM
which appears to show the code below or similar:
/*
### Get GPS data
1. This example is used to test SIM808 GPS/GPRS/GSM Shield's reading GPS data.
2. Open the SIM808_GetGPS example or copy these code to your project
3. Download and dial the function switch to Arduino
4. open serial helper
4. Place it outside, waiting for a few minutes and then it will send GPS data to serial

create on 2016/09/23, version: 1.0
by jason

*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

//#define PIN_TX    10
//#define PIN_RX    11
//SoftwareSerial mySerial(PIN_TX,PIN_RX);
//DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

DFRobot_SIM808 sim808(&Serial);

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

  //******** Initialize sim808 module *************
  //while(!sim808.init()) {
  while(!sim808.checkPowerUp()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");

}

void loop() {
   //************** Get GPS data *******************
   if (sim808.getGPS()) {
    Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

I have mounted the DFRobot shield on a UNO and powered through the barrel connector with a 2_amp 5V stabilised power supply. The DFRobot shield shows a red LED power light and pressing reset flashes the blue LED next to it, but nothing else does anything - the serial monitor just repeats "Sim808 init error". In the video the blue "net" LED flashes even before the SIM card is inserted, but my card does not flash. Do I return the board to Farnell and ask for my money back?
Any help greatly appreciated!

The problem is probably that you are trying to use Serial for both communication with the SIM808 and the PC at the same time. That can't really work.

Do you have a genuine Arduino or a cheap chinese knock-off?

@Majenko: Thanks for help. This is with genuine Arduino Uno from RobotShop not a knock off and the DFRobot shield came from Farnell in a proper labelled box and in antistatic bags for antenna and shield. The code quoted is just one of many I have tried.

Not entirely relevant, but I have just connected up a Chinese generic Sim900 board and it worked 'straight out of the box' using the LastMinuteEngineers' code so I think my DFRobot Sim808 shield is broken/ unserviceable.

The dfrobot board has a weird boot button system that you need to follow to boot up the board. I spent ages attempting to get it to work before I finally achieved anything.
There is a blue led on the board that will flash continuously at different rates if the chip has been correctly powered and is searching for a mobile network.
I noticed that you commented it the while(!sim808.init()) line. This attempts to power the board on automatically, but I do remember something being funny about the implementation.
From doing a while load of research the dfrobot breakout board is not the best hardware implementation of this chip. Actually from memory there aren't any modules I have been able to find which satisfy all my requirements for a project. I'd recommend looking at all the documentation dfrobot provide on their website. Hopefully that should get you working.
Summary: it's an insanely fiddly process to get it working, but the boards are functional


text:
Accelerometer Orientation (LIS3DH)
Newbie here!
I’m trying to make a pocket level using an LIS3DH but I don’t know how to “reset” all the axis to start reading from a certain orientation since my LIS3dh won’t be mounted flat and will change often.
Ideally whenever the level starts it would start reading everything at 0 no matter the orientation.
I’m sure it’s just math, but it’s way over my head to begin to understand it.
Starting with the absolute basics I’m using the adafruit lib. I can easily get all the readings, and I understand they are acceleration forces. But how do I start them all from 0?
Initially I was thinking to take the very first reading and store it, then add or subtract the new readings from the originals based on if the new numbers are higher or lower than original (subjectively) but that only works in some instances which means that it wasn’t a good solution.
I don’t have specific code to share as I’m using the adafruit LIS3DH example.
Here’s a reading from the sensor of it not flat
X: -11408 Y: -3152 Z: 10560 X: -6.87 Y: -1.87 Z: 6.27 m/s^2
And here’s readings closer to a flat surface
X: -80 Y: 704 Z: 16176 X: -0.02 Y: 0.46 Z: 9.86 m/s^2

Take an initial reading. Convert that to a 3D vector. Normalize it. That's "zero". Take any other reading. Convert it to a 3D vector. Normalize it. The angle between those two vectors is the angle of the level. This is maths, not Arduino.

"subtract the new readings from the originals [...] only works in some instances" - that's exactly what you have to do. When doesn't it work?

The last 3 number from the Adafruit example look to be the gyroscope.  Unless you are doing something like motion tracking (i.e. 3D gaming) or a "very reactive" tilt compass you don't need to bother w/those.

Consider taking on this project in sever steps.  Some you might do now and other later if necessary
First, accelerometers do not usually need alignment.  But if accuracy and reproducibility is important, a project may benefit from finding any offset a single accelerometer may need and finding any magnitude adjustments between the three accelerometers.  Using gravity rotate each accelerometer through their maximum negative and positive values.  Use these values to find an offset such that the absolute values are equal for each individual accelerometer.  Then select one accelerometer as the bases and find the appropriate coefficients to normalize the other two accelerometers such that the absolute values of all maximums and minimum are equal.  As hinted, this is one of the step you can skip until later if necessary.  If you need a more thorough explanation you can find it in section 2 of this STMicro document.
To find angles it would be best to consider the classic airplane example where pitch (nose up or down) and roll (rotation around the axis passing through the nose and tail).  Here is a good submersible Arduino project to consider. In this project the accelerometer Z axis is pointed down and the X to the side.  To find ROLL the author calculates the inverse tangent of the negative of the ratio of acceleration in the X direction over the acceleration in the Z direction.

The pitch calculation is a bit more involved.  This can be found by taking the inverse tangent of the acceleration in the Y direction over the square root of the sum of the square of the X plus Y acceleration.

That out of the way, now consider how to zero the angles out.  First decide on if you will adjust the roll or the pitch.  Let's consider the roll case.  Record the current roll angle and subtract it from the current calculated roll angle before displaying it as zero.  Now rotate your accelerometer such that you do it around the Y axis (remember, we are only considering the roll case and do not want to change the Y accelerometer's reading!).  If you have done the math correctly, the displayed angle will be the difference between when you started and finished your rotation.
All that out of the way, now consider what would happen if you rotated your accelerometer through a roll position where the acceleration in the Z direction falls to zero.  Your trigonometric inverse tangent function for roll would go to infinity!  In the physical world, where gimbals are used for air and space navigation, this is referred to as Gimbal lock!
What to do about Gimbal lock?!  Well, it's a story that starts in 1843 (yeah, that does sound odd doesn't it WRT air and space navigation).  In short, if you stop using classical trigonometry to convert acceleration to angle an start using Quaternions you avoid Gimbal lock entirely.  Quaternions use complex numbers to describe rotation in 3D space.  People who write 3D gaming programs absolutely love how Quaternions simplify their efforts.  This is another of those steps you don't have to do.  But doing so will make your project all the more robust.
(BTW, this is the STMicro LIS3DH data sheet.)

You're new @CarmexLover13.  If the above answers your question select it as the correct answer.  If you want to wait and try it fist to see if it works that's ok too.  Or write a comment/question here if something is not clear and I'll edit the answer.  Feel free to edit your question too if you find you forgot to ask something in particular.

I'm not intentionally ignoring. I'm attempting to understand enough trig to be able to test this.. it's currently way over my head ha.

I fixed the link to the 1st STMicro document.  Maybe that will help.  Review the unit circle.  Get a feel for how angle and Sin and Cos relate.  Tan is just Sin/Cos.  After you wrap you head around that you can take a stab at converting the accelerameter's readings to angles.

If you want, you can skip over trigonometry and jump to quaternion. Also, you are using an STMicro IMU chip.  If you are also using an STMicro processor you can simply skip over all of this by using STMicro development tools and ready made compass libraries.  It would be even better if you are using recent vintage STMicro development boards. But fair warning, unlike Arduino tools, these are complex tools meant for enterprise development.

I should have noted the pitch and roll are figured out. Resetting the starting leveling or accounting for gimbal lock I believe are the only hold up now and they share the same solution.
Also for the time being I'm using an arduino uno, not stmicro based I don't believe
I'll be back when I understand quaternions a bit more


text:
RFID reading function returning null
I have a function that reads an RFID card and returns the RFID string. The function reads the string well but I am using the ArduinoJson library to generate JSON.
This is the function that I am using to read RFID cards:
String rfidOku() {
  String kartid= "";
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
    for (byte i = 0; i < mfrc522.uid.size; i++) {
      kartid.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
      kartid.concat(String(mfrc522.uid.uidByte[i], HEX));
    }
    kartid.toUpperCase();
    //Serial.println(kartid);
  }
  kartid.trim();
  return kartid;
}

And in the loop function, if a button is pressed I am getting an RFID and I am creating json using it.
const size_t capacity = JSON_OBJECT_SIZE(4);
DynamicJsonDocument doc(capacity);
const String str_rfid = rfidOku();
doc["id"] = odeme.id;
doc["fiyat"] = odeme.fiyat;
doc["rfid"] = str_rfid;
serializeJson(doc, Serial);

When I look at serial monitor the RFID field is null. Why does this happen? I tried to write another string there, and it works well with the other string. Why doesn't it work with str_rfid?
I also printed the value of str_rfid using Serial.print, str_rfid is getting the RFID card id from the function well.

Your function create a local variable and return it value at end of the function, a local variable will out of Scope upon exiting the function and no longer available. Furthermore, String object uses dynamic memory allocation in the heap, and get free up when it is out of scope. Read a book about C++ programming and try not to use String object if you are new to Arduino/C++ programming.

@hcheung sir how can fix this, what should i do to fix this problem.

@hcheung: The function returns a String, and that return value is used and present, according to the OP. Variable scope has nothing to do with it.

@ocrdu the function works and returns string, i output it using serial print. It is correct. But when i assign it to doc["rfid"], the in the json output the field is null. I created a string to test String a = "example" i assign it to the doc["rfid"] , in the json i show this value it works well with other strings.

@Enver-Pasha: It could be your JSON object capacity is too small because of string duplication when you deserialise to print it. You could try a capacity like JSON_OBJECT_SIZE(3) + 500 for deserialising, just for testing. Have a look at https://arduinojson.org/v5/assistant/ for more. Also see https://arduinojson.org/v6/how-to/determine-the-capacity-of-the-jsondocument/ . Not sure it is the problem, but worth a try. Also: you could try: doc["rfid"] = str_rfid.c_str(); to see if that works better (CString instead of String object).

@ocrdu Sir tank you so much it worked.

Which one worked?

@ocrdu The second one , doc["rfid"] = str_rfid.c_str();  this worked.

So maybe ArduinoJson doesn't play nice with String objects, or there is some other reason I don't know about. I'll write an answer based on my comment; please accept it (if you accept it 8-).

It could be that your JSON object capacity is too small because of string duplication when you deserialise it to print it.
You should try a capacity like JSON_OBJECT_SIZE(3) + 500 for deserialising, and see what happens.
Also, try: doc["rfid"] = str_rfid.c_str(); to see if that works better (CString instead of String object).
More information on object capacity can be found here; there's a calculator here.


text:
ESP8266 wakeup from deep sleep, both by timer and by button
In a project powered by batteries, the ESP8266 should go to deep sleep for a long time, having RF disabled. After some number of sleep cycles, it should restart with RF enabled, synchronize time via NTP, and again go to sleep. I think this could work with a counter saved in RTC Memory or SPIFFS.
Additionally, s.o. should be able to wake up via push button (at any time), which should result in different behaviour (running as WiFi AP, allowing for configuration of new WiFi credentials).
The question is: Is it possible to find out what did wake the ESP (timer or pushbutton)?
Using external circuitry this might be possible. To avoid this, we switch to ESP32, which is overkill for the project, but easy to find out the source of the wakeup (and with the possibility to use touch sensors). Additionally, ESP32 allows for easy use of "Preferences" in NVR and variables in RTC memory (when using the Arduino IDE), which will survive deep sleep (RTC) and even reset/power loss (NVR).

Does this answer your question? Wake up ESP8266 from deepSleep with a button

Well, not really. Resetting the ESP with a button is not the problem; in both cases /by button/by timer the ESP will be reset, running through setup() code. But how to know why it was reset? I read something about rtc_get_reset_reason() and ESP.getResetReason(); will try that and report on success.

In case of wakeup from deep sleep, rtc_get_reset_reason() always responds with "wakeup from deep sleep" - that is correct, but does not help here.

it is the same reset with button and with io 16. the software can't distinguish it. the reset with io 16 is a workaround for a bug in ROM code of the esp8266

Place a capacitor on the ESP side of the button to one power rail or the other (my preference is to ground, but either should work), and have the setup() routine read the state of the pushbutton switch as its first instruction.  You probably don't even need the capacitor, but if you don't have it, you'll have to read the switch state multiple times to account for possible contact bounce.
If the ESP wakes up due to a timer, there will be no activity on the PB line; if it wakes up due to the PB being pressed, there will be activity on the PB line for several 10s of millisecinds no matter how quickly it is pressed and released.

The only button I know to wakeup an ESP8266 is the reset button - and this one as well has to be used by the timer. Or am I mistaken?

Ah, I thought the OP was referring to an external button.  This solution still might work if the state of the reset button can be read programmatically during setup().

If D0 is positive and D1 is negative, your shorting the power, BAD.... That will reset the chip all right, but burn the chip up... I would simply use an "and gate" like the MC74VHC1G08... I have not tried your Idea, But connecting 2 chip outputs together is never a good idea...

it is just TTL. It is how TTL works.

The capacitor solution works, but I wanted to expand on what I did in particular and why I found it beneficial. Here's my circuit:

At wakeup, the first thing I do is read D1. After that, I then set D1 to an output and set it high to keep the capacitor charged. That prevents a second button press from resetting the ESP.
Then, when going to sleep, I set the pin low for a few ms to discharge the capacitor.
I picked the smallest capacitor possible because there's no downside to charging quickly.
Note that the ESP will reset as the button is pressed down - the pin will go low, and soon after go high as the capacitor charges, all before the button is released. This is ideal in circumstances where you want the act of pushing the button to cause the wake up, not the release.


text:
Trying to use a gyro sensor and having issues
My setup is Arduino Mega.
I have a gyro sensor that I'm trying to use to measure the acceleration or G force in X axis (forward movement).
So far I'm trying to figure a way to use the value of Acc or Ax (acceleration X axis) in an if statement in order to activate a relay.
I tried everything and the example file the supplier sent is so confusing.
Please help. I'm attaching the main code and the header file too!
#include <Wire.h>
#include <JY901.h>
/*
Test on Uno R3.
JY901   UnoR3
TX <---> 0(Rx)
*/
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  //print received data. Data was received in serialEvent;
  Serial.print("Time:20");Serial.print(JY901.stcTime.ucYear);Serial.print("-");Serial.print(JY901.stcTime.ucMonth);Serial.print("-");Serial.print(JY901.stcTime.ucDay);
  Serial.print(" ");Serial.print(JY901.stcTime.ucHour);Serial.print(":");Serial.print(JY901.stcTime.ucMinute);Serial.print(":");Serial.println((float)JY901.stcTime.ucSecond+(float)JY901.stcTime.usMiliSecond/1000);

  Serial.print("Acc:");Serial.print((float)JY901.stcAcc.a[0]/32768*16);Serial.print(" ");Serial.print((float)JY901.stcAcc.a[1]/32768*16);Serial.print(" ");Serial.println((float)JY901.stcAcc.a[2]/32768*16);

  Serial.print("Gyro:");Serial.print((float)JY901.stcGyro.w[0]/32768*2000);Serial.print(" ");Serial.print((float)JY901.stcGyro.w[1]/32768*2000);Serial.print(" ");Serial.println((float)JY901.stcGyro.w[2]/32768*2000);

  Serial.print("Angle:");Serial.print((float)JY901.stcAngle.Angle[0]/32768*180);Serial.print(" ");Serial.print((float)JY901.stcAngle.Angle[1]/32768*180);Serial.print(" ");Serial.println((float)JY901.stcAngle.Angle[2]/32768*180);

  Serial.print("Mag:");Serial.print(JY901.stcMag.h[0]);Serial.print(" ");Serial.print(JY901.stcMag.h[1]);Serial.print(" ");Serial.println(JY901.stcMag.h[2]);

  Serial.print("Pressure:");Serial.print(JY901.stcPress.lPressure);Serial.print(" ");Serial.println((float)JY901.stcPress.lAltitude/100);

  Serial.print("DStatus:");Serial.print(JY901.stcDStatus.sDStatus[0]);Serial.print(" ");Serial.print(JY901.stcDStatus.sDStatus[1]);Serial.print(" ");Serial.print(JY901.stcDStatus.sDStatus[2]);Serial.print(" ");Serial.println(JY901.stcDStatus.sDStatus[3]);

  Serial.print("Longitude:");Serial.print(JY901.stcLonLat.lLon/10000000);Serial.print("Deg");Serial.print((double)(JY901.stcLonLat.lLon % 10000000)/1e5);Serial.print("m Lattitude:");
  Serial.print(JY901.stcLonLat.lLat/10000000);Serial.print("Deg");Serial.print((double)(JY901.stcLonLat.lLat % 10000000)/1e5);Serial.println("m");

  Serial.print("GPSHeight:");Serial.print((float)JY901.stcGPSV.sGPSHeight/10);Serial.print("m GPSYaw:");Serial.print((float)JY901.stcGPSV.sGPSYaw/10);Serial.print("Deg GPSV:");Serial.print((float)JY901.stcGPSV.lGPSVelocity/1000);Serial.println("km/h");

  Serial.println("");
  delay(500);
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent()
{
  while (Serial.available())
  {
    JY901.CopeSerialData(Serial.read()); //Call JY901 data cope function
  }
}

The header file:
#ifndef JY901_h
#define JY901_h

#define SAVE        0x00
#define CALSW       0x01
#define RSW         0x02
#define RRATE       0x03
#define BAUD        0x04
#define AXOFFSET    0x05
#define AYOFFSET    0x06
#define AZOFFSET    0x07
#define GXOFFSET    0x08
#define GYOFFSET    0x09
#define GZOFFSET    0x0a
#define HXOFFSET    0x0b
#define HYOFFSET    0x0c
#define HZOFFSET    0x0d
#define D0MODE      0x0e
#define D1MODE      0x0f
#define D2MODE      0x10
#define D3MODE      0x11
#define D0PWMH      0x12
#define D1PWMH      0x13
#define D2PWMH      0x14
#define D3PWMH      0x15
#define D0PWMT      0x16
#define D1PWMT      0x17
#define D2PWMT      0x18
#define D3PWMT      0x19
#define IICADDR     0x1a
#define LEDOFF      0x1b
#define GPSBAUD     0x1c

#define YYMM                0x30
#define DDHH                0x31
#define MMSS                0x32
#define MS                  0x33
#define AX                  0x34
#define AY                  0x35
#define AZ                  0x36
#define GX                  0x37
#define GY                  0x38
#define GZ                  0x39
#define HX                  0x3a
#define HY                  0x3b
#define HZ                  0x3c
#define Roll                0x3d
#define Pitch               0x3e
#define Yaw                 0x3f
#define TEMP                0x40
#define D0Status        0x41
#define D1Status        0x42
#define D2Status        0x43
#define D3Status        0x44
#define PressureL       0x45
#define PressureH       0x46
#define HeightL         0x47
#define HeightH         0x48
#define LonL                0x49
#define LonH                0x4a
#define LatL                0x4b
#define LatH                0x4c
#define GPSHeight   0x4d
#define GPSYAW      0x4e
#define GPSVL               0x4f
#define GPSVH               0x50

#define DIO_MODE_AIN 0
#define DIO_MODE_DIN 1
#define DIO_MODE_DOH 2
#define DIO_MODE_DOL 3
#define DIO_MODE_DOPWM 4
#define DIO_MODE_GPS 5

struct STime
{
    unsigned char ucYear;
    unsigned char ucMonth;
    unsigned char ucDay;
    unsigned char ucHour;
    unsigned char ucMinute;
    unsigned char ucSecond;
    unsigned short usMiliSecond;
};
struct SAcc
{
    short a[3];
    short T;
};
struct SGyro
{
    short w[3];
    short T;
};
struct SAngle
{
    short Angle[3];
    short T;
};
struct SMag
{
    short h[3];
    short T;
};

struct SDStatus
{
    short sDStatus[4];
};

struct SPress
{
    long lPressure;
    long lAltitude;
};

struct SLonLat
{
    long lLon;
    long lLat;
};

struct SGPSV
{
    short sGPSHeight;
    short sGPSYaw;
    long lGPSVelocity;
};
class CJY901
{
  public:
    struct STime        stcTime;
    struct SAcc         stcAcc;
    struct SGyro        stcGyro;
    struct SAngle       stcAngle;
    struct SMag         stcMag;
    struct SDStatus     stcDStatus;
    struct SPress       stcPress;
    struct SLonLat      stcLonLat;
    struct SGPSV        stcGPSV;

    CJY901 ();
    void StartIIC();
    void StartIIC(unsigned char ucAddr);
    void CopeSerialData(unsigned char ucData);
    short ReadWord(unsigned char ucAddr);
    void WriteWord(unsigned char ucAddr,short sData);
    void ReadData(unsigned char ucAddr,unsigned char ucLength,char chrData[]);
    void GetTime();
    void GetAcc();
    void GetGyro();
    void GetAngle();
    void GetMag();
    void GetPress();
    void GetDStatus();
    void GetLonLat();
    void GetGPSV();

  private:
    unsigned char ucDevAddr;
    void readRegisters(unsigned char deviceAddr,unsigned char addressToRead, unsigned char bytesToRead, char * dest);
    void writeRegister(unsigned char deviceAddr,unsigned char addressToWrite,unsigned char bytesToRead, char *dataToWrite);
};
extern CJY901 JY901;
#include <Wire.h>
#endif

why did you post this? ... is there a problem of some kind? ... do you have a question?

Gyro does not measure Acceleration like gravity.  Gyro measures rotation around an axis like a twist or rotation.  Maybe that is why your project is not working as you expect it to.

All your sketch do is print a lot of data, where is the code you said about "use the value of Acc or AX (acceleration X axis) in If function in order to activate a relay."? You said you want to "use the value of Acc", yet, there is a method shown in the header file GetAcc(); that you never bother to try. Read the source code if document is confusing and come back with some tangible question.