text:
Driving a servo with an ATTiny13A
So, I managed to fry my cheap servo/ESC (electronic speed controller) and decided to make my own using an ATTiny13A on some perfboard. But, I have run into some issues getting the servo to respond.  I'm assuming the servo.h library is not compatible with the ATTiny13A because of incompatible internal clock speeds not creating the right PWM signals. And I haven't found a solution for this.
I have messed around with the Servo8Bit.h library, but this also doesn't seem to work (as its designed for the ATTiny45 and the ATTiny85 ). Is the ATTiny13A even able to produce the needed PWM signals?
Any help/links to documentation would be appreciated!
Thanks in advance.
Code:
#include <Servo.h>

Servo myservo;
int potpin = A3;
int val;    // variable
int Toggle = 2;

void setup() {
  Serial.begin(9600);
  pinMode(Toggle, INPUT);
  myservo.attach(1);  // Servo/ESC is attached to pb1
}

void loop() {
  int ToggleState = digitalRead(Toggle);
  Serial.println(ToggleState);
    val = analogRead(potpin);

  if (ToggleState == 0) {
  val = map(val, 0, 1023, 0, 180);  //Servo motor
   myservo.write(val);
  delay(15);
}
else {
  val= map(val, 0, 1023,1000,2000); //ESC
  myservo.write(val);
  delay(15);
 }
}

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an 8-bit timer. It should not be too hard to port this library to that micro. Study the source code, then study the datasheet of the tiny13A (mostly the chapter dedicated to the timer). You should then be able to easily see what changes are needed.

Are you sure, that the ATtiny is actually running at the frequency you think it does? I did have timing problems with my ATtiny85, whem trying to use it with 8MHz. The fuses actually were still set for 1MHz. I first had to burn the bootloader to set the fuses correctly.

does a blink sketch run at an expected speed?

Servo8Bit and ATTiny13(A)
I had a look at the Servo8Bit and had pretty much the same thoughts on this as Edgar Bonet in his comment:

Servo8Bit relies on an 8-bit timer, and the ATtiny13A does have an
8-bit timer. It should not be too hard to port this library to that
micro. Study the source code, then study the datasheet of the tiny13A
(mostly the chapter dedicated to the timer). You should then be able
to easily see what changes are needed.

Ignoring the timing differences between the ATTinyx5 and ATTiny13(A), I just went ahead and saw if I could get it to compile.  And yeah, it's pretty easy to compile.  This mostly consists of adding 0 to some hardware register names.  The bad news is:

Sketch uses 1486 bytes (145%) of program storage space. Maximum is 1024 bytes.
Global variables use 31 bytes (48%) of dynamic memory, leaving 33 bytes for
local variables. Maximum is 64 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
Error during build: text section exceeds available space in board

So, yeah, that was a bit much to hope for, I guess.  The library does use ISRs to support a number of servos kind of like the more common servo library that you'd use on an UNO.  I haven't looked into chopping it down to size; I expect that will be impractical.
PWM... sort of.
Prior to considering modifying Servo8Bit, I kind of thought it made sense to just use the timer counter directly to produce a waveform.  The problem is the conventional servo signal is 20ms long, and does all of its control in a 1ms window.  If you try to fit the whole 20ms frame into a single 8bit timing interval, what you end up with is pretty crappy angular control.  So, doing it is a bit painful without a 16-bit timer counter.  But, I guess that's the game.
So, the below is a crude and barely tested attempt at it.  The code that follows is state machine inside the OCR0B overflow vector that schedules the rising an falling edges is "normal" mode.  Just to warn you, I don't actually have an ATTiny13(A) on hand.  And in fact I don't happen to have a servo hand either.  But I do have an ancient storage scope and an ATTiny85 and the ability to compile for ATTiny13(A), and a calculator for working out the 8 MHz vs 9.6 MHz difference.
So here's what I came up with, which I think (but don't know) will work if you compile and upload using MCUDude MicroCore, ATTiny13(A) with the 9.6 MHz internal oscillator chosen.
It's only designed to operate 1 servo.  Extending it to two should be easily doable.  Going beyond that you're likely run into problems.
Code:
// +---------------------------------------------------------------------------------------+
// |                                                                                |
// |                                 +-------------+                                       |
// |                                 |             |                                       |
// |                                 |      A      |                                       |
// |  PCINT5 ADC0 dW  /RESET  PB5 *--|-1    T    8-|--* VCC                                |
// |                                 |      T      |                                       |
// |  PCINT3 ADC3      CLKI   PB3 *--|-2    I    7-|--* PB2  SCK   ADC1 T0         PCINT2  |
// |                                 |      N      |                                       |
// |  PCINT4 ADC2             PB4 *--|-3    Y    6-|--* PB1  MISO  AIN1 OC0B  INT0 PCINT1  |
// |                                 |      1      |                                       |
// |                          GND *--|-4    3    5-|--* PB0  MOSI  AIN0 OC0A       PCINT0  |
// |                                 |      A      |                                       |
// |                                 |             |                                       |
// |                                 +-------------+                                       |
// |                                                                                |
// +---------------------------------------------------------------------------------------+

#if !defined(__AVR_ATtiny13__) && !defined(__AVR_ATtiny13A__)
#error This code is written specifically for ATTiny13(A) devices.
#endif

#if F_CPU != 9600000
#error  This code is written specifically for 9.6 MHz
#endif

//
//
//
#include <avr/io.h>
#include <avr/interrupt.h>

//
//
//
constexpr uint8_t TCCR0A_config(
  int com0b // two bits
) {
  return
      (    0 << COM0A1) // normal
    | (    0 << COM0A0) //   port operation
    | (com0b << COM0B0) // bits 5 AND 4
    | (    0 <<      3) // reserved
    | (    0 <<      2) // reserved
    | (    0 <<  WGM01) //  lower two bits
    | (    0 <<  WGM00);//     of Normal (mode 0);
}

//
//
//
constexpr uint8_t TCCR0A_config_for_go_low()  {return TCCR0A_config(0x2);}
constexpr uint8_t TCCR0A_config_for_go_high() {return TCCR0A_config(0x3);}

//
// 50 Hz (hobby servo frame frequency); period 20 ms
//
// In the below you'll see the numbers 150 and 300 and 3000.
// The reason for these numbers is that I've chosen to to use a /64
// timer prescaler.  At 9.6 MHz, with a /64 prescaler, 1 millisecond
// is 150 timer timer counts.  There's as fixed 1 MS high in the servo,
// followed by 0 to 1ms variable portion.  The number 150 helpfully
// fits within the 8-bit timer registers and also gives a reasonable
// number of increments to the servo control.  For 180 degrees, 150 increments
// is 1.2 degrees.
//
// The maximum high time is the fixed 1ms high time and the maximum
// variable high time, totalling 2 MS, or 300 timer ticks, that's what that
// number is about.
//
// 3000 is the number of timer ticks for a full 20ms signal frame,
// that is 20 * 150 = 3000.
//
//
// Deriving the 150 figure:
//
//  At 9.6 MHz and /64 prescaler
//
//        1 second         64 mcu_cycles   A_MS_DURATION timer_counts
//  -------------------- X ------------- X ---------------
//  9_600_000 mcu_cycles   1 timer_count    0.001 seconds
//
//
//       1      64    A_MS_DURATION
//  --------- X -- X  -----
//  9_600_000   1     0.001
//
//
//     64       A_MS_DURATION
//  --------- X -----------
//  9_600_000      0.001
//
//
//     64 x A_MS_DURATION
//  --------------------
//        9_600
//
//
//  A_MS_DURATION
//  -------------
//      150
//

static constexpr uint8_t  ONE_MS_WORTH_OF_TICKS    = 150;
static constexpr uint8_t  MAXIMUM_HIGH_PERIOD      = ONE_MS_WORTH_OF_TICKS * 2;
static constexpr uint16_t TWENTY_MS_WORTH_OF_TICKS = 3000;
static constexpr uint16_t MAX_WASTE_CYCLES         = 0x80;

static volatile uint8_t g_pulse_width = ONE_MS_WORTH_OF_TICKS / 2;  // default to mid-range.

ISR(TIM0_COMPB_vect) {
  static uint8_t l_pulse_width; // this caches g_pulse_width
                                // and is updated from g_pulse_width
                                // only between frames

  //
  // The ISR is a state machine with four macro states.
  //
  enum class t_signal_generator_state : uint8_t {
    timing_to_variable_high_period,
    timing_to_set_pulse_width,
    calculate_time_to_start_of_next_pulse_and_waste_a_bit,
    timing_to_start_of_pulse
  };

  //
  // Macro state variable
  //
  static t_signal_generator_state g_signal_generator_state =
    t_signal_generator_state::timing_to_variable_high_period;

  // low_time_remaining is an extended state variable
  // for the timing_to_start_of_pulse state
  static uint16_t low_time_remaining;

  switch (g_signal_generator_state) {
    case t_signal_generator_state::timing_to_variable_high_period:
      // We just went high at the OCR0B value that triggered this interrupt
      // and we need to retrigger ((MAXIMUM_HIGH_PERIOD==300) - 256 == 44)
      // timing cycles later such that there are 256 timing cycles left of the
      // 2ms (maximum) high part of the frame.
      OCR0B += (MAXIMUM_HIGH_PERIOD - 256);  // 2ms worth of timer nicks minus the resolution of our timer

      // We're remaining HIGH as we head into the variable portion of the HIGH period.
      g_signal_generator_state = t_signal_generator_state::timing_to_set_pulse_width;
      break;
    case t_signal_generator_state::timing_to_set_pulse_width:
      // We're retrieving the global variable which holds a (potentially new) value from 0 to 150
      // representing a span of 0ms to  1ms (the full range of the servo), but
      // we're starting out the variable pulse a head of time, part way through the always-on first ms.
      // There are (150 - 44) timer cycles, that's 1 ms worth of timer cycles
      // where the timer remains high to finish out first millisecond of HIGH.
      // So we add this to the requested variale pulse width time.
      l_pulse_width = g_pulse_width + (ONE_MS_WORTH_OF_TICKS - 44);

      // Set adjust pulse width
      OCR0B += l_pulse_width;

      // We'll be going low and the end of the variable high period.
      TCCR0A = TCCR0A_config_for_go_low();

      g_signal_generator_state = t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit;
      break;

    case t_signal_generator_state::calculate_time_to_start_of_next_pulse_and_waste_a_bit:
      // We just went low at the OCR0B value.

      // Calculate remaining timer cycles to the beginning of the next pulse
      // accounting for the MAX_WASTE_CYCLES we're about to waste in this state.
      low_time_remaining = (TWENTY_MS_WORTH_OF_TICKS - 44 - MAX_WASTE_CYCLES) - l_pulse_width;
      OCR0B += MAX_WASTE_CYCLES;

      // We will remain LOW since the pulse is done and we've not finished out the 20ms period
      g_signal_generator_state = t_signal_generator_state::timing_to_start_of_pulse;
      break;

  case t_signal_generator_state::timing_to_start_of_pulse:
      // Continue retriggering the timer until we've used up 20ms total,
      // in increments of not more than MAX_WASTE_CYCLES.

      if (low_time_remaining > MAX_WASTE_CYCLES) {
        low_time_remaining -= MAX_WASTE_CYCLES;
        OCR0B += MAX_WASTE_CYCLES;
        // We'll need to wast more, so we're remaining LOW.
      } else {
        OCR0B += low_time_remaining;
        low_time_remaining = 0;

        // This is out last round through this state to finish out the 20ms
        // window, so we'll be returning to HIGH.
        TCCR0A = TCCR0A_config_for_go_high();

        g_signal_generator_state = t_signal_generator_state::timing_to_variable_high_period;
      }
      break;
  }
}

//
//
//
void servo_init() {
  const auto SREG_saved = SREG; cli();

  DDRB |= 1U << 1;  // Servo data pin attached on Attiny PB1 aka (OCR0B)

  // select no clock source / stop counter
  TCCR0B &= ~(
      (1U << CS02)
    | (1U << CS01)
    | (1U << CS00)
  );

  // reset counter
  TCNT0 = 0x00;
  OCR0B = 0x80;

  TIMSK0 =
      (0 <<      7) // reserved
    | (0 <<      6) // reserved
    | (0 <<      5) // reserved
    | (0 <<      4) // reserved
    | (1 << OCIE0B) // we *ARE*  using output-compare B interrupt
    | (0 << OCIE0A) // we aren't using output compare A interrupt
    | (0 <<  TOIE0) //             nor overflow interrupt
    | (0 <<      0);// reserved

  TIFR0 = 1U << OCF0A;

  TCCR0A = TCCR0A_config_for_go_high();

  TCCR0B =
      (0 << FOC0A) // We're not doing any
    | (0 << FOC0B) //   output compare forcing.
    | (0 <<     5) // Reserved.
    | (0 <<     4) // Reserved.
    | (0 << WGM02) // High order bit of Normal mode (0)
    | (0 <<  CS02) // Clock source
    | (1 <<  CS01) //    prescaled
    | (1 <<  CS00);//      by 64.

  SREG = SREG_saved;
}

//
//
//
void setup() {
  servo_init();
}

//
//
//
void loop() {
  for (g_pulse_width = 0; g_pulse_width < 150; ++g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
  for (; g_pulse_width > 0; --g_pulse_width) {
    __builtin_avr_delay_cycles(F_CPU >> 5);
  }
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:

On the scope, this produces servo signal that should sweep a servo on pin OCR0B (PB1).  Something like 4 to 5 seconds going one way and same going back.
If I put an ATTiny13A on an order sometime and manage to dig out a servo myself, I'll actually test it.  It may be a very long time before I can do that though.  But the results on the scope look good.  Admittedly everything is scaled by 9.6/8.0.  It should be accurate on a ATTiny13(A).  I verified that it compiles for it.  The workings of the thing are explained in the code as I can.
For comparison:

Sketch uses 490 bytes (47%) of program storage space. Maximum is 1024 bytes.
Global variables use 10 bytes (15%) of dynamic memory, leaving 54 bytes for local variables. Maximum is 64 bytes.

That's still a good chunk of what little code space you have, but it should be enough to read a switch and potentiometer.  This is using the timer the device has, so millis()/delay() usage are kind of out-the-window, I think, I didn't try to see what happen when you call them or study their code in MicroCore.  You could recreate your own millis() by making a timer overflow interrupt and it would overflow at about 1.7 ms intervals.  As you can see, I just used __builtin_avr_delay_cycles to keep things simple.
If you, or anyone else, gets it working on at ATTiny13 before I try it myself, I'm curious to know that it worked (or didn't).

+1. A few comments: 1. MAX_WASTE_CYCLES = 256 would reduce the interrupt load and remove the need for OCR0B += MAX_WASTE_CYCLES;. 2. Possible race condition: if low_time_remaining is 1 and the interrupt is slow or delayed, TCCR0A could be updated too late. This could be mitigated by putting the variable part of the low time (low_time_remaining % MAX_WASTE_CYCLES) at the beginning of the low period. 3. The include file <util/delay.h> provides a macro for writing the fixed delay in a more convenient form: _delay_ms(32.25);. The generated code is the same.

Yeah, I was considering bumping MAX_WASTE_CYCLES all the way up (and probably giving it a better name). The original plan, I think, was to find a value to advance OCR0B by that such that the final pass through the that state somewhere TCNT0 and OCR0B half the timer ticks (0x80) ahead the rising edge, so it was scheduling that rising at at a more idea moment. So that constant was supposed to be something like FINAL_APPROACH_LENGTH_TO_HIGH_EDGE, but I just never got to doing that.  That sounds like what you're describing with the modulus.

I was hoping to find a way to do without without division (modulus), like find some happy medium that was close enough on both extremes.  But yeah, the way it is now it probably makes more sense to put it all the way up to 0xFF.

Modulus 256 is cheap: it is achieved automatically by casting low_time_remaining to uint8_t.

I'm aware with regard to modulo 256.  I'm probably not explaining myself well or I'm just not awake enough to be thinking about it.  When I get back into looking at the code, I'll look at your comments again, and it may get updated in exactly the way you're thinking.  I don't have that much time into that part of the problem, to the point where you may have actually spent more time thinking about than I have.


text:
Arduino Due Digital Inputs without Response
On two of my Arduino Due, when connecting the pin 3.3V to any digital inputs (37,36,35,34), no serial message nor LED_BUILTIN is thrown as output, only the Test message.
Digital Pins are set as INPUT by default. Blink works.
I have never connected any other thing on those pins, even 5V.
What I am missing?
void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(LED_BUILTIN,OUTPUT);
    Serial.print("Test");
}

void loop() {
    if (digitalRead(37))
        Serial.print("37");
    if (digitalRead(36))
        Serial.print("36");
    if (digitalRead(35))
        Serial.print("35");
    if (digitalRead(34))
        Serial.print("34");
    digitalWrite(LED_BUILTIN,digitalRead(37));
}

No. They are not defined as INPUTs by default (??).

And if you manually set those pins to INPUT, does it start working?

Yes... that was the problem...

I am guessing that, since those pins are also PWM pins, the alternate function was stuck in PWM mode until you manually forced it to change. Possibly from some earlier sketch or something. I don't know the SAM chips well enough to know how the pin functions work.

A good practice is to set the pin mode for all the pins used by the sketch.
void setup() {
    Serial.begin(115200);
    while(!Serial);
    pinMode(34, INPUT);
    pinMode(35, INPUT);
    pinMode(36, INPUT);
    pinMode(37, INPUT);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.print("Test");
}

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.
Cheers!

source: Stack Exchange

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

sort: votes


text:
Serial Port fails with speeds greater than 19200
In Arduino Mega 2560 R3, properly selecting the Serial Monitor bauds, this code works with #define R 38400, but for some reason, not with #define R 19200 (?),

#define R 38400
int rate=R;
HardwareSerial* hwSerial[]={&Serial,&Serial1,&Serial2,&Serial3};
void setup() {
    for (int i=0;i<=3;i++){
        hwSerial[i]->begin(rate);
        while (!hwSerial[i]);
    }
    hwSerial[0]->print("Hello World");
}

void loop() {
}

Both speeds should be not problematic for Arduino, what is happening?
It seems the int rate R; is problematic when changing speeds (??).

19200 is OK and 38400 fails? int can't hold 38400

Yes. And int RATE=38400; fails but #define RATE 38400 works (??)

@Juraj That is the solution... Thanks...

I made the same mistake  few days ago. Took mi 10 minutes to realize

Answer is simple. You assign 38400 to a variable of type int. The signed range of integer values that can be stored in 16 bits is −32,768 through 32,767;

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


text:
Do I need an Microchip ATSAM3X8E Evaluation Kit?
I am intending to use the Arduino Due processors into my own designs. We have a very extensive (dozen of thousands of lines in .c code) sets of Arduino Due functional codes, and now I intend to move into a more solid form shape.
I have the following questions. What i need is some sort of feedback in order to answer those by myself and realize how to proceed.

I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E? R: No, they are the same.

I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E? R: No, they are the same.

As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

If my concern about High Speed Serial is real, how should I evaluate it?

Aren't the chips from Microchip and Atmel now the same, since Microchip bought Atmel quite a while ago?

@chrisl Should but, I am not absolutely sure about real differences for me as user. If there are differences.

there is no difference because it is the same product. only the owner of the factory changed. so please remove this part of the question to make it clearer

@Juraj. Thanks for your clarification. I marks these questions as answered, i did not delete since somebody answered that.

I understand some of the Fast Speed Serial options in the Microchip IC cannot be tried in the Arduino Due (such as USBOTG?)?. What I actually need is some Serial Speed close to 2Mbps and a USB Programming Port.

What would make you think that? The chip is the chip regardless of what board it's soldered to. You have the native USB and you have all the UART connections direct to the chip. The board has no effect on that at all.  2Mbps is nothing. You can go much faster than that.

Which are the main differences between the Microchip ATSAM3X8E and the Atmel ATSAM3X8E?

The label. When Microchip bought Atmel a few years back they bought everything. That includes the Malaysian factories where the Atmel chips are made (a friend of mine had the job of inventory combining and spent quite some time in Malaysia sorting it all out). Microchip ATSAM3X8E chips are made in the same factory by the same people to the same designs on the same machines. It's just they are now labelled "Microchip" instead of "Atmel".

I notice there are some functionalities in the Microchip ATSAM3X8E or even in the Atmel ATSAM3X8E not able to be reproduced in the Arduino Due Board?

Is that a question or a statement. Or aren't you sure? The Due is just a chip on a board with some support circuitry. Everything that is in the chip is there, you can't remove it. There may be the case that a specific pin may not be brought out to a header, but you will have to compare the datasheet with the schematic in that case. The chip is not at fault here.

Do The Microchip ATSAM3X8E IC have its own functionalities not present in the Atmel ATSAM3X8E?

No. The two are 100% identical.

As note, there is a Keil ARM SAM3X-EK Evaluation Kit (also also here with its brochure), with a ATSAM3X8H, which is not the same IC series, but somehow exposes my concern (if real).

The ATSAMA3X8H is not commercially available. It was a specific custom chip made only for the SAM3X-EK kit. It is, essentially, a SAM3X8E with more IO pins and the ability to connect to SDRAM.

If my concern about High Speed Serial is real, how should I evaluate it?

Your concern is not real. Only imagined. The only possibility is that the UART to USB chip used on the Due may not be able to keep up at high baud rates. That has nothing to do with what the SAM3X8E can do, just what the interface to your PC is capable of. You can replace that with an external USB to UART interface if you want, such as an FT232R based interface. That is if it's communication with your PC that you're concerned about, in which case you would be better with the native USB interface as it's not restricted by whatever external hardware is added.

Thank you for all your answers and detailed clarifications.

Open Question: https://arduino.stackexchange.com/questions/72127/sam3x8e-maximum-serial-speed


text:
How to use a variable format in `sprintf`
How should I make a variable format sequence for sprintf?.
int i=2,d=9;
String sf;
sprintf(sf,"%%0%d",i);
fprintf(sf,d);

While expecting the output.
09

The compilation fails, with several errors, according the failing change I apply.
Invalid cast from type 'String' to type 'char*'

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

Hint: Try char sf[32]; and then correct the rest.

sprintf cannot be used to write data into String objects. More precisely, it is possible to come up with a "hackish" way to write the result directly into a String object, but the latter is definitely not designed for such use.
The target buffer should be an array of char, not a String. Which is what the compiler is telling you.
char buffer[64];
sprintf(buffer, "%%0%d", i);

or better
char buffer[64];
snprintf(buffer, sizeof buffer, "%%0%d", i);

The format string you used in your sprintf will generate %02 result (since i contains 2 at that moment). Why you are expecting 09 is not clear. Why are you expecting the % character to disappear is not clear either, considering that the format string seems to be deliberately designed to include it.
A String object cannot be used as the first parameter of fprintf. It is not clear what that fprintf is doing in your code.

Apparently you are trying to use sprintf to generate another format string at run time (using i as field width), which is later used to output the d variable. In that case that would be something like
char format[16];
snprintf(format, sizeof format, "%%0%dd", i);
fprintf(file, format, d);

That fprintf will indeed output 09.


text:
Adafruit Datalogger and Bluefruit LE issues
I'm having issues using the Adafruit Bluefruit LE shield at the same time as the Adafruit Datalogger shield. I can use either shield independently without issue. When I stack the two, I can talk with the SD card and the RTC on the datalogger, however, the Bluefruit fails all communication.
The Bluefruit is powered and I can connect to it via Bluetooth, however, it does not communicate with the Arduino at all.
I'm assuming there is a conflict over SPI, but I can't figure out the root cause. The SD chip select is 10. The Bluefruit chip select is 8. I have put 100 kΩ pullup resistors on both chip select pins, but that did not resolve the issue.
I've tried shield specific example sketches to remove coding / memory issues as a cause. These sketches work great until the shields are stacked. Once stacked, the Bluefruit loses all communication with the Arduino.


text:
I can't connect a microSD card
I can’t connect a microSD card to either the Arduino or the ESP32. It needs to be connected to the ESP32; I just tested it on the Arduino to see if it works at all.
Equipment: ESP32 devkit v1, Arduino Nano, MicroSD card adapter, MicroSD card SanDisk 64gb eXFat.
Software: Arduino IDE, library SdFat (version: 2.2.2). The sketch is an example from the sdfat library - (sdinfo).
Connection to pin: SD adapter pin - CS, SCK, MOSI, MISO, VCC, GND
Arduino to SD Adapter - (CS, D10) (SCK, D13) (MOSI, D11) (MISO, D12) (VCC, +5V) (GND, GND)
ESP32 to SD Adapter - (CS, D27) (SCK, D14) (MOSI, D12) (MISO, D13) (VCC, VIN) (GND, GND)
Result ESP32:
rst:0x1 (POWERON_RESET),boot:0x13 (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:1044
load:0x40078000,len:8896
load:0x40080400,len:5828
entry 0x400806ac

Result Arduino:
SdFat version: 2.2.2

Assuming the SD is the only SPI device.
Edit DISABLE_CS_PIN to disable an SPI device.

Assuming the SD chip select pin is: 10
Edit SD_CS_PIN to change the SD chip select pin.

type any character to start

These are the full port monitor results.

Found out what's wrong

Common for connecting to any equipment

SdFat doesn't work for me, I still don't understand what's wrong with this library
so it's better to use standard SD library

Common for connecting to any equipment

SD card (no name, SDHC, 32 GB)
Formatting an Sd card for an SD library (possibly for SdFat) should be in Fat32 with a msdos partition table
I found the answer here (https://forum.arduino.cc/t/yet-another-sd-initialization-fail/286017)
Due to an incorrect partition table, my card could not be read

ESP32 pin connection
ESP32 to MicroSD Adapter - (CS , D5) (SCK , D18) (MOSI , D23) (MISO , D19) (VCC , VIN) (GND , GND)

Arduino Pin Connection
Arduino to MicroSD Adapter - (CS , D4) (SCK , D13) (MOSI , D11) (MISO , D12) (VCC , +5V) (GND , GND)


text:
Why does an ESP01 WiFi module reset when it's connected to a DC motor/water pump?
When I connect an ESP01 WiFi module and water pump in a parallel circuit to an Arduino Uno's 5 V pin, the ESP01 stops working.
The ESP01's built-in LED starts blinking chaotically and the serial monitor outputs trash logs like these:
`��PA���PCA��B��PCA��B�Z-
T���B�������|��B��P�

�D  �'�VB������P�

 �`

Note that I don't connect the ESP01 to WiFi: I just power it on and observe its behavior, so the ESP-01 shouldn't consume peak voltage and current.

Water pump parameters:
Voltage: 3-5 V DC
Current: 100-200 mA

ESP-01S parameters:
Voltage: 3 V to 3.6 V
Current: 70-170 mA

Arduino Uno parameters connected via USB to my laptop:
Voltage: 5 V
Current: 500 mA

Circuit diagram:

I know that an ESP01 shouldn't operate on 5 V and that a voltage regulator should be used, but I omitted it for test purposes and example simplicity.

the battery is drawn upside down ... the power supply may he getting overloaded... measure the voltage with the circuit powered on

You omitted a voltage regulator for test purposes? The abs. max. supply voltage for the ESP-01s is 3.6 V, and I/O is 3.3 V. Using 5 V will likely kill it. Also, the water pump needs a flyback diode. It would be a good idea to supply the water pump from a separate power supply, and not from the Uno's 5 V pin.

You supply your ESP-01 with a more than 50% higher voltage than it was designed for and you wonder why it doesn't work?

Use 74880 baud in the serial monitor. Use Serial.begin(74880); in your sketch to match. Odds are your trash logs will become more comprehensible then.

Thank you all for taking the time to help me solve my problem. Hi, @jsotola. My bad I fixed the battery diagram. I measured the voltage when the water pump and esp01 are powered and it's 4.77V. Without the water pump its 4.9V

Hi, @StarCat, in my initial test I used a voltage regulator but the result was the same. At the moment I power on the water pump the ESP01 stops working.

You say "in a parallel circuit to the Arduino's 5V pin".  Does the power to the motor come from the 5V pin of the Arduino?

@timemage baud rate it's 74880. Usually, when ESP01 works logs are readable but when I turn on the water pump and ESP01 reset/freeze then these trash logs show up.

@Delta_G, yes. The 5V pin of the Arduino powers up the water pump and the ESP01.

You shouldn't power a motor from the Arduino 5V pin.  The Arduino is NOT a power supply.  It can give 5V for logic circuits, but it can't supply current for a motor.  You may have already damaged your board.  Motors need their own power.  Look at some reputable tutorials on driving motors with Arduino.

When the motor starts it pulls too much current and sags the voltage on your board.  This causes your problem.

"I know that an ESP01 shouldn't operate on 5 V and a voltage regulator must be used, but I omitted it for test purposes and example simplicity."  -- How does it simplify the test to do something that you know will make the test fail?  Ok, I see.  You know the test will fail, that's actually pretty simple.

@Delta_G thanks I understand that I'll need separate power supply for the water pump.

The abs. max. supply voltage for the ESP-01s is 3.6 V; leaving out the voltage regulator and using 5 V for its power supply will likely have killed or at least damaged it.
Also, the water pump needs a flyback diode, and it would be a good idea to supply the water pump from a separate power supply, and not from the Uno's 5 V pin; the motor's (start-up) current may be more than the Uno can handle, and the motor will introduce noise in the wrong places.
The quoted 200 mA is the running current of the pump motor; start-up current will be about equal to the stall current and much higher. This will drop the voltage and crash the ESP01.
You may want to google something like "powering water pump from arduino start up current" and read about how it should be done; you're not the first with this problem.

Hi, @ocrdu  in my initial test I use voltage regulator to power the esp01 with 3.3V, flyback diode to handle voltage spike from the water pump, capacitors to handle changes in voltage, noise and to make the circuit more stable. Also I use transistor as a switch to turn on/off the water pump. Then the problem with the esp01 came and I found out that it's when the water pump is turned on. So I removed all other parts and for the test simplicity I left only the water pump and esp01.  In both ways the result is the same and esp01 freezes and stops working when the water pump is turned on.

For me it's not an option to use separate power supply to the water pump I want all to be powered from one place (Arduino Uno or li-on battery). As my understanding in parallel circuits the voltage across each of the components is the same and the total current is the sum of the currents flowing through each component. So 5V should be enough to power 3.3V eps01 and 3-5V water pump. And current should be enough too. Because Arduino Uno current is 500mA, esp01 is 170mA and the pump 200mA. Am I getting it right?

What is the pump's start-up current? Does the 5 V supply drop at the moment the motor starts? Did you have a look at the 5 V supply with an oscilloscope while the motor is running?

Start-up current is 200mA I got the pump from here.
Yes, usually voltage is 4.9V when I power on the pump voltage drops to 4.77V.
Unfortunately I don't have oscilloscope yet

200 mA is the pump's running current; at the moment it starts it will pull much more than that for an instant, hence start-up current aka stall current. Did you measure this initial current and the voltage drop at the moment the pump starts? You will find this current is higher than what the Arduino can provide. In general, you should supply a motor from a separate power supply, and not from an Arduino's 5 V pin.


text:
Where to use "static volatile bool"?
Why in the piece of code below we use "static volatile bool"?
static volatile bool wifi_connected = false;

taken from here: https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino

You could easily answer this question yourself with a little research. Maybe a good book, to start: The Definitive C Book Guide and List

The use of "static" confused me because I thought that static is a variable that remains in memory while the program is running. Thank you for the list of books!

There is a lot about C that is confusing, which is why I recommend a good book or article. A quick search found these examples: Static_(keyword) or C Static Variables and Static Functions Explained with Examples

static means that the global will only be accessible inside the current translation unit.
volatile means that while(!wifi_connected){/*...*/} cannot be optimized to if(!wifi_connected)while(true){/*...*/}
These things are orthogonal. So you would use static volatile when you need both properties.

as a C noob, i only see volatile used in interrupt routines.

@dandavis volatile is a hint to the compiler that the variable may be changed in another thread or an interrupt routine. This is to tell the optimizer not to get rid of loading the variable from memory each time we check the status.

@zeta-band: makes sense, thanks for the insight.

In your volatile case - would the compiler also include a jump out of the loop if wifi_connected were changed? If not - how would it handle exiting the loop in the (eventual) case that the variable changes?

@BrydonGibson variables are only checked when you tell them to be checked so the compiler will not introduce a break into the middle of the while body that you didn't put there. The while acts just like a normal while.

I understand. In the given example however, the while loop will run forever even if wifi_connected is changed inside. I guess the compiler wouldn't make that optimization in that scenario

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


text:
Can i store a SqlLite DB into an (old) ESP32? (not using SD card)
I would like to know if it is possible to store a (little, basic) SqlLite DataBase (or of any other type) into the (old) ESP32.
I don't want to use an SD card for that (for which I already know it is possible).
Thanks in advance for any hint on this

Sure, you can store it. You can store anything you like, size permitting, it's just a file after all. But I assume you actually want to use it from the ESP32 too?

@Majenko sure! ;-) i would load data "once" on programming the ESP32, and then "just" read it to take decissions and drive the program on different settings.

Then a database file is probably overkill. You could just use a simple text file for that.

@Majenko thanks!

I found these two post to be a useful answer to my question:

ESP32: Best way to store data frequently?

Sqlite3 Library for ESP32 Arduino Core

It could be really educating and clarifying if the downvoter would shine to explain why he downvoted... downvoting without an explanation may be considered impolite and unsmart...

Possibly because it mostly consists of links.  You can always add more details on how they helped.  Broadly you can make the answer more useful to future readers.

Yes you can - or you can certainly store it. ESP32 can use its flash as a filesystem (SPIFFS, LittleFS, FAT, etc) so you can store whatever data you like on there.
Whether the SQLite library can work with that file is another matter though, and is something you would have to explore yourself.
However for your use case using a database file is a bit silly. If all you want is some pre-defined runtime settings then all you really need is a simple text file. Maybe something like an INI file (key=value pairs) would be plenty for your needs, and pretty simple to parse without any libraries.


text:
Problem with load cell and ADS1262
I'm using PROTOCENTRAL ADS1262 32-BIT PRECISION ADC BREAKOUT BOARD to read the voltage in simple a load cell.
The connections follows the instructions on its library
But I cannot make it work, the readings has lots of spikes and i cannot discover what is happening.
Can someone help?

That is a very hard question to answer. Every pulse is followed by a slope, that means it could be an analog charge that is released. Can you do more tests ? Beside the spikes, can you actually measure the analog signal ? What happens if you shortcut the inputs ? Do you use the library provided by ProCentral ? Have you enabled the right 50Hz or 60Hz noise suppression ? How large are those spikes ? Have you tried a different power supply ? The ADS1262 has test modes, perhaps you can try one of them. The datasheet is very long. It will not be easy to fix.

This problem was solved on Texas Instruments Forum.
Thanks.
http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/p/627185/2344271#2344271

From the TI forum:

I noticed that you are polling data ready and then performing the data processing/serial output. The serial output operation is likely taking a long time and preventing you from capturing data at the faster data rates. You can try disabling the serial output and using an oscilloscope to see if you're able to reading data at the full throughput; however, when outputting this data over a serial interface you might not be able to capture and display all of the data...
I would try capturing data to memory and outputting the serial data in batches (for example, output 10 samples of data at a time). This might give you a little more data throughput.

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


text:
Can I use my Arduino nano to upload sketch in Uno's ATmega328p chip?
I can not upload sketch to my UNO directly. My ATmega16U2 doesn't work.But the Atmega328P processor still work.
 I have an arduino nano lying around. Can I use it to upload sketches to Atmega328P directly.
Thanks in advance

Yes. You can. Either as a USB to UART adaptor and use the Uno's bootloader as you would with any bootloader-enabled breadboard Arduino, or as an Arduino ISP to program the chip directly through the ICSP pins as you would when putting the bootloader onto a blank chip.


text:
error at compiling : 'class TwoWire' has no member named 'setClock'
I am a newbie C programmer and I just started with Arduino web editor (Win10-Firefox)to code for a Raspberry Pi (3B) board. RPi is on line via ethernet connection.
I tried to compile an example from Garmin Lidar_lite v3HP for I2C, as available in the library collections for Arduino.
When compiling the example I get after a while this error message:
Using library Wire in folder: /home/builder/.arduino15/packages/arduino/hardware/mraa/1.0.8/libraries/Wire (legacy)
Using library lidar_lite_3_0_3 at version 3.0.3 in folder: /home/builder/opt/libraries/latest/lidar_lite_3_0_3
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino: In function 'void setup()':
/tmp/967842743/v3HP_I2C/v3HP_I2C.ino:51:18: error: 'class TwoWire' has no member named 'setClock'
Wire.setClock(400000UL); // Set I2C frequency to 400kHz (for Arduino Due)
^
exit status 1
Checking the arduino forum I find some similar question, but of many years ago and likely not applicable any longer.
I appreciate your expert inputs on how to resolve in simple terms.
Thanks a lot! Greetz, Ivan

You're trying to compile code to run on a Pi? What core did you install into the IDE to do that?

Yes, that is the intent. Arduino web editor offers possibility to select not only arduino boards, but also linux based ARM systems such as RPi  board and also other SBC are supported by the web editor. I have seen Youtube tutorial that was demonstrating web editor en RPi.- see https://www.youtube.com/watch?v=yVS9zIcWa7w . That triggerd my interest.

Then probably the library in that (unknown?) core doesn't support that functionality. Maybe that functionality doesn't make any sense on a Linux computer where I guess the clock speed may be set in the DT overlay.

Thanks for the reply. I tried again with the arduino on PC with RasPiDuino librarie and had no further problem. The resulting executable does work on a RPi3 wirh Buster OS. Apparently the arduino webeditor lacks some libraries to succesfully compile for raspberry  . I continue this road. Item can be closed.

You should write that as an answer then wait the prescribe period (if there is one) and accept your own answer. That way people looking for an answer to the same problem can easily find it.

Thanks for the reply. I tried again with the arduino on PC with RasPiDuino librarie and had no further problem. The resulting executable does work on a RPi3 with Buster OS. Apparently the arduino webeditor lacks some libraries to succesfully compile for raspberry . I continue this road. Item can be closed.

If you now wish to delete your question, just use the 'delete' button on the question.


text:
Problem regarding on HC-SR04 sonar with an additional stepper and SG90 servo motor
I'm making a project based on HC-SR04 ultrasonic sensor with a stepper motor and an SG90 servo motor. I have done some conditions for my stepper motor that is given below. Now I want to include my servo in it. When the distance goes below 10cm the servo rotates at 90 degrees (N.B. the stepper remain the same as it is) and when the distance is above 10cm then the servo comes back to 0 degree.
Please help me out to complete this.
Thanks.
#include <Stepper.h>

// Define number of steps per rotation
const int stepsPerRevolution = 2048;

int rotationCW = 0;
int rotationCCW = 0;
int location = 1;

// Create stepper object called 'myStepper' note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

const int trigPin = 2;
const int echoPin = 3;

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup()
{
  myStepper.setSpeed(15); //Set the speed to 5 rpm

  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
}

void loop()
{
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)

  // Displays the distance on the Serial Monitor
  //Serial.print("Distance: ");
  //Serial.print(distance);
  //Serial.println(" cm");

  if (distance >= 20 && location == 1)
  {
    rotationCW = (.4 * stepsPerRevolution);
    myStepper.step(rotationCW);
    location = (2);
    delay(500);

    Serial.println ("Gate closed");
  }
  else if (distance <= 20 && location == 2)
  {
    rotationCCW = .4 * -stepsPerRevolution;
    myStepper.step(rotationCCW);
    location = 1;
    delay(500);

    Serial.println ("Gate opened");
  }
}

What is your exact problem in doing this? I don't see any servo code.

There is no problem with this code. I just want to added an extra servo with it, and it will rotate 90 degrees when the distance measurement is under 10cm, and goes back to its initial stage (i.e. 0 degree) when the distance will be up to 10 cm.

But why are you not just doing this? Adding an if statement for 10cm and adding servo code (like in the examples that come with the Servo library). You can find many tutorials and examples online about how to use a servo with Arduino. Have you looked and tried them? What exactly didn't you understand? What exactly makes you problems here? We need to know that to provide a good answer. We won't just write the code for you.

Yes, I tried. I actually want to do a project that meets the following conditions. Those conditions are:

When the distance is less than 20cm the stepper motor rotates clockwise (specific step) - gate open
When the distance goes above 20cm, the stepper rotates counterclockwise (specified step) - gate closed

When the distance goes below 10cm, a servo will rotate 90 degrees + as well as the stepper will fulfill its previous conditions.
When the distance goes above 10cm, the servo fire will come to the previous position + the stepper will still keep the gate open because 20cm has been fixed before.

I don't understand how to create the loop, and which conditional loop is useful to fulfill those conditions.

What do you mean by "loop"? Sounds just like ifstaments with distance < 10 (and the corresponding else statement), where you execute the Servo.write() in. Maybe it helps you to write that down. Imagine you are the program. What steps do you need to do in exactly which order to reach your goal. Each instruction needs to be one single action, like "set motor to 90°" or "if distance smaller than 10cm" or "rotate stepper Y steps". Check your own logic. When thats correct you can nearly directly translate each line into Arduino code


text:
ESP32 can not deep sleep longer than 35 minutes
I'm trying to get my Lilygo T5 4.7" epaper to deep sleep for 12 hours.
But I only seem to be able to get about half an hour (2100s) of deepsleep on it.
If I set the timer for longer, it just reboots right away.
#include <Arduino.h>
#include "epd_driver.h"

long DEEP_SLEEP_TIME_SEC = 43200;

void start_deep_sleep()
{
    epd_poweroff_all();
    esp_sleep_enable_timer_wakeup(1000000L * DEEP_SLEEP_TIME_SEC);
    Serial.println("Starting deep-sleep period...");
    esp_deep_sleep_start();
}

void setup() {
  Serial.begin(115200);
  Serial.println("\n- - - - - - - - -INITIALIZING - - - - - - - - - -");
  delay(10000);
  start_deep_sleep();
}

void loop() {
}

The sbove code gives the following:
16:44:25.104 -> - - - - - - - - -INITIALIZING - - - - - - - - - -

16:44:35.105 -> Starting deep-sleep period...

16:44:35.105 -> ets Jul 29 2019 12:21:46

and it just continues to reboot..

Maybe I'm using the wrong variables in some way?
Regards
Kasper

refer the ESP32 datasheet for the longest deep sleep available

I will try Ul tommorrow, but searching the datasheet for timer and sleep didn't help me learn how long it will go to sleep for..

I don't know what the max duration is, but the function you're calling seems to accept uint64_t, in which case you're probably looking for 1000000ULL rather than 1000000UL. Or uint64_t(1000000) or (uint64_t)1000000 or static_cast or ... whatever. In other words, the same thing Juraj appears to be saying, only more so.

alright, so I changed this esp_sleep_enable_timer_wakeup(1000000ULL * DEEP_SLEEP_TIME_SEC); and tried for 1 hour (3600s) and that worked (+- 15 seconds). Could you post an answer @timemage, so that I can close the question? Still unsure as to how long it will work for.. I don't seem to have the problem @hcheung suggests..

I can, I kind of figured Juraj had dropped an L and was otherwise thinking this, but I see their comment is gone.

So, formalizing this into an answer:
long DEEP_SLEEP_TIME_SEC = 43200;
// ...
esp_sleep_enable_timer_wakeup(1000000L * DEEP_SLEEP_TIME_SEC);

This is attempting to calculate the result of 1000000L * DEEP_SLEEP_TIME_SEC as a long type because both operands are of long type. The language does not consider the values of the operands (your constant and variable) of an operator (the multiplication) when determining the type of the result (the product) nor what you do with the result after that (passing it to the function).
The long type on ESP32 has a maximum value of 2147483647 which is as you said, "about half an hour" (not quite 36 minutes) worth of microseconds.
According to the documentation esp_sleep_enable_timer_wakeup accepts a uint64_t type for its requested duration parameter. I don't know what the valid maximum value to call with is, but the original poster confirmed it was large enough for 12 hours.
An unsigned long long is 64-bit on the ESP32 and the ULL suffix on 1000000ULL forces the compiler to only consider types which are unsigned and which are not smaller than a long long. In practice it means make me an unsigned long long with value 1000000. In
esp_sleep_enable_timer_wakeup(1000000ULL * DEEP_SLEEP_TIME_SEC);

the compiler follows something called the usual arithmetic conversions which will cause it to upconvert the long type of DEEP_SLEEP_TIME_SEC to match the unsigned long long that it is finding in 1000000ULL. The multiplication is therefore carried out in the unsigned long long type, so that the calculation itself accommodates more microseconds than you'll ever know what to do with. What the actual maximum is for esp_sleep_enable_timer_wakeup is still unclear. If I find out I will update with that information.

The ESP32-Arduino support comes with a fairly complete C++ standard library. So, if you want to get fancy you can use the <chrono> header. Just to give an example of what that could look like in your context:
#include <chrono>
// ...
static constexpr auto DEEP_SLEEP_TIME = std::chrono::hours{12};
// ...
esp_sleep_enable_timer_wakeup(
    std::chrono::duration_cast<std::chrono::microseconds>(
        DEEP_SLEEP_TIME
    ).count()
);

I'm being very explicit in the above. But you can import parts of the chrono namespace so you don't have to name everything fully. You can also import chrono literals support so that you can use time constants that look more like natural language(not yet apparently; there's still no C++14 support in Arduino-ESP32 I guess). You can control the underlying integer type used to represent the unit. It is also possible to create and name your own duration types to represent things like bit durations in a serial protocol etc. The default underlying type for chrono::microseconds is large enough for what you're doing; the default widths of underlying types are generally pretty sensible.  Different time units are different std::chrono types so you can't mix them up accidentally. duration_cast is a means of explicit conversion of time units. The .count() in the above is just a way to get the raw integer value out of the chrono type for when you need to do that, like calling this function.
If you wrap the function with your own taking std::chrono::milliseconds the unit conversion could just happen automatically in the call to your own wrapper:
static constexpr auto DEEP_SLEEP_TIME = std::chrono::hours{12};
//...
esp_err_t esp_sleep_enable_timer_wakeup_using_chrono(
  std::chrono::milliseconds duration
) {
  return esp_sleep_enable_timer_wakeup(
    duration.count()
  );
}
// ...
esp_sleep_enable_timer_wakeup_using_chrono(DEEP_SLEEP_TIME);

The way durations work in chrono is such that you don't need to duration_cast when you're going to type that can represent the same values as the source type. The the prior example the point of the duration_cast was just so that .count() was getting a count of microseconds. In other words, the duration_cast performed the multiplication and would have selected a more appropriate underlying integer size. Here that conversion takes place during the call. Anyway, it may be worth some effort to learn about as it tends to help avoid problems with unit conversions and integer ranges.


text:
PCA9685 servo not working

I am working on a project where I want to connect 12 servos together.
I got:

Arduino Nano Every
PCA9685 16-channel, 12-bit PWM/servo shield
Power supply 5 V, 10 A

I got a PCA9685 16-channel, 12-bit PWM/servo shield from Adafruit. I connected all the wires as they are supposed to be and I connected the shield to an external power supply, but the servos are not moving.
I don't know where the problem comes from.
I'm using the Adafruit library. It's not even moving one servo (although the servo moves when connected directly to the Arduino).
I have another wire connected to add a button. Here is my wiring diagram:

I am using code from the original project, so that shouldn't be the problem.

First, you should solder the connections to the Arduino properly, and check you haven't shorted reset to ground with stray wire strands sticking out.

Maybe use more flux when soldering, sl that you get nice smooth connections. The green while doesn't look like it is actually connected to the solder pad

I use many of these boards. Run an i2c scan on your Arduino to make sure the two boards can communicate.


text:
ESP8266-01E is not responding after successful flash
I have flashed an ESP8266 with the ESP8266 flash downloader that said my flashing had succeeded.
But when I sent an AT command from the serial monitor it didn't respond and the TX/RX LED from the ESP8266 didn't respond either. I checked all baudrates from 300-200000, but nothing.
I was using CH340 USB to TTL for flashing wired like this:
USB -> ESP8266
3,3v ->CH_PD and VCC
GND -> GND and GPI0 (only when flashing)
TX -> RX
RX -> TX

I was flashing to downgrade the firmware; the default firmware from shop was SDK 1.5.4, AT VERSION 1.1.0.0.

I have been frustrated with this, because this is my second module.

There are several files that need to upload the the ESP-01, it is unclean what you have done, what files to uploaded and where to upload also depend on the size of the flash memory you have for your ESP-01. Take a look at this =link to see if it will help.

SOLVED
My module is esp8266-01S, i need to set the SPI MODE to DOUT, BAUDRATES=115200, SPI SPEED 40MHz and the software is NODEMCU FLASHER.
The important keyword is "DOUT".
I have been flash many times but with not DOUT SPI METHOD. I thought change it will not fix that. I was using QIO SPI MODE but it doesn't work.


text:
Why am I getting a "SendCommand was not declared" error?

#include <Adafruit_Fingerprint.h>
#include  <SoftwareSerial.h>
#include <LiquidCrystal.h>

uint8_t id;
int getFingerprintIDez();
//pin #16 is IN from sensor (GREEN wire)
//pin #15 is OUT from arduino (WHITE wire)
int Contrast = 100;
SoftwareSerial mySerial(52, 16);
LiquidCrystal lcd(13, 12, 11, 10, 9, 8); // initialize the library with the numbers of the interface pins
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
#define S1 22 //Button candidate A
#define S2 24 // Button candidate B
#define S3 26 // Button candidate c
#define S4 28 // Button candidate D
#define S5 30 // Button Result
#define S6 2 // Button submit
#define S7 32 // Button to cast vote
int can1 = 0;
int can2 = 0;
int can3 = 0;
int can4 = 0;
int total;
SoftwareSerial ESP8266(50, 18);// RX, TX

void setup() {
  Serial.begin(9600); // initialize the serial communications:
  lcd.begin(16, 2); lcd.clear();
  lcd.print("  Polling Day  ");
  lcd.setCursor(0, 1);
  lcd.print("      UPM      ");
  delay(2000);

  mainpage();

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(A0, INPUT);

  finger.begin(57600); // set the data rate for the sensor serial port

  pinMode(S1, INPUT);
  pinMode(S2, INPUT);
  pinMode(S3, INPUT);
  pinMode(S4, INPUT);
  pinMode(S5, INPUT);
  pinMode(S6, INPUT);
  pinMode(S7, INPUT);

  ESP8266.begin(9600);

  digitalWrite(S1, HIGH);
  digitalWrite(S2, HIGH);
  digitalWrite(S3, HIGH);
  digitalWrite(S4, HIGH);
  digitalWrite(S5, HIGH);
  digitalWrite(S6, HIGH);
  digitalWrite(S7, HIGH);

  SendCommand("AT+RST", "Ready");
  delay(5000);
  SendCommand("AT+CWMODE=1", "OK");
  SendCommand("AT+CIFSR", "OK");
  SendCommand("AT+CIPMUX=1", "OK");
  SendCommand("AT+CIPSERVER=1,80", "OK");
}

void loop() { // run over and over again
  getFingerprintID();
  delay(100);
  digitalWrite (13, HIGH);
  if (digitalRead(S5) == 0) { // To view the result for admin only
    int total = can1 + can2 + can3 + can4;
    lcd.clear();
    lcd.setCursor(1, 0);
    lcd.print("1");
    lcd.setCursor(1, 1);
    lcd.print(can1);
    lcd.setCursor(5, 0);
    lcd.print("2");
    lcd.setCursor(5, 1);
    lcd.print(can2);
    lcd.setCursor(9, 0);
    lcd.print("3");
    lcd.setCursor(9, 1);
    lcd.print(can3);
    lcd.setCursor(13, 0);
    lcd.print("4");
    lcd.setCursor(13, 1);
    lcd.print(can4);
    delay(4000);
    if (total) {
      if ((can1 > can2 && can1 > can3 && can1 > can4)) {
        lcd.clear();
        lcd.print("Can A is Winner");
        delay(3000);
        lcd.clear();
      } else if ((can2 > can1 && can2 > can3 && can2 > can4)) {
        lcd.clear();
        lcd.print("Can B is Winner");
        delay(3000);
        lcd.clear();
      } else if ((can3 > can1 && can3 > can2 && can3 > can4)) {
        lcd.clear();
        lcd.print("Can C is Winner");
        delay(3000);
        lcd.clear();
      } else if (can4 > can1 && can4 > can2 && can4 > can3) {
        lcd.setCursor(0, 0);
        lcd.clear();
        lcd.print("Can D is Winner");
        delay(3000);
        lcd.clear();
      } else if (can4 > can1 && can4 > can2 && can4 > can3) {
        lcd.setCursor(0, 0);
        lcd.clear();
        lcd.print("Can D is Winner");
        delay(3000);
        lcd.clear();
      } else {
        lcd.clear();
        lcd.print(" Tie Up Or ");
        lcd.setCursor(0, 1);
        lcd.print(" No Result ");
        delay(3000);
        lcd.clear();
      }
    } else {
      lcd.clear();
      lcd.print("No Voting....");
      delay(3000);
      lcd.clear();
    }
    can1 = 0; can2 = 0; can3 = 0; can4 = 0, total = 0;
    lcd.clear();
    adminpage();
  }

  if (digitalRead(S7) == 0) { //To cast avote for user
    voterpage();
  }

  if (digitalRead(S1) == 0) {
    can1++;
    votereceived();
    mainpage();
  }

  while (digitalRead(S1) == 0);
  if (digitalRead(S2) == 0) {
    can2++;
    votereceived();
    mainpage();
  }
  while (digitalRead(S2) == 0);
  if (digitalRead(S3) == 0) {
    can3++;
    votereceived();
    mainpage();
  }
  while (digitalRead(S3) == 0);
  if (digitalRead(S4) == 0) {
    can4++;
    votereceived();
    mainpage();
  }
  while (digitalRead(S4) == 0);
  if (digitalRead(S6) == 0) {
    lcd.clear();
    lcd.print("Submitting...");
    delay(1000);
    ESP8266.println("AT+CIPSEND=0,23");
    delay(1000);
    SendCommand("AT+CIPCLOSE=0", "OK");
  }
  String IncomingString = "";
  boolean StringReady = false;

  while (ESP8266.available()) {
    IncomingString = ESP8266.readString();
    StringReady = true;
  }

  if (StringReady) {
    Serial.println("Received String: " + IncomingString);

    if (IncomingString.indexOf("LED=ON") != -1) {
      digitalWrite(LED, HIGH);
    }

    if (IncomingString.indexOf("LED=OFF") != -1) {
      digitalWrite(LED, LOW);
    }
  }

  boolean SendCommand(String cmd, String ack) {
    ESP8266.println(cmd); // Send "AT+" command to module
    if (!echoFind(ack)) // timed out waiting for ack string
      return true; // ack blank or ack found
  }

  boolean echoFind(String keyword) {
    byte current_char = 0;
    byte keyword_length = keyword.length();
    long deadline = millis() + TIMEOUT;
    while (millis() < deadline) {
      if (ESP8266.available()) {
        char ch = ESP8266.read();
        Serial.write(ch);
        if (ch == keyword[current_char])
          if (++current_char == keyword_length) {
            Serial.println();
            return true;
          }
      }
    }
    return false; // Timed out
  }
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      lcd.clear();
      lcd.print(" Image taken... ");
      delay(1000);
      break;
    case FINGERPRINT_NOFINGER:
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      return p;
    case FINGERPRINT_IMAGEFAIL:
      return p;
    default:
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      break;
    case FINGERPRINT_IMAGEMESS:
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      return p;
    case FINGERPRINT_FEATUREFAIL:
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      return p;
    default:
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    if (finger.fingerID == 26) {
      lcd.clear();
      lcd.setCursor(1, 0);
      lcd.print("Redirecting to");
      lcd.setCursor(1, 1);
      lcd.print("Admin process");
    } else {
      lcd.clear();
      lcd.setCursor(2, 0);
      lcd.print("Valid Voter!");
      lcd.setCursor(2, 1);
      lcd.print("ID : ");
      lcd.print(finger.fingerID);
    }

    digitalWrite(11, HIGH);
    delay(1000);
    digitalWrite(11, LOW); // turn on green LED to indicate match
  } else if (p == FINGERPRINT_NOTFOUND) {
    lcd.clear();
    lcd.setCursor(1, 0);
    lcd.print("Unregistered");
    lcd.setCursor(3, 1);
    lcd.print("Voter!");
    delay(1000);
    lcd.clear();
    lcd.setCursor(2, 0);
    lcd.print("scan finger");
    lcd.setCursor(6, 1);
    lcd.print("again");
    return p;
  } else {
    return p;
  }

  // IF FOUND A MATCH............
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Found ID #");

  if (finger.fingerID == 26) {
    adminpage();
  } else {
    voterpage();
  }
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK) return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK) return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK) return -1;
  // found a match!
  digitalWrite(13, LOW);
  delay(10);
  digitalWrite(13, HIGH);
  delay(10);
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Found ID # ");
  lcd.print(finger.fingerID);
  lcd.setCursor(0, 1);
  lcd.print("confidence ");
  lcd.print(finger.confidence);
  return finger.fingerID;
}

void voterpage() {
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Candidate 1");
  lcd.setCursor(1, 1);
  lcd.print("Mohd Faiz");
  delay(3000);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Candidate 2");
  lcd.setCursor(1, 1);
  lcd.print("Siti Nur Ila");
  delay(3000);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Candidate 3");
  lcd.setCursor(1, 1);
  lcd.print("Muhammad Aus");
  delay(3000);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Candidate 4");
  lcd.setCursor(1, 1);
  lcd.print("Wan zakaria");
  delay(3000);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Choose 1 only");
  lcd.setCursor(1, 1);
  lcd.print("1");
  lcd.setCursor(5, 1);
  lcd.print("2");
  lcd.setCursor(9, 1);
  lcd.print("3");
  lcd.setCursor(13, 1);
  lcd.print("4");
}

void votereceived() {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Vote Received");
  lcd.setCursor(2, 1);
  lcd.print("Thank You :)");
  delay(2000);
}

void adminpage() {
  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("1");
  lcd.setCursor(1, 1);
  lcd.print("Result");
  lcd.setCursor(11, 0);
  lcd.print("2");
  lcd.setCursor(8, 1);
  lcd.print(" Submit");
  delay(2000);
}

void mainpage() {
  lcd.clear(); lcd.setCursor(0, 0); lcd.print("Scan your finger");
}

I guess you don't have a SendCommand() function in your code. Though we cannot know. Please show the complete code as text (by copy&pasting it). Also copy the complete error output into the question, including the line, where the error happens

@chrisl Hi here my complete code. appreciated if you could detect where my error was.

Please no text as images. You can copy the text inside the compilation output field (where the error message show up) and copy it in your question as text. That makes it way better to read

The problem is, that you try to define functions inside of other functions. The SendCommand() function is currently definied inside the loop() function, which is not allowed. Move all function definitions at the lowest level (alongside the loop() function, not in it). BTW: The autoformat function of the Arduino IDE is your friend. I formatted your code, so that you can easier see, where the functions are placed.

Though, this is a pure programming error. As I wrote the solution in the comments, I'm now voting to close this question, as it is not about Arduino. Have fun with your project :)

Both boolean SendCommand() and boolean echoFind() are defined inside loop(), and they shouldn't be; it is not allowed to define functions inside functions.
Take them out of loop() and define them at (move them to) the same level as uint8_t getFingerprintID(), etc.


text:
How to make my LCD screen brighter
I'm trying to make my LCD screen brighter, can someone can help?
These are the code and the connections:
//LCD
#include <LiquidCrystal.h>
int Contrast=75;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

//LED
int LdrPin = A0;   // the cell and 10K pulldown are connected to a0
int LdrValue = 0;  // the analog reading from the sensor divider
int LedPin = 10;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness;

//כתום
int LdrPin2 = A0;  // the cell and 10K pulldown are connected to a0
int LdrValue2 = 0; // the analog reading from the sensor divider
int LedPin2 = 9;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness2;

//צהוב
int LdrPin3 = A0;  // the cell and 10K pulldown are connected to a0
int LdrValue3 = 0; // the analog reading from the sensor divider
int LedPin3 = 8;   // connect Red LED to pin 11 (PWM pin)
int LedBrightness3;

//serial monitor
char rx_byte = 0;
//random
long randNumber;

void setup()
{
  //אתחול LCD
  analogWrite(6, Contrast);
  lcd.begin(16, 2);

  //אתחול LED
  pinMode(LdrPin, INPUT);
  pinMode(LedPin, OUTPUT);
  Serial.begin(9600);

  pinMode(LdrPin2, INPUT);
  pinMode(LedPin2, OUTPUT);
  Serial.begin(9600);

  pinMode(LdrPin3, INPUT);
  pinMode(LedPin3, OUTPUT);
  Serial.begin(9600);

  //serial monitor
  Serial.begin(9600);

  //random אתחול
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop()
{
  // lcd.setCursor(2, 0);
  // lcd.print("Good Morning");

  LdrValue = analogRead(LdrPin);
  //Serial.print("LDR reading = ");
  //Serial.println(LdrValue);    // print the raw analog reading
  LedBrightness = map(LdrValue, 679, 6, 255, 0);

  if (Serial.available() > 0) // is a character available?
  {
    rx_byte = Serial.read();       // get the character
  }
  //check if morning and show good morning on thr LCD
  if (LdrValue == 679 && rx_byte == '7')
  {
    lcd.setCursor(2, 0);
    lcd.print("Good Morning!");
    //random 50% order of lights
    randNumber = random(0, 2);
    Serial.print(randNumber);
    if (randNumber == 1)
    {
      //אדום
      for (int i=0; i<8; i++)
      {
        digitalWrite(LedPin, HIGH);
        delay(1000);
        digitalWrite(LedPin, LOW);
        delay(1000);
        //led start working on red
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("red");
      }
      //כתום
      for (int i=0; i<4; i++)
      {
        digitalWrite(LedPin2, HIGH);
        delay(1000);
        digitalWrite(LedPin2, LOW);
        delay(1000);
        //led start working on orange
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("orange");
      }

      //צהוב
      for (int i=0; i<5; i++)
      {
        digitalWrite(LedPin3, HIGH);
        delay(1000);
        digitalWrite(LedPin3, LOW);
        delay(1000);
        //led start working on yellow
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("yellow");
      }
    } else
    {
      //צהוב
      for (int i=0; i<5; i++)
      {
        digitalWrite(LedPin3, HIGH);
        delay(1000);
        digitalWrite(LedPin3, LOW);
        delay(1000);
        //led start working on yellow
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("yellow");
      }

      //כתום
      for (int i=0; i<4; i++)
      {
        digitalWrite(LedPin2, HIGH);
        delay(1000);
        digitalWrite(LedPin2, LOW);
        delay(1000);
        //led start working on orange
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("orange");
      }

      //אדום
      for (int i=0; i<8; i++)
      {
        digitalWrite(LedPin, HIGH);
        delay(1000);
        digitalWrite(LedPin, LOW);
        delay(1000);
        //led start working on red
        lcd.setCursor(2, 0);
        lcd.print("working on");
        lcd.setCursor(2, 1);
        lcd.print("red");
      }
    }
  } else
  {
    lcd.setCursor(2, 0);
    lcd.print("Good night!");
  }
}

Provide more power to the back light

Use a lower value resistor than the 1kOhm shown in the diagram. Around 100Ohm if your LCD uses a white led. Some modules already have a resistor on the board, to limit the current thought the backlight led, but you'd have to check if yours does.

Use a 220 ohm resistor for the backlight. Treat it just as an LED. That's what it is, just a normal LED.

For a complete answer, we would need the datasheet of the LCD screen, but in general, LCD screens have a pin for the backlight, or two, one for plus and one for ground.
In the datasheet you can find what voltage the backlight wants, and what the maximum voltage is, and then set it to what you want.
For extra points, you can feed the backlight with PWM and set the brightness from the Arduino; if you do, make sure you don't pull too much current from the Arduino pin; add a FET if necessary.


text:
Run method every hour
I have a method. I need to trigger it every hour (cron job).
I mean:
10.00 p.m -> Trigger
11.00 p.m -> Trigger
12.00 p.m ->Trigger
...
...
Card: Arduino Uno + Wifi Shield.
Draft Code
  void setup() {

  }

  void onTimeChanged() {
      runTask();
  }

  void loop() {

  }

  /*run this method when:
  13.00 p.m
  14.00 p.m
  15.00 p.m
  ........
  ........    */
  void runTask() {

  }

It is unclear what you want. Wild guess: do you want an Arduino to connect to a server when the timezone the travelling Arduino is in changes?

Do you want the Arduino to determine in what timezone it is (by IP or GPS geolocation) or do you want the Arduino to determine when local Daylight Saving Time starts or ends? There are libraries available for both.

I just want to make cron jobs. Such as; 10.00 pm,11.00 pm, 12.00pm -> Execute Method

It is not confusing anymore. I edited question.

Do you need the task to trigger at the exact hour (xx:00, full hour with zero minutes), or do you only care about the period being one hour (like at 10:23, 11:23, 12:23, 13:23...). In the former case, do you have an RTC? A GPS receiver? A WiFi module?

I need to trigger at the exact hour. I don't have any of them. If needed, i can buy them.

An Arduino Uno doesn't have a Real Time Clock, but you could contact a NTP time server on the internet using the WiFi shield you mention, and get the time from there, and then keep track of time using millis(). Every so often, you should adjust the time with a new call to the NTP time server, because the Arduino's clock isn't all that accurate.
The easiest way would be to get a RTC module (I think the most accurate and still affordable at the moment are DS3231-based). They have a slot for a backup battery so they keep time even when there is no power supply.
Connect the module using I2C to your Arduino, install the appropriate library, and ask it every second (or however accurate you want to be) in your loop() for the exact time.
These modules usually also have an interrupt pin and can generate an interrupt when an alarm time is reached; you could use that also.

FWIW, RTClib supports alarms only with the DS3231. A pull request is in progress to add support for the alarms of the PCF8563. There may be other RTC/library alternatives though.


text:
HTTP-POST returns 400 when posting a value from the sensor
I'm trying to POST the data of total, but it returns 400. but when I try a sample data like
int httpResponseCode = http.POST("{\"amount\":\"total\"}"); (400)
into
int httpResponseCode = http.POST("{\"amount\":\"15\"}"); it works (201).
How to make it work? Thanks!
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

const byte interruptPin = 4;
const int interval = 500;
volatile unsigned long tiptime = millis();
volatile float rainrate = 0.3;
volatile float total;
void ICACHE_RAM_ATTR count();

void loop() {
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if (WiFi.status()== WL_CONNECTED) {
      HTTPClient http;

      // Your Domain name with URL path or IP address with path
      http.begin(serverName);

      // Specify content-type header
      http.addHeader("Content-Type", "application/json");

      // Data to send with HTTP POST
      int httpResponseCode = http.POST("{\"amount\":\"total\"}");

      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);

      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

void count() {
  // Grab the current ms count for common calculations
  unsigned long curtime = millis();

  // Make sure we don't record bounces
  if ((curtime - tiptime) < interval) {
    return;
  }

  // How long since the last tip?
  unsigned long tipcount = curtime - tiptime;
  tiptime = curtime;

  total += rainrate;
  Serial.println(total);
}

For debugging purposes, would you please try to serial output the exact strings that are sent in both cases to maybe find what's the important difference between them? You can post the results as edit to your question. Good luck!

Your line
int httpResponseCode = http.POST("{\"amount\":\"total\"}");

is not doing what you think it's doing. You're not placing the contents of the variable called total in the string, you're placing the word total in the string.
Instead you need to build up the string from components before sending. I'd use something like:
char temp[32];
snprintf(temp, 32, "{\"amount\":\"%.2f\"}", total);
int httpResponseCode = http.POST(temp);

That is assuming the http.POST() function will take a char * parameter. If not you may need to resort to a String:
String temp = "{\"amount\":\"";
temp += String(total, 2);
temp += "\"}";

However it is best to avoid String as it can cause heap fragmentation causing your code to become unstable over time.

Note that his total is a float, so the format should have %f or %g.

@EdgarBonet So it is...

If you're going to go the sprintf route, it would be better to use snprintf:  char temp[32]; snprintf(temp, sizeof temp, "{.  Reasons to use the old non-n version are few and far between.

I was going to but couldn't remember off hand the order of the first two arguments.

Thanks! it worked :)


text:
Several Software Serial Ports
I am planning to use an Arduino (Nano ideally, or Other) to send and receive information from several software serial ports to other arduinos, over their available pins, ideally 8 ports.
I could understand an Asynchrounous Communication having one master and 8 slaves, with the master enabling communication from one port, receiving the data from that port, and then move onto the next port, into a sampling loop.
The SoftwareSerial library allows to set up the pins individually, and set the listen() port (thanks Juraj).
I read the AltSoftSerial library handle some of the limitations of the SoftwareSerial library, but I just realized the pins cannot be configured (without... cloning the full library?).
Question is:

Option 1: Should I stick with the SoftwareSerial library?,
Option 2: Should I try the AltSoftSerial library, and figure how to duplicate it (i think this is a NO)?
Option 3: Understand that none of these libraries are prepared for this, and seek for other alternative?
Option 4: It is pointless to have several serial trunks in Arduino, if only one will work at a time, and should hence try to arrange just one serial trunk?

you must set which instance should listen with listen(). only one can listen

You might be better off with an rs485 multi-drop bus.

I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.

You could use a part with 2 hardware serial ports (Atmega1284P), and use a simple mux chip to switch between the slaves for the master to receive from, such as DG406
https://www.digikey.com/products/en/integrated-circuits-ics/interface-analog-switches-multiplexers-demultiplexers/747?k=dg406&k=&pkeyword=dg406&sv=0&pv1989=0&pv433=170&sf=0&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25
Hardware serial will allow for faster comm's too, vs software serial.
1284P is Arduino friendly too.


text:
Serial Module Echoing a `0x00`
I am having a problem with a MAXIM Serial module (Config A) with a simple repeating code from COM port. When sending a character (k:0x6b) I receive a (0x00) echo.
Without the module and just connecting the arduinos crossing the TX/RX cables, I do not have any echo.
The echo persists, disregarding of:

The speed (from 38400 to 2000000 bps),
Using or not the high speed options (2.3MOhm for 250000bps) of the MAXIM,
Using or not 120 ohm terminal resistors,
Both grounds are 0V, connecting them has no effect,
Removing the A (red) B (green) Serial Bus Cables (???). Message not send in this case, as expected (!).

What could be the problem?
Devices:

Two Arduino Mega 2560,
Two MAX3292, one for each arduino,
AWG24 Cable, shorter than 7 in each.

Config A: With Module (00 echo), Half Duplex (f.19 p.13).

Config B: Without Module (No echo), only crossed cables

Code:
long rate=38400;
void setup() {
    Serial.begin(rate); while (!Serial);
    Serial1.begin(rate); while (!Serial1);
    pinMode(22,OUTPUT);
    pinMode(23,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(22,1);
        digitalWrite(23,1);
        s=Serial.read();
        Serial1.write(s);
        Serial1.flush();
        digitalWrite(23,0);
        digitalWrite(22,0);
    }
    if (Serial1.available()){
        s=Serial1.read();
        Serial.write(s);
    }
}

Execution: Four k sent, 0x00 echoes received. After this, four k send from other arduino, received successfully.

Epilogue.
Actually, the problem was a resistor at the RO output, not shown in the diagram ("The problem is in the code you didn't post").
It was a voltage divider for a 5V3.3 conversion in the Arduino Due case, useless in the Arduino Mega, but still there.
Theorizing a reason, that resistor caused a spike at the output (?), thus forcing the module to interpret it as another byte, an empty one (?).
After removing the resistors, it worked perfectly.
Now I migrated this back into Arduino Due, but with a diode plus a pull up resistor as a 5V3.3 converter.

You do have the grounds of the Arduinos connected together don't you?

All are plugged from a same USB splitter, but even connecting them in the breadboard, the effect persists.

Ok, looking in more detail - what code is at the other end? You have two megas, but only show one code.  Second - your terminal program is set to a different baud rate than your program.

Same code for both. The effect is the same for all speeds.

With that code for both, why do you expect anything to echo back? The 00 is the error, not the no response.

Yes, the 0x00 is an error. No echo or response should be received. If I disconnect the AB bus, the echo is still there... If I remove the RE'DE signal, the echo dissapears (but no reception, since it is disabled).

Does your fritzing diagram precisely describe reality, or is your right-hand chip actually wired differently to how you are showing it?

It is almost exactly as the diagram. In a same breadboard, wiring the cables as named into the proper arduino. The named and the AB cables are about 7 in length.

So, you actually have your right-hand chip wired wrong? Inspect the wires going between the Arduino and the right hand chip...

Oh right, it is a drawing error (unfortunately?)... Already corrected.

Looks like you have wired it for the MAX3291 instead of the MAX3292.  Remove the PEE wire , since it's not PEE, it's PSET.  Connect a resistor and capacitor to VCC. Read page 11 of the datasheet.

I had them previously and i have just added them now, but unfortunately still the same echo, one per character in a string, after sending strings or sending individual characters...

Check your wiring! My guess is the twisted pair (A-B swap).
I've checked your code, it seems right. Please note that /RE and DE were designed that way so you can simply connect them and control with only one pin.
I don't have the exact same hardware, I had MAX485 and Arduino Nano at hand. Nano only has one hardware serial, so I've used the SoftwareSerial library instead.
I've connected them, adjusted your code to my setup, and it worked. Here it is in case it helps to troubleshoot your issue. I've also optimized your version a little bit (but it worked before so the bug is somewhere else).
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX

const int dir_pin=9;
const int dir_transmit=1;
const int dir_receive=0;
long rate=38400;

void setup() {
    Serial.begin(rate); while (!Serial);
    mySerial.begin(rate); while (!mySerial);
    pinMode(dir_pin,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(dir_pin,dir_transmit);
        while(Serial.available())
        {
          s=Serial.read();
          mySerial.write(s);
        }
        mySerial.flush();
        digitalWrite(dir_pin,dir_receive);
    }
    while (mySerial.available()){
        s=mySerial.read();
        Serial.write(s);
    }
}

Well, the code and the configuration was ok but... a resistor divider at the RO output not shown in the diagram was causing the problem. After removing it, everything worked fine. Thanks for the effort anycase...


text:
Would this substitute for an Interrupt timer?
class Pseudo_Interrupt {
  //only cummulative time is important, exact interval is not
  // Class Member Variables
  // These are initialized at startup
  long OffTime = 1000; // milliseconds of off-time
  // These maintain the current state
  unsigned long previousMillis; // will store last time updated

  void Update() {
    // check to see if it's time for an Interrupt
    unsigned long currentMillis = millis();
    if ((currentMillis - previousMillis >= OffTime) {
      //Time to execute the one second code
    }
  }
}

You are almost there. You have to set previousMillis to currentMillis (inside the if-statement) for the next interval. The previousMills and currentMillis must be unsigned long. The 'Offtime' can be a signed integer, or signed long, but if you make that a unsigned long as well, then everything is unsigned long which makes the code more clear and the compiler doesn't have to convert variables.

Latest Version:  7/6/17
//--------------------------------------------------------
class Pseudo_Interrupt {

{   // These maintain the current state of the timer
public:
volatile unsigned long previousMillis;   // will store last time updated
volatile unsigned long lateMillis = 0;       // how late was it
volatile bool CallOneMinute = false; //facilitates while loops,
}
// to prevent a callback set previousMillis = millis(); periodically within the 'period'
// to start the callback set previousMillis = millis() - period; lateMillis = 0;
volatile unsigned long currentMillis;
static const unsigned long period = 1000;     // milliseconds of off-time delay
volatile unsigned long delta;
    void (*callback)();
public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {       currentMillis = millis();
            CallOneMinute = false
            delta = currentMillis - previousMillis - period
        if (lateMillis + delta >= 0)
            lateMillis = delta;
            CallOneMinute = true
        {
            callback();   // with correction to keep net correct cumulative time
            previousMillis += ( period - lateMillis );
    }
};
//----------------------------------------------------------

Your test if (lateMillis + delta >= 0) is always true. The volatile keyword is useless here.

The whole idea is sound, but I would make a few changes:

as explained by Jot in a comment, you have to update previousMillis
inside the if statement. You have two choices:

set it to currentMillis, then OffTime will be the minimum time
between the pseudo-interrupts
increment it by a constant amount, which I would call period, then
this will be the average time between pseudo-interrupts; this is
more similar to how real timer interrupts work

add a constructor for:

making the period user-selectable
making the action of the timer user-selectable via a callback
initializing previousMillis

With those changes, the class will look like:
class Pseudo_Interrupt {
    unsigned long period;
    unsigned long previousMillis;
    void (*callback)();

public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {
        if (millis() - previousMillis >= period)
        {
            callback();
            previousMillis += period;
        }
    }
};

For a steady period (increment previousMillis with a constant), it can create a burst, for example when setup takes a long time. In that case I set previousMillis to millis at the end of setup. It prevents a burst when the sketch starts and setup takes a long time.

I have since put the following in a continuous fast loop. When the program gets to it, it executes.   The one second is a little erratic, but the total cumulative is approximately correct.
long OffTime = 1000;     // milliseconds of off-time

// These maintain the current state of the timer
long previousMillis;   // will store last time updated
long lateMillis;       // how late was it

//----------------------------------------------------------------------

currentMillis = millis();     //correct for millis() overflow
if (currentMillis - previousMillis < 0 )
    currentMillis = currentMillis + 32768;
{
    if (currentMillis - previousMillis >= OffTime - lateMillis )

        // Assume the difference is longer than 1000 milliseconds
        // because the sample time will be late but not by much
        lateMillis = currentMillis - previousMillis - OffTime;

        // Thus, cumulative time is essentially correct
        //Time to execute the one second code here
        do some code
    else
        return;
    }
// ----------------------------------------------------
}  //  End Of Run Repeatedly

Your handling of the millis() overflow is misguided. You should just let it roll over through zero, and make all your timing variables unsigned. Actually, the way you avoided having to handle this in the code from your question was correct.

A function called by your program can do some, but not all, of what an interrupt function does. If you call it frequently enough, you can get timely execution of your "one second code". How frequently you must call it depends on how precisely an execution interval you need. That may require your mainline code to spend more time polling the timer than you can afford; it depends on your particular circumstances.
A true interrupt function will be called nearly immediately on the occurrence of whatever event is set to trigger it. Until then, no time will be taken from your mainline code.
Whether that is that is an effective substitute depends on your particular situation.
The code you supplied is not syntactically correct and does not compile. Nested functions are not include in C or C++, and in the 'if' statement, the parentheses are unbalanced.

Nested functions are not include in C or C++,... it is compiler specific.

Regardless, the code did not compile in the Arduino IDE.

that still doesn't make your original statement correct

No, it is not compiler specific; it is standards specific. Some compilers may implement extensions to the language. That does not make them part of the language.

Yes, if you advance previous millis by 1000 once that comparison is true.
Setting previous millis to current millis is the wrong approach as it will accumulate timing errors.
edit:
here is a simple piece that hopefully will do what you are trying to do.
//pseudo timer isr
//return 1 if the timer overflows MYTMR_PR
uint8_t mytmr_ovf(void) {
    static uint32_t last_time=0;        //previous time
    uint32_t current_time;

    current_time = millis();            //take current time
    if (current_time - last_time >= MYTMR_PR) {
        last_time += MYTMR_PR;          //update last time
        return 1;                       //indicate overflow
    }
    return 0;                           //indicate no overflow
}

as I suggested earlier, the code is written so that the timer is long-term accurate.
Hope it helps.
edit 2: here is the above code running on a PIC24F, with MYTMR_PR set to 100 (=100ms)
//user loop
void loop(void) {
    //looping around
    if (mytmr_ovf()) digitalWrite(LED, !digitalRead(LED));   //flip the led
}

I'm guessing you typed this on a cell phone....

@dannyf, I just read the "only cummulative time is important, exact interval is not". You are right, increment with constant will make it work with the same accuracy as the crystal of the microcontroller/processor.


text:
Synchronising LEDs
Say I have 3 LEDs. I want LED1 to blink 5 times. At its third blink, LED2 should start blinking as well, also 5 times. While LED2 is at its 3rd blink, LED3 should start blinking. How do I do this in Arduino?
Here's what I have.
int timeStep = 200; // delay time
int myPins[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // array with Pins
int myPinsSize = sizeof(myPins) / sizeof(myPins[0]); // Length of my array
int counter = 0;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  for (int i = 0; i < myPinsSize; i++) {
    pinMode(myPins[i], OUTPUT);
  }
}

// the loop function runs over and over again forever
void loop() {
  LEDsequence();
  if(counter >= 9) {
    counter = 0;
  } else {
    counter++;
  }
}

void LEDsequence() {
  if(counter < 5) {
    switchOn(0);
  }
  if(counter >= 2 && counter < 7) {
    switchOn(1);
  }
  if(counter >=4 && counter < 9) {
    switchOn(2);
  }
  delay(timeStep);
  switchAllOff();
}

void switchOn(int index) {
  digitalWrite(myPins[index], HIGH);
}

void switchOff(int index) {
 digitalWrite(myPins[index], LOW);
}

void switchAllOff() {
  for (int i = 0; i < myPinsSize; i++) {
    digitalWrite(myPins[i], LOW);
  }
}

Building on Michel's answer (this is a bit long to put in a comment):
Rather than using a 2 dimensional array or an array of strings (which is also a 2d array) it would be far more efficient to use a bitmask system.
const uint8_t TIME_PERIODS = 20;
const uint8_t NR_LEDS = 3;
const uint8_t ledStates[] = [1,0,1,0,3,0,3,0,7,0,6,0,6,0,4,0,4,0,4,0];

and then the loop becomes:
  for (int period = 0; period < TIME_PERIODS; period++)
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, ledStates[period] & 1<<led ); // set the led on or off
    }
    delay(500); // 0.5 s
  }

How this works:
1<<led will be 0001 in binary for led=0, 0010 for led = 1, 0100 for led = 2.
So if ledStates[period] was 3 (0011 in binary) then ledStates[period] & 1<<led will be non-zero for leds 0 and 1 and zero for led 2. The way the switch function is written any non zero value turns the LED on, 0 turns it off.
Why do it this way? Mainly size. Memory is always important, this uses 1 byte per state rather than 3. It could even be expanded to up to 8 LEDs without increasing the amount of memory used.

Since you have 3 leds, make a 2 dimensional array, first index for the leds (3), second for the period in which you want to have the led on or off.
E.g.
const uint8_t NR_LEDS      = 3;
const uint8_t TIME_PERIODS = 20;

uint8_t period[NR_LEDS][TIME_PERIODS] = [
// Time  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17, 18, 19
        {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // Led 1
        {0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0 }, // Led 2
        {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }}; // Led 3

This means over 18 time periods, each state shows which led is on and off.
You can use HIGH or LOW, but that makes the lines too wide.
Now you can easily create a loop:
void loop()
{
  for (int period = 0; period  < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period ]); // set the led on or off
    }
    delay(1000); // 1 s
  }
}

void switch(uint8_t led, uint8_t state)
{
  digitalWrite(led, state == 0 ? LOW : HIGH);
}

So instead of switchOn and switchOff, use the switch and set it on or off by a parameter.
Also, this way it is very easy to change the schema (you can always visually see it in code). If you want longer schemes you can change the array into strings, like:
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

And check the index within the correct string and check for '0' and '1' instead of 0 and 1.
Since blinking is done for all leds 'in sync' (meaning during blinking leds change at the same time), you can also define a '1' as blink and '0' as off.
Than change:
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "10101010100000000000", // LED 1
        "00001010101010000000", // LED 2
        "00000000101010101010", // LED 3

to
char* period[NR_LEDS] = [
 // Time 0         10
 // Time 012345678901234567890
        "111110000", // LED 1
        "001111100", // LED 2
        "000011111", // LED 3

And change the loop in
void loop()
{
  for (int period = 0; period < TIME_PERIODS; period ++) // Time
  {
    for (int led = 0; led < NR_LEDS; led++)
    {
      switch(led, states[led, period]); // set the led on or off
    }
    delay(500); // 0.5 s

    for (int led = 0; led < NR_LEDS; led++)
    {
       switch(led, '0');
    }
    delay(500); // 0.5 s
  }
}

(use a constant for 0.5 s delay) and optionally create a function for the two small for loops above)

How do I do this in Arduino? Here's what I have.

easy:
1) write a routine that blink a pattern on a given pin;
something like this would work
void myblinking(uint8_t pin, uint8_t *ptrn, uint8_t steps) {
  uint8_t index;

  pinMode(pin, OUTPUT);  //set pin as output
  for (index=0; index<steps; index++) {
    digitalWrite(pin, !digitalRead(pin)); delay(ptrn[index]); //flip pin, waste sometime
  }
}

then all you need is to call that routine, like this:
myblink(LED_PIN0, led_ptrn0, 10); //blink led_pin0, per led_ptrn0, for 10 steps
  myblink(LED_PIN1, led_ptrn1, 20); //blink led_pin1, per led_ptrn1, for 20 steps
  ...

That would only blink 1 LED at a time, it wouldn't allow you to run 2 different patterns on two different leds at the same time.