text:
Display not showing output - Arduino Wattmeter
I have been playing with this code for some time now, I am able to show the results in an 16X2 LCD display, but I am not able to do it in an OLED.
here is the code
    #include <SPI.h>
    #include <Wire.h>
    #include "U8glib.h"  //Library for display

    U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

    int index = 0; //size of array
    const int number_of_readings = 200; //total number of readings arduino takes before it averages
    const int current_zero = 510; //initial value of current from arduino with 0 amps
    int current_reading[number_of_readings]; //create array for current_reading
    int voltage_reading[number_of_readings]; //create array for voltage_reading

    float R1=30000; //resistance of R1 in voltage sensor
    float R2=7500; //resistance of R2 in voltage sensor
    float current_average = current_zero; //initial value of current average
    float current_total = 0; //initial value of current_total
    float voltage_average = 0; //initial value of voltage_average
    float voltage_total = 0; //initial value of voltage_total

    int x = 0;
    int row = 0;
    float voltage = 0.1;

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

      void draw(void) {
       u8g.setFont(u8g_font_fub14r);
       {

       u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);

    }
    }

     void loop() {
      voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
      voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
      current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
      current_total = current_total + current_reading[index]; // add current to current_total
      index = index + 1;

      if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
        current_average=current_total/number_of_readings;
        voltage_average=voltage_total/number_of_readings;
        Serial.print("Current average=");
        Serial.print(current_average);
        Serial.print("   Voltage average=");
        Serial.println(voltage_average);
        current_total=0;
        voltage_total=0;
        index=0;

      }

      float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
      float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
      float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
      float power = (voltage*current); //calculate power

     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }

The function of the code is to read data from a "ACS712 - 30A Range Current Sensor Module" and a "Voltage Detection Sensor Module".
Display is a "0.96 inch 128x64 OLED Display Module - SPI/I2C - 7 Pin    ", it is converted to I2C, and working with other codes.
Board : Arduino Uno
Max input voltage will be 12.8V, DC.
The code is supposed to display the voltage on top, ampere in the middle, and watt usage at the bottom.
But it is not working when edited for OLED display.
Someone please make this a working code.
I am new to C+ and coding , so need detailed help.
Here is the code that worked with 16X2 LCD
#include <LiquidCrystal.h>
#include <Wire.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

/*The circuits
 * LCD RS pin to digital pin 12
 * LCD enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4                                                             21333333
 * LCD D6 pin to digital pin 3
 *
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 */

byte lightning[8] = {
  B00001,
  B00110,
  B01100,
  B11000,
  B00011,
  B00110,
  B01100,
  };

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total

void setup (){
  Serial.begin (9600);
  lcd.begin(16,2); // size of LCD
  lcd.createChar(6,lightning); //create charecter named lightning

  //STARTUP MESSAGE
  lcd.setCursor (3,0); //set cusror to row 0, column 3
  lcd.print(" "); //lcdprint
  lcd.print("Arduino"); //lcdprint
  lcd.setCursor(1,1); //set cursor to row 1, column 1
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  lcd.print("Power Meter"); //lcd.print
  lcd.write(6); //lcd write charecter 6 (lightning bolt)
  delay(5000); //delay by 5 seconds
  lcd.clear();  //clear lcd screen
  }

void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }
  float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  float current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  float current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  float power = (voltage*current); //calculate power

  lcd.clear(); //print voltage, current, and power values to LCD screen
  lcd.setCursor(0,0);
  lcd.print(voltage);
  lcd.print("V");

  lcd.print (" ");
  lcd.print(current);
  lcd.print("A");

  lcd.setCursor(0,1);
  lcd.print(power);
  lcd.print("W");
  delay(1);

}

 it is not working in that way. what do you mean by this?

@Vaibhav, it was a mistake, It is not working, that is what I mean.

In your Sketch
void draw(void)
{
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( Bat_Volt,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

current, power, Bat_Volt are local variables define in loop function. Bat_Volt in not even defined in your sketch that's why they are not printing anything in draw function.
Initialize then as global variable in your sketch and in place if Bat_Volt you had use voltage here float voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read in your sketch.
Correct that to.
Your code after edit:
#include <SPI.h>
#include <Wire.h>
#include "U8glib.h"  //Library for display

U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C interface for OLED

int index = 0; //size of array
const int number_of_readings = 200; //total number of readings arduino takes before it averages
const int current_zero = 510; //initial value of current from arduino with 0 amps
int current_reading[number_of_readings]; //create array for current_reading
int voltage_reading[number_of_readings]; //create array for voltage_reading

float R1=30000; //resistance of R1 in voltage sensor
float R2=7500; //resistance of R2 in voltage sensor
float current_average = current_zero; //initial value of current average
float current_total = 0; //initial value of current_total
float voltage_average = 0; //initial value of voltage_average
float voltage_total = 0; //initial value of voltage_total
float voltage = 0.0,current_mV = 0.0,current = 0.0,power = 0.0;

int x = 0;
int row = 0;
float voltage = 0.1;

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

  void draw(void) {
   u8g.setFont(u8g_font_fub14r);
   u8g.drawStr(0, 20, "V: ");
   u8g.drawStr(0, 40, "A: ");
   u8g.drawStr(0, 60, "Watt: ");
   u8g.setPrintPos(58,20);
   u8g.print( voltage,2);
   u8g.println("V");
   u8g.setPrintPos(58,40);
   u8g.print( current,0);
   u8g.println("mA");
   u8g.setPrintPos(58, 60);
   u8g.print( power ,1);
}

 void loop() {
  voltage_reading[index]=analogRead(A0); //read voltage reading from pin A0 (value 0-1023)
  voltage_total = voltage_total + voltage_reading[index]; //add voltage to voltage_total
  current_reading[index]=analogRead(A3); //read current reading from pin A3 (value 0-1023)
  current_total = current_total + current_reading[index]; // add current to current_total
  index = index + 1;

  if (index >=number_of_readings) { //once you have read number_of_reading, create average value of all readings taken
    current_average=current_total/number_of_readings;
    voltage_average=voltage_total/number_of_readings;
    Serial.print("Current average=");
    Serial.print(current_average);
    Serial.print("   Voltage average=");
    Serial.println(voltage_average);
    current_total=0;
    voltage_total=0;
    index=0;

  }

  voltage = ((5*(voltage_average)*(R1+R2))/(1023*R2)); //convert unit value of voltage_average (0-1023) to actual voltage, substract voltage average value when not voltage should be read
  current_mV = (current_average-current_zero)*5; //convert unit value of current_average(0-1023) to mV reading, substract surrent_average value when no current should be read
  current = current_mV/185; //sensor is rated for 185mV/amp according to pdf, may need to change depending on calibration
  power = (voltage*current); //calculate power

 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

Thank you for the reply, I have corrected the "Bat_Volt" into "voltage", but while saving it is showing error "'current' was not declared in this scope". is possible please edit the code for me.

declare current , power, voltage globally. You will get this error removed.


text:
Power supply while using a shield
Sorry if this is a dumb question, I'm new to Arduinos. I'm planning to use a MOVI voice shield with SparkFun's RedBoard Turbo (3.3v). The RedBoard Turbo requires a power supply under 6VDC, but the MOVI website recommends a power supply of 9VDC to the Arduino, because the MOVI can't have its own power supply. Will this destroy my RedBoard? Or is this safe and just something you have to do when using shields? Thank you.
The product website says: "A 7V to 16V 500mA external power supply that powers MOVI™ through the Arduino board. The power consumption of both boards is just above what the USB port can provide. If you don't have already one, this 9V adapter from Adafruit will work perfectly."

You can add LDO in between the power supply to the before providing it SparkFun's RedBoard Turbo.

use instructions for Arduino Zero. http://www.audeme.com/uploads/4/3/9/9/43997575/movi_11usermanual111.pdf

Although I have not used either SparkFun's RedBoard Turbo or the MOVI voice shield, reading the specifications, which you can find on their respective web sites, it would appear that they have incompatible power requirements.
The SparkFun's RedBoard Turbo board web page says
The barrel jack connection on the RedBoard Turbo has a lower input voltage than most Arduino development boards. Make sure that you are using a power supply below 6V. Please be aware that the RedBoard Turbo is also a 3.3V device and not a 5V one like the original RedBoard.
Whilst the MOVI voice shield PDF manual (page 7) says
What you don’t see in Figure 1 is a power supply jack. MOVI is powered through the
Arduino board that needs to be powered using an external power supply. The external
power supply should provide between 7V and 16V and at least 500mA current. During tests
we usually used either 9V or 12V. Battery packs with this specification work as well.
So the one needs less than 6V whilst the other more than 7V. I don't know if you can break the power connection between the two boards and feed the MOVI from a separate supply (9V is very common in the Arduino world) or you may have to swap your SparkFun for an Arduino that runs on 5V and uses a 9V supply.
The gotcha is that Arduino boards, their clones and code compatible boards such as the ESP32 etc fall into 2 different groups, those that run on 3.3V and those that use 5V, and you must be very careful you don't over voltage the latter.
I haven't delved into the specifications further, but you will almost certainly find that the logic levels used by the two boards are also incompatible. One will be using 0 & 5V whilst the other 0 & 3.3V. Connecting a 5V logic output to a 3.3V logic input is not conducive to long life and happiness for the latter.

you understand it wrong. the answer is wrong. the shield takes 5 V from the 5 V pin of the board and the regulator on the board can provide it. the Uno has a different regulator and needs a different input voltage but provides same 5 V on 5 V pin. problem is if the external power supply can provide the necessary current and that doesn't depend on voltage

@Jraj If you compare the schematic of the original RedBoard
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/RedBoard-V22.pdf
with that of the Turbo
https://cdn.sparkfun.com/assets/6/5/4/5/0/RedBoard_Turbo.pdf
There is no 5V regulator on the Turbo board, all it does is pass the 5V from the USB straight across to the 5V socket on the edge connector. There doesn't appear to be any connection between that and the rest of the board.
This query is about powering via the barrel connector.
The original board does have a 5V regulator and it is connected to the edge socket.

@Juraj Sorry, typo

@Juraj The MOVI manual clearly states that it takes its power from the Arduino and that it should be between 7V and 16V not 5V and Please note: MOVI cannot be powered through a USB power supply or the USB cable of the Arduino board as the voltage provided is less than 6V. So if the input supply to the RedBoard Turbo (<=6V) was passed to the MOVI it would not work.

does the shield have a power regulator and takes the power from Vin? I don't believe it.

@Juraj Have a look at the manual
https://www.audeme.com/downloads.html
and tell me what you think. Maybe I'm wrong, but my reading is that it takes the raw (9V say) power from an arduino and has it's own on board power conditioning circuits. If you look at the photograph of the MOVI there are some components that look suspiciously like a power supply (an inductor for example) near the power input pins. Unfortunately, unlike SparkFun) Arduinos do not provide a circuit diagram of the MOVI to confirm this.

it uses Vin, but it can be used with Arduino Zero, so it can be used with SparkFun's RedBoard Turbo

Let us continue this discussion in chat.

source: Stack Exchange

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

sort: votes


text:
UDP Packet not receiving
I started a project where I wanted to send sensor data from one arduino to another and let this 2nd Arduino send the data to a tablet to visualize sensordata like speed, temperature etc.
I wanted to send this in intervalls so UDP would be my way to go. I used the sketches which were provided from the Arduino software which worked well for a while. But after relocating to a new place it doesn't seem to work and I do not know why - I readjusted IP's, Ports and resetted my router.
This is my UDPWrite
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include "dht.h"
#define dht_apin A0 // Analog Pin sensor is connected to
dht DHT;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 178);
IPAddress IP_Remote(192, 168, 1, 177);
IPAddress Port_Remote(8887);

unsigned int localPort = 8887;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP

EthernetUDP Udp;

void setup() {

  // start the Ethernet and UDP:
  Serial.begin(9600);
  Ethernet.begin(mac,ip);

  Udp.begin(localPort);

  Serial.println(Ethernet.localIP());

}

void loop() {

  DHT.read11(dht_apin);

  Udp.beginPacket(IP_Remote, Port_Remote);
    Udp.write("hello");
    Udp.write("Current humidity");
    Udp.endPacket();

         Serial.println("Test");

    delay(2000);//Wait 2 seconds before accessing sensor again.

}

This is my UDPRead
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);

unsigned int localPort = 8887;      // local port to listen on

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,

void setup() {
  // start the Ethernet and UDP:

  Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);
  Serial.print(Ethernet.localIP());
}

void loop() {

  int packetSize = Udp.parsePacket();
  if(packetSize)
  {
      Serial.println("Test");
Serial.print("Received packet of size ");
    Serial.println(packetSize);
    Serial.print("From ");
    IPAddress remote = Udp.remoteIP();
    for (int i =0; i < 4; i++)
    {
      Serial.print(remote[i], DEC);
      if (i < 3)
      {
        Serial.print("Test");
      }
    }
    Serial.print(", port ");
    Serial.println(Udp.remotePort());

    // read the packet into packetBufffer
    Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
    Serial.println("Contents:");
    Serial.println(packetBuffer);
}
}

This is what Wirehsark shows:

eceived.
The Arduinos are connected to my Switch Port5 and Port6 which are mirrored to Port8 to which I am connected via Notebook.
After a few tests, I do not seem to get into my
int packetSize = Udp.parsePacket();

if(packetSize) {

statement for a reason I cannot yet grasp. Udp.parsePacket should receive the UDP package from 192.168.1.178
I can Ping the .178 but not the .177.
I changed cables, ports, IPs, Switch and even the Arduinos. So I would think that the problem is code based.
Thank you very much for your help.

not the cause, but: 1) you can print the IPAddress with Serial.print(ip). 2) why do you have Udp.begin() on reader. it starts listening

if you can't ping the board, the shield is not connected to the network. run some of the example sketches of the Ethernet 2.00 library. for example the WebClient example

Change local port to 8080, other ports are not generally available for local network communication.

@Vaibhav - Well I'll be damned, it works now. I assure you, it has worked before with the ports I have assigned and I even switched ports. But 8080 works. Thank you very much

what could block the port? the router? between two local devices? I don't believe it

@Juraj - No, I do not either. But it works after changing the port. I changed it back for testing reasons and it didn't work anymore.

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


text:
I2C interference SENSOR(SCL+SDA) and MasterSlave comm
I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.
When I enable Wire.begin for slave communication, my BMP280 readings go nuts

#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bmp;

// masterSlave
#include <Wire.h>
#define I2CAddressESPWifi 8
...

void setup() {

    if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP280 sensor, check wiring!");
        while (1);
    }

    // masterSlave - generates problem with BMP280...
    Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

BMP280 Temp = -136.42 *C
Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.
    // COMMENTED OUT FOR DEBUGGING
    //masterSlave - generates problem with BMP280...
    //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

BMP280 Temp = 20.01 *C
Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

Hint#1: I2C pullup resistors.

share your full sketch here.

The I2C is designed for short distances on a PCB. How far will be the slave?

@Juraj some few centimeters - same board (there's a 10m extension cable for the rain gauge -  that part is working perfectly).

@MikaelPatel I'll play some more with the pullup resistor and get back to you.

@Vaibhav 1300 lines of code...  Which parts interest most?  until setup?

The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.
The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.
The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.

So, as far as I2C is concerned, the sensor can be addressed as a slave.  I'll try that and get back to you by the end of the day.  Makes total sense.  UPVOTED

not "to be addressed". but "having an address". some sensors have fixed address, some have a choice from a few addreses

yeah, i'll check up on that.  I'll start by changing the slave's address (currently 8)

the default I2C address of the Adafruit BMP280 is 0x77

I attempted this solution with no result.

this is not a solution but an explanation. what is wrong after you use the Wire library on one set of pins?

when i place the slave and the sendor on the same set of pins is that the sensor is not recognized.

on D1, D1 and you removed Wire.begin(0, 2)?

yes, i did.  everything using D1 and D2, removed Wire.begin(0,2).  Sensor works without slave, but when slave is wired in, sensor stops being recognized

@tonygil, the slave Arduino works without the sensor on esp8266?

50 bonus points for effort, even though i havent at, at this time, been able to confirm or disprove this answer because of other incidental issues which arise AND because of my limited knowledge of Wire library.

I added a note about logic level conversion. and thank you.

got it working.  fixed connections and set a small delay before reading

As per your descriptions, I'm answering here. There is a fact we forget about the load capacitance calculation for selecting I2C pull-ups. It's calculated when more than one slave and variant to distance. Check the jumpers and for pullups try 10k or 4.7K or better you can calculate. It's better to provide a small delay after the wire.begin() function to stabilize the module

would you care to scribble that on the fritzing diagram in the question?

The solution I implemented uses the BMP280 sensor in SPI mode, connected as follows:

with this code before setup
#include <Adafruit_BMP280.h>
#define BMP_SCK D5
#define BMP_MISO D8
#define BMP_MOSI D6
#define BMP_CS D7

//Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

which doesnt EXACTLY answer my answer, though it solves the practical problem (just in case anyone wants a workaround).  ;)


text:
ESP8266 remapping or UART boot
I am trying to make an DFRobot Wifi Bee sleep periodically. The first run executes fine, but after the wakeup a lot of gibberish is shown in the serial monitor. I changed to baud rate to 74880 to see what was going on.
void setup() {
  Serial.begin(74880);
  Serial.setTimeout(2000);
  while (!Serial) { }
  Serial.println("Started.");
  delay(5000);
  Serial.println("Going to sleep.");
  delay(10);
  ESP.deepSleep(10e6);
}
void loop() { }

If I short-circuit D0 and RST, I get the following output
18:28:25.250 -> Going to sleep.
18:28:54.197 ->
18:28:54.197 ->  ets Jan  8 2013,rst cause:5, boot mode:(3,7)
18:28:54.197 ->
18:28:54.197 -> ets_main.c

Indicating that both GPIO0 and GPIO2 are high (which they should) and the cause of reset is power on and hardware watchdog reset.
A similar question has already been asked and answered ESP-01 not waking correctly up after deep sleep, but my issue is different, since I get the correct first boot parameter = 3 (both GPIO0 and GPIO2 are high)
I read here https://www.esp8266.com/viewtopic.php?f=6&t=8386#sthash.82ae9lvh.dpuf that the second boot parameter means
7 SDIO HighSpeed V2 IO  Uart1 Booting
6 SDIO LowSpeed V1 IO   Uart1 Booting
5 SDIO HighSpeed V1 IO  Uart1 Booting
4 SDIO LowSpeed V2 IO   Uart1 Booting
3 FLASH BOOT
2 Jump Boot
1 UART Boot
0 Remapping

I believe that I must change something to receive `boot mode:(3,3). If I remove the wire from GPIO16 to RST, I get almost the same result
18:41:25.250 -> Going to sleep.
18:41:54.197 ->
18:41:54.197 ->  ets Jan  8 2013,rst cause:5, boot mode:(3,0)
18:41:54.197 ->
18:41:54.197 -> ets_main.c

So now a Remapping occurs (or?).
I am running the module using an FDTI USB connector from SparkFun.
Any help is appreciated.

how do you wire io 16 to rst on this board?

They has a link showing that the XPD signal (GPIO16) and RST were connected to physical PIN 9 and 12. Just added a jumper wire.

The schematic link https://raw.githubusercontent.com/Arduinolibrary/DFRobot_Wifi_Bee_ESP8266/master/TEL0092%20Wifi%20Bee%20ESP8266%20SCH.pdf in this document https://www.dfrobot.com/product-1279.html shows how the signals are connected to physical PINS.

it doesn't match this. https://wiki.dfrobot.com/SKU_TEL0092_WiFi_Bee-ESP8266_Wirelss_module#target_2  it is a schematics for some diferent board

I just added a probe to the corner leg of the chip (XPD / GPIO16) and it is indeed connected to PIN9. DFRobot links to this diagram. If it doesn't match, they provide wrong information

@Juraj Thank you for the information. DFRobot apparently provides different information in different places. I managed to pull high DIO0 and use it to flash a LED. According to your link, this should be NC (impossible)h

I used PIN 12 (shown in lower corner of the schematic).... I could try 8 instead

Let us continue this discussion in chat.


text:
How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?
The hid_keyboard example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the F1 key, or keys with shift/control modifiers?

Yo can use the keyboardReport() function to send key-codes with modifiers. Here is an example that will send an ! by sending the keycode for 1 plus a shift key modifier...
    // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
    // press the keys consecutively,. it presses them simultainiously.

    // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

    uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
    blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

    // This release seems to be required. Without it, the last pressed key just repeats forever.
    blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188
...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212
Unfortunately the hid_keycodes example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...
https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928


text:
Aruino RTC using rtclib not understanding functions
I am missing something fundamental using RTClib.
When I use the rtc.adjust function to change the time in the RTC, I cannot get the updated time from the RTC, just increments a fixed time. I have searched for examples for what I need, and the same few samples of code keep getting quoted.
I want my code to set the RTC at compile to the system time, which it does,
then in the Loop I want to increment the hour.  In reality I will use a button for this, but for now I am just trying to understand how DateTime now = rtc.now and rtc.adjust work.  How to write to the RTC, how to read it back. I am missing something regarding these variables.
Two version of my code.  One with output showing the clock working, and one where the output is static, just increments the hour.
This one works:
#include <RTClib.h>
#include <Wire.h>
int ArduinoHour;
int ArduinoMin;
int ArduinoSec;
RTC_DS1307 rtc;

void setup()
{
  Serial.begin(250000);
  Wire.begin();  //sets up the I2C
  rtc.begin();   //initializes the I2C to the RTC

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
    if (rtc.isrunning()) {
    Serial.println("RTC IS running!");
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}
void loop()
{
  DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

  ArduinoHour = now.hour();
  ArduinoMin = now.minute();
  ArduinoSec = now.second();

  Serial.print("AT TOP");
  Serial.println();
  Serial.print("RTC Time");
  Serial.println();
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  Serial.print("Arduino Time");
  Serial.println();
  Serial.print(ArduinoHour, DEC);
  Serial.print(':');
  Serial.print(ArduinoMin, DEC);
  Serial.print(':');
  Serial.print(ArduinoSec, DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  //RTC increments when these are commented out. Does not when active
  //ArduinoHour = ArduinoHour +1;
  //rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

}

Here is the output.  Looks fine:
RTC IS running!
AT TOP
RTC Time
11:38:3

Arduino Time
11:38:3

AT TOP
RTC Time
11:38:5

Arduino Time
11:38:5

AT TOP
RTC Time
11:38:7

Arduino Time
11:38:7

AT TOP
RTC Time
11:38:9

Arduino Time
11:38:9

This one does not Work:
Now I try to simply increment variable ArduinoHour and then write it to the RTC using rtc.adjust. The only change are the two lines at the bottom are uncommented.
#include <RTClib.h>    //https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code
#include <Wire.h>

int ArduinoHour;
int ArduinoMin;
int ArduinoSec;

RTC_DS1307 rtc;

void setup()
{
  Serial.begin(250000);
  Wire.begin();  //sets up the I2C
  rtc.begin();   //initializes the I2C to the RTC

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
    if (rtc.isrunning()) {
    Serial.println("RTC IS running!");
    rtc.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop()
{
  DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

  ArduinoHour = now.hour();
  ArduinoMin = now.minute();
  ArduinoSec = now.second();

  Serial.print("AT TOP");
  Serial.println();
  Serial.print("RTC Time");
  Serial.println();
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  Serial.print("Arduino Time");
  Serial.println();
  Serial.print(ArduinoHour, DEC);
  Serial.print(':');
  Serial.print(ArduinoMin, DEC);
  Serial.print(':');
  Serial.print(ArduinoSec, DEC);
  Serial.println();
  Serial.println();
  delay(1000);

  //RTC increments when these are commented out
  ArduinoHour = ArduinoHour +1;
  rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

}

Here is the output, RTC time is not changing. I know I am doing something basically wrong with how I am updating the variables writing/reading from the RTC.  Can't figure it out.
RTC IS running!
AT TOP
RTC Time
11:41:54

Arduino Time
11:41:54

AT TOP
RTC Time
12:41:54

Arduino Time
12:41:54

AT TOP
RTC Time
13:41:54

Arduino Time
13:41:54

AT TOP
RTC Time
14:41:54

Arduino Time
14:41:54

If by "RTC time is not changing" you mean minutes and seconds frozen at the same value, then this is entirely of your doing.
Your sketch spends 99% of the time between the initial rtc.now() request
 DateTime now = rtc.now(); // pings RTC and loads time info into the now variable.

and the final rtc.adjust() call
rtc.adjust(DateTime(now.year(),now.month(),now.day(),ArduinoHour,ArduinoMin,ArduinoSec));

This period is the period when your RTC is supposed to be "ticking", progressing forward.
But you actually store the original minutes and seconds values in ArduinoMin and ArduinoSec at the beginning of this period. And later, at the end of this period, you bash these values back into the clock. By doing this you forcefully erase whatever progress the clock made between these two lines. No wonder your minutes and second do not change.
This problem actually has no perfect solution. RTC_DS1307 class (and, I suspect, the underlying RTC hardware) provide no means to change just the hours value without disrupting minutes and seconds. When you call adjust(), you have to set everything, which means that you will always somehow "disrupt" the whole clock.
In your sketch you can minimize the adverse effects by re-requesting the minutes and seconds values right before doing adjust():
//RTC increments when these are commented out
ArduinoHour = ArduinoHour +1;
now = rtc.now();
rtc.adjust(DateTime(now.year(), now.month(), now.day(), ArduinoHour, now.minute(), now.second()));

Note, that I'm using your updated ArduinoHour values, but everything else comes from a just-refreshed now object.
This is still not perfect, since it still suffers from a race condition against a real-time clock, but it is better than what you had originally.

@ AnT -  Thank you.  That perfectly explains it.

@AnT, there is a suggested edit, which moves ArduinoHour = ArduinoHour +1; after now = rtc.now();. should it be accepted?

@Juraj: I don't see why. The whole idea of the workaround is to place the second now = rtc.now(); call as close as possible to the rtc.adjust call - in order to minimize the time "lost" between these actions. Moving the ArduinoHour = ArduinoHour + 1; after now = rtc.now(); (for what reason?) goes against that idea.

Sorry, it was my mistake. My edits has nothing useful, sorry again.

This is the content of ajust method:
void RTC_DS1307::adjust(const DateTime& dt) {
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)0); // start at location 0
  Wire._I2C_WRITE(bin2bcd(dt.second()));
  Wire._I2C_WRITE(bin2bcd(dt.minute()));
  Wire._I2C_WRITE(bin2bcd(dt.hour()));
  Wire._I2C_WRITE(bin2bcd(0));
  Wire._I2C_WRITE(bin2bcd(dt.day()));
  Wire._I2C_WRITE(bin2bcd(dt.month()));
  Wire._I2C_WRITE(bin2bcd(dt.year() - 2000));
  Wire.endTransmission();
}

You can write new Hour value directly to the clock without erasing other clock data:
  Wire.beginTransmission(DS1307_ADDRESS);
  Wire._I2C_WRITE((byte)2); // Hour location
  Wire._I2C_WRITE(bin2bcd(ArduinoHour));
  Wire.endTransmission();


text:
128x64 and pushButtons
Could someone give me some advice related to building a menu for a 128x64 LCD using 5 pushButtons?
i have 5 screens.
btn1 is for display MainMenu and Selection.
btn2 and btn3 is for up and down scrolling
btn 4 and btn4 is for switching on/off and increase decrease values.
the problem which i encounter is related to btn2 and btn3.
i don;t know how to use them for scrolling in in another screen except screen1 (MainMenu).

#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(13,12,11); //Enable, RW, RS, RESET

int selectionButton = A1, selectionButtonState, selectionButtonLastState = 0, cntSelectionButtonPressed = 0, cntSelectionButtonPressed2ForMenu2 = 0;
int menuButton = A0, menuButtonState, menuButtonLastState = 0;
int scrollDownButton = A3, scrollDownButtonState, scrollDownButtonLastState = 0;
  boolean mainMenu = false;

void setup()
{
    Serial.begin(9600);
    if ( u8g.getMode() == U8G_MODE_R3G3B2 )
    u8g.setColorIndex(255);     // white
    else if ( u8g.getMode() == U8G_MODE_GRAY2BIT )
    u8g.setColorIndex(3);         // max intensity
    else if ( u8g.getMode() == U8G_MODE_BW )
    pinMode(selectionButton,INPUT);
    pinMode(menuButton,INPUT);
    pinMode(scrollDownButton,INPUT);

}

void loop()
{

 scrollDownButtonState = digitalRead(A3);
 selectionButton = digitalRead(A1);
 menuButton = digitalRead(A0);

//pin A1 = RiGHT
 if(selectionButton != selectionButtonLastState)
 {
  if(digitalRead(A1) == HIGH)
  {
    cntSelectionButtonPressed += 1;
    if(cntSelectionButtonPressed == 4)
    {
      cntSelectionButtonPressed = 0;
    }
  }
  selectionButtonLastState = selectionButton;
 }

////////////////////////
 if(menuButton != menuButtonLastState)
  {
    if(cntSelectionButtonPressed == 1 && digitalRead(A0) == HIGH)
    {
         cntSelectionButtonPressed2ForMenu2 += 1;
    }
      if(cntSelectionButtonPressed2ForMenu2 == 4)
      {
        cntSelectionButtonPressed2ForMenu2 = 0;
      }
       u8g.firstPage();
       do{
           Menu2();
         }while(u8g.nextPage());

       menuButtonLastState = menuButton;
  }
 else
 {
 u8g.firstPage();
  do{
    MainMenu();
  }while(u8g.nextPage());
 }

}

void MainMenu(){
switch(cntSelectionButtonPressed)
{

  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("> Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("  Exterior casa");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Ceas");
           u8g.setPrintPos(15,25);
           u8g.print("  Interior casa");
           u8g.setPrintPos(15,35);
           u8g.print("> Exterior casa");
           break;
}
}

void Menu2()
{

  switch(cntSelectionButtonPressed2ForMenu2)
{
  case 1:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("> Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
  case 2:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("> Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("  Stil3");
           break;
           break;
  case 3:
           u8g.setFont(u8g_font_6x13);
           u8g.setPrintPos(15,15);
           u8g.print("  Stil1");
           u8g.setPrintPos(15,25);
           u8g.print("  Stil2");
           u8g.setPrintPos(15,35);
           u8g.print("> Stil3");
           break;
}
}

First, I'm a bit surprised you use analog pins for button checks, instead of digital pins.
About the code, without analyzing it completely, the easiest way is to make a state diagram in pseudo code first.
E.g.suppose you want to have the following screens(a screen 'title/content' is shown in[], a button transition with ---(key)-->
InitScreen--- (right)--> MenuOption1Highlight---(right)-->MenuOption1Items
                              |       ^     \---(left)----+
                           (down)    (up)
                              v       |
                           MenuOption2Highlight---(right)-->MenuOption2Items
                                              \---(left)----+

To program this (roughly), create an enumeration for each menu page :
enum EMenuPage
{
        None,
    InitScreen,
    MenuOption1Highlight,
    MenuOption1Items,
    MenuOption2Highlight,
    MenuOption2Items
};

Than create a current state for it as global variable:
EMenuPage _eMenuPage;

And initialize it in Setup:
_eMenuPage = None;

Create an enum for the keys :
enum EKey
{
    None,
    Up,
    Down,
    Right,
    Left
};

It is easier to create a function that reads keys, and returns one key, maybe one key has priority over another,
or you can combine keys (in that case add in EKey e.g. UpAndDown). If no key has been pressed, None is selected.
In the loop, use a state transition diagram to program out the options :
EKey pressedKey = GetPressedKey(); // This is for yourself to implement, it updates _pressedKey;

switch (_eMenuPage)
{
case None:
    InitScreen();
    break;

case InitScreen:
    ProcessInitScreenKeys();
    break;

case MenuOptions1HighLighted:
    ProcessMenuOptions1HighLightedKeys();
    break;

...
default:
    // Illegal key
    break;
}

For each page you make a function (e.g. InitScreen) which updates the state and shows the content on the display:
void InitScreen()
{
    _eMenuPage = InitScreen;

    // Show content on display.
}

Also, you create a Process...Keys function to handle the keys. Like:
void InitScreen()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Right:
        MenuOptions1HighLighted();
        break;

    default:
        // Ignore other keys
        break;
    }
}

For another function it would look like:
void ProcessMenuOptions1HighLightedKeys()
{
    EKey pressedKey = GetPressedKey();
    switch (pressedKey)
    {
    case Down:
        MenuOptions1HighLighted();
        break;

    case Right:
        MenuOption1Items();
        break;

    default:
        // Ignore other keys
        break;
    }
}

(Btw I did not check neither compiled the code).
Probably there is a nicer more object oriented way to do this, but it costs more memory and is more advanced. This is to create an abstract Page class, which has two virtual methods (one to show and one to handle keys), and create a derived class for each page implementing the two functions from the base class.


text:
Basic communication with nrf24l01 between nodemcu and arduino nano
I spent the last two days to find a way to set up a basic communication between a nodemcu amica and an arduino nano with a nrf24l01 module; all of this without success..
Here the code uploaded on my nodemcu:
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(D4, D8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openWritingPipe(address);

  //Set module as transmitter
  radio.stopListening();

  Serial.println("inizio ad trasmettere");
  Serial.println(radio.isChipConnected());
}
void loop()
{
  Serial.println("qui");
  const char text[] = "Hello World";
  bool ret = radio.write(&text, sizeof(text));
  Serial.print("Write ret: ");
  Serial.println(ret);
  delay(1000);
}

and here the code on the arduino side
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(5, 6);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();

  Serial.println("inizio ad ascoltare");
  Serial.println(radio.isChipConnected());
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

Following my wiring config of
nodemcu
and
arduino nano
Can anyone see something that I don't see?
I'm really frustrated
My nrf24l01 module is this https://www.amazon.it/gp/product/B06WD17WLS, not the module in the fritzing scheme.

how does it fail? does the esp8266 boot? the D8 wiring can make problems

Simply I don't see a successful communication, both Nano and nodemcu appear to transmit and receive normally, but no frame arrive at the receiver


text:
Can I use a TCS34725 color sensor with a LilyPad?
I have been trying to get a TCS34725 color sensor working with a LilyPad Arduino USB - ATmega32U4 board, but with no success. I am wondering if it possible?
I have been using the following sketch to try and get a reading but nothing appears in the monitor:
#include <Wire.h>
#include "Adafruit_TCS34725.h"

/* Example code for the Adafruit TCS34725 breakout library */

/* Connect SCL    to analog 5
   Connect SDA    to analog 4
   Connect VDD    to 3.3V DC
   Connect GROUND to common ground */

/* Initialise with default values (int time = 2.4ms, gain = 1x) */
// Adafruit_TCS34725 tcs = Adafruit_TCS34725();

/* Initialise with specific int time and gain values */
Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_700MS, TCS34725_GAIN_1X);

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

  if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("No TCS34725 found ... check your connections");
    while (1);
  }

  // Now we're ready to get readings!
}

void loop(void) {
  uint16_t r, g, b, c, colorTemp, lux;

  tcs.getRawData(&r, &g, &b, &c);
  // colorTemp = tcs.calculateColorTemperature(r, g, b);
  colorTemp = tcs.calculateColorTemperature_dn40(r, g, b, c);
  lux = tcs.calculateLux(r, g, b);

  Serial.print("Color Temp: "); Serial.print(colorTemp, DEC); Serial.print(" K - ");
  Serial.print("Lux: "); Serial.print(lux, DEC); Serial.print(" - ");
  Serial.print("R: "); Serial.print(r, DEC); Serial.print(" ");
  Serial.print("G: "); Serial.print(g, DEC); Serial.print(" ");
  Serial.print("B: "); Serial.print(b, DEC); Serial.print(" ");
  Serial.print("C: "); Serial.print(c, DEC); Serial.print(" ");
  Serial.println(" ");
}

When really nothing appears on the serial monitor, then your serial connection doesn't work. Do you have selected the correct port and baud rate?

Can I use TCS34725 Color Sensor with Lilypad?

Yes but please note that the I2C pins are D2 (SDA) and D3 (SCL). No extra components are required when connecting to the Adafruit TCS34725 breakout board. It contains pull-up resistors, and voltage/signal level converters (if needed).
Cheers!
Ref. https://cdn.sparkfun.com/datasheets/E-Textiles/Lilypad/Lilypad_Arduino_USB_v12.pdf


text:
Stack smashing protect failure ESP32 with Modbus RTU
I'm doing a project using an ESP32 TTGO with LoRa, the Max485 and a WELLPRO ADAM 8082 for Modbus communication. I'm trying to use the ESP32 as a master to and the ADAM as a slave.
I'm also using Node-RED to send the input signals (reading the digital inputs on the ADAM or sending signals to the digital outputs).
Whenever I send a signal there's no problem, the ADAM receives it correctly and sends the answer. But when my ESP32 receives the answer, I get the following error:
Stack smashing protect failure!

abort() was called at PC 0x400dc860 on core 1

I tried debugging my program and the error happens when my program comes back from the function that has my reading modbus loop.
I'm pretty new to Arduino, so I don't really understand what could be causing this stack overflow.
Here's my code.
My global variables:
unsigned char ucSt[N_MAX];
int delayTime;

HardwareSerial modbusData(2);

WiFiClientSecure espClient;
PubSubClient client(espClient);
boolean bWifiConnected = false;

const byte button = PRG_BUTTON;

Modbus reading with loop:
void vReadingModBus()
{
  int i, nCmpt = 0;
  unsigned int uiCRC;

  while (modbusData.available() > 0)
  {
    Serial.print("nCmpt: ");
    Serial.println(nCmpt);
    ucSt[nCmpt] = (unsigned char)modbusData.read();
    nCmpt++;
    delay(delayTime - 2);
  }
  if (nCmpt)
  {
    Serial.print("He llegit aquests ");
    Serial.print(nCmpt);
    Serial.println(" bytes: ");
    char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    client.publish(TEMA_RESPOSTA_MODBUS, szResposta);
    uiCRC = uiModRTU_CRC(ucSt, nCmpt - 2);
    if ((byte)(uiCRC >> 8) == ucSt[nCmpt - 1] && (byte)(uiCRC & 0xFF) == ucSt[nCmpt - 2])
    {
      Serial.println("Trama amb CRC correcte");
    }
    else
    {
      Serial.println("Trama amb CRC incorrecte");
    }
  }
  nCmpt = 0;
}

Modbus transmission:
void vModbusTx(unsigned char *uc, int nLen)
{
  int i;

  Serial.print("Enviat: ");
  for (i = 0; i < nLen; i++)
  {
    Serial.print(uc[i], HEX);
    Serial.print(" ");
  }
  Serial.println();

  vModeTxRxRS485(RS485Transmit);
  delay(1);
  for (i = 0; i < nLen; i++)
  {
    modbusData.write(uc[i]);
  }
  delay(delayTime);

  vModeTxRxRS485(RS485Receive);
}

My setup:
void setup() {
  Serial.begin(115200);    // U0_RXD:GPIO3, U0_TXD:GPIO1 (UART0)
  modbusData.begin(9600); // U2_RXD:GPIO16, U2_TXD:GPIO17 (UART2)

  pinMode(PRG_BUTTON, INPUT_PULLUP);
  pinMode(GPIO_R2, INPUT); // 39
  pinMode(SSerialTxControl, OUTPUT); // hardwired to GPIO_R2
  pinMode(LED, OUTPUT);

  vModeTxRxRS485(RS485Receive); // RS485Receive is a 0, and vModeTxRxRS485 controls the DE/RE bits for the Max485

  delayTime = 0;

  //Wire.begin(I2C_SCL_OLED);

  delay(1000); // give me time to bring up serial monitor
}

My loop:
void loop() {
  boolean bButtonState = !digitalRead(button);
  static boolean bLastButtonState = bButtonState;

  // MODBUS READING LOOP
  vReadingModBus();

  if (!client.connected())
  {
    reconnect();
  }

  // BUTTON STATE CHECK
  if (bButtonState != bLastButtonState)
  {
    bLastButtonState = bButtonState;
    vDelayESP(50);
    if (!bButtonState)
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "UNPRESSED");
    else
      client.publish(TEMA_PUBLICA_ESTAT_BOTO, "PRESSED");
  }

  client.loop();
}

And finally here's an example of my program running and giving the error mentioned:
Connecting to WiFi network
Waiting for WIFI connection...
..............................................
Attempting MQTTS connection...connected
Message arrived [/clot/dam/biel/esp32/escriuModbus] 010F000000080111
Petició a ModBus:
010F000000080111
Mida: 8
ucSt[0] = 1
ucSt[1] = F
ucSt[2] = 0
ucSt[3] = 0
ucSt[4] = 0
ucSt[5] = 8
ucSt[6] = 1
ucSt[7] = 11
Enviat: 1 F 0 0 0 8 1 11 3E 99
He llegit aquests 8 bytes:
1 F 0 0 0 8 54 D
Trama amb CRC correcte

Stack smashing protect failure!

abort() was called at PC 0x400dc7d8 on core 1

Backtrace: 0x4008c800:0x3ffb1ef0 0x4008ca31:0x3ffb1f10 0x400dc7d8:0x3ffb1f30 0x400d1eed:0x3ffb1f50 0x400d23c0:0x3ffb1f90 0x400d513d:0x3ffb1fb0 0x4008879d:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x17 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:928
ho 0 tail 12 room 4
load:0x40078000,len:8424
ho 0 tail 12 room 4
load:0x40080400,len:5868
entry 0x4008069c

tl;dr: The message probably means your function is overwriting its array:
A stack overflow is caused by a stack that grows downward into the allocated heap space, either causing damage to data within the heap, or code using that heap space causing damage to the contents of the stack.
But "stack smashing" refers to damage caused by function code writing past the bounds of an automatic local variable and damaging the stack contents, typically including the function's return address.
[Feel free to skip rather long explanation:]
A function's stack-frame begins with the return address - the address following the instruction that calls the function, i.e., the address of the next instruction to be executed after the function returns. Then, building downwards, the call parameters are put on the stack and become local variables. Then any variables allocated during the function execution are allocated, still building downward.
Assume one of those allocated variables is an array. Its zero-th element is in the lowest address of the allocated space, and subsequent elements are at successively higher addresses. If I start writing into the array, and continue past its length, I'll eventually overwrite other automatic locals, my parameters, and and my return address. Then, when the function tries to return, instead of jumping to the code that called the function, the MCU uses the damaged return address and jumps to ... ????
To catch this error, the compiler can insert code that 1) allocates and writes a "canary" - a known value - just after the return address, and 2), checks the canary for damage just before the function returns. If the canary has been altered, you get the message you saw, because it's likely that the return address will have been altered also. But regardless, the canary isn't part of your code and isn't accessible to it. Thus, it detects writing-out-of-bounds errors.
[End of wordy explanation]
Check the code in your function 'void vReadingModBus()' - my money is on the loop that writes into szResposta[]:
  char szResposta[N_MAX] = "", szByte[3];
    for (i = 0; i < nCmpt; i++)
    {
      sprintf(szByte, "%02X", ucSt[i]);
      strcat(szResposta, szByte);
      Serial.print(ucSt[i], HEX);
      Serial.print(" ");
    }

Update:

If I understood correctly, it means szResposta must be overwriting the
  function's return address? How should I avoid this?

The short answer is make your array big enough for what you're going to put in it. But that's probably not a satisfying answer though, so let's take a closer look. I'm not sure exactly what your intent is in that loop, but since you print the strcat() result at every iteration and you don't seem to use szResposta after that, perhaps you meant to call strcpy() (replace the contents of the array) instead of strcat() (extend the contents of the array). If so, strcat() would quite likely write past the array bounds.

Thank you so much for this fantastic explanation! It certainly was the loop. The line giving the error is strcat(szResposta, szByte). If I understood correctly, it means szResposta must be overwriting the function's return address? How should I avoid this? Thank you, again!


text:
esp8266 deep sleep timer slightly inaccurate?
I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets.  However, I'm getting output like this:
08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE?  I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.

How to use an external RTC to wake the ESP8266: https://arduino.stackexchange.com/a/91504/78174

A (now 3 year old) GitHub thread suggests using an external RTC if time tracking is of importance.  It also points at a dead NodeMCU document link.  That document appears to have moved.  This document describes the lengths taken to provide a better account for time passage during sleep.  Which, apparently, includes guessing at the sleeping chip's temperature:

Time keeping on the ESP8266 is technically quite challenging. Despite
being named RTC, the RTC is not really a Real Time Clock in the normal
sense of the word. While it does keep a counter ticking while the
module is sleeping, the accuracy with which it does so is highly
dependent on the temperature of the chip. Said temperature changes
significantly between when the chip is running and when it is
sleeping, meaning that any calibration performed while the chip is
active becomes useless mere moments after the chip has gone to sleep.
As such, calibration values need to be deduced across sleep cycles in
order to enable accurate time keeping. This is one of the things this
module does.

Update:
A recent Arduino stack exchange answer goes into detail using a DS3231 Real Time Clock.

Yes a RTC can be very inaccurate. Some RTCs will let you synchronise them.


text:
Reading byte per byte from a txt file on SD Card without using the 512Bytes buffer
I am trying to read every sequenced-byte that is located on a txt file in the SD card. I have been reading quite a lot about the SPI and SD libraries, But I have found a lot of different information that makes me feel confused.

Is it really possible to read information byte per byte without buffering by default as usually happens when you use the SD or SDFat? Do you know a Library that makes it really possible?

Also, I found on the SDFile.cpp that is located in the src folder in the SD library, a part that mentions " // no buffering needed if n == 512 or user requests no buffering" How is it possible to request no buffering? I found the unbufferedread() function but I am afraid that this actually reads the number of bytes and not the information on the bytes (Is it possible?).
Do you know where may I found examples of this kind of low level functions for me to find out How may I use them  for the mentioned purpose. Or a library that would make my life easier in order to get the unbufferred read.
I want a continuous data sending into a DAC, that's why I am trying no to get the unbufferred in order to make all the data's sent as continuous as possible.

Sorry for making so many questions, I just started to use Arduino a couple of months ago  so I am not that familiarized with all the terms.
Thanks for your advise.

There are block sides transfers in SD specs. I'm not sure if there are also byte sized transfers. With SDHC and later, data on SD card is addressed in blocks, so you probably won't be able to just read a byte or two without transferring a whole block. I guess I'm saying "check the SD card specs".


text:
How to connect L298N motor driver to 5v input supply?
I'm trying to connect 5v supply to a L298N motor driver at it's 12V-35V input pin but it's not working. If I'm connecting to 7.2V supply it's working. Is there any way to connect 5v supply? I want a constant 5v at output pins for motors.

You are either not telling us something or making someting up. Did you remember to supply 5V logic power to your L298N board? What do you have connected to "5V" terminal of L298N?

Without looking at the L298N dtatasheet, connecting 5V to an input labeled with 12V-35V seems not to be a good idea.

Short answer: Don't. A 12V-35V input pin needs to be supplied with... wait for it... 12V to 35V. A 5V supply won't be enough.

@Duncan C: Not true. As far as the pure motor power is concerned, the VIN terminal (aka 12V-35V terminal) is just a passive switched terminal. It can be supplied with any voltage the motor requires (as long as it doesn't cross the upper limit). 5V is perfectly fine, if that's what the motor needs. The only case when the lower voltage limit applies on the VIN terminal is when one plans to use the board's built-in linear regulator to obtain 5V logic supply from it. In that case one has to consider the voltage drop (around 2V), meaning that VIN should be at least 7V.

In fact, I have no idea who and why came up with the bizarre idea to label that terminal as 12V-35V. In newer boards it is simply labelled VIN. 12V-35V label makes no sense whatsoever. Apparently someone simply assumed that no one will ever want to use a lower voltage motor. I see conflicting information on the logic supply voltage though. Some sources say 7V, others: 5V. In practice the boards I tried work perfectly fine with 5V logic supply.

Note: Since all vendors (checked Mouser, Octopart, and Sparkfun) link to the L298 datasheet when listing the L298N I will assume they are reasonably equivalent.
I will assume that the "12V-35V input pin" is the V_S pin, despite that label. There are only two supply pins on the L298 with the following electrical characteristics:

V_S, Supply Voltage, pin 4, Operative Condition V_IH + 2.546V (max.: 46V)
V_SS, Logic Supply Voltage, pin 9, typical 5V (min.: 4.5V, max.: 7V)

with

V_IH, Input High Voltage, ranging from 2.3V to V_SS

Which would explain that the circuit works at 7.2V under the assumption that the logic inputs (enable A and B as well as inputs 1 through 4) are at close to 5V high levels. And here's the trick that might make it work: as noted V_S (the supply voltage) needs to be at a level of V_IH + 2.546V while V_IH could be as low as 2.3V and 2.3V + 2.546V < 5V. So driving the L298's logic inputs with a lower voltage for logic 1, i.e. closer to 2.3V high levels, could help.
Why is this? (source):

[..] The actual restriction is that the motor supply be somewhat greater than the logic "1" input, but that need not match the logic supply. [..]

A warning though:

this circuit is now operating at the fringes, one might call it shady at best, intolerable at worst
saturation voltage is related to output current and other parameters, e.g. temperature, so this might work now under certain conditions and fails horribly another day

Therefore better bets are:

use a higher supply voltage
ditch the L298 and its high voltage drop Darlingtons and use a MOSFET H-bridge motor driver, such as the TB6612FNG, see also
ditch the L298 and use single bipolar transistors, depending on the output current

Other things to check:
Make sure V_SS is connected to the logic supply voltage (see AnT's comment). Make sure GND of the Arduino's power supply is connected to the L298's GND.


text:
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
How do I move more than 128 pixels when using Arduino Leonardo's Mouse.move?
Is it possible to modify the header file or use a different library?
I used the MouseTo library, but it wasn't the move I wanted.
We want to move as fast as possible to the relative coordinates, not as one pixel.
I've searched almost every community, but I haven't.
Give them a hand.

The USB HID protocol for mouse is the limitation on sending more then a byte sized value for the mouse movement in one event.
You can't create a faster USB mouse. Repeat the call of the move() function. Of course you can use a function to call move() repeatedly to move to target destination.
void mouseMove(long x, long y) {
  long max = max(abs(x), abs(y));
  int count = (int) (max / 127);
  signed char stepX = x / (count + 1);
  signed char stepY = y / (count + 1);
  for (int i = 0; i < count; i++) {
    Mouse.move(stepX, stepY);
  }
  signed char resX = x - (stepX * count);
  signed char resY = y - (stepY * count);
  if (resX != 0 || resY != 0) {
    Mouse.move(resX, resY);
  }
}

There were times when the exact value was not available when I called multiple times. Anyway, thank you for your answer.

For X and Y values between -64 and 64, consider multiplying the X and Y values you are passing to the method mouse.move() by 2.  In the above linked page, the example call to mouse.move() looks like this:

mouse.move(xVal, yVal, wheel)

Consider writing it like this for twice the change in either direction:

mouse.move((2 * xVal), (2 * yVal), wheel)

For values less then -128 or greater than 128, consider calling the method multiple times instead of once for each time it is desired to move the mouse.
A more difficult approach: You may also consider re-writing or adding to the Arduino mouse driver.  It appears the Arduino mouse driver is located here.  As this is C++ you will need to change the definition of the "mouse" method as well as how you handle int as opposed to char sized variables.  In this case you can take advantage of the C++ Method Overloading feature.  That is, you can have 2 methods of the same name with different parameter types.  C++ will treat them as two individual methods.  So the original mouse.move method can remain untouched.  While the new mouse.move method will be able to handle type singed int instead of type singed char values.

Wouldn't the multiplying approach let the parameters overflow? The explanation after that seems better to me, calling the method multiple times or changing the library.

what? the unsigned chars (-127 to 127) are defined in the HID event. how would you reimplement that?

I see. Your answer was helpful to me even if it was not possible.

@juraj, If the HID definition limit mouse movement the library can abstract this from the Arduino sketch by sending multiple HID commands should the value passed to the library be larger than allowed by the HID interface.  So a library call using ints instead of chars can still be created.

@chrisl, yes, I'll rephrase the answer.


text:
Arduino Sensor Values to Raspberry Pi using NRF24
Im trying to send temperature sensor data through NRF24L01 to Raspberry Pi and read it in Raspberry Pi using python. But the temperature sensor data comes to the Raspberry Pi as letters, which I found out is in Ascii values. Im not sure how to display the actual readings from the Arduino to the Raspberry Pi
Here is the Arduino code:
#include <DallasTemperature.h>
#include <OneWire.h>
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define ONE_WIRE_BUS 2

OneWire oneWire (ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

RF24 radio(9, 10);

void setup(void) {

  Serial.begin(9600);
  sensors.begin();
  radio.begin() ;
  radio.setPALevel(RF24_PA_MAX) ;
  radio.setChannel(0x76) ;
  radio.openWritingPipe(0xF0F0F0F0E1LL) ;
  radio.enableDynamicPayloads() ;
  radio.powerUp() ;
}

void loop(void) {
  sensors.requestTemperatures();
  float temperature = sensors.getTempFByIndex(0);
  radio.write(&temperature, sizeof(float));
  delay(1000);
  Serial.print(sensors.getTempFByIndex(0));
}

Here is the code for Raspberry Pi in Python
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()

while True:

    while not radio.available(0):
        time.sleep(1/100)

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating...")
    string = ""

    for n in receivedMessage:
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Our received message decodes to: {}".format(string))

I want to get the temperature value in numbers instead of letters. Instead of like this:
Translating ... Our received message decodes to: N

why are you asking a python question at an arduino site? ... arduino does not run python

Im trying to see if there is a way to modify the Arduino's code to get the sensor values as a string so that it can be read by rpi


text:
Two sensors using I2C
We have two sensor one of them(MPU6050-gyro) is communicating using I2C, the other is via SPI(SD card reader). Now, we need an additional component as a sensor that the barometer which communicates via I2C.
Can we use all three modules without any problem? I wonder if two I2C modules is used in a hassle-free manner? Otherwise, what can be done?

Yes, that's the idea behind bus protocols like i2c. You only require the sensors on i2c to have different bus adresses. A sensor's address usually can be chosen by soldering a jumper (the mpu6050 provides this feature on pin AD0). If you can't avoid an address collision you could use an i2c multiplexer or a microcontroller in between the sensor and the actual mcu (but probably that's not neccessary when using only two sensors).
Using SPI and I2C at the same time is absolutely no problem on the atmega!

I2C is a bus. There can be many devices connected to that bus, each one having it's own address. Everytime you want to communicate with one of them, you have to send the address of the device. When you are using the Wire library, thats done by calling Wire.beginTransmission() or Wire.requestFrom(). Most slave devices have an adress, that is partly configurable, often by wiring special pins to Vcc or ground. Make sure, that every device on the bus has a unique address, or you will run into problems with corrupted data or a stuck bus.


text:
16-Channel 12-bit PWM/Servo Shield check if it is powered by adapter
I'm using Adafruit 16-Channel 12-bit PWM/Servo Shield with Arduino Uno controller
In setup() I have a number of default positions with PWM commands for motors with plug of USB to PC and turning on
I'm trying to figure out, how to avoid setup() commands, or any other signals during process to servos, in case if shield is not powered from power adapter, which is 6V 8Amp in my case, to not send signal to servo while it is not powered by power supply

Have you thought of using an input pin to sense the voltage of the power adapter? You only have to isolate it from Vcc with a diode (as long as the voltage of the adapter is not higher than the Unos 5V. In that case you also would need a voltage divider.

@chrisl Hello, and what is the program part in this case, since I need this condition in sketch code. It would be very useful to find some more detailed guide on this task

The only releveant code here is to use a value = digitalRead(pin_number). Youc an then do whatever you want with this, for exmple check in an if statement, if the result is HIGH or LOW by doing if(value){...} else {...}. I don't know, what I should write there in my answer.

@chrisl Yes, but I could not yet use this scheme to check result. As I've said below, it is not enough voltage with using of diode

I would propose a circuit like the following:

simulate this circuit – Schematic created using CircuitLab
The voltage divider (consisting of the resistors) will divide the 6V to 5V for the Arduinos digital input. The values are not critical, they can be made higher, but maintain the relationship to still get the 5V. The diode will prevent current to flow from the shield into the voltage divider, when the shield is powered through other means. Now you can simply do a digitalRead() on the corresponding digital input pin of your Arduino, to check, if the power was applied.

Please notice, that the diode will reduce the voltage a little by it's forward voltage (depends on the diode). But that shouldn't be a big problem.

Thank you for answer. Can you clarify, if this way I could monitor power to the servos using one of "digital input pins" with resistor divider to divide that down to 5v or less for the Arduino Uno, what is a difference of using "analog pin" in this case, I found number of close guides: 1. Measuring DC Voltage 2. Arduino Battery 3. Energy meter

From your question I assumed, that you use a normal power adapter, which means, that the 6V for the shield are already regulated beforehand. I think of a wall wart. In this case there are inly two possibilities: 6V or no voltage at all. Then the digital pin is sufficient. If you have a battery connected there and want to also sense the low voltage case, you can use an analog pin.

Hello, I could not yet use this scheme to check result. Something is incorrect for particular shield. I've soldered scheme exactly as you shown, 2 resistors 1.0 and 5.07, diode 1N4148. Without anything power jack shows 6.56V, shield turns on. Through scheme voltage runs from 6.29 to 6.52V, shield does not turns on, seems like it is not enough voltage

The shield should also work with voltages down to 5V. Is the green LED on the shield on? Does it work, if you bridge the diode? Is it mounted the right way? (Putting it in reverse will block the voltage to reach the shield)

Yes cathode (pole with black line) directed with output wire to the shield, should prevent flow from the shield into divider. Anode pole directed to 1kΩ resistor from plus. Voltage from VCC and GND runs 6.18, 6.29, 6.52V... Green LED on the shield off, shield does not works. Without scheme direct meter test shows 6.56V, green led on, shield works. I did not tried bridge the diode

The lower voltage shouldn't be a problem. Adafruit states directly, that you can use 5 or 6V and they suggest power supplies with 5V. The problem must lie somewhere else. Do you have motors connected at this time? If yes, try without any motors connected. If this works, the current may be too small

Your diode has a maximum of 300mA continous forward current. Depending on connected motors, that might not be enough.

Are you sure that the diode is needed? I use only one source of servo power. Also  it is quite  tiny, I'm not sure if it is  rated for sufficient current to drive a servo

I looked closer at the schematics and there seems to be no connection between Vcc and the servo power. Then it would be ok without the diode. Also you can test this: Check the voltage at the servo power  pins, when the external power is not connected. If there is 0V, you don't need the diode. I will update the answer with this

Sorry for late answer. Yes, without diode works as needed. Thank you for support


text:
Reducing static on button reading
I have a very simple code for a controller I'm working on for a robot.
void setup() {
  // put your setup code here, to run once:
  pinMode(3,INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}

The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.
Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

Is the GND correctly connected? Sounds like that's your problem

It sounds more like you have no pullup or pulldown resistor wired. When using pinMode(pin, INPUT_PULLUP), you are activating the Arduinos internal pullup resistor.

Sounds like you need a pull-down resistor.
If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.
Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.
If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.
(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting INPUT_PULLUP instead of INPUT when you configure the pin with the pinMode() function. That way you don't need an extra resistor.)
Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)


text:
how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees
I am currently working on a project which involves picking up plastic balls and depositing them in a box. I am trying to use a stepper motor to move an arm which is attached to a square piece of plywood which has Pringles cans on it. This is how I plan to collect the plastic balls.
The stepper motor needs to move the arm back and forth 180 degrees to collect and deposit the plastic balls. But I am unsure as to how to write the code to accomplish this as I am quite new to Arduino coding. Any form of help would be greatly appreciated. Thank you in advance.

you cannot move the arm 180 degrees until you know how to turn a stepper motor .... start with continuously moving the motor in both directions .... then learn how to move only a specific number of steps

Plenty of examples on the web already.  You can find these via a search engine.

There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

Arduino,
stepper motor,
stepper motor driver (like EasyDriver or some kind of Pololu drivers)
power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is example of EasyDriver). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply when you do not use microstepping). To spin motor 180 degrees you need 100 steps.
To summarise:

Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
DIR low (selecting one of directions)
STEP pulse 100 times (step motor rotates 180 degrees)
pause (for whatever needs to be done)
DIR high (opposite direction to rotate back)
STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)


text:
Looking for some help with an RGB LED animation
I'm working on a project that is running off of a Sparkfun Pro Micro 5V. I'm trying to accomplish a color rainbow cycle animation which will have a function when triggered to fade the rainbow to black and fade-in some white LED. I'm using a Adafruit RGBW Neopixel for this. I'm having trouble getting some code that does this as when I try to trigger my fade-out it's turning off faster than expected due to the way I wrote it. I'm hoping someone can point me to a piece of code or suggest an edit that will help.
Constraints for animation:

Must execute quickly (if at all possible avoid floats or other constructs that take a lot of time; relatively)
Be able to configure a maximum brightness set on initialization (0 - 255)
Must not have any "delay" or "while" loops that are designed to hold the code up.
When triggered by a button press the rainbow should fade to black (i.e. off) and previously off white LED should fade in.
When button pressed a second time white should fade out and rainbow starts or resumes.

I don't really care how the color animation works. It can cycle to/between specified colors or use whatever. To keep it simple what I tried was to have it just cycle RGB values with each 1/3 out of phase. My cycle includes a "dead" time where the color stays off for a part of the loop to keep the colors more distinct so they don't merge into white through color mixing. I specifically didn't use any sort of HSV conversion or sin/cos/whatever to calculate position in the cycle I am because those require a lot of calculation relative to incrementing a number.
Here is the code I wrote for your review. This has some servo control and the button checking and the LED in it. The bit at the very end is to prevent the pixels from updating during the time the servo pulses are being sent which prevents servo jitter due to the neoPixels.

#include <Servo.h>
#include <Adafruit_NeoPixel.h>

#define usToTicks(_us) (( clockCyclesPerMicrosecond()* _us) / 8)

class ColorCycle {
  private: int maxB;
  private: int offH;
  private: int stepD;
  private: int curD;
  private: int rVal;
  private: int gVal;
  private: int bVal;
  private: int wVal;
  private: int rHold;
  private: int gHold;
  private: int bHold;
  private: int wHold;
  private: bool rDir;
  private: bool gDir;
  private: bool bDir;
  private: bool wDir;
  private: bool showWhite;

  public: ColorCycle(int maxBrightness, int offHold, int stepDelay) {
      maxB = maxBrightness;
      offH = offHold;
      rVal = gVal = bVal = wVal = 0;
      rHold = 0;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      wHold = 0;
      rDir = gDir = bDir = true;
      wDir = false;
      stepD = stepDelay;
      curD = 0;
    }

    void moveStep() {
      moveSteps(1);
    }

    void moveSteps(int count) {
      if (count == 1) { //going to skip the delay if you are trying to move more than one step intentionally.
        if (curD > 0) {
          curD--;
          return;
        }
        curD = stepD;
      }

      for (int s = 0; s < count; s++) {
        if (showWhite) {
          whiteHold();
          wDir = true;
        } else {
          wDir = false;
        }

        //setting the direction and holds when appropriate
        if (rVal == 0)
          rDir = true;
        if (rVal == maxB) {
          rDir = false;
          rHold = offH;
        }

        if (gVal == 0)
          gDir = true;
        if (gVal == maxB) {
          gDir = false;
          gHold = offH;
        }

        if (bVal == 0)
          bDir = true;
        if (bVal == maxB) {
          bDir = false;
          bHold = offH;
        }

        //stepping the values
        if (rDir && rHold == 0)
          rVal++;
        if (!rDir && rVal > 0)
          rVal--;
        if (rVal == 0 && rHold > 0) {
          rHold--;
        }

        if (gDir && gHold == 0)
          gVal++;
        if (!gDir && gVal > 0)
          gVal--;
        if (gVal == 0 && gHold > 0) {
          gHold--;
        }

        if (bDir && bHold == 0)
          bVal++;
        if (!bDir && bVal > 0)
          bVal--;
        if (bVal == 0 && bHold > 0) {
          bHold--;
        }

        if (wDir && wVal < maxB)
          wVal++;
        if (!wDir && wVal > 0)
          wVal--;
      }
    }

    int getRedValue() {
      return rVal;
    }
    int getGreenValue() {
      return gVal;
    }
    int getBlueValue() {
      return bVal;
    }
    int getWhiteValue() {
      return 0;
    }

    void setShowWhite(bool sw) {
      showWhite = sw;
    }

    void whiteHold() {
      rHold = 5;
      gHold = (maxB + offH) * .5;
      bHold = (maxB + offH);
      rDir = gDir = bDir = false;
    }
};

#define BUTTON_LED_PIN 16
#define BUTTON_SWITCH_PIN 14

Servo lidServo;
int lidServoPosition;
Servo leftServo;
int leftServoPosition;
Servo rightServo;
int rightServoPosition;

#define LID_LED_CONTROL_PIN 3
#define LID_LED_COUNT 8
Adafruit_NeoPixel lidPixel(LID_LED_COUNT, LID_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccLid(50, 50, 10);

#define BASE_LED_CONTROL_PIN 4
#define BASE_LED_COUNT 8
Adafruit_NeoPixel basePixel(BASE_LED_COUNT, BASE_LED_CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
ColorCycle ccBase(50, 50, 10);

void setup() {
  pinMode(BUTTON_LED_PIN, OUTPUT);
  digitalWrite(BUTTON_LED_PIN, LOW);
  pinMode(BUTTON_SWITCH_PIN, INPUT);
  lidServo.attach(5);
  leftServo.attach(6);
  rightServo.attach(9);
  lidPixel.begin();
  lidPixel.show();
  basePixel.begin();
  basePixel.show();

  Serial.begin(9600); //This pipes to the serial monitor
  Serial.println("Starting");
}

void loop() {
  if (digitalRead(BUTTON_SWITCH_PIN) == true)  {
    digitalWrite(BUTTON_LED_PIN, HIGH);
    lidServoPosition = 0;
    leftServoPosition = 0;
    rightServoPosition = 0;
    ccLid.setShowWhite(true);
    ccBase.setShowWhite(true);
  } else {
    digitalWrite(BUTTON_LED_PIN, LOW);
    lidServoPosition = 180;
    leftServoPosition = 180;
    rightServoPosition = 180;
    ccLid.setShowWhite(false);
    ccBase.setShowWhite(false);
  }
  lidServo.write(lidServoPosition);
  leftServo.write(leftServoPosition);
  rightServo.write(rightServoPosition);

  ccLid.moveStep();
  ColorCycle tempCc = ccLid;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    lidPixel.setPixelColor(i, lidPixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  ccBase.moveStep();
  tempCc = ccBase;
  for (int i = 0; i < lidPixel.numPixels(); i++) {
    basePixel.setPixelColor(i, basePixel.Color(tempCc.getGreenValue(), tempCc.getRedValue(), tempCc.getBlueValue(), tempCc.getWhiteValue()));
    tempCc.moveSteps(10);
  }

  if (TCNT1 > usToTicks(8192)) {
    lidPixel.show();
    basePixel.show();
  };
}

You are updating the LEDs in a timed way through TCNT1, but the setting of the pixels is not part of that, so that will be done very fast. I think, that code should also be timed. Then you only change the values, when you are really updating the colors.

The TCNT1 timer is only used to make sure that the "show" command doesn't execute during a servo update as this would cause servo jitter.

You are writing your code non-blocking, but you don't introduce any way of timing code. This way the calculation of the new color values happens as fast, as the code can run. You can write timed action in a non-blocking way by using the coding style from the BlinkWithoutDelay example, that comes with the Arduino IDE. Then the LED code will only be executed, if the correct time has come. You save a timestamp of the last calculation execution in a global variable  and then check, if enough time since then has passed. Only then you again execute the calculation and update your timestamp.
unsigned long timestamp = 0;
unsigned int interval = 10;

void loop(){
    //--------
    // Omitted the servo code
    //--------
    if(millis() - timestamp > interval){
        timestamp += interval; // update the timestamp to the next value
        //--------
        // Omitted the calcuation and the LED update (show() method)
        //--------
    }
}

Note, that here I used millis(), which will return the number of milliseconds, that passed since the Arduinos startup. I used an interval of 10 milliseconds, so that the LEDs will be updated every 10 milliseconds. You can change this value as you need it (also during the code execution). If you need faster execution, than a few milliseconds, you can use micros() instead of millis(), so that you work with microseconds. Of course, you cannot get faster, than the rest of the code runs.
For further explanation of this principle, you can google it. It has been described numerous times on the web and on this site.


text:
Arduino yes! and after?
I am new to electronics and am currently working with an Arduino UNO. I know the basics of PCB manufacturing (Besides, I'm fiddling with mine, very basic of course) Anytime I'm curious about how to get from Arduino to a finished PCB with the same result only on my Arduino prototype?
For example, my project has several components such as leds, An RFID module, a TFT LCD Shield 3.5 ", another 240x320 OLED screen ... How to put all this on a printed circuit board?
Do I need to solder the same components to my PCB?
-Do I need to run my Arduino code on my PCB once it is assembled?
-.......................................

put it all in a box

No, I want my own PCB without Arduino inside! Arduino just serves me for prototyping and see how it all works. I just wanted to know about my program for example my RFID module on an Arduino and then I want to wear it on my PCB how to do it without Arduino is integrated into the device I want to create!

A printed PCB can be used to place your components on (typically resistors, ICs, capacitors etc).
However, if you want to connect an LCD or big components, it would be a waste of space for your PCB. So in that case, I guess the best way is to create an enclosure where your displays fit in (and your RFID module if it is big too), and create some kind of connector from the PCB (e.g. using a terminal block or other way) and connect it to your displays.
On your PCB also an Arduino needs to be added, I guess the best solution is to use the Arduino chip (AtMega328P probably), and some external circuitry needed. Optionally using an IC socket in case you want to change the program later on.
On some Arduinos you can take out the AtMega328 DIP28 IC from your Arduino Uno board. Program it, than place it in the socket on your PCB board.
Update
Maybe you can use an Arduino Micro or Nano and place that directly onto your PCB (with headers preferably). Than you get something like below:

is there any way to make my own 100% PCB without component but that works exactly like my prototype on Arduino?

What do you mean without component? Without components like resistors/capacitors/etc? Or without an AtMega IC? For the first, I doubt, for the second, that depends if you can convert your software code into hardware components; if your code is using a library or has some formulas or using a communication protocol, it will be very hard. There are very many transistors in your AtMega and you don't want to copy those with separate components... What is the problem using an AtMega on your PCB?

Did you think about using e.g. an Arduino Nano or Micro instead? Than you can place one of those directly on your PCB (with a socket preferably).

I have no problem inserting an AtMega chip on my PCB it's just that I thought I could program my own microcontroller! I do not think the PCBs we have (those of our old electronic devices do not have arduino micro or nano inside). So I told myself that I could program everything myself but my concern is that it will work as well as my prototype or I will have things changed!

I doubt it will be easy to make your own microcontroller .... if you post your sketch someone can check if it is feasible.

Ok thank for all!

" Optionally using an IC socket in case you want to change the program later on."
No need, put an FTDI header on for serial programming, or put an ICSP header on and use a Programmer to program via the SPI pins.
Making your own PCB is very straightforward. I use EAGLE CAD software and design boards all the time. To duplicate a Promini for example, one only needs a '328P, 16 MHz xtal, two 22pF caps, 4 0.1uF caps, and a 10K resistor.  Then the 2 headers for convenient bootloading and/or programming.  Bootload and program it just like it was an Uno.

Thanks for this very good alternative, upvoted.


text:
Can't connect my ESP-12F to WiFi with my Arduino Uno
Recently I bought this wifi adapter for my IOT projects that I connected to my arduino uno that seems to not working.
I have tried with the arduino ESP8266WiFi library with RX connected to pin 0 and TX connected to pin 1 I have also tried the softwareSerial and still the same result that is, in the serial monitor i always get "error" or I get nothing
Thank you in advance and sorry if I made a mistake in the post, I am new to StackExchange :)
edit (added code to question):
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications
  Serial.begin(115200);
  // set the data rate for the SoftwareSerial port
  // if this doesnt work you for you then try different baud rate
  ESPSerial.begin(115200);
  ESPSerial.println("Ready to take AT commands");
}

void loop() { // run over and over
  if (ESPSerial.available()) {
    // reads input from serial console and writes to esp8266
    Serial.write(ESPSerial.read());
  }
  if (Serial.available()) {
    // reads input from esp8266 and writes to serial console
    ESPSerial.write(Serial.read());
  }
}

Please add your source code as text to your post and what is your expected output? Also please tell us for which board the shown code is.

did you set in Serial Monitor the line ends?

@TarickWelling I am using arduino uno and I was expecting to enter some at commands.

gpo0 goes to ground to program the module


text:
Why I am connecting positive wire in the circuit?
I have constructed a simple fade in and fade out circuit similar to given on this website https://roboindia.com/tutorials/arduino-analog-output-led-fade Now I am connecting a wire from 5V power pins to +ve side line, but i don't know why I am doing this because when I remove this wire or connect it to 3.5V pin the led is still running fine. Also as side lines are connected horizontally there is no other further connection given to the +ve wire. Can you tell me why I am joining the wire?

You should include the diagram in the questions, so that people can see which wire you're talking about without following the links.

This is indeed not needed. As you can see in the diagram, the horizontal line which you connected the 5 V pin to.
The horizontal line of holes just above the red horizontal line) are connected. However, since it only connected to the 5V pin of the Arduino, the all pins on that horizontal line have 5 V, but since there is nothing connected to it (thus no closed circuit), the effect is zero.
The reason why the connection is made (the wire from Arduino to 5V), is that it is 'default' to connect both GND and 5V (or 3.3V) as a starting point. It is easy to forget later and than no current will flow when you connect something to the +5 V horizontal line of pins.
Btw, the 3.5 V pin you mention, is 3.3 V, not 3.5 V.


text:
Code for two bulb fading alternatively
I have written this code
const int A = 3;
const int B = 5;
void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);

}

void loop() {
  for(int i=1;i<=255;i++)
  {
    int j =255-i;
    analogWrite(A,i);
    analogWrite(B,j);
    delay(100);
  }
  for(int i=255;i>0;i--)
  {
    int j =255-i;
    analogWrite(B,j);
    analogWrite(A,i);
    delay(100);
  }
}

Is  this code correct? If yes then can it be modified in any way to make it better?

Other than a little asymmetry, I don't think I see a problem (i goes from 1 to 255 while j goes from 0 to 254).  Why?  Is it not working?

The pins you picked should work on most Arduino boards.  But when asking these types of question you should list what Arduino board type you are using.

Define "better". Your code uses delay, which is OK if your code has nothing else to do, but completely unacceptable if your code will be used in context of other code. Is this something that you want/need to make "better" or not?

Depending on what effect you want to achieve, you might want to add gamma-correction.

To keep the two loops more symmetrical, let the first loop go from 0 until 254: [0 .. 255) and the second loop from 255 to 1: [255 .. 0), so both iterations have 255 values each.
Also, it is quite common in programming to include the start element, and not include the end element (as in the values above: [start_element .. end_element).
Also, for the simple formula (255 - i), I would leave out the formula. And to make things more clear define constants for the min/max values (0,255) and the delay.
Than you get:
const int A = 3;
const int B = 5;

const int MIN_INTENSITY = 0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
}

void loop()
{
  for(int i = MIN_INTENSITY; i < MAX_INTENSITY ; i++)
  {
    analogWrite(A, i);
    analogWrite(B, MAX_INTENSITY - i);
    delay(DELAY_TIME);
  }

  for(int i = MAX_INTENSITY ; i > MIN_INTENSITY; i--)
  {
    analogWrite(B, MAX_INTENSITY - i);
    analogWrite(A, i);
    delay(DELAY_TIME);
  }
}

By making a function and use arguments for the variable values, and create some better names for constants and variables you get this:
const int LED_1_PIN     =   3;
const int LED_2_PIN     =   5;

const int MIN_INTENSITY =   0;
const int MAX_INTENSITY = 255;
const int DELAY_TIME    = 100;

void setup()
{
  pinMode(LED_1_PIN, OUTPUT);
  pinMode(LED_2_PIN, OUTPUT);
}

void loop()
{
  fade(MIN_INTENSITY, MAX_INTENSITY,  1);
  fade(MAX_INTENSITY, MIN_INTENSITY, -1);
}

void fade(int startIntensity, int endIntensity, int stepValue)
{
  for(int intensity = startIntensity; intensity < endIntensity; intensity += stepValue)
  {
    analogWrite(LED_1_PIN, intensity);
    analogWrite(LED_2_PIN, MAX_INTENSITY - intensity);
    delay(DELAY_TIME);
  }
}