body:
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 [![project][1]][1].

What I want to do with this project is:
1. When the water reaches 2 cm, then the water pump is on while the fan is off.
2. 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][2]).

How to eliminate this problem?

```c
#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");
}
```

  [1]: https://i.stack.imgur.com/U65Xi.jpg
  [2]: https://drive.google.com/file/d/1ZnZDB_p5DCyQzRFeX6tikA9K75JRICJK/view?usp=sharing

title: Please help me with my project of water pump relay switching too fast

Answers: 1

body:
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:

```c
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.

[hysteresis]: https://en.wikipedia.org/wiki/Hysteresis


body:
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:

```c
{ 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:

```c
  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:

```c
  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.

title: Use TCC1 timer to generate PWM on personnal board built with SAMD21E18A

Answers: 1

body:
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
    }


body:
The function of this circuit is that whenever the button is pushed a random led lights up, it’s a relatively simple circuit and I’ve checked my connection and code multiple times i truly don’t know why it doesn’t generate any light
The code is:

```cpp
const int buttonPin = A0;// button pin
const int LEDpins[] = {2, 3, 4, 5, 6, 7, 8};// led pins

void setup() {

    pinMode(buttonPin, INPUT_PULLUP);// declaring button pin as input

    for (int i = 0; i < 7; i++) {
        pinMode(LEDpins[i], OUTPUT);//declaring led pins as output
    }

    for (int i = 0; i < 7; i++)
    {
        digitalWrite(LEDpins[i], LOW);// turing off all the leds
    }

}

bool firstTime = true;

void displayNumber(byte number) { // function for displaying numbers

    digitalWrite(2, number > 1 ? HIGH : LOW);
    digitalWrite(3, number > 3 ? HIGH : LOW);
    digitalWrite(4, number == 6 ? HIGH : LOW);
    digitalWrite(5, number % 2 == 1 ? HIGH : LOW);

    digitalWrite(6, number == 6 ? HIGH : LOW);
    digitalWrite(7, number > 3 ? HIGH : LOW);
    digitalWrite(8, number > 1 ? HIGH : LOW);

}

void loop() {

    while (digitalRead(A0) == HIGH) {
        // do nothing
    }

    if (firstTime) {
        randomSeed(micros());// to increase randomness
        firstTime = false;
    }

    for (byte i = 0; i < 10; i++) {
        int num = random(1, 7);//gives a random number from 1 to 6
        displayNumber(num);
        delay(50 + 20 * i);
    }
}
```

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/aaFuf.jpg

title: Arduino nano roll dice

Answers: 0


body:
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.

title: How to compile without adding the bootloader?

Answers: 3

body:
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

body:
I found [this question](https://stackoverflow.com/questions/46346816/understanding-flash-composition-of-arduino-bootloader) 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.](https://en.wikipedia.org/wiki/Intel_HEX)*

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](https://arduino.stackexchange.com/users/23841/kiiv)'s answer, credit goes to him.

body:
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.


body:
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);
}
```

title: How do I control a BLDC with greater precision using bluetooth?

Answers: 0


body:
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:

https://arduino.stackexchange.com/questions/54625/pir-motion-wake-esp8266-from-deepsleep/54642#54642?newreg=39eea8186cf24833bc4f89d459642c41

It's pretty much what I need.

Is there a final circuit diagram or a similar solution?

Thanks.

title: Wake esp8266 from deep sleep with PIR but disable while running code

Answers: 0


body:
[![Motor Shield][1]][1]

  [1]: https://i.stack.imgur.com/gABEh.jpg

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:

```lang-cpp
// 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);
}
```

title: Motor Shield Enable and Input Pins

Answers: 0


body:
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);
}
```
[![Image of Tinkercad of my work][1]][1]

  [1]: https://i.stack.imgur.com/0crVI.png

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

title: Why my pushbutton always reads LOW?

Answers: 1

body:
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.


body:
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?**

 1. Sequential read of all Serial ports - Obviously poor performance
 2. Used Serial Events - For some reason never able to get the callback triggered.
 3. 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.

title: Best Solution to Parallel UART reads with Arduino Due

Answers: 1

body:
> 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:

```c++
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.


body:
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);
}

```

title: Make two LEDs fade in and out with with different PWM values

Answers: 1

body:
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.


body:
I am attempting to jump to a desired menu item ID in `LCDMenuLib2` using the callback function:

    void  mFunc_jump_to_ID(uint8_t param)
    {
        LCDML.OTHER_setCursorToID(4);
    }

I have also tried the callback function below with the same results.

    void  mFunc_jump_to_ID(uint8_t param)
    {
        SETTINGS_MENU.OTHER_jumpToID(4, 0);
    }

In this menu structure:

    SETTINGS_MENU_add(0, SETTINGS_MENU_0, 1, "Item 1", mFunc_digit);

    SETTINGS_MENU_add(1, SETTINGS_MENU_0, 2, "Item 2", mFunc_jump_to_ID);
    SETTINGS_MENU_add(2, SETTINGS_MENU_0_2, 1, "Item 2, Sub 1", NULL);
    SETTINGS_MENU_add(3, SETTINGS_MENU_0_2, 2, "Item 2, Sub 2", NULL);
    SETTINGS_MENU_add(4, SETTINGS_MENU_0_2, 3, "Item 2, Sub 3", NULL);
    SETTINGS_MENU_add(5, SETTINGS_MENU_0_2, 4, "Item 2, Sub 4", NULL);

The above function when called should jump straight to ID #4 in this case:

    SETTINGS_MENU_add(4, SETTINGS_MENU_0_2, 3, "Item 2, Sub 3", NULL);

Although the function only works if it is not called from a parent but only from a child, as I suspect the parent is already bound to "open the submenu function", in fact, I am not able to call any callback function from a menu item that has submenus.

Therefore for example,

This works:

    SETTINGS_MENU_add(2, SETTINGS_MENU_0_2, 1, "Item 2, Sub 1", mFunc_jump_to_ID);

This does not work:

    SETTINGS_MENU_add(1, SETTINGS_MENU_0, 2, "Item 2", mFunc_jump_to_ID);

I am not sure what I am missing here, I am also not seeing any other settings to call a function when the submenu is opened which would be useful to jump to the desired item. What I am trying to achieve is to jump to the desired value of each submenu previously stored elsewhere showing the current setting selected.

Any ideas on how to solve this would be greatly appreciated.

title: Cannot call callback function from parent menu item using LcdMenuLib2

Answers: 0


body:
I have an Adafruit Feather RP2040 ([pinouts](https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts)) connected via pin 6 to a [relay](https://www.adafruit.com/product/2895). 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:
```cpp
// 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.

title: Why isn't pin 6 on my Adafruit Feather RP2040 being sent high when I ask it to?

Answers: 2

body:
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.

body:
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:

[![feather with pin "6" circled][1]][1]

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

[![reverse face of feather with the same location labeled "GP08"][2]][2]

... and so my code needs to use pin 8, not pin 6.

User [timemage](https://arduino.stackexchange.com/users/70020/timemage) pointed out similar confusion on a recent post: https://arduino.stackexchange.com/questions/94659/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](https://learn.adafruit.com/adafruit-feather-rp2040-pico/pinouts) 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".

  [1]: https://i.stack.imgur.com/hLxZ2.jpg
  [2]: https://i.stack.imgur.com/zi9kS.jpg


body:
I have an Old Feather I am trying to get up and running. To start with I jumper the DFU and enter bootloader. From here I connect on my Phone using the blueconnect app and flash the latest firmware (0.8.1) With the proper arch. I then reboot and everything seems fine with the Phone app. So I go ahead and connect to the computer and try to upload a sketch using the ui. It sees the port just fine and I can get the board information but when I try to upload the blink sketch per the instructions I get...

```
avrdude: ser_open(): can't open device "\\.\COM7": Access is denied.

Failed uploading: uploading error: exit status 1
```

I see some people talking about not using a hub, etc so I tried a USB port on the MB and that didn't help.

Here is the full output...
```
waiting for upload port...
No upload port found, using COM7 as fallback

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmic"C:\..\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\..\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -patmega32u4 -cavr109 -PCOM7 -b57600 -D "-Uflash:w:C:\Users\jacki\AppData\Local\Temp\arduino\sketches\EB761D1819C60BDB44C9F75BB4C9C1A2/sketch_nov12a.ino.hex:i"
ro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\jacki\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM7
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
avrdude: ser_open(): can't open device "\\.\COM7": Access is denied.

avrdude done.  Thank you.

Failed uploading: uploading error: exit status 1
```

I also tried double clicking the reset button right before I uploaded per the additional instructions and that just results in the same

```
Waiting for upload port...
No upload port found, using COM7 as fallback
...
         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
```

And an infinite loop on the upload...

title: (Arduino Feather 32u4) Cannot upload with IDE even after resetting the bootloader on Windows 11

Answers: 0


body:
I have NodeMCU v3 ESP8266 and RFID RC522 card reader. I want to send some data using the insert_status.php API on the server. But it gives an error.
What I want to do is very simple, the php API will run and then add the data to the database.
Also, to see if the problem might be related to https, I tried it as http and this time it gave me a 301 error.

insert_status.php
```
<?php
$servername = "localhost";
$username = "test_user";
$password = "test_password";
$dbname = "test_db";

$name = $_GET['name'];
$time = $_GET['time'];
$rfid = $_GET['rfid'];

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO status (name, time, uid) VALUES ('$name', '$time', '$rfid')";
if ($conn->query($sql) === TRUE) {
    echo "Record inserted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

```

Code

```
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <MFRC522.h>
#include <SPI.h>

#define SS_PIN D4
#define RST_PIN D3

char ssid[] = "Qwerty";
char pass[] = "12345678";

String serverUrl = "https://website.org/insert_status.php";
MFRC522 mfrc522(SS_PIN, RST_PIN);

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

  Serial.printf("\nConnecting to %s", ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nConnected to network");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
    String rfid = "";
    for (byte i = 0; i < mfrc522.uid.size; i++) {
      rfid += String(mfrc522.uid.uidByte[i], HEX);
    }
    Serial.printf("RFID Code: %s\n", rfid.c_str());

    HTTPClient http;
    String url = serverUrl + "?rfid=" + rfid.c_str() + "&name=TEST" + "&time=TEST_TIME";

    http.begin(url);

    int httpCode = http.GET();

    if (httpCode > 0) {
      Serial.printf("HTTP durum kodu: %d\n", httpCode);
      if (httpCode == 200) {
        Serial.println("Success!");
      } else {
        Serial.println("Fail!");
      }
    } else {
      Serial.printf("Fail. Error:: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();

    delay(5000);
  }
}

```

Result:

```
��
Connecting to Qwerty...
Connected to network
IP Address: 192.168.43.177
RFID Code: 97****** (I did)
Fail. Error:: connection failed
```

title: ow can I send data with GET method NodeMCU?

Answers: 0


body:
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...

title: How to find out all #define used by arduino-cli in compile?

Answers: 1

body:
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`:

```shell
arduino-cli compile | \
    sed -n '/g++.*\.ino\.cpp\.o/{s/-MMD//;s/-o .*/-E -dM -o defines.dump/;p}'
```


body:
How can I count the number of prox switches and at the same time reference this value for conditionals within loop()? The delays make my loop counter stop adding. I need to know the total number of prox changes because this is used to figure out the distance my robot has walked, and I want it to do certain things at certain distances.

    My code:

        // dc motor pins
    const int enable1=10;
    const int in2=7;
    const int ref_high=4;
    const int in1=8;

    // servo pins
    const int ref_high2=12;

    const int in1_a=6;
    const int in2_a=9;
    const int enable1_a=5;

    const int in1_b=13;
    const int in2_b=2;
    const int enable1_b=3;

    //prox
    const int proxPin=11;
    int proxState=0;
    int intitialProxPresses=0;
    int totalProxPresses=0;
    int PreviousProxState=0;

    void walkStraight() {
      digitalWrite(ref_high, HIGH);
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      analogWrite(enable1, 50);
    }
    void stopWalking() {
      digitalWrite(ref_high, HIGH);
      digitalWrite(in1, LOW);
      digitalWrite(in2, HIGH);
      analogWrite(enable1, 0);
    }
    void turnRight() {
        analogWrite(enable1_a,0);
        digitalWrite(in1_a,LOW);
        analogWrite(in2_a,255);
    }

    void setup() {
      // put your setup code here, to run once:
      pinMode(enable1, OUTPUT);
      pinMode(in2, OUTPUT);
      pinMode(ref_high, OUTPUT);
      pinMode(in1, OUTPUT);

      pinMode(ref_high2, OUTPUT);

      pinMode(in1_a,OUTPUT);
      pinMode(in2_a,OUTPUT);
      pinMode(enable1_a,OUTPUT);

      pinMode(in1_b,OUTPUT);
      pinMode(in2_b,OUTPUT);
      pinMode(enable1_b,OUTPUT);

      pinMode(proxPin,INPUT);
      Serial.begin(9600);
    //servo power supply
      digitalWrite(in1_b,LOW);
      digitalWrite(in2_b,HIGH);
      analogWrite(enable1_b,150);
      digitalWrite(ref_high2, HIGH);
      //initial servo state (on startup)
      analogWrite(enable1_a,255);
      digitalWrite(in1_a,HIGH);
      digitalWrite(in2_a,LOW);

    void loop() {
      proxState=digitalRead(proxPin);
      if (proxState != PreviousProxState) {
        if (proxState==HIGH) {
          totalProxPresses++;
          Serial.println(totalProxPresses);
        }
        }

      if ((totalProxPresses>=1) && (totalProxPresses<=10)) {
        walkStraight();
      }
      if (totalProxPresses==10) {
        stopWalking();
        // delay(1000);
        turnRight();
        // delay(1000);

      }
      if ((totalProxPresses>=10) && (totalProxPresses<20)) {
        walkStraight();
        // delay(1000);
      }
      if (totalProxPresses>=20) {
        stopWalking();
      }

    PreviousProxState=proxState;
    }

title: Arduino IDE: Delays in void loop() prevent counting number of switches

Answers: 0


body:
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.

```cpp
#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:

```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...

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/yMTiD.png

title: Reading serial data from Arduino in Python continually

Answers: 1

body:
> 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][1], 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.

  [1]: https://arduino.stackexchange.com/questions/72189/what-happens-to-serial-output-when-no-one-is-listening


body:
I'm new with RTOS concept. Tried a few example, also have tried http request with FreeRTOS over WiFi and it works. Now I have project using ESP32 and SIM808 for GPS and SIM Card Module. SIM808 support GPRS for the connection. I try using TinyGsmClient library. I get the result that I want. But then, I migrate it to FreeRTOS so I can multitask, but it doesn't work as fine. My FreeRtos code look like:

```
void httpsGETTask2(void *pvParameters) {

  while(1){
    delay(0);
    yield();
    vTaskDelay(pdMS_TO_TICKS(100));

          if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
        SerialMon.println(" fail");
        vTaskDelay(pdMS_TO_TICKS(10000));
        continue;
      }

      SerialMon.println(F("Performing HTTPS GET request... "));

      http.connectionKeepAlive();  // Currently, this is needed for HTTPS

      int err = http.get(resource);

      vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

```

I have a lot of Serial print on it for debug. This task take 10s to complete if I do it normally without RTOS. When I try to use RTOS, I got Watch Dig Timer Error.

```xTaskCreate(httpsGETTask2, "HTTPTask", 50*1024, NULL, 1, &httpsTaskHandle);```

The error looks like:
```
Initializing modem...

Connecting:

Performing HTTPS GET request... Response status code: 200

duration before body: 7974099

duration after body: 12484338

Response:

Head \u003cb\u003esoutheast\u003c/b\u003e

duration: 12484660

E (20012) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time:

E (20012) task_wdt: - IDLE (CPU 0)

E (20012) task_wdt: Tasks currently running:

E (20012) task_wdt: CPU 0: HTTPTask

E (20012) task_wdt: CPU 1: IDLE

E (20012) task_wdt: Aborting.

abort() was called at PC 0x400da6b5 on core 0

Backtrace: 0x40083415:0x3ffbe9dc |<-CORRUPTED
```

I solve it by putting this task to priority 0.
```xTaskCreate(httpsGETTask2, "HTTPTask", 50*1024, NULL, 0, &httpsTaskHandle);```

 But that makes this task took a lot longer to complete. It complete in 40s with RTOS. At first I thought this caused by memory, so I add more for the task, but nothing change. I can't get it to work if the priority is higher than 0. but at 0 priority it took so much longer.

Anyone has an experience working with FreeRTOS and GPRS? If so do you have suggestion on how to do http request in FreeRTOS using GPRS? Or is there a better lib to use then TinyGsmClient to handle RTOS?

title: How to send high priority http request with FreeRTOS?

Answers: 0


body:
I am creating a menu system for my project. I have successfully finished my code to configure up to 2 menu items on my 16x2 LCD I2C. I would like to extend it and add up to 5 menu items in the code with scrolling functionality using the up and down buttons. Here's the function for my main menu:

```c
uint8_t mnMainPage(uint8_t ctlButton)
{
  static int8_t
  highlight = 0;
  static uint8_t
  state = ST_INIT;

  switch (state)
  {
    case ST_INIT:
      // initialize this menu page
      lcd.clear();
      lcd.setCursor(1, 0);
      lcd.print(F("Set #LEDblnk"));
      lcd.setCursor(1, 1);
      lcd.print(F("Tgl LEDblnk"));

      highlight = 0;
      lcd.setCursor(0, highlight);
      lcd.print(F(">"));

      state = ST_MAIN;
      break;

    case ST_MAIN:
      // we stay in the main page until we hit SEL
      switch (ctlButton)
      {
        case UP:
          lcd.setCursor(0, highlight);
          lcd.print(F(" "));
          highlight--;
          if (highlight < 0)
            highlight = 1;
          lcd.setCursor(0, highlight);
          lcd.print(F(">"));
          break;

        case DN:
          lcd.setCursor(0, highlight);
          lcd.print(F(" "));
          highlight++;
          if (highlight > 1)
            highlight = 0;
          lcd.setCursor(0, highlight);
          lcd.print(F(">"));
          break;

        case SEL:
          // user hit select
          // move to the "wipe" state to "animate" clearing the menu...
          state = ST_WIPE;
          break;
      }

      break;

    case ST_WIPE:
      // when WipeMenu returns true, the old menu is erased so...
      if (WipeMenu() == true)
      {
        // set the activeFunc to the menu item the user selected
        activeFunc = (highlight == 0) ? &mnSetNumBlinks : &mnEnableBlinks;
        // and set the local state here to INIT again so when
        // we get back to this menu the screen is properly initialized
        state = ST_INIT;
      }
      break;
  }
  return MN_CONTINUE;
} // mnMainPage
```

Can someone help me on how can I achieve vertical scrolling for up to 5 menu items? Heres the complete [code][1] for reference. Thank you.

  [1]: https://wokwi.com/projects/381159361212240897

title: Scrolling function for existing Arduino menu using 16x2 LCD

Answers: 0


body:
I have a Arduno Uno R3 and ESP8266 Module Module CH340G. Currently using a Macbook.

With google and youtube, I saw that I can test if my ESP8266 module (via connection through Arduino) is working, I can do so by typing "AT" into the serial monitor, and if there is an 'OK' response back, it means it is working.

But when I keyed and entered the "AT", it did not reflect my command in the serial monitor and neither was there any response. Like to know if anyone faced the same issue and how I can fix this.

Below is my pin connection between Arduino and ESP8266 if it is also needed:

Arduino | ESP8266

3.3V - EN

3.3V - 3V

TX - TX

RX - RX

GND - GND

Note: I also tried to connect Arduino TX - ESP8266 RX and Arduino RX - ESP8266 TX but it is also not working.

Do forgive me if it takes me a while to understand as I am new and I am still trying to understand.

Thanks in advance for helping!

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/d94CU.png

title: Serial Monitor not reflecting commands (Connecting Arduino and ESP8266 Module CG340G)

Answers: 0


body:
I have found several posts detailing exactly what I'm trying to do, and I am at my wits end. Below is a picture of the schematic I am using:
I know for a fact that the USB-UART controller is working because after programming with USPtinyISP I am able to open a serial monitor tab and communicate with the Atmega.

I have selected "arduino nano" under "arduino avr boards" for the board, processor "atmega328p", and know for a fact that my com port is correct. I select "upload" (not using programmer) in the sketch tab, and get the error below:
```
avrdude: stk500_recv():programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x2e
```

From the posts I have read, this means there is a total disconnect somewhere.

Here is a list of things I have tried to no avail:

 1. Switch Tx/Rx pins around/removed 1k series resistance
 2. connect ~DTR directly to ~RESET
 3. invert ~DTR with a mosfet (as shown [here][1])
 4. replaced atmega twice
 5. bootload the atmega with the USBtinyISP before attempting to upload sketch
 6. used a [different library][2] with more customization options for oscillators, etc
 7. completely disconnect ~DTR pin
 8. connect ~DTR and ~RTS pins through both very large (1M) resistors and short to reset as shown [here][3]

Other posts I've looked at:

https://arduino.stackexchange.com/questions/78195/how-to-upload-a-sketch-to-an-atmega328-via-ftdi-ft232rl-uart-and-arduino-ide

https://electronics.stackexchange.com/questions/661056/uploading-sketch-to-atmega328-via-ftdi-with-some-pins-set-to-high-logic

https://www.reddit.com/r/arduino/comments/argdze/arduino_uno_to_atmega328_via_ftdi_successfully/

[![enter image description here][4]][4]

  [1]: https://www.avrfreaks.net/s/topic/a5C3l000000LqQ5EAK/t193555
  [2]: https://github.com/sleemanj/optiboot/tree/master/dists#installation-&-usage
  [3]: https://forum.arduino.cc/t/avrdude-ser_open-cant-open-device-com9-access-is-denied/532659/6
  [4]: https://i.stack.imgur.com/9OCVl.png

title: How can I upload a sketch to atmega328 using FT231XS-R?

Answers: 0


body:
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:
<pre>
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��
</pre>

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);
}
```

title: Need help with parsing NWS JSON weather alerts causing reset on ESP8266

Answers: 2

body:
By default, the size of the stack is [limited to 4KB](https://github.com/esp8266/Arduino/blob/3.1.2/cores/esp8266/cont.h#L27) on ESP8266, so you cannot store an 8KB document there.

To fix this issue, replace the [`StaticJsonDocument`](https://arduinojson.org/v6/api/staticjsondocument/) with a [`DynamicJsonDocument`](https://arduinojson.org/v6/api/dynamicjsondocument/) to move the buffer to the heap.

See also: [Why does my device crash or reboot?](https://arduinojson.org/v6/issues/crash-or-reboot/)

body:
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][1] 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][2]. For the ESP8266, you might find [this techtutorialsx document][3] 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)

  [1]: https://github.com/me-no-dev/EspExceptionDecoder
  [2]: https://e2e.ti.com/blogs_/b/powerhouse/posts/what-is-a-watchdog-timer-and-why-is-it-important
  [3]: https://techtutorialsx.com/2017/01/21/esp8266-watchdog-functions/


body:
Below are my codes for transferring string data between two Arduinos from Master to Slave via SPI. Similarly, how can I transfer string data from Slave to Master?
Any suggestions?

**Master Code:**
```
#include <SPI.h>

char input;

const int size_arr = 150;  // define array size (must be less than size of slave)
char buf[size_arr]; // define char array, use for convert from string for send to slave
String main_dat = "hello from master"; // real String data

void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV16);
}

void loop() {
  input = Serial.read();

  if(input == 's'){
    main_dat.toCharArray(buf, size_arr); // convert String data to char array
    Spi_tranmis(buf); // send char array
  }

  delay(500);
}

void send_spi(byte pram) {

  digitalWrite(SS, LOW);
  SPI.transfer(pram);
  digitalWrite(SS, HIGH);
  delayMicroseconds(5);
}

void Spi_tranmis(char buf[]) {
  for (int i = 0 ; i < size_arr  ; i ++) {
    send_spi(buf[i]);
  }
  send_spi('\n');
}

```

**Slave Code:**

```
#include <SPI.h>

const int size_arr = 151; // define array size (must be more than size of master)
char buf[size_arr]; // char array , use for recive from master

#define SS_Pin 9

volatile byte pos = 0;
volatile boolean process = false;

String msg; // real data

void setup() {
   Serial.begin(9600);
   pinMode(MISO, OUTPUT);
   digitalWrite(MISO, LOW);

   pinMode(SS_Pin, OUTPUT);
   //SPI.begin();
   SPCR |= bit(SPE);
   SPCR |= bit(SPIE);
}

ISR(SPI_STC_vect) {
  char c = SPDR;

  if (pos < sizeof buf) {
    if (c == '\n') {
      buf[pos] = '\0';
      process = true;
    }
    else {
      buf[pos++] = c;
    }
  }
}

void loop() {
  recvHandle();
}

void recvHandle() {
  if (process) {  // when SPI available
    msg = String(buf);   // convert char array to String
    Serial.println(msg);
    process = false;
    pos = 0;
  }
}
```

title: Arduino SPI Mutual Communication

Answers: 0


body:
```
/*
 *   Basic example code for controlling a stepper with the AccelStepper library
 *
 *   by Dejan, https://howtomechatronics.com
 */

#include <AccelStepper.h>

const int DIR = 12;
const int STEP = 14;

#define motorInterfaceType 1
// Define the stepper motor and the pins that is connected to0
AccelStepper motor(motorInterfaceType, STEP, DIR); // (Type of driver: with 2 pins, STEP, DIR)

void setup() {
  // Set maximum speed value for the stepper
  motor.setMaxSpeed(1000); // Set maximum speed value for the stepper
  motor.setAcceleration(500); // Set acceleration value for the stepper
  motor.setCurrentPosition(0); // Set the current position to 0 steps
  Serial.begin(115200);
  //pinMode(32,OUTPUT);
}

void loop() {
  Serial.println("Moving to 800");
  motor.moveTo(800); // Set desired move: 800 steps (in quater-step resolution that's one rotation)
  motor.runToPosition(); // Moves the motor to target position w/ acceleration/ deceleration and it blocks until is in position
     // Move back to position 0, using run() which is non-blocking - both motors will move at the same time
  motor.moveTo(0);
  Serial.println("Moving to 0");
  while (motor.currentPosition() != 0) {
    motor.run();  // Move or step the motor implementing accelerations and decelerations to achieve the target position. Non-blocking function
    //
    //
  }
}
```
I tried using this code to check if my motor can move in a clockwise and anti-clockwise direction as stated by the tutorial. However it only manages to turn into anti-clockwise direction. I tried connecting the four motor pins to the driver as the order, the if the black wire is connected to the pin 2B of the driver, the motor will move anti-clockwise. Else if the black wire is connected to the pin 1B of the driver, the motor will move clockwise. I also have tried changing `motor.moveTo(800)` to `motor.moveTo(100)` and `motor.moveTo(0)` to `motor.moveTo(-100)` yet it still outputs the same thing. What is wrong with my code that may cause the motor to only move in one direction?

title: ESP32 + Stepper Motor 17HS3401S + A4988 driver. Stepper cannot move in Clockwise direction

Answers: 1

body:
I'm fortunate enough to know the cause. It's because of my fault in Wiring pins. At first, the orders on my driver pins (2B-2A-1B-1A) were black, green, blue, and red. Luckily, I came across this picture and changed the orders as in the pic. 2B-Black, 2A-Green, 1B-Red, 1A-Blue. It now can move towards both directions (clock-wise and anti-clockwise) [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/ejBVT.png


body: I am currently trying to detect an approaching car with a microphone. Currently, I am using an Arduino Uno in conjunction with a SparkFun sound detector. I have tried using FFT and am currently trying a code that assesses the current peaks of the output of the microphone compared to the average of the peaks generated from the background noise. both of these do what they are supposed to do but neither are nearly as accurate as I would like them to be. I have done some DAQ analysis of an approaching car and there is a distinct, gradual curve, of the output voltage of the car, but I cannot seem to create an algorithm to accurately assess this external stimulus. I need to do this in real-time to as high a degree of accuracy as possible. Some constrictions I'm currently facing are that it needs to be self-contained, small, and have a low-energy draw. I am considering pattern recognition at this point but am worried about energy consumption and memory. Does anyone have any thoughts on how to accomplish this?

title: Detecting an approaching car with a microphone?

Answers: 0


body:
 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_ Manual_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](https://i.stack.imgur.com/IXwmk.png)

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:

title: Pn532 doesnt detect sometimes

Answers: 0


body:
im just started doing this robot thing (like a week ago) and i really dont know who to ask regarding this problem. my seniors who supposedly help us is busy all the time so idk who to turns to. and we have a competition by weekend and the only problem is this. since the motor wont work at all. also i tried to make it switchable between rc and autonomous line tracing mode.it also supposedly make use of servo to throw and carry some object. we are using 2 yellow motor (idk the exact name) 4 1.5V battery to power the motor and currently using laptop/powerbank to power the esp as it is in testing phase. so anyway here is the code:

```
#include "BluetoothSerial.h"
#include <ESP32Servo.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error
#endif

const int mot1right = 13;
const int mot2right = 12;
const int mot1left = 2;
const int mot2left = 15;
const int sensorleft = 17;
const int sensormid = 5;
const int sensorright = 34;
int servoPin1 = 26;
int servoPin2 = 27;

BluetoothSerial SerialBT;
Servo Servo1,Servo2;
bool automaticMode = false;

void setup() {
Serial.begin(115200);
SerialBT.begin("kete");
pinMode (mot1right, OUTPUT);
pinMode (mot2right, OUTPUT);
pinMode (mot1left, OUTPUT);
pinMode (mot2left, OUTPUT);
pinMode(sensorleft, INPUT);
pinMode(sensormid, INPUT);
pinMode(sensorright, INPUT);
Servo1.attach(servoPin1);
Servo2.attach(servoPin2);
}
void move (){
  analogWrite(mot1left, 255);
  analogWrite(mot2left, 0);
  analogWrite(mot1right, 0);
  analogWrite(mot2right, 255);
  Serial.println("moto jalan depan");
}
void stop (){
  analogWrite(mot1left, 0);
  analogWrite(mot2left, 0);
  analogWrite(mot1right, 0);
  analogWrite(mot2right, 0);
}
void back (){
  analogWrite(mot1left, 0);
  analogWrite(mot2left, 255);
  analogWrite(mot1right, 255);
  analogWrite(mot2right, 0);
  Serial.println("moto jalan blakang");
}
void kanan (){
  analogWrite(mot1left, 0);
  analogWrite(mot2left, 0);
  analogWrite(mot1right, 0);
  analogWrite(mot2right, 200);
  Serial.println("moto jalan kanan");
}
void kiri (){
  analogWrite(mot1left, 200);
  analogWrite(mot2left, 0);
  analogWrite(mot1right, 0);
  analogWrite(mot2right, 0);
  Serial.println("moto jalan kiri");
}

void toggleMode(char command) {
  if (command == 'X') {
    automaticMode = true;
    Serial.println("Automatic mode activated");
  } else if (command == 'Y') {
    automaticMode = false;
    Serial.println("Remote control mode activated");
  }
}

void loop() {

int stateL = digitalRead(sensorleft);
int stateM = digitalRead(sensormid);
int stateR = digitalRead(sensorright);

if (SerialBT.available()) {
    char inputChar = SerialBT.read();
    if (inputChar == 'X' || inputChar == 'Y') {
      toggleMode(inputChar);
    }

    if (automaticMode && inputChar == 'X') {
      // Your existing code for automatic mode control
       if (stateM == LOW && stateL == HIGH && stateR == HIGH){
        move();
        Serial.println("depan");
        }
       else if (stateL == LOW && stateM == HIGH && stateR == HIGH){
        kiri();
        Serial.println("kiri");
       }
       else if (stateR == LOW && stateL == HIGH && stateM == HIGH){
        kanan();
        Serial.println("kanan");
       }
       else if (stateR == LOW && stateL == HIGH && stateM == LOW){
        kanan();
        Serial.println("kanan");
       }
       else if (stateR == HIGH && stateL == LOW && stateM == LOW){
        kiri();
        Serial.println("kiri");
       }
       else if (stateR == LOW && stateL == LOW && stateM == LOW){
        stop();
        Serial.println("benti");
        Servo2.write(180);
        delay(3000);
        Servo2.write(90);
       }
      // Additional conditions for automatic mode...

    } else if (!automaticMode && inputChar == 'Y') {

        char RCinput = SerialBT.read();
        switch (RCinput){

         case 'F':
          move ();
          Serial.println(inputChar);
          break;

         case 'R':
          kanan ();
          Serial.println(inputChar);
          break;

         case 'L':
          kiri ();
          Serial.println(inputChar);
          break;

         case 'G':
          back ();
          Serial.println(inputChar);
          break;

         default:
          stop();
          break;
         }
        Serial.println(RCinput);
        if (RCinput == 'J'){
        int angle1 = SerialBT.parseInt();
        Servo1.write(angle1);
    }
  }
  delay(1);
}
}
```

and im sorry if this question is already being ask. since idk how to navigate around the forum as it is my first time asking here due to suggestion of my friend. therefore, thanks in advance for your help.

title: esp32 line following & remote controlled robot

Answers: 0


body:
I have this data I'm getting through EEPROM "Emergency Contacts:  +639*********, +639*********, +639*********;"
Using this I want to send a message to these numbers.

I have this function but it only sends to the first number:
```cpp
void sendSms(String text)
 {
  sim800.print("AT+CMGF=1\r");
  delay(1000);
  String contacts = EMERGENCY_CONTACTS;
  int commaPos;
  boolean allSent = true;
  do {
    commaPos = contacts.indexOf(',');
    String contact;
    if (commaPos != -1) {
      contact = contacts.substring(0, commaPos);
    } else {
      // If no comma found, it's the last contact
      contact = contacts;
    }
    contact.trim();  // Trim leading/trailing spaces
    contacts = contacts.substring(commaPos + 1);
    contacts.trim(); // Trim leading/trailing spaces and update contacts
    sim800.print("AT+CMGS=\"" + contact + "\"\r");
    delay(1000);
    sim800.print(text);
    delay(100);
    sim800.write(0x1A);
    delay(1000);
    Serial.println("SMS Sent Successfully to " + contact);
    BTSerial.println("SMS Sent Successfully to " + contact);
    if (commaPos == -1) {
      allSent = false;  // Mark that it's the last contact
    }
  } while (commaPos != -1);
  return allSent;
}
```

title: Sim800l v2 send message to multiple numbers

Answers: 0


body:
I'd like to use SCD30 sensor on ESP8266. I know it's possible to use for example [Adafruit library to connect SCD to Arduino][1], but it requires SDL and SDA pins, which my ESP doesn't have. The library in tutorial at least doesn't allow changing the connection pins. I know that connecting SCD30 and ESP8266 is at the very least possible using yaml format. With that you can use regular D-pins. But I'd like to know if it's possible to do it with Arduino code as well.

If SCD30 isn't possible to use this way, then how about other air sensors, such as CSS811?

  [1]: https://learn.adafruit.com/adafruit-scd30/arduino

title: How to use SCD30 on ESP8266

Answers: 0


body:
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:

 - https://arduino.stackexchange.com/questions/28663/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

title: Arduino Uno, does a lower Aref voltage work well for measuring current? without increasing ADC integral non-linearity

Answers: 1

body:
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.


body:
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:

```lang-cpp
/*

  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.
}
```

title: 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?

Answers: 1

body:
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](https://github.com/arduino/ArduinoCore-sam/blob/790ff2c852bf159787a9966bddee4d9f55352d15/cores/arduino/Tone.h).
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](https://github.com/arduino/ArduinoCore-sam/blob/790ff2c852bf159787a9966bddee4d9f55352d15/cores/arduino/Tone.cpp.disabled) that they'd copied into the project for reference with the intention of replacing it but never did.

There a [github issue](https://github.com/arduino/ArduinoCore-sam/issues/24) tracking this. But it hasn't been updated since 2020. That issue [references the Arduino forum](https://forum.arduino.cc/t/arduino-due-and-tone/133302) 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](https://github.com/arduino-libraries/Audio/tree/master). It's a bit overkill for producing basic tones, but you could modify [the example](https://github.com/arduino-libraries/Audio/blob/master/examples/SimpleAudioPlayer/SimpleAudioPlayer.ino) there to fill the buffer with a tone's waveform rather than loading it from an sdcard file.


body:
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?

title: PubSubClient constructor parameter type mismatch

Answers: 1

body:
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.


body:
I'm trying to flash a spiffs on a esp32 but it is not working, i'm using these commands from this [source][1]:

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][2] it works fine, but if i run the esptool write command the files are not overrided.

 can someone help-me?

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/storage/spiffs.html
  [2]: https://github.com/me-no-dev/arduino-esp32fs-plugin

title: ESP32 SPIFFS Write problem

Answers: 0


body:
While connecting arduino uno to the system showing **unknown usb device**. Tried many ways like updating drivers, restarting system, installing ch340 drivers, etc. but no use.

Don't understand what the problem is?

title: Arduino USB PORT PROBLEM

Answers: 0


body:
I would like to install on an Arduino DUE:

 1. micropython
 2. a minimum of Pytorch

Is it possible? If it is, then how?

title: Arduino DUE and Pytorch

Answers: 0


body:
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][1].

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.

  [1]: https://forum.arduino.cc/t/use-attiny85-reset-pin-as-input-switch/1189555/30

title: Use attiny85 reset pin as analog pin

Answers: 1

body:
The following was in answer to the question in [its original form](https://arduino.stackexchange.com/revisions/94863/1).

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](https://github.com/SpenceKonde/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.