text:
Using Adafruit RTClib without fragmenting the heap
I'm getting ready to add DS1307 support to my Arduino app, and was horrified when I looked at the sourcecode for the RTC_DS1307 class in Adafruit's RTClib library...
DateTime RTC_DS1307::now() {
  uint8_t buffer[7];
  buffer[0] = 0;
  i2c_dev->write_then_read(buffer, 1, buffer, 7);

  return DateTime(bcd2bin(buffer[6]) + 2000U, bcd2bin(buffer[5]),
                  bcd2bin(buffer[4]), bcd2bin(buffer[2]), bcd2bin(buffer[1]),
                  bcd2bin(buffer[0] & 0x7F));
}

... and realized that it appears to be instantiating a new throw-away DateTime object on the heap every time you call now()... which AFAIK, is the ultimate Arduino C++ taboo.
I was about to tear into the class and rewrite it to reuse a singleton DateTime object that gets created once and reused forever... but then I remembered about return value optimization.
Is this actually a scenario where RVO will automagically kick in to save the day and prevent a heap-allocation (by pre-allocating space for the DateTime object on the caller's stack prior to calling now()), or is this library indeed doing something as taboo as I think it is?

I wrote a minimal sketch that calls RTC_DS1307::now(), disassembled
it, and here is what I saw:

The caller allocates 6 bytes on the stack for holding the return
value.

It writes the address of this stack location in the register pair
r25:r24, as per the AVR calling convention,1 then calls
RTC_DS1307::now().

As the callee computes the fields of the resulting DateTime (by
means of inlined calls to bcd2bin()), it writes them directly into
the caller's stack frame, with no intermediate copy in RAM.

This looks to me like return value optimization.
However, in order to witness this behavior, I had to call
RTC_DS1307::now() twice. If the method is called from a single place
within the sketch, the compiler inlines it, and there isn't even a
function call to begin with.
Then, of course, the heap is never touched.
1 You would expect the this pointer to be passed as the
first argument, in r25:r24. It would seem it has been optimized out,
which makes sense given that there is only one RTC_DS1307 object in
the whole sketch.

Surely the heap is never touched in any case?

with no intermediate copy in RAM - using RAM is not the same thing as using the heap.

@NickGammon: The heap is not touched by RTC_DS1307::now(). On AVR, new calls malloc. Thus, if the heap is ever touched, avr-nm the_sketch.elf | grep malloc will show you: malloc, __malloc_heap_start, __malloc_heap_end and __malloc_margin.

I wish I could give points for both answers, but I'm going with Edgar's due to the info about being able to determine with certainty whether the heap is being touched by something. I've been dying to find info about that particular topic for months.

Edgar Bonet's answers are usually excellent. I think we are in agreement that there is no problem with heap fragmentation in this particular case.

I wonder how could one assume some heap allocation from the code presented in the question. I guess return of object by copy is not intuitive. Usually the compiler even optimizes it so there is no copying.

I think you are confusing the stack and the heap. For something to appear in the heap you would expect to see the words new or malloc which I don't see.
What is happening here is that a DateTime object is being created (in the stack frame of the current function) by RTC_DS1307::now which is being (presumably) copied into a variable of that type in the caller's stack frame when the function returns.
No memory is being wasted here.

it appears to literally be instantiating a new throw-away DateTime object on the heap

What gives you that idea? The heap is not involved without you using new or malloc.

The heap is a block of memory used for dynamic memory allocation by using malloc or new, generally speaking. Typically it will be allocated past the place in RAM where variables are allocated (ie. after all the variables) and grow upwards, whereas the stack will be allocated at the end of available memory and grow downwards. Thus they don't clash until they collide, either by using too much stack (eg. by recursive function calls) or by allocating too much of the heap (by repeatedly calling malloc and without calling free).
When you use the heap, by using malloc you will get a pointer which you can then use, and pass around. That memory which you have reserved is yours until you free it, by literally calling free. In C++ something very similar is done by using new and delete.
If you don't call malloc or use new then you aren't using the heap, end of story.

Prior to about an hour ago, I didn't realize there was a mechanism in c++ to create an object on a subroutine/method's stack & atomically copy it to the caller's stack upon return. I thought the called method/subroutine's stack vanished the instant return executed, so an object created in & returned by a method/subroutine had to either go in the heap or use RVO. Up to now, I always tiptoed around it by doing the 'Android' thing & passing my return-object containers TO methods & reusing them.

@Bitbang3r Well, yes, you could always pass one by reference.

@Bitbang3r See amended answer for more explanations about the heap.

In most cases, thanks to return value optimization the returned object is constructed in the stack frame of the caller, avoiding the copying step.


text:
Arduino secure mqtt example not subscribing to topic
I am wrestling with the below example.
I have a RasPi on the network running Mosquito with username and password credentials setup and I know this is working.
If I load the below example, I can confirm the following:

It does connect to my Wi-Fi
It does connect to the mqtt broker
It does publish the example data (confirmed in serial monitor window and MQTTBox running separately)
But, it never receives a message on the subscribed topic.

I also have a VM with Mosquito running without credentials and if I swap to that, then messages sent on the subscribed topic do appear in the serial monitor.
I am using an ESP8266 D1 and am perplexed. Any thoughts appreciated.
/***************************************************
  Adafruit MQTT Library ESP8266 Example

  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino

  Works great with Adafruit's Huzzah ESP board & Feather
  ----> https://www.adafruit.com/product/2471
  ----> https://www.adafruit.com/products/2821

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

/************************* WiFi Access Point *********************************/

#define WLAN_SSID       "my_network_ssid"
#define WLAN_PASS       "my_network_ssid_password"

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "ipaddress for a raspberry pi only running mosquitto with username and password enabled - tested and working"
#define AIO_SERVERPORT  1883                   // use 8883 for SSL
#define AIO_USERNAME    "mosquitto_username"
#define AIO_KEY         "mosquitto_password"

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiClientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell");

// Setup a feed called 'onoff' for subscribing to changes.
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/mytestfeeds/onoff/");   //have changed the topic from default

/*************************** Sketch Code ************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

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

  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

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

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&onoffbutton);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &onoffbutton) {
      Serial.print(F("Got: "));
      Serial.println((char *)onoffbutton.lastread);
    }
  }

  // Now we can publish stuff!
  Serial.print(F("\nSending photocell val "));
  Serial.print(x);
  Serial.print("...");
  if (! photocell.publish(x++)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
  if(! mqtt.ping()) {
    mqtt.disconnect();
  }
  */
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

Have you tried listening to all topics? Just mytestfeeds/#? It's also typically not recommended to start or begin topics with a '/'.

Also, this should help pin down the issue.

source: Stack Exchange

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

sort: votes


text:
Please help me with my project of water pump relay switching too fast
I have some problems with my project.
I'm using a water level sensor with two outputs, a 5V fan and a water pump. Here's the wiring .
What I want to do with this project is:

When the water reaches 2 cm, then the water pump is on while the fan is off.
When the water is less than 2 cm, then the water pump is off and fan is on.

The problem is, when the water is below the threshold, the sensor reading is quite unstable, thus making the relay switching too fast (see the video).
How to eliminate this problem?
#include <Wire.h>
#include <Blynk.h>
#include <LiquidCrystal_I2C.h>
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

//Initialize the LCD display
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "xxx";//Enter your Auth token
char ssid[] = "xxx";//Enter your WIFI name
char pass[] = "xxx";//Enter your WIFI password
BlynkTimer timer;

#define pinSensor A0
#define PIN_RELAY_1  D3
#define PIN_RELAY_2  D4
const int startThreshold = 2; // pumping shall start at startThreshold [cm] and above
const int stopThreshold  = 1; // pumping shall start at stopThreshold  [cm] and below

int sensorValue = 0; // sensor reading integer
float tinggiAir = 0; // height of water
float sensorVoltage = 0; // voltage sensor
int nilaiMax = 686; // max value of sensor after fully drowning it in water
float panjangSensor = 4.0 ; // sensor's height in cm

enum StatusType {CHECKLEVEL, LEVELHIGH, PUMPING};
StatusType status = LEVELHIGH;   // Let's start with LEVELHIGH to check level and set the display correctly

void setup() {
  Serial.begin(115200);
  lcd.begin();
  Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
  lcd.backlight();
  pinMode(PIN_RELAY_1, OUTPUT);
  pinMode(PIN_RELAY_2, OUTPUT);
  digitalWrite(PIN_RELAY_1, LOW);
  digitalWrite(PIN_RELAY_2, LOW);
  lcd.setCursor(0, 0);
  lcd.print("Water level");
  lcd.setCursor(4, 1);
  lcd.print("Monitoring");
  delay(1000);
  lcd.clear();
  timer.setInterval(100L, wLevel);
}
void wLevel() {
   sensorValue = analogRead(pinSensor);
  tinggiAir = sensorValue*panjangSensor/nilaiMax;
  sensorVoltage = sensorValue*5.0/686;
}

void loop() {
      Blynk.run();
     timer.run();
     handleStatus();
}

void handleStatus() {
  switch (status) {
    case CHECKLEVEL:
      // Wait for level above threshold
      if (tinggiAir >= startThreshold) { // if wlevel more than startThreshold [cm], then
        status = LEVELHIGH;
        Serial.println("LEVELHIGH");
      }
      break;
    case LEVELHIGH:
      levelIsHigh();
      break;
    case PUMPING:
      if (tinggiAir < stopThreshold) { // if wlevel less than stopThreshold [cm] (use hysteresis!) then
        levelIsLowAgain();
        status = CHECKLEVEL;
        Serial.println("CHECKLEVEL");
      }
      break;
  }
  displayValues();
}

void displayValues() {
  static int oldSensorValue = -1; // variable untuk menampung nilai baca dari sensor dalam bentuk integer
  float oldTinggiAir = -1; // variabel untuk menampung ketinggian air
  float oldSensorVoltage = -1; // untuk menampung nilai ketinggian air

  if (oldSensorValue != sensorValue ||
      oldTinggiAir   != tinggiAir   ||
      oldSensorVoltage != sensorVoltage) {
    Serial.print("Sensor Value = ");
    Serial.println(sensorValue);
    Serial.print("Sensor Voltage = ");
    Serial.println(sensorVoltage);
    Serial.print("Tinggi Air = ");
    Serial.println(tinggiAir);
    Serial.println();
    // Display ke LCD
    lcd.setCursor(0, 0);
    lcd.print("WLevel:");
    lcd.print(tinggiAir);
    lcd.setCursor(12, 0);
    lcd.print("cm");
    oldSensorValue = sensorValue;
    oldTinggiAir   = tinggiAir;
    oldSensorVoltage = sensorVoltage;
    Blynk.virtualWrite(V0, tinggiAir);
  }
}
void levelIsHigh() {
  digitalWrite(PIN_RELAY_1, HIGH);
  digitalWrite(PIN_RELAY_2, LOW);
  lcd.setCursor(0, 1);
  lcd.print("F:OFF P:ON");
  Blynk.logEvent("wlevel", "wLevel more than 2cm");
  status = PUMPING;
  Serial.println("PUMPING");
}

void levelIsLowAgain() {
  digitalWrite(PIN_RELAY_1, LOW);
  digitalWrite(PIN_RELAY_2, HIGH);
  lcd.setCursor(0, 1);
  lcd.print("F:ON P:OFF");
  status = CHECKLEVEL;
  Serial.println("CHECKLEVEL");
}

You could read multiple values from the level sensor and average them to get a more stable reading.

And add some hysteresis

Try de-bouncing the sensor for several seconds unless you need a faster response.

Do you prefer a software solution - or  hardware solution?  If hardware, you need to find a comparator (or op-amp) - perhaps on your ESP8266, or a stand-alone hardware item. REF1, REF2.

The problem lies in the specification itself. According to your rules,
what should the pump do if the water level is exactly 2 cm?
Granted, there is no such thing as an exact physical measurement. But
you have to realize that every measurement system is noisy. Noise is a
fact of life you have to cope with when playing with hardware. You may
try to make it smaller (by filtering), but it will always be there. Now
the question is: what should the pump do if the difference between the
water level and the required 2 cm is less than the noise amplitude?
The standard solution, as suggested by KIIV, is to implement some
hysteresis. You define two thresholds: one for turning the pump on
and another, lower threshold for turning it off. When the readings are
in between these two thresholds, you live the pump alone, in whatever
state it was before.
In pseudo-code:
const float low_threshold = 1.9;
const float high_threshold = 2.1;

void loop() {
    float water_level = get_level_reading();
    if (water_level < low_threshold)
        turn_pump_off();
    if (water_level > high_threshold)
        turn_pump_on();
}

If the difference between these thresholds is larger than the noise
amplitude, noise will not disturb your system.

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


text:
Use TCC1 timer to generate PWM on personnal board built with SAMD21E18A
I'm trying to generate a PWM signal from TCC1. I have a personnal board built with SAMD21E18A. I want to use pin 27 PA30, in my variant.cpp I have this line:
{ PORTA, 30, PIO_PWM, PIN_ATTR_DIGITAL|PIO_SERCOM, No_ADC_Channel, NOT_ON_PWM, TCC1_CH0, EXTERNAL_INT_10 }, // SWCLK

I understand I can use TCC1_CH0 on this pin with PIO_TIMER. Here is what I've tried at the end of my setup:
  pinPeripheral(27, PIO_TIMER);
  pinMode(27, OUTPUT);

  ....

  Tcc* TC = (Tcc*)GetTC(TCC1_CH0);
  TC->CTRLA.reg &= ~TCC_CTRLA_ENABLE;
  TC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV1;
  TC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM;
  TC->PER.reg = 255;
  TC->CC[0].reg = 128;
  TC->CTRLA.reg |= TCC_CTRLA_ENABLE;

But it's not working: I have nothing on my pin.
Edit: I've also tried this in my setup:
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(TCC1_GCLK_ID) |
                     GCLK_CLKCTRL_GEN_GCLK0 |
                     GCLK_CLKCTRL_CLKEN;
  while (GCLK->STATUS.bit.SYNCBUSY);

  Tcc* TC = (Tcc*) TCC1;
  TC->CTRLA.reg &= ~TCC_CTRLA_ENABLE;

  TC->WAVE.reg = TCC_WAVE_WAVEGEN_NPWM;

  TC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV1 |
                   TCC_CTRLA_RUNSTDBY;

  PORT->Group[PORTA].PINCFG[30].bit.PMUXEN = 1;
  PORT->Group[PORTA].PMUX[15].reg = PORT_PMUX_PMUXE_E;

  TC->CC[0].reg = 1000;
  TC->CC[1].reg = 4000;

  // Activer le timer
  TC->CTRLA.reg |= TCC_CTRLA_ENABLE;
  while (TC->SYNCBUSY.bit.ENABLE);

I have something on my oscilloscope, but the signal seems not to be good, HIGH signal is very very quick and low signal very long.

For example, settings for ATSAMR21G18A (it is similar to you MCU), PA08 PWM:
Pin init:
// GPIO PA08 PWM (DO)
PORT->Group[0].PINCFG[8].reg = PORT_PINCFG_PMUXEN;
PORT->Group[0].PMUX[8/2].bit.PMUXE = PORT_PMUX_PMUXE_E_Val; // TCC0/WO[0]

Timer init:
void timer0_init()
{
    GCLK->CLKCTRL.reg =   GCLK_CLKCTRL_ID_TCC0_TCC1 // Gen Clk Sel ID TCC0_TCC1
                | GCLK_CLKCTRL_GEN_GCLK0    // Generic clock generator 0
                | GCLK_CLKCTRL_CLKEN;       // Clock Enable

    PM->APBCSEL.reg = PM_APBCSEL_APBCDIV_DIV1;      // Divide by 1
    PM->APBCMASK.reg |= PM_APBCMASK_TCC0;           // TCC0 APB Clock Enable

    TCC0->WAVE.reg = TCC_WAVEB_WAVEGENB_NPWM;

    TCC0->PER.reg = 80; //TCC0/WO[0] PWM 100kHz DT=50%
    TCC0->CC->reg = 40;

    TCC0->CTRLA.reg = TCC_CTRLA_CPTEN0 | TCC_CTRLA_ENABLE;  // Enable
}

I have tried something similar @Dimitri but it's doesn't work my doubt come from this line in my variant.cpp{ PORTA, 30, PIO_PWM, PIN_ATTR_DIGITAL|PIO_SERCOM, No_ADC_Channel, NOT_ON_PWM, TCC1_CH0, EXTERNAL_INT_10 }, // SWCLKI'm not sure about NOT_ON_PWMcan I useTCC1_CH0for PWM`??


text:
How to compile without adding the bootloader?
I'm using a standalone atmega328p with a 16MHz crystal.
I'm programming it via avrdude on a raspberry pi, using the SPI and RESET pins.
When I compile my program, this is what I see at the end of the output:
----------------
Device: atmega328p

Program:    4152 bytes (12.7% Full)
(.text + .data + .bootloader)

Data:        253 bytes (12.4% Full)
(.data + .bss + .noinit)

As far as I understand, the bootloader is used to program the chip via UART, which I do not need(?). I'm assuming that the bootloader is still being compiled because of the output above containing .bootloader in the program part.
My program is compiled using the arduino SDK, with the following Makefile
ARDUINO_DIR = /usr/share/arduino
BOARD_TAG = uno

include /usr/share/arduino/Arduino.mk

I went through Arduino.mk and found this on line 1626:
ifndef AVRDUDE_ISP_BURN_BOOTLOADER
    ifneq ($(strip $(BOOTLOADER_FILE)),)
        AVRDUDE_ISP_BURN_BOOTLOADER += -U flash:w:$(BOOTLOADER_PARENT)/$(BOOTLOADER_PATH)/$(BOOTLOADER_FILE):i
    endif
endif

Which supposedly provides an option to turn off adding the bootloader but I couldn't figure out how to use it, so I just commented the line out:
ifndef AVRDUDE_ISP_BURN_BOOTLOADER
    ifneq ($(strip $(BOOTLOADER_FILE)),)
        # AVRDUDE_ISP_BURN_BOOTLOADER += -U flash:w:$(BOOTLOADER_PARENT)/$(BOOTLOADER_PATH)/$(BOOTLOADER_FILE):i
    endif
endif

But still, after compiling i see the .bootloader part and the program size remains the same.
Is it possible to tell it to skip adding the bootloader?
And yes, this is completely unnecessary for my application, I just want it, I want it bad.

Seeing .bootloader section in size output doesn't mean it's really present. It just means the sum of all three is 4152 bytes.
You can check the hex file if it contains large block of data at the bootloader address space. The main program starts at the lower adresses and then there should be big gap and at the end bigger chunk of data with adresses in bootloader section (but only if you really have a bootloader).
But unless you program also BOOTRST fuse, it won't start in bootloader anyway.
Usage of AVRDUDE_ISP_BURN_BOOTLOADER is normal environment variable (can be also set inside of Makefile) and as it's tested for not being present so you can just check if it's not being set somewhere in Makefile

Is there any tool that allows for easier preview of the whole address space?

I found this question which shows that the bootloader's address space is 7800 to 7FF0. I also confirmed that by taking a look at atmega328p's bootloader hex file stored in /usr/share/arduino/hardware/arduino/bootloaders/atmega/ATmegaBOOT_168_atmega328.hex and indeed the first line is this:
:107800000C94343C0C94513C0C94513C0C94513CE1

Hex file format explained here.
So I then went back to my compiled hex file and checked whether there's anything at this address and there wasn't.
So apparently my program does not contain the bootloader.
I'm adding this as a separate answer with all the details because it took me some time to figure it out after reading KIIV's answer, credit goes to him.

I strongly doubt the compiler adds the bootloader. What that message is probably trying to tell you is that the bootloader is being included in its assumed address space.
There are various bootloaders, Optiboot is only 512 bytes. If you are programming directly (not via a bootloader) then the bootloader isn't required, of course.
If you program via SPI and set the BOOTRST flag appropriately then the processor will boot directly into your code which will save a small amount of time as the bootloader waits to see if there is any serial input for reprogramming. Plus, you get another 512 bytes for your code.
In your case, it hardly matters as the reported 4152 bytes is way short of 32 KB.


text:
How do I control a BLDC with greater precision using bluetooth?
I am building a quadcopter drone and I have 4 BLDC motors that I can control using an HM10 Bluetooth module and the "Dabble" application.
My problem is that when I use a virtual joystick in the "gamepad" module of the Dabble application to control the speed of the motors, it seems to be limited to 2 or 3 speeds. The joystick module that I am using is supposed to have values of 0 to 7 depending on the distance of the joystick from its center. Yet the motor only moves once the joystick is halfway away from center, and then it only spins at a couple different speeds when I push the joystick further. Here is my code:
#include <Servo.h> //Servo library
#include <Dabble.h> //Dabble library for bluetooth connection

#define INCLUDE_GAMEPAD_MODULE //Includes Dabble Gamepad module
#define CUSTOM_SETTINGS

Servo ESC1; //define the 4 motors
Servo ESC2;
Servo ESC3;
Servo ESC4;

int Speed; //create a variable for speed of motors

void setup() {
  Dabble.begin(9600); //Set the baud rate for the HM10 to 9600
  ESC1.attach(9); //Set the motors to their corresponding pins on the arduino
  ESC2.attach(10);
  ESC3.attach(11);
  ESC4.attach(12);
}

void loop() {
  Dabble.processInput(); //Refresh information from the Dabble application
  Speed = GamePad.getRadius(); //Get a value from the Dabble application corresponding to the distance  of the joystick from center (0 to 7)
  Speed = map(Speed, 0, 7, 0, 180); //translate the value from the Dabble application (0 to 7) into the "language" of the motors (0 to 180)

  ESC1.write(Speed); //Set the motors to the new speed
  ESC2.write(Speed);
  ESC3.write(Speed);
  ESC4.write(Speed);
}

Can you check what values the Dabble application actually sends? That might show us on which side the problem is.

that sounds like a good idea but I am not too sure how to go about that. The dabble app is on my phone and I cannot have my laptop connected to the arduino while this is running as apparently it will fry the USB port

Update: I'm silly, I can simply unplug the motor and then read the data while connected to my laptop. Turns out the arduino is receiving all values 0 through 7 as intended. The problem must be with the BLDC somehow.


text:
Wake esp8266 from deep sleep with PIR but disable while running code
I am using an ESP8266 to control a ring of neopixels. I want to use a PIR to trigger a brief light show. I'm using batteries and need them to last as long as possible.
I have it working by checking the PIR for motion.  If there is motion I run the light show. If no motion I put the ESP8266 into deep sleep for 15 seconds. When I wake I try again.
I would prefer to use the PIR to reset the ESP, and I did get it to do that but the problem was that further movement would reset again and start the light show from the beginning. I would like to be able to disable reset while I'm running code.
I did some research and found this:
PIR motion wake ESP8266 from deepsleep
It's pretty much what I need.
Is there a final circuit diagram or a similar solution?
Thanks.

Hi I have being using the circuit below now for a few weeks and all seems to work.
When I wake from deep sleep I set the Latch pin to 0 to prevent any more resets. I do the work, I check if there is still motion by reading PIR out, if no movement I set the Latch pin to 1 and go into deep sleep.

Have you measured the current consumption when the PIR is not detecting anything ? To me it looks like 2.5mA if R3 is only 1k.

Updated R3 to 47K and works fine for the last few days. Thanks.


text:
Motor Shield Enable and Input Pins

Hello,
I am new to the Arduino UNO board and am trying to make a dc motor run using the MATLAB software. The motor is connected to the motor shield board in a similar way shown in the picture below (taken from another question asked here). It runs use the IDE software with the motor shield library but I would like it to run it on MATLAB. I am not able to find out what enable pin, input A and input B for any of the motors. Any help would be greatly appreciated.
The working code from Arduino IDE examples:
// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

AF_DCMotor motor(4);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  // turn on motor
  motor.setSpeed(200);

  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tock");

  motor.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tech");
  motor.run(RELEASE);
  delay(1000);
}

please copy the working code and paste it into your question

Thank you for having a look at this issue. I pasted the working code to the question.

you almost had the code formatting correct ... the code delimiter is ```

the motor shield uses a shift register to control the motors ... the arduino GPIO pins are not connected directly to the motor driver


text:
Why my pushbutton always reads LOW?
This is the code I used in  my project
void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(5,INPUT);
}
void loop() {
  Serial.println(digitalRead(5));
  if(digitalRead(5)==HIGH){
    blink(12,100);
    blink(11,100);
    blink(10,100);
    blink(9,100);
    blink(8,100);
    blink(7,100);
    blink(6,100);
    Serial.println("blink done");
  }

}
void blink(int a,int b)
{
  digitalWrite(a,HIGH);
  delay(b);
  digitalWrite(a,LOW);
  delay(b);
}

Project link
https://www.tinkercad.com/things/55vY18FFxDR-blinking-led-wave/editel?sharecode=xQAM80Uu6sJ-hBnLLd04KasomJ2eNNzWLgKZMARe4ig

connect only the switch, resistor and LED ... determine which two pins are connected when you press the button ... I suspect that the top left pin is always connected to the bottom left pin

L1 and L2 or R1 and R2(L for left, R for Right) are connected when the button is open.
[link]https://www.tinkercad.com/things/kMT2yOJpFzg-analog-read/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=OoTMPbTeJWJGX6WAKZCwLJWxiERzOEBsVfjqZH9p4Kw
this is where I checked it.

you have brown wire connected to L1, which is always connected to L2, and L2 is connected to ground ... why are you surprised that the brown wire is always grounded?

Yes I am aware of it, but the issue I am concerned about is that it neither displays 1 nor does the blink function after pressing the button. I tried moving the D5 pin jumper to j30 and it displayed 1 and the blink started to work (as R1 and R2 are connected but it defies the purpose of switch).

You mean when you short 5V to GND by pressing button (that is how you have that wired), it's not working? Maybe polyfuse is taking some time to reset, or USB port protection

remove the 5 V wire at a30 ... move D5 to j30 ... enable internal pullup resistor pinMode(5,INPUT_PULLUP);

I changed the if condition digitalRead as LOW and as @jsotola said I have changed the pinMode to INPUT_PULLUP, IT WORKED...somehow....
It is highly appreciated if you could explain why the 5 v wire and that typical pushbutton connection didn't work

in the circuit above, D5 is always connected to GND ... connecting 5 V to GND does not do anything to raise the voltage at D5 ... in a real circuit, a connection between 5 V and GND could easily damage something

Understood but why the below given typical pushbutton circuit even works and not here.
Is it possible to remake that pushbutton here......?
My simulation references:
https://imgur.com/a/jUagd1q     (image)
https://imgur.com/a/vnZSJ6H     (video)

When you press the button, you short the bottom blue (GND) and the bottom red (+5V) lines. That will in the least serious case cause your Arduino to reset, but could also damage the button, burn a wire or a capacitor, or brick your Arduino. There's some protection on the board to prevent serious damage or even injury to someone, but still you should absolutely avoid shorting +5V to GND.
The fix is actually quite simple: Replace the short blue wire with a large resistor, something like 10k. Then the Button will still read low when it's not pressed, but read high when it's pressed. That's called a "pull-down" resistor.

the OP is running a simulation ... the short circuit probably is not simulated ... your answer is applicable to real hardware only

That's an point to be noted but it did not work here as it is just a simulation.


text:
Best Solution to Parallel UART reads with Arduino Due
I have 4 Arduino boards pushing data over UART to 4 serial ports on the Arduino Due at 115200 baud rate.
Data format - <Short URL>,<Number of the Node>
Eg: px.ht/d/mCxG,1"
Arduino Due has 4 hardware serial ports and one native USB port. I want to interface all the 4 UART nodes to each hardware serial of the Due and then push this data onto the SerialUSB port which is native USB at baud rate of 2000000.
What did I try?

Sequential read of all Serial ports - Obviously poor performance
Used Serial Events - For some reason never able to get the callback triggered.
Used some FreeRTOS library and there are a lot of data misses.

When using RTOS, the data from multiple nodes is getting mixed up and printed incorrectly. I'm looking for some efficient way to read parallel data from all UARTs without data overlap and stream data and given the MCU on Arduino Due is very powerful I don't think that's what is bottlenecking the performance.

Sequential read of all Serial ports - Obviously poor performance ... why should the performance be poor? ... have you tested this?

Add a line terminator to your data format (e.g. '\n'). This will make your life much easier.

@jsotola It seems the arduino's wrappers for serial API's are very slow and reading/managing the data is very slow. Yes i did test it

@EdgarBonet Yes I do have a delimiter at the end, however what's the idea you have that could make it easier? You want me to implement a logic to look for this \n and not print until it is found?

this may help ... https://gammon.com.au/serial

@Ergophobia - FWIW, "Grammer" is spelt grammar, i.e. with an "a", not an "e".

It seems the arduino's wrappers for serial API's are very slow

They aren't. There are some functions that depend on timeouts: these can
indeed be very slow. However, if you read the ports in a non blocking
fashion, everything should be fast. Non blocking basically means never
waiting, and never trying to read more bytes than what is currently
available(). For example:
const int buffer_size = 64;  // tune to taste

char buffer1[buffer_size];
int size1 = 0;
// same for buffer2, size2, etc.

void loop() {
    while (Serial1.available()) {
        char c = Serial1.read();
        if (size1 < buffer_size - 1)
            buffer1[size1++] = c;  // buffer the incoming character
        if (c == '\n') {  // found end-of-message
            buffer1[size1] = '\0';  // terminate the string
            Serial.print(buffer1);  // send through USB
            size1 = 0;  // get ready for next message
        }
    }
    // then the same for Serial2, ...
}

If you know a bit about object oriented programming, you can easily
rewrite this in a more elegant way, with no repeated code.

Thanks @EdgarBonet, I'll definitely try out this logic, however I'm wondering if there's a way I can utilize DMA of the SAM3X to directly push data from UART buffer into the USB buffers. I believe this significantly increases performance. What do you say? Is there a DMA wrapper you're aware of that I can use with Arduino IDE?

There is no DMA-specific support in the Arduino APIs that I know about. But given that you have a fast CPU, I would expect you don't need it.

@Hako don't lose sight of the fact that the data arrives at snail's pace ... if the computer was a person, a byte would arrive once a week

@jsotola hahahaha, ofcourse i understand sam3x runs at high frequencies but my concern is these nodes might increase in future and I need my code to be scalable. Anyway, let me first try out the edgar's code and come back with some quick results.


text:
Make two LEDs fade in and out with with different PWM values
I have two UV leds, one Vf 3.3V @ 150 mA and the second one Vf 5V @ 150 mA. I need a circuit to make them fade in and out alternatively, i.e., as one goes dimmer the other goes brighter and vice versa. I tried an Arduino PWM transistor approach with the Attiny85 board and the code below and it works, but I need the ledPin2 led to work with at a lower maxbrightness. How can I modify the code so that I can set the maxbrightness for ledPin2 to be around 25, while the maxbrightness for ledPin1 remains 255 and yet both take the same time to fade in and out?
int ledPin1 = 0;
int ledPin2 = 4;
int minbrightness = 0;
int maxbrightness = 255;
int fadeAmount = 1;
int tim=4;

void setup()  {
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
}

void loop()  {
  analogWrite(ledPin1, minbrightness);
  analogWrite(ledPin2, maxbrightness);
  minbrightness = minbrightness + fadeAmount;
  maxbrightness = maxbrightness - fadeAmount;
  if (minbrightness == 0 || minbrightness == 255 ){
    fadeAmount = -fadeAmount ;
  }
  delay(tim);
}

Why not make the change in hardware? Much simpler and no need to change any code. If you really don't want to, why not simply try putting maxbrightness/10 into the analog write for the second LED? You might have to change the variable to a float to do it in the approximately similar time (otherwise you'll only really change a value for the brightness of the second one approximately every 5 counts).

I'd like a code solution so it's easier to use it in another configurations. Also, if I just divide maxbrightness by 10, I am afraid the leds might get out of synch after some cycles.

I don't think you have much choice than to come up with a sort of a counter and instead of having a single variable for the brightness of all the LEDs, you'll have to maintain a separate brightness variable for each channel which will have its own unique dimming profile. You'll then have to empirically determine how many counts it'll take for you to decrease/increase the PWM duty cycle on each separate channel (since perceived brightness isn't linear).
Something like this? The brightness of 32 and a modulo 8 was chosen to be a factor of 256, so it's more or less synced.
int ledPin1 = 0;
int ledPin2 = 4;
int brightnessLP1 = 0;  //begin with the LED off
int brightnessLP2 = 32; //begin with the LED on
int fadeAmount = 1;
int tim=4;

void setup()  {
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
}

void loop()  {
  //counter value accommodates the modulo below
  for(int brightnessCounter = 1; brightnessCounter < 257; brightnessCounter++) {

     analogWrite(ledPin1, brightnessLP1);
     analogWrite(ledPin2, brightnessLP2);
     brightnessLP1 = brightnessLP1 + fadeAmount;
     if(brightnessCounter  % 8) {
       brightnessLP2 = brightnessLP2 - fadeAmount;
     }
     delay(tim);
  }
  fadeAmount = -fadeAmount;
}

I'm sure you could make it cleaner or link the brightness values to the counter, but I'll leave that to you.

Thank you. I can work from there.

Of course, you're welcome!


text:
Why isn't pin 6 on my Adafruit Feather RP2040 being sent high when I ask it to?
I have an Adafruit Feather RP2040 (pinouts) connected via pin 6 to a relay. The code (below) triggers the relay when a separate color sensor returns "enough" red values.
The color sensor works (confirmed by the serial print statements); the on-board LED (connected internally to pin 13) lights up when it should; but I don't get any voltage on pin 6 when I should. I'm testing the voltage with a standard multimeter. If I move my connecting wire from pin 6 to pin 13, I get voltage (and the relay activates). Why doesn't pin 6 get voltage? What else can I do to diagnose the issue?
Software versions:

Arduino.CC IDE v2.2.1 (latest)
Arduino IDE Board manager: added https://github.com/earlephilhower/arduino-pico, version 3.6.0 (latest)
Adafruit APDS9960 Library from https://github.com/adafruit/Adafruit_APDS9960, version 1.2.3, released Jan 30 of this year. According to https://github.com/adafruit/Adafruit_APDS9960/tags there is a version 1.2.4 released on May 12th, but since this is just the light sensor code, which is behaving correctly, I don't believe the issue lies here.

Code:
// copied & modified from the source at:
// https://github.com/adafruit/Adafruit_APDS9960/blob/master/examples/color_sensor/color_sensor.ino

#include "Adafruit_APDS9960.h"
Adafruit_APDS9960 apds;

// the pin on the feather that we're using to talk to the relay
#define PIN_TO_RELAY 6

#define BUCKET_FULL_RED 50

void setup() {
  // enable Serial communication
  Serial.begin(115200);

  // try to start the color sensor
  if(!apds.begin()) {
    Serial.println("failed to initialize device! Please check your wiring.");
  }
  else {
    // Assume success
    // Serial.println("Device initialized!");

    // we want color readings
    apds.enableColor(true);
  }

  // define the relay pin as an OUTPUT pin
  pinMode(PIN_TO_RELAY, OUTPUT);
  // start with the relay "open" AKA not running the pump
  digitalWrite(PIN_TO_RELAY, LOW);

  // use the built-in LED as an external signal for "pumping"
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // create some variables to store the color data in; unused, except for 'red'
  uint16_t red, green, blue, clear;

  // for checking the relay pin state
  int relay_pin_state = 0;

  // for extra printing
  int debug = 1;

  // wait for color data to be ready
  while (!apds.colorDataReady()) {
    delay(5);
  }
  // get fresh data; we only care about the red, but we have to read them all
  apds.getColorData(&red, &green, &blue, &clear);

  if (debug) {
    Serial.print("current red value is:"); Serial.println(red);
  }

  if (debug > 2) {
    relay_pin_state = digitalRead(PIN_TO_RELAY);
    if (relay_pin_state == HIGH) {
      Serial.println("steadystate: Relay pin is HIGH / enabled");
    } else {
      Serial.println("steadystate: Relay pin is LOW / disabled");
    }
  }

  if (red > BUCKET_FULL_RED) {
    if (debug) {
      Serial.println("start the pump (for 5 sec)");
    }

    // light up the built-in LED
    digitalWrite(LED_BUILTIN, HIGH);
    // "close" the relay to turn on the pump
    digitalWrite(PIN_TO_RELAY, HIGH);

    if (debug > 2) {
      relay_pin_state = digitalRead(PIN_TO_RELAY);
      if (relay_pin_state == HIGH) {
        Serial.println("pumping: Relay pin is HIGH / enabled");
      } else {
        Serial.println("pumping: Relay pin is LOW / disabled");
      }
    }

    // wait for a while for the pump to do its work
    // 5 sec in ms; TODO: eventually circa 4 min
    delay(5 * 1000);

    if (debug) {
      Serial.println("stop the pump");
    }

    // turn off the built-in LED
    digitalWrite(LED_BUILTIN, LOW);
    // "open" the relay to turn off the pump
    digitalWrite(PIN_TO_RELAY, LOW);
  }
  // no need to cycle quickly; wait 1 sec in ms
  delay(1 * 1000);
}

I just looked more closely at the pinouts page again, and was surprised to see the hole labeled "6" on the front is labeled "GP08" on the back, which corresponds to "GPIO8" in https://learn.adafruit.com/assets/107203. I wonder if I'm sending the "D4" pin HIGH ("GPIO6") instead of the one I'm expecting.

Before getting to far into debugging your code, make sure all your supporting software & libraries are up to date.  I've had early versions of Adafruit libraries act just terribly.

probably because you are not telling it to go high ... set all pins high ... if the pin goes high, then set 1/2 of the pins low ...etc

@st2000 good callout; I've edited the post to include the software versions I'm aware of that could impact this. If there's anything else I could check, please let me know. Thank you!

@jsotola I'm confused; I'm specifically telling pin 6 to go "HIGH" with the digitalWrite(PIN_TO_RELAY, HIGH); line, and then telling it to go "LOW" later. The surrounding lines for the LED_BUILTIN are working correctly, so I assumed that telling pin 6 to go HIGH would work the same way. Maybe not?

A closer look at the pinout chart indicates that "pin 6" may not be the thing that's labeled "6"; will be retesting with pin 8.

... and that was it. What do you all think? Close as a typo for pin "6" vs GPIO pin 8, or put up a self-answer as a warning to others?

I don't know what you should do, but this is a recurring pattern with boards where there are D-numbers and actual proper GPIO-numbers, particularly on ESP8266 boards. You may find this file enlightening. The Philhower stuff may (or may not) have a map in it somewhere from D# to GPIO#

It would be nice if you put up a self-answer, preferably with a photo to make it clear how you were confused by "8" looking like "6" on a PCB.

Turns out I misled you with my ignorance. I took for granted that the thing labeled "6" on the front was in fact Pin 6, but it's not:

Indeed, if I turn it over, that's "GP08":

... and so my code needs to use pin 8, not pin 6.
User timemage pointed out similar confusion on a recent post: D1 mini ESP8266 no sound on speaker where the silk-screened label on the front of the board did not match the actual pin number. They additionally point out a file that I would have never stumbled upon, but demonstrates this mapping: https://github.com/adafruit/circuitpython/blob/16c8c9a739cfe0db2c712696eb340de2d7944d41/ports/raspberrypi/boards/adafruit_feather_rp2040/pins.c#L24, namely:
    { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) },
    { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) },
    { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO7) },
    { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO8) },  /* right here */
    { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) },
    { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) },

The description of the pinout still contains some misleading information, in my opinion:

D6/GP08 - Digital I/O pin 6. It is also SPI1 MISO, UART1 TX, I2C0 SDA and PWM4 A.

Here, it seems to me that this spot is still being called "pin 6".

Doesn't Arduino have defines for pins? E.g. can't you simply type "D6" (or "GPIO_8")? I know it used to have that...

It's a whole new world for me, Daniël! I feel like I'm slowly learning the "language" of things, and being new -- I just took things at face value. It sounds like there's a translation that happens with the MP_QSTR_D6 term, but I don't yet know what that turns into, and if it's obvious at all that it relates to "the thing on the front of the board that says 6".

@DaniëlvandenBerg you linked to unrelated platform

@Juraj whoops... Seems like the library mentioned by adafruit does indeed include the pin definitions: https://github.com/earlephilhower/arduino-pico/blob/db7ba160ae238534ac1d89381748db3ed3b6dfe9/variants/generic/common.h and https://github.com/earlephilhower/arduino-pico/blob/db7ba160ae238534ac1d89381748db3ed3b6dfe9/variants/adafruit_feather/pins_arduino.h , but then it's still D8, not D6. I would've expected D6 to refer to the silk screen up-front, and translate to the correct GPIO number... Odd...

The pin labeled as GP06 on the bottom side of the PCB is labeled as D4 on the top side of the PCB. It is pin 4.
from https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts

D4/GP06 - Digital I/O pin 4. It is also SPI0 SCK, I2C1 SDA and PWM3 A.


text:
How to find out all #define used by arduino-cli in compile?
How to find out all #define used by arduino-cli in compile?
I had seen something some time ago, but I cannot find it again. I think that it was some option somewhere, and the result was that the compile did not end normally, but some generated file contained lots of useful and lots of obscure defined names.
I would like to find everything that's defined in my program, which I want to write, compile, and then run on different Arduinos, but it sometimes need different Serial to be used, different pin assignments, different internal buffer sizes and so on.
And I would like to organize the differences better, than just put all and everything to one big #ifdef - #endif for each extra platform.
Something like:

if it does not have Serial but Serial1, #define Serial Serial1
if it has 2kB RAM or less, set MY_BUF_SIZE to 10; if it has less than 3kB use 30, else use 100.
but if it is Micro Pro, use this pin assignment, else if it is Nano Every use that, else issue error/warning for user, that pins need to be assigned.

And many others...

@dda: Thank for your help :) English is my third foreing language and I am still not good at it.

I am not familiar with arduino-cli. If you can manage to find the g++
command line it uses for compiling your sketch, then you can get the
list you are looking for by using a modified version of that command:

add the options -E -dM
find the option -o output_file and change the name of the output
file to something more appropriate.

Edit: Following a suggestion by @gilhad, you can build the required
command line by piping the output of arduino-cli through sed:
arduino-cli compile | \
    sed -n '/g++.*\.ino\.cpp\.o/{s/-MMD//;s/-o .*/-E -dM -o defines.dump/;p}'

Thank you very much - I just made script, that use the make, which normally runs arduino_cli and simply reuse its output:
make |grep g++|grep .ino.cpp.o|sed "s/-o .*/-E -dM -o defines.dump/"|sh removed one unneeded file
rm defines.d and got defines.dump as result :)  You can add this to your answer for better visibility (or I vill make extra answer for that, but in your answer it would fit better)

@gilhad: I added this to my answer, with a some modifications: I merged the two grep command into the sed call, and removed the compiler option -MMD in order to prevent the generation of defines.d.

Nice, thank you :) I just typed that without thinking much, to try it as soon as possible :) (And to have all the flags and all as near as possible to original build, because my builds are sometimes more complicated)


text:
Reading serial data from Arduino in Python continually
Using a stepper motor and a range finder (TFLuna), I am trying to build a "Lidar" (like a Radar, but with light). Here is the algorithm:

Turn motor one step, calculate angle, measure distance to whatever it hits, giving polar coordinates;
Calculate Cartesian coordinates and send to Python;
Collect a few hundred measurements and show the scatter plot.

This works, but only if I restart the sketch and the Python routine at the same time. After I collected all the data for one plot, I cannot restart the Python script to collect another round of data - it shows that there is no data in waiting. Also, the Arduino script never hangs due to the buffer getting full (as Python has stopped reading).
How can I make it so that the Arduino and the motor do their thing (swinging back and forth 180º, looking at stuff), and I am able to collect an amount of data in Python intermittently -- whenever I choose to restart the script one more time?
Here is the code. First, Arduino. "count" is the number of steps by which the motor has rotated; tflI2C is the range-finder object.
#include <Stepper.h>
#include <Arduino.h>
#include <Wire.h>        // Instantiate the Wire library
#include <TFLI2C.h>      // TFLuna-I2C Library v.0.1.1
#include <math.h>

TFLI2C tflI2C;
int16_t  tfDist;    // distance in centimeters
int16_t  tfAddr = TFL_DEF_ADR;  // Use this default I2C address

const int stepsPerRevolution = 2048;  // change this to fit the number of steps per revolution

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);
int stepCount = 0;         // number of steps the motor has taken

void serialFlush(){
  while(Serial.available() > 0) {
    char t = Serial.read();
  }
}

void setup() {
  // initialize the serial port:
  Serial.begin(115200);
  Wire.begin();           // Initalize Wire library
  myStepper.setSpeed(10);
  //myStepper.step(stepsPerRevolution/2);
  //delay(1000);
  //myStepper.step(-stepsPerRevolution/2);
}

void coordinates(int count){
  struct Polar {
    float angle;
    int16_t distance;
  } pPoint;
  struct Cartesian {
    float xCoord;
    float yCoord;
  } cPoint;

  float angle = count*(2.0*PI)/stepsPerRevolution;
  byte flag = 0;
  //Serial.flush();
  while (Serial.availableForWrite() < sizeof(struct Cartesian)){}
  if(tflI2C.getData(tfDist, tfAddr)){
    pPoint.angle = angle + PI/2.0;
    pPoint.distance = tfDist;
    cPoint.xCoord = pPoint.distance * cos(pPoint.angle);
    cPoint.yCoord = pPoint.distance * sin(pPoint.angle);
    if (pPoint.distance <= 50 ){
      Serial.write((char*)&cPoint, sizeof(struct Cartesian));
    }
  }
  return;
}

void loop() {
  // step one step:
  for (int k=0; k<stepsPerRevolution/4; k++){
    myStepper.step(1);
    coordinates(stepCount);
    stepCount += 1;
    delay(10);
  }
  for (int k=0; k<stepsPerRevolution/2; k++){
    myStepper.step(-1);
    coordinates(stepCount);
    stepCount -= 1;
    delay(10);
  }
  for (int k=0; k<stepsPerRevolution/4; k++){
    myStepper.step(1);
    coordinates(stepCount);
    stepCount += 1;
    delay(10);
  }
  delay(5000);
}

and here is Python:
ardu = serial.Serial('/dev/cu.usbserial-1460', baudrate=115200, timeout=.1)
radarImage = []
structSize = struct.calcsize("ff")
ardu.reset_input_buffer()

i = 0;
while True:
    if ardu.in_waiting >= structSize:
        arduRead = ardu.read(structSize)
        point = list(struct.unpack("ff",arduRead))
        if i <= 10:
            print(point)
        radarImage.append(point)
        i += 1
    else:
        pass
    if i > 2000:
        break
ardu.close()

Here is a sample from a "first round" data collection. Yes, my desk is messy...

the arduino code does not compile without error

I'm not surprised - I only gave you the code that pertains to the serial communication. I'll pop in the entire thing if that helps. Hold on...

RE: "I cannot restart the Python script to collect another round of data" - perhaps you have an issue with the python code too?

What Arduino are you using? It is unclear to me, what exactly happens, when you restart the python script. When exactly did you try to restart it? During the 5s delay? Or during a measurement round? What exactly does happen then? Currently your Serial code doesn't have any possibility to sync between Arduino and python. The python script is not able to detect the start of a new point struct inside the serial stream (you didn't implement any protocol for that).

You might want to reduce your sources to the minimum, reproducible and compilable example that shows the behavior. For example, start removing the Lidar stuff and replace it, if necessary, with a simple dummy.

@chrisl: I have tried to restart the Python at various points during the Arduino execution. I have tried to print "in_waiting" and it gives me zero. You are right about the syncing as such -- but I'd accept nonsensical data for a first draft. I am puzzled why the Arduino code isn't simply stopping at "Serial.availableForWrite()" when I stop reading data on the Python side -- it keeps on running. If there isn't a simple idiom I am missing, I'll try to work with explicit "start running" and "stop running" bytes from Python to Arduino...way more complicated than I wanted for a proof of principle.

@thebusybee: Understood. However, I was really hoping someone would know of a code "idiom" that'd contain the right combination of "waiting for data" and/or "flushing the buffer" for a middle-of-runtime restart of the data transmission. If not -- no big deal. Reducing the code to a minimum is just as much work as upgrading the code to have proper hand-shake communication with explicit start and stop "commands" issued by the Python code...a lot more effort that I wanted because ultimately I just want to visualize the data on a TFT display.

Well, you do not expect each of us to invest the time to wade through all that code, do you? ;-) Lesson to learn: develop software in baby-steps, not as big-bang. Separate issues. Experiment to understand how things work.

@thebusybee: Absolutely not!! If the solution isn't obvious, or what I am missing isn't trivial, I wouldn't expect anyone to go into more troubleshooting efforts than I am willing to engage in. However, sometimes it happens that a problem has a, "Oh, you simply do..." solution. It's worth checking whether there is. :) It is very hard to be diligent when the purpose of the code is to simply check whether the quality of the provided data makes in even worth to pursue the project any further.

I am puzzled why the Arduino code isn't simply stopping at "Serial.availableForWrite()" when I stop reading data on the Python side -- it keeps on running.

This depends on the Arduino board used - specifically on if it has native USB support. Boards without native USB support (like Uno or Nano) use a second chip, which receives UART (Serial) data from the main chip and interfaces that to USB. The main chip cannot know about the state of the USB chip, so it will send regardless of a program listening.
Boards with native USB support somewhat depend on the OS/driver/program to collect the data from the USB endpoints. If your program doesn't collect that data, but also doesn't close the connection, then the data will pile up in the buffer and availableForWrite() should return 0 when the buffer is full (blocking further writing to Serial). But if your program closes the connection correctly (as it should on exiting), then the Serial data doesn't even get send, but discarded. See Majenkos answer to this question, which is relevant here.
So generally: No, the Arduino won't stop sending data, only because you don't listen. Building a simple command system to tell the Arduino to start/stop sending data is a common way to handle this situation. Or you could implement a protocol, which lets the python script correctly detect start and end of each data packet.

This was way more effort than what was warranted for a quick-and-dirty data dump and visualization, but ultimately I did succeed, sort of, by implementing a "Send 'TURN' command to Arduino, Arduino calculates struct and sends to Python, Python sends next 'TURN' command," song and dance. After that it was STILL hanging randomly until I added a whole bunch of explicit buffer flushes and carefully timed "delay()-s" into both codes. The irony is that the data ultimately didn't even look that impressive -- not impressive enough to polish the project further.


text:
Need help with parsing NWS JSON weather alerts causing reset on ESP8266
I'm trying to parse the JSON string from the National Weather Service Alerts and am encountering a problem where the code can't parse the value and the device auto-resets.  I've used this code before on a different API to get the current weather conditions, and that works fine - I'm not sure what I'm doing wrong and would greatly appreciate any advice or help.  Thanks!
Here is the error:

21:13:07.521 -> wdt reset
21:13:07.521 -> load 0x4010f000, len 3424, room 16
21:13:07.521 -> tail 0
21:13:07.521 -> chksum 0x2e
21:13:07.521 -> load 0x3fff20b8, len 40, room 8
21:13:07.521 -> tail 0
21:13:07.521 -> chksum 0x2b
21:13:07.521 -> csum 0x2b
21:13:07.521 -> v00045d00
21:13:07.521 -> ~ld
21:13:07.555 -> ����n�r��n|�l�l`b��|r�l�n��n�l`��r�l�l��

And here's my code:
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>

const char* ssid     = "mySSID";                      // SSID of local network
const char* password = "myPassword";                 // Password on network

WiFiClient client;
char weatherServerName[] = "api.weather.gov";
String result;

//For testing change this zone to any zone from the NWS that's currently experiencing a weather alert
//Find an active alert area by going to https://api.weather.gov/alerts/active and looking for the code in the "affectedZones"
String zone = "LEZ144";

bool hasAlert = false;

void setup() {
  Serial.begin(115200);
  Serial.println("=====================================================================================================");
  Serial.println("Connecting");

  WiFi.begin(ssid, password);

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

  Serial.println("Connected");
  delay(1000);
}

void loop() {
  Serial.println(":D");
  getWeatherAlerts();
  delay(100000);
}

void getWeatherAlerts()
{
  String server = weatherServerName;

  if (client.connect(server, 443))
       {
          client.println("GET /alerts/active?zone=" + zone);
          client.println("User-Agent: ArduinoWiFi/1.1");
          client.println("Connection: close");
          client.println();
          }
  else {
         Serial.println("connection failed");        //error message if no client connect
         Serial.println();
       }

                                       //waits for data
  while (client.connected() || client.available())
       {                                             //connected or data available
         char c = client.read();                     //gets byte from ethernet buffer
         result = result+c;
       }

  client.stop();                                      //stop client
  result.replace('[', ' ');
  result.replace(']', ' ');
  Serial.println(result);
  char jsonArray [result.length()+1];
  result.toCharArray(jsonArray,sizeof(jsonArray));
  jsonArray[result.length() + 1] = '\0';
  StaticJsonDocument<8196> root;
  DeserializationError error = deserializeJson(root, jsonArray);

  if (error)
    {
      Serial.println("parseObject() failed");
    }

  String features = root["features"];

  Serial.println(features);

  if(features.length() == 0)
  {
    Serial.println(features);
    hasAlert = false;
  }
  else
  {
    String severity = root["features"]["severity"];
    Serial.println(severity);
    if(severity == "Moderate" || severity == "Severe")
    {
      hasAlert = true;
    }
    else
    {
      hasAlert = false;
    }
  }

  Serial.println(hasAlert);
}

print what is received before you start trying to alter it

By default, the size of the stack is limited to 4KB on ESP8266, so you cannot store an 8KB document there.
To fix this issue, replace the StaticJsonDocument with a DynamicJsonDocument to move the buffer to the heap.
See also: Why does my device crash or reboot?

There is a good clue in the first line of your reported error:
21:13:07.521 -> wdt reset

The ESP-8266 Watchdog Timer (WDT) will reset the device if it has not been correctly 'fed' for a period of time (the watchdog timeout).
As @Juraj noted, the ESP-8266 Arduino libraries 'helpfully' add WDT feeds at various points, suggesting the timeout is because your code is either crashing (overflowing into invalid program code) or is timing out (valid code, but stuck in a loop).
The backtrace information printed on the reset can be used to find where the WDT happened specifically in your code, so you can find the issue (which could be the one @Benoit Blanchon noted). I have found this exception decoder to be very useful to translate the code to the functions in your code.
Also worth noting that the 'garbled characters' after the WDT reset backtrace information is the bootloader startup message, which is fixed at 74880 baud, you can change baud rate of your serial terminal to see those (and 'garble' the other messages).
(Info about watchdog timers and feeding below isn't directly relevant in this case, as @Juraj noted, but is left in for context)
This is an example document from TI introducing watchdog timers. For the ESP8266, you might find this techtutorialsx document more useful. In summary, you need to either turn off the watchdog, or issue periodic
ESP.wdtFeed();

commands. Turning off the watchdog is an appealingly easy option, but it disables a really useful tool to help you to make your project/product handle unexpected conditions/bugs more gracefully, so I'd encourage you to learn how to use it and then feed it as above.
(As @Benoit Blanchon noted, there are other issues on the implementation, which should be addressed, and perhaps deserve a separate post in code review. However I wanted to explain the reason for the reset you asked about, which isn't specifically JSON-related, and will continue to occur unless you take action as above)

here the wdt is not fed after the crash

@Juraj the wdt is not fed at all, which is causing the reported wdt reset.

on esp8266 the wdt feeding is automatic if the loop() ends,in delays, in many function calls

Thanks @Juraj, updated accordingly.

so "the size of the stack is limited to 4KB on ESP8266, so you cannot store an 8KB document there." is for me a good explanation for the crash. the "wdt reset' is just a distraction. Benoit Blanchon is author of the ArduinoJson library


text:
Pn532 doesnt detect sometimes
Im using ESP32 with PN532 NFC module with I2C
And Im using this library https://github.com/elechouse/PN532
And using this documents https://www.elechouse.com/elechouse/images/product/PN532_module_V3/PN532_%20Manual_V3.pdf
Normally, it finds the PN532 and reads the card successfully when I scan it. However, sometimes after starting, it doesn't detect the PN532 and never finds it.It say PN53x card not found!. When I unplug and plug in the sensor cable, the ESP32 can detect the sensor, but I shouldn't have to do it this way. Therefore, if it can't find the PN532 twice, I wanted to reset it as follows:
void resetPN532() {
digitalWrite(PNP532_IRQ_Pin, LOW);
delay(100);
digitalWrite(PNP532_IRQ_Pin, HIGH);
delay(100);
digitalWrite(PNP532_RSTO_Pin, LOW);
delay(100);
digitalWrite(PNP532_RSTO_Pin, HIGH);
 }

This is code for the find:
`  uint32_t versiondata = nfc.getFirmwareVersion();

  if (Serial.available() > 0) {
  processCommand("command");
  }

  if (!versiondata) {
    Serial.println("PN53x card not found!");
    resetCounter++;
    if (resetCounter >= 2) {
      Serial.println("Reset PNP");
      resetPN532();
      resetCounter = 0;
    }

    return false;
  }

`

This is my connections:
enter image description here
Why I faced with this issue I dont know but how can I solve this problem ?
. When I unplug and plug in the sensor cable, the ESP32 can detect the sensor, but I shouldn't have to do it this way. Therefore, if it can't find the PN532 twice, I wanted to reset it as follows:

the code does not compile without error

I share the part of the code. Not all of them

@jsotola what you mean?

" PN53x card not found" basically means it can't establish a communication with PN53x. You need to check your wiring, your power supply, your noise, and your code. to find out the root cause. If the sensor can't be found, how can you be sure that you can reset it via software? You got one problem in establishing a communication, instead of finding the root cause, now you got two problems.


text:
Arduino Uno, does a lower Aref voltage work well for measuring current? without increasing ADC integral non-linearity
I want to measure current using a Arduino Uno and use a very low resistance of 0.1Ohm or lower for the shunt resistor to measure the current(to reduce power waste and heat generation),
as a result resolution wouldn't be good at lower currents, while I do not need a very good resolution better resolution makes it more dependable and more easy to use and more universal.
and it is very unlikely that I would run close to that many amps through it, as for that it would need 10A of current to reach 1V.
my idea to solve this was to set the Aref to a lower voltage of 1.1V by setting it to the internal Aref this would mean it could measure up to 11A of current but also has 5 times as much resolution.
but I noticed people online seemed to never do this, and instead just use higher restance of 1Ohm or such or directly use a external higher resolution ADC(and still only use a small part of it) or some dedicated amp measuring hadware. so I started to wonder does the internal ADC in the arduino behave worse when set to 1.1V aref instead of the default 5V aref despite the datasheet saying it can go down to 1V aref?
setting the Aref inside of the arduino to the internal Aref of 1.1V and using a 0.1 Ohm resistor would give +-10mA resolution(up to 11A), if I where to use a 1 Ohm resistor like most others do it would even give 1ma resolution(up to 1.1A).
is there something I am missing? which is the reason why other people do not change the Aref for this?
does lowering the Aref to 1.1V cause a reduction in the lineairity of the ADC curve(so that at some places the steps are a bigger difference than at some other places) compared to when it is kept to the default 5V Aref?
or as a shorter more TLDR question:
does anyone have graphs or data available about the linearity of the arduino ADC with the ADC Aref at different voltages?
mostly to compare the linearity at a Aref of 1.1V and 5V.
definitions
ADC Linearity in this context refers to integral non-linearity
extra
I already looked into those 4 sources:

Can i supply the AREF pin with an Analog pin from the same board?
https://support.arduino.cc/hc/en-us/articles/360018922239-About-the-AREF-pin
https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/
https://electronics.stackexchange.com/questions/45664/voltage-limitations-on-aref-for-arduino
https://content.arduino.cc/assets/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf?#G1202563

they all seem to confirm exactly what I was thinking with my solution.
but none of them seem to give any info about how actually the Analog to Digital converter works on different Aref voltages, so for example if using a lower Aref might for example make the steps per volt less of a straight line and instead more of a curve or such where steps might all have different voltage difference differences?
the datasheet I found only gave a fixed offset value but not how or if it was affected by the used Aref voltage, and neither any form or graph or such of the typical integral non-linearity.
only one value that it has a integral non-linearity of 0.5LSB
things people mentioned

apaerently the arduino ADC indeed has some non linearity, but no actual values are given and neither if it also depends on the Aref voltage, people mention/reffer that the arduino ADC should be most efficient at the middle value of the ADC https://arduino.stackexchange.com/a/69390/70020
to reduce energy wasting and maintain higher resolutions people recommend adding in a differential amplifier which would allow using even lower shunt resistors and still a good resolution. in theory this should do the same as changing the Aref, but then allowing even more sensitivity since the Aref can only go down to 1v so 5 times amplificaton

It may be impossible to answer without being in the heads of the people you mention. My guess is that they were simply unaware that Aref can be changed. You may want to measure the conversion noise with INTERNAL, but I doubt it could be larger (in real voltage) than with DEFAULT.

With respect to answerability, like Edgar Bonet said. They and you are potentially going down the wrong path anyway. The most essential part of what I would say about that has been said by somebody else in this answer or its comments.

is there a reason or do they just all follow and clone similar guided - we can't really explain why some people are not doing something. This sounds a bit like an XY problem to me. You say resolution is bad at lower currents. Why do you need good resolution? What are you actually trying to achieve? Even a poor resolution solution could detect if a motor is drawing too much current. The Uno isn't really designed as a high-precision instrumentation device. Having said that, using a lower voltage on AREF could help in your situation.

@NickGammon I don't actually need such good precission or accuracy indeed, as long as it is roughly right,
it is for a simple project where it needs to generate output currents in between +-100ma to around +-1A perhaps more in some cases but this is the main usage, it would need steps of around 50ma at most.
the main reason for wanting improved resultion is because with such a arduino setup I doubt many people will actually use high enough currents to not make changing Aref worth it since going over 10A with such a setup doesn't seem smart in general, and most people use it much lower anyway

@EdgarBonet it was indeed surrounding how it would affect such noice and offset in the curve of steps per volt as if they stay lineair or not.
I was thinking about testing it, perhaps wouldn't be the best way, but I thought about using a voltage divider and then comparing the 3.3v to the 5v or comparing some known voltage divider options which might perhaps show some curve shape difference when plotted, for the noise I wouldn't know how to properly test that safely since when it is connected it seems to not be to noisy anyway.

@timemage the comment you linked actually was somewhat usefull, using a opamp might be usefull even though not needed in my case probably, but it would be usefull for using way lower resistance shunts.
it also confirmed the thing I doubted about, about if there are non linearities,but it doesn't show any data or graphs on them or if changing the Aref alters that.
I shall edit my question to be more direct.

for people who don't know, they often don't know what they don't know. For those who know, they thought it is common sense, so not really talk about unless been explicitly asked for. Many nowadays prefer to read internet articles or tutorials instead of reading datasheet or application note, such as this one which talk about things like Ref source.

If you used the 3.3 volt pin as external AREF a 1.5Ω resistor would drop 3V @ 2 Amps, 3V would produce an ADC value of 930 or 2.15mA per ADC count.
If you use the 1.1V internal AREF, a 0.5Ω resistor would drop 1V @ 2A, ADC values would be the same.

Hi, that was the thing I thought as well, my question was a little unclear at first however.
but essentially in my question I more meant to ask about if I change the Aref will that change the accuracy at which the real hardware follows the calculations.
since the calculations asume each step is a fixed voltage difference but at different voltages it might be that the hardware would become less consistent in that, so I mostly wanted to know if that was the case for the arduino uno, if the consistency with which the ADC follows the calculations would change decently at a different Aref


text:
The Arduino copy of example code for tone() function produces a compile error: 'tone' is not declared in this scope. How can I fix this?
It's 32-bit ARM core processor is SAM3X8E ARM Cortex-M3 CPU.
Error:
sketch_nov16b\sketch_nov16b.ino: In function 'void setup()': sketch_nov16b:49:43: error: 'tone' was not declared in this scope tone(8, melody[thisNote], noteDuration);
^ sketch_nov16b:61:13: error: 'noTone' was not declared in this scope noTone(8);
^ exit status 1 'tone' was not declared in this scope

Code:
/*

  Melody

  Plays a melody

  circuit:

  - 8 ohm speaker on digital pin 8

  created 21 Jan 2010

  modified 30 Aug 2011

  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/Tone

*/

#include "pitches.h"

// notes in the melody:
int melody[] = {

  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {

  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {

  // iterate over the notes of the melody:

  for (int thisNote = 0; thisNote < 8; thisNote++) {

    // to calculate the note duration, take one second divided by the note type.

    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.

    int noteDuration = 1000 / noteDurations[thisNote];

    tone(8, melody[thisNote], noteDuration);

    // to distinguish the notes, set a minimum time between them.

    // the note's duration + 30% seems to work well:

    int pauseBetweenNotes = noteDuration * 1.30;

    delay(pauseBetweenNotes);

    // stop the tone playing:

    noTone(8);

  }
}

void loop() {

  // no need to repeat the melody.
}

What core are you using?

It's 32-bit ARM core processor is SAM3X8E ARM Cortex-M3 CPU

Does this meet jsotola's request?sketch_nov16b\sketch_nov16b.ino: In function 'void setup()':
sketch_nov16b:49:43: error: 'tone' was not declared in this scope
tone(8, melody[thisNote], noteDuration);
^
sketch_nov16b:61:13: error: 'noTone' was not declared in this scope
noTone(8);
^
exit status 1
'tone' was not declared in this scope

@JohnB I said do not paste into a comment and you pasted into a comment ... this site is not a forum ... it is a question and answer site ... all info must be contained in the question

In short, they just never implemented tone() in the Due/SAM core.
So you're not going to get the normal tone() function working.

The tone.h header is empty.
They probably should done any number of things that would produced a somewhat clearer warning about this.

The counterpart .cpp file has been renamed to .cpp.disabled so that the no attempt is made to compile it and is full of AVR-based code that they'd copied into the project for reference with the intention of replacing it but never did.

There a github issue tracking this. But it hasn't been updated since 2020. That issue references the Arduino forum for apparently working alternative code for producing tones. So maybe try their code.
I don't see any popular alternative packaged as an Arduino library for producing simple tones. However, the chip has a DAC and there is an Audio Library. It's a bit overkill for producing basic tones, but you could modify the example there to fill the buffer with a tone's waveform rather than loading it from an sdcard file.


text:
PubSubClient constructor parameter type mismatch
I am just learning an Arduino so this is totally educational purpose call.
I want to instantiate PubSubClient client with WiFiClient parameter.

#include <WiFiClient.h>
#include <PubSubClient.h>

WiFiClient *wifi = NULL;
PubSubClient client(wifi);

void setup() {
  // put your setup code here, to run once:
}

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

compilation gives me back:
Compilation error: no matching function for call to /home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:116:4: note:   candidate expects 0 arguments, 1 provided
/home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note: candidate: 'PubSubClient::PubSubClient(const PubSubClient&)'
 class PubSubClient : public Print {
       ^~~~~~~~~~~~
/home/tepo/Arduino/libraries/PubSubClient/src/PubSubClient.h:88:7: note:   no known conversion for argument 1 from 'WiFiClient*' to 'const PubSubClient&'

exit status 1

Compilation error: no matching function for call to 'PubSubClient::PubSubClient(WiFiClient*&)'

and listing all the other constructors.
type chain seems to hold:
class WiFiClient : public ESPLwIPClient -> class ESPLwIPClient : public Client -> class Client: public Stream
PubSubClient ctor:
 PubSubClient(Client& client);

so why is it not accepting a WifiClient as a parameter?

PubSubClient client(*wifi);. it will compile, but it will just crash in runtime since there will be no WiFiClient object at address 0

look at the example code in the library

The issue you're encountering with the PubSubClient constructor in Arduino is related to how you're passing the WiFiClient object. You're currently using a pointer (WiFiClient *wifi), but the PubSubClient constructor expects a reference to a Client object, not a pointer.
The WiFiClient class inherits from the Client, so it can be used with PubSubClient. However, you need to pass an instance of WiFiClient, not a pointer to an instance.
Here's how you can correct your code:
#include <WiFiClient.h>
#include <PubSubClient.h>

WiFiClient wifi;
PubSubClient client(wifi);

void setup() {
  // put your setup code here, to run once:
}

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

In this corrected version, wifi is an instance of WiFiClient, not a pointer. When you pass wifi to the PubSubClient constructor, it correctly matches the expected Client& client parameter type.
In C++ a pointer (WiFiClient *) is a variable that holds the memory address of an object.
A reference (WiFiClient &) is an alias for an object.
The PubSubClient constructor expects a reference because it needs to interact with the Client object throughout its lifecycle, and references are generally safer and more straightforward to use in this context than pointers.

yeah, that got it working; however I'm failing to understand where the actual instance of 'wifi' is comming from as I'm not constructing int, rather in the sketch I am using WifiManager that seems 'injecting' it to the declared variable. (I come from java-spring world) That's why I thought pointer will do in this case; it seems a bit weird to me it just "gets supplied" somehow..

What do you mean you're not constructing it? WiFiClient wifi; constructs it. Unlike Java you don't need to do a new procedurally to instantiate a class variable.


text:
ESP32 SPIFFS Write problem
I'm trying to flash a spiffs on a esp32 but it is not working, i'm using these commands from this source:
to create the image:
mkspiffs -c /data/ -b 4096 -p 256 -s 0x100000 spiffs.bin

my output was this:
/test.txt

looks it worked.
to flash the image:
esptool.py --port /dev/ttyCH341USB0 --baud 115200 write_flash -z 0x110000 spiffs.bin

and the output:
esptool.py v4.7.dev3
Serial port /dev/ttyCH341USB0
Connecting...
Failed to get PID of a device on /dev/ttyCH341USB0, using standard reset sequence.
.
Detecting chip type... Unsupported detection protocol, switching and trying again...
Connecting...
Failed to get PID of a device on /dev/ttyCH341USB0, using standard reset sequence.
.
Detecting chip type... ESP32
Chip is ESP32-D0WD (revision v1.0)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: c4:4f:33:24:4f:49
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash will be erased from 0x00110000 to 0x0020ffff...
Compressed 1048576 bytes to 2025...
Wrote 1048576 bytes (2025 compressed) at 0x00110000 in 3.2 seconds (effective 2592.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

To test the file system im using this code to list all files:
  File root = SPIFFS.open("/");
  File file = root.openNextFile()
  while(file){
    Serial.print("FILE: ");
    Serial.println(file.name());
    file = root.openNextFile();
  }

the image is not being written, when i use this arduino plugin it works fine, but if i run the esptool write command the files are not overrided.
can someone help-me?

How do you know the Arduino Plugin works and the ESP tool doesn't? How do you check that the image has been flashed?

@NickS. using a program to list all files, i've edited the question with it.


text:
Use attiny85 reset pin as analog pin
I want to use the reset pin of the attiny85 as an analog pin to read the battery voltage, to be used as low level battery indicator.
So there is a lipo battery that will always be connected to this pin.
I need a high-voltage programmer to do so but I read that the reset pin can be simply an analog pin if the voltage to it is above 2.5v . Is it true?
If so, I can program it with Arduino SPI normally as the battery will never go below 2.5v.
Edit
Thanks @timemage for your answer, it really has good info.
But I can verify that if you give 5v to the Vcc of the attiny and connect a lipo (above 2.5v) to the reset pin, it will work as an analog pin.
I used a potentiometer and yes it is working, you can see more info about this as well in this post.
The real info starts from Post#10.
It is really a complex situation here as what I did was using the reset pin as reset and as an analog pin at the same time. It is not recommended but it works!
Please if you can review the post in the Arduino forums and rewrite your thoughts here it will be useful for more people to get useful info.

See http://www.technoblogy.com/show?LSE

The following was in answer to the question in its original form.
This is kind of more on an electronics question. But it may be of some interest people here, mostly because of Digispark clones that still have their reset functionality.
It's easier to answer these in a different order.

I read that pin reset can be simply analog pin of the voltage to it is above 2.5v Is it true?
If so, i can program it with arduino spi normally as the battery will never go below 2.5v

Practically speaking the answer is best summarized as "no".
It took me a while to realize what you were talking about, mostly because of
this 2.5V number, which I still don't completely understand. Originally I thought you talking about the internal 2.56V reference.  The way I'm interpreting this is "As long as I don't actually cause a reset, is it true that I can use the ADC0 channel that is on the ATtiny85 RESET pin."
Practically, I think no. But, this idea is amusing and also more than a little disturbing.  It seemed that the answer could be a qualified yes only because it seemed ATMEL would need to have done extra work to make this not possible, even if trying to do it is a bit nuts. Naturally, I had to try it.
In testing I found that yes, the RESET pin still seems to function as an ADC channel.  I was able to hook the division point of 2/3rds (ish) voltage divider to the reset and got a reading of 0xAD (as an 8-bit measurement) which is indeed about 2/3rds of 0xFF. At least this is the case with my particular chip under whatever operating conditions.
According to the datasheet the V_RST (nRESET pin voltage threshold)
is specified at 3V to be between 0.2 VCC and 0.9 VCC.  It doesn't seem like you would have good reason to think the chip is certain to stay out of reset below 0.9 VCC which at 5V is 4.5V. I did not experiment with mine to find out where the threshold happened to be except that 1/3 VCC did trigger a reset.
So, I don't know where your 2.5V comes from except to say it's a number near the middle of the possible V_RST range for an AVR at 5V. Even if you find this is where the threshold is for your chip, it isn't specified to be exactly there. The fact that I got a reading at 2/3rds instead of a reset does not seem specified to happen that way according to the datasheet.
Another thing about this is when the pin is used as RESET has its internal pullup is enabled, which is listed between 30K and 60K.  So whatever you connect to your reset pin (your battery) is connected to the AVR VCC through a pullup.
Anyway, it's interesting but is ultimately probably a bad idea.

So there is a lipo battery will be always connected to this pin

If you want to play with this using-RESET-pin-for-ADC-channel thing anyway,
definitely don't have your battery connected to reset when you program, at least not without reasonable series resistance.  Otherwise when your programmer goes to reset your ATtiny85 it will short your battery to GND through the programmer.

I want to use reset pin of attiny85 as analog pin to read the battery voltage to be used as low level battery indicator

Voltage isn't a great indication of the state of charge of batteries generally. Under some conditions you can get a rough idea with it. The flatter the discharge voltage curve is the less useful voltage is as an indication of charge state. Lithium chemistries are sort of prized for producing fairly flat discharge curves at a voltage level high enough to do useful work. Typically a "coulomb counting" method is used instead. Basically you sample current over time and integrate (sum) this, not reading instantaneous (or short term averaged) battery voltage. And that has its own intricacies with not drifting from true value. Getting a reasonable sense of lipo's state of charge is enough of a pain to do well that there exist metering chips specifically designed to do this.  I don't have good recommendations for them, but MAX17043 and MAX17048 are among the first part numbers for this sort of chip found on modules from suppliers of Arduino-related stuff.

I want to use reset pin of attiny85 as analog

For most Arduino users it's really best to leave the reset pin alone. The ATtiny84 is not much larger than an ATtiny85 and gives you an few extra pins and is otherwise very similar. The ATtiny84 also supported by attinycore. If you are hard set on using the ATtiny85 make sure you've exhausted all your options for using your other pins. There are ways to connect multiple switches to a single analogRead() capable pin. There are ways to put LEDs and switches on the same pin if you don't mind the light coming on when you push button, etc.

I need high voltage programmer to do so but

Right, so back onto using non-RESET functionality of the RESET pin the normal way.
Sort of. You don't need high voltage serial programming mode to program your code that use the reset pin onto the chip and then to disable the reset pin and use it via digitalRead()/digitalWrite()/analogRead()/etc.. But you do need high voltage mode to program again after that, either by programming code via high voltage mode or programming (unprogramming really) the RSTDISBL fuse to re-enable RESET functionality that ISP/SPI mode requires. In other words: if you're treating the parts as one-time-programmable then you need only an ISP programmer. But, during development you're probably not going to want to just toss out piles of otherwise perfectly good chips.
If you're determined to use the ADC channel that's on the reset pin, programming RSTDISBL fuse is the thing you want to do. Then you get useful range out of the ADC channel and the ability to disable the pullup, and maybe even fewer random resets.
And yeah, you need a high-voltage mode programmer to recover from that, and you need to be either able to remove the chip from the board or design the board to handle HVSP signals coming to it; in particular to handle 12V that will be applied to reset.  Which is also something that should not make its way to your lipo.

could you see the edit?

I am not chasing down a moving target. If you want to know where the forum poster got their 2.5V figure from ask them, I can't get inside their head. If you'd already taken the time to do what I'd dove in verifying that the reset pin behaves the way it manifestly does, then you should have put that in your original question.