body:
I am trying to send RF signal from Digispark Attiny 85 ([this one](https://www.laskakit.cz/digispark-usb-attiny85/)) and receive the signal with Arduino NANO V3.0 ATmega328 ([this one](https://dratek.cz/arduino/823-arduino-nano-v3.0-atmega328-precizni-klon.html?gclid=Cj0KCQjwnf-kBhCnARIsAFlg491PODagE9YdGuO869yCfuaKXnG1UHQOJkBvEm3FXVhvdJBdAJFf39caAu2ZEALw_wcB)). Transmitter and receiver are STX882 and SRX882 ([these](https://www.laskakit.cz/nicerf-sada-vysilac-prijimac-433mhz--stx882-srx882/?gclid=Cj0KCQjwnf-kBhCnARIsAFlg492_jYhO6HHj_cT6lmOUAnVObjfCiVMPqOWO0zIOnSoxLHxmezE4nvQaAs9bEALw_wcB)). Library used is [RCSwitch.h](https://github.com/sui77/rc-switch).

The goal is to light up the external LED connected to NANO when I press the button connected to Attiny.

I am not skilled in Arduino stuff, but I have really tried to figure this one out on my own and find answers online. Sorry if this question does not belong here. Anyways, here is the problem:

```
// NiceRF 433MHz reciever SRX887

#include <RCSwitch.h>

RCSwitch reciever = RCSwitch();

void setup() {
  Serial.begin(9600);
  reciever.enableReceive(2);
  pinMode(7, OUTPUT);
}
void loop() {
  if (reciever.available()) {
    int size = reciever.getReceivedValue();
    if (size == 0) {
      Serial.print("Unknown message"); //probably kinda useless line
    }
    else {
      digitalWrite(7, HIGH); // Turn on the LED
      delay(1000); // Wait for 1 second
      digitalWrite(7, LOW); // Turn off the LED
      delay(1000); // Wait for 1 second
    }
    // reset of module to be able to recieve next message
    reciever.resetAvailable();
  }
}
```
I understand the code like this: The Receiver will check if it receives anything and if so, it will light up pin 7 and therefore the LED connected to the pin 7 will be on.

Now for the Digispark Attiny 85 transmitter:

```
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  pinMode(1, OUTPUT);
  mySwitch.enableTransmit(2);
}

void loop() {
    mySwitch.send("000110110001010100010001");
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
}
```
I found this piece of code online and did not modify it. If I understand this correctly, it is not important, what the message is, but if it is sent at all. The receiver should light an LED up in every time it receives the signal.

I am confident that the wires are connected correctly.

Do you have any idea why this setup does not work?

-------------------------------------------------------
Edit: As @jsotola suggested, I tried to make a circuit that will simply send HIGH signal to transmitter module, receive this signal at receiver module and if arduino board recognises that there is HIGH signal coming from receiver, it will send HIGH signal to the LED pin and LED would light up.

For this experiment, I switched Digispark for generic Arduino UNO ATmega clone to make things simpler. There is no library used in this example.

TRANSMITTER CODE:
```
const int TPin = 10;

void setup() {
  // Initialize the LED pin as an output
  pinMode(TPin, OUTPUT);
}

void loop() {
  // Turn on the LED
  digitalWrite(TPin, HIGH);
  delay(500); // Wait for 1 second

  // Turn off the LED
  digitalWrite(TPin, LOW);
  delay(500); // Wait for 1 second
}
```

RECEIVER CODE:

```
// Pin connected to the LED
const int ledPin = 7;
// Pin connected to input signal
const int inputPin = 2;

void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
  // Initialize the input pin as an input
  pinMode(inputPin, INPUT);
}

void loop() {
  // Read the state of the input pin
  int inputState = digitalRead(inputPin);

  // Check if the input pin is HIGH
  if (inputState == HIGH) {
    // Turn on the LED
    digitalWrite(ledPin, HIGH);
  } else {
    // Turn off the LED
    digitalWrite(ledPin, LOW);
  }
}
```
TRANSMITTER SETUP:

 [1]: https://i.stack.imgur.com/5gYoG.jpg
[![Transmitter setup][1]][1]

(note that there is an antenna soldered to the transmitter module, but it is out of frame) The LED is simply for me to see when a signal is send to the transmitter. (Blinks in intervals as intended)

RECEIVER MODULE SETUP:
Pins on receiver from left to right (form orange to green wire) are GND, CS, DATA, VCC.
GND and CS are connected to the GND pin on Nano, VCC is connected to the 5V pin on Nano (this receiver works on 5V and does not require the usual ~3.3V). DATA is connected to the D2 pin on Nano.

 [2]: https://i.stack.imgur.com/SXP6m.jpg
[![Receiver module setup][2]][2]

The LED is simply connected to GND and pin D7 on Nano (out of frame) and does light up even if I touch the pin. LED stays off when D2 is grounded.

This setup does not work correctly and I have tried it for different Receivers/Transmitters (i have multiple of each). Once again thank you for all your suggestions. Does anyone have any idea what do I do wrong in here?

Thanks!

title: Arduino NANO RF reciever and Digispark Attiny 85 transmitter issues

Answers: 0


body:
I have a code that is working fine using WatchDog timer to auto reset in case something goes wrong, but now i got a arduino with **ATMega328PB**, and the old code just don't active the watchdog.

    #include <avr/wdt.h>

    wdt_enable(WDTO_8S);
    for(int i = 0; i < 10; i++)
    {
        delay(1000);
    }

This is the code to test, but the reset that should happen just doesn't happen.

In the datasheet say that the watchdog still there to use, but i have no idea how to active it now.

title: Watchdog don't work with Atmega328PB

Answers: 0


body:
Here's my code. I don't know if the issue is the power source though. I only have access to my computer for a power source.

    #include <Servo.h>

    Servo servo1;
    Servo servo2;
    Servo servo3;
    Servo servo4;

    int joyX = A2;
    int joyY = A5;
    int Joyx = A2;
    int Joyy = A5;

    int servoVal;

    void setup()
    {
      servo1.attach(A0);
      servo2.attach(A1);
      servo3.attach(A3);
      servo4.attach(A4);
    }

    void loop()
    {

      servoVal = analogRead(joyX);
      servoVal = map(servoVal, 0, 1023, 0, 180);
      servo1.write(servoVal);
      delay(15);

      servoVal = analogRead(joyY);
      servoVal = map(servoVal, 0, 1023, 70, 180);
      servo2.write(servoVal);
      delay(15);

      servoVal = analogRead(Joyx);
      servoVal = map(servoVal, 0, 1023, 0, 180);
      servo3.write(servoVal);
      delay(15);

      servoVal = analogRead(Joyy);
      servoVal = map(servoVal, 0, 1023, 70, 180);
      servo4.write(servoVal);
      delay(15);
    }

title: I am trying to control 4 servos with a joystick, but after a few seconds, they start spinning and don't stop until the power source is cut

Answers: 0


body:
I've got an Arduino Mega periodically running an (~400ms) operation that is sensitive to repeatable timing, so I don't ever want it to be interrupted.  But, I'd like to be able to use an interrupt flag from one of the built-in peripherals (PCINT, comparator, etc.) to check afterward if an external event (say, a pin going high momentarily) ever happened during the operation.

That is, it'd be nice if I could just treat one of the interrupt flags as a kind of async hardware latch that I can check (and reset) at my next earliest convenience instead of having my code interrupted.

It wouldn't be hard to add a discrete latch IC, but I was hoping I could get away with just using what was already built into the AVR without adding more hardware (and using an extra pin to reset the latch).

Looking at the documentation for each of the peripherals, it was unclear whether the flags will still be set when the interrupts themselves are disabled.  I saw a mention someplace of an "EMPTY_INTERRUPT" macro, but I'm guessing that still generates an interrupt vector with a single "return" instruction, so I'd still be losing cycles to the interrupt preamble, etc.

Can this be done without any ISR being called at all?  Or do I need to add more hardware?  I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice unless that also doesn't interfere with UART receiving.  Thanks!

title: Using interrupts as flags/latches without any ISR

Answers: 2

body:
The answer to your question is: yes, you can use an interrupt flag even
if the interrupt itself is disabled. The flag is raised whenever the
peripheral detects the relevant event. You can check it at your
convenience.

As for resetting the flag, the way to do it varies from flag to flag.
Most are reset by writing a 1 bit to it (yes, it is kind of backwards,
but that's how it works). Others are reset by removing the condition
that raised them in the first place (e.g. the USART Data Register Empty interrupt). You will have to check the datasheet for the specific
interrupt flag you are interested in.

That being said, I would question your idea that you don't want your
code to be interrupted at all. As Nick Gammon writes in a comment, the
minimum time to execute an ISR is 2.625 µs. This is about 0.0007%
of the process period. If your operation is so time-sensitive that it
cannot tolerate this kind of variation, then it cannot run on a Mega _at
all_. The ceramic resonator that clocks a Mega has a typical accuracy of
about 0.1%, which is 150 time worse than the effect of a minimal
interrupt. Even if you calibrate this oscillator against an atomic
clock, in only a few hours its frequency will drift past 0.0007%.

In addition, if you want the code to work with no interrupts, you will
have to disable them explicitly with `noInterrupts()`. You will then
loose the Arduino timing function `millis()`, `delay()`, etc. And you
will not be able to receive data from the UART unless you write your own
code that polls the “receive complete” UART interrupt flag and then
grabs the data from the UART data register.

body:
> I'm not sure wrapping the long-running task in noInterrupts()/interrupts() is a choice ...

That's right. Turning off interrupts would stop the timing/delay working so you wouldn't be able to time your 200 µs (unless you use delayMicroseconds).

>  Each exposure is only a couple hundred microseconds, so even 2.625µs of periodic jitter would increase the exposure time by at least 1%.

I think you might be better off using a hardware timer to time the exposure, rather than a loop. I generated VGA signals [in a post here](https://gammon.com.au/forum/?id=11608) where I wanted the horizontal and vertical sync to have no jitter whatsoever. The timers can be set to turn on, or off, an output pin, so that could be used to control your shutter. Then it would be completely precise.

> I didn't know the UART interrupts the CPU ...

Incoming (or indeed outgoing) serial communications causes interrupts. The timers cause interrupts. In particular, if you haven't disabled it, Timer 0 generates interrupts which are counted so that millis() and micros() can function. You can disable interrupts but then timing exact intervals becomes problematic. My suggestion of using the timer hardware will give the most reliable and repeatable performance, in the same way that my VGA signal generation was completely without jitter.

Because of the timer interrupts, if you haven't disabled interrupts, some of your exposures may have the timer interrupt in the middle (making them longer) and some not, or at least, a different number of interrupts. This will make the exposure time non-precise.

---

Another approach would be to turn off interrupts for the exposure only (ie. your 200 µs, not the 400 ms you mention), and then use delayMicroseconds() to time the exposure. Then when interrupts are back on the closure of a switch (an external interrupt) could be processed by a normal ISR. This might add slight differences to the time *between* exposures, but the exposure time itself would be constant.

Even with interrupts off, an external interrupt is "remembered" and would be processed when interrupts are enabled again.

---

This is turning into [an XY problem](https://en.wikipedia.org/wiki/XY_problem) somewhat. It would have been better to mention your exact requirements (the photography part) rather than launching into questions about using interrupts as latches.

---

# Example code

To demonstrate how you can do this with timers, I have written some sample code:

<!-- language: c++ -->

    // Example of strobing a flash FRAMES_TO_TAKE times to take pictures
    // The time between each flash is in TIME_BETWEEN_SEQUENCES
    // The flash "on" time is in STROBE_ON_TIME
    //
    // For Atmega328P (Arduino Uno and similar)
    // and Atmega2560 (Arduino Mega)

    // Author: Nick Gammon
    // Date: 4 July 2023

    const byte FRAMES_TO_TAKE = 12;
    const byte CPU_CLOCK_SPEED = 16;  // MHz

    const unsigned long TIME_BETWEEN_SEQUENCES = 20000;  // µs
    const unsigned long STROBE_ON_TIME = 200;  // µs
    const byte PRESCALER = 64;

    // set correct output pin
    #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
      const byte FLASH_PIN = 10;  // OC1B (Output Compare Timer 1: B side) - Atmega328P
    #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      const byte FLASH_PIN = 12;  // OC1B (Output Compare Timer 1: B side) - Atmeg12560
    #else
      #error Processor not supported
    #endif

    volatile byte count;  // how many times it fired

    // Timer 1 Compare "B" ISR vector
    // count up to the required number of exposures, then stop
    ISR (TIMER1_COMPB_vect)
      {
      if (++count > FRAMES_TO_TAKE)
        {
        // stop timer 1
        TCCR1A = 0;
        TCCR1B = 0;
        } // end if number of frames reached

      }  // end of TIMER1_COMPB_vect

    // does one sequence of FRAMES_TO_TAKE shots and then stops
    void startSequence ()
    {
      // stop timer 1
      TCCR1A = 0;
      TCCR1B = 0;

      TCCR1A = bit (WGM10) | bit (WGM11);  // fast PWM - top at OCR1A
      TCCR1B = bit (WGM12) | bit (WGM13);  //  (mode 15)

      TCCR1A |= bit (COM1B1);   // Set OC1B during duty cycle

      OCR1A = ((TIME_BETWEEN_SEQUENCES * CPU_CLOCK_SPEED) / PRESCALER) - 1;  // total cycle time
      OCR1B = ((STROBE_ON_TIME * CPU_CLOCK_SPEED) / PRESCALER) - 1;          // duty cycle time
      count = 0;

      TCNT1 = 0;    // reset timer count

      TIFR1   = bit (OCF1B);    // clear "compare B" flag
      TIMSK1  = bit (OCIE1B);   // interrupt on compare B match
      TCCR1B |= bit (CS10) | bit (CS11);     // start timer with prescaler of 64
    } // end of startSequence

    void setup ()
      {
      // stop timer 1
      TCCR1A = 0;
      TCCR1B = 0;

      // set up pin so we can toggle it
      pinMode (FLASH_PIN, OUTPUT);
      digitalWrite (FLASH_PIN, LOW);

      // for debugging etc.
      Serial.begin (115200);
      }  // end of setup

    void loop ()
      {
      startSequence ();
      delay (20);
      Serial.print ("But does it get goat's blood out?\n");
      delay (1000);
       }  // end of loop;

---

# Code explanation

What this code does is use Timer 1 to time the intervals you require. Based on what you posted earlier, I have assumed:

* 12 exposures in a "session" (FRAMES_TO_TAKE) - you said "a dozen or so"
* Exposures are to be 20 ms apart (TIME_BETWEEN_SEQUENCES) - so a session is 240 ms
* Exposure time is to be 200 µs (STROBE_ON_TIME) - you said "a couple of hundred microseconds"
* You want to do other stuff like serial comms, checking switches etc.

The function `startSequence` initiates the timer which has a period of 20 ms and a duty cycle of 200 µs. At the completion of a duty cycle the ISR is called which counts duty cycles. At the end of the nominated number (12) the timer is turned off.

The output pin (pin 12 on the Mega, pin 10 on the Uno) is turned on during the duty cycle (ie. for 200 µs and off the rest of the time). Because this is done in hardware there is no jitter at all. In my demo I am doing serial comms to show that the intervals are exactly correct, despite the interrupts caused by the comms.

---

# Logic analyser output

The logic analyser screenshot shows that the intervals are exactly correct (to within a fraction of a percent). In any case the intervals are consistent with each other.

[![Logic analyser output][1]][1]

This second screenshot shows that there are 12 pulses in that interval.

[![Logic analyser showing count of pulses][2]][2]

I have used a prescaler of 64 to get a nice long interval that can be timed (without overflowing the 16-bit counter size). This gives a granularity of 64 clock cycles (4 µs).

---

# Timer 1 cheat sheet

---

[![Timer 1 cheat sheet][3]][3]

  [1]: https://i.stack.imgur.com/inRFb.png
  [2]: https://i.stack.imgur.com/Fh9DJ.png
  [3]: https://i.stack.imgur.com/yPLpA.png


body:
The pro micro has no hardware reset circuitry that would allow host PC to cause a reset via USB.  But when programming using the bootloader, the host PC must have a way to reset the pro micro to allow it to enter bootloader mode and then upload code.

How is it reset?  Is the pro micro sensing the serial rate in some kind of way?  And if so, what is it looking for?  Or does the PC just disconnect the USB and then reconnect (but surely this would not work if the board was externally powered)

[![Schematic of pro micro][1]][1]

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

title: How does arduino pro micro reset via USB?

Answers: 0


body:
I'm attempting to wire two breakout boards with i2c devices to a Mega2560:

* a HD44280 LCD with PCF8574 i2c backpack
* a combo board with DS1307 + AT24C32

There are two obvious possibilities for cabling:

* two 10-inch ribbon cables that come together right before connecting to the Arduino's SDA and SCL pins. Technically, one could be 6 inches... but I know that with RS485, you're asking for trouble if you do a star with branches of unequal length. The cables can't really be any shorter without seriously impairing my ability to debug it while partially disassembled (the LCD is mounted to the lid, and the cables are long enough to allow me to lay the lid on the desk next to the enclosure and power everything up without putting stress on the cables).

* Same 10-inch segments of ribbon cable, but daisy-chained... Arduino to LCD, LCD to RTC. In this case, the second one really needs to be 10", because it's mounted to the only clear spot inside the case I have.

Is one likely to be better or worse than the other?

Are there any rules about WHERE the pullup resistors have to go? The DS1307 module has built-in pullup resistors. Do I have to somehow disable them & use resistors right at the point where the bus connects to the Arduino's SDA & SCL pins, or can the pullups go pretty much anywhere on the bus (including at one end of a star, or at the far end of a daisy chain)?

title: I2C cabling rules for 2+ devices

Answers: 1

body: I2C is generally slow. You don't have to worry about how to route the device connection. Because propagation delay won't be a matter. The main goal should be to minimize the capacitance of the wiring, which means minimizing the total wire length. But as you mentioned one of the cable lengths is fixed, then keep the other one to a minimum. The star topology will work if you keep the wire lengths within 10 inches.


body:
I connected an Adafruit color sensor to my Arduino and am having it make calculations. However, when the calculations are done and sent to the serial monitor, it says "NDVI: " without printing the value. The code is attached below. Thanks!

Code:

    /* TSL2591 Digital Light Sensor */
    /* Dynamic Range: 600M:1 */
    /* Maximum Lux: 88K */

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include "Adafruit_TSL2591.h"

    #define IR850 5
    #define IR940 6
    #define BLUE 9
    #define GREEN 10
    #define RED 11

    // Example for demonstrating the TSL2591 library - public domain!

    // connect SCL to I2C Clock
    // connect SDA to I2C Data
    // connect Vin to 3.3-5V DC
    // connect GROUND to common ground

    Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)

    /**************************************************************************/
    /*
        Displays some basic information on this sensor from the unified
        sensor API sensor_t type (see Adafruit_Sensor for more information)
    */
    /**************************************************************************/
    void displaySensorDetails(void)
    {
      sensor_t sensor;
      tsl.getSensor(&sensor);
      Serial.println(F("------------------------------------"));
      Serial.print  (F("Sensor:       ")); Serial.println(sensor.name);
      Serial.print  (F("Driver Ver:   ")); Serial.println(sensor.version);
      Serial.print  (F("Unique ID:    ")); Serial.println(sensor.sensor_id);
      Serial.print  (F("Max Value:    ")); Serial.print(sensor.max_value); Serial.println(F(" lux"));
      Serial.print  (F("Min Value:    ")); Serial.print(sensor.min_value); Serial.println(F(" lux"));
      Serial.print  (F("Resolution:   ")); Serial.print(sensor.resolution, 4); Serial.println(F(" lux"));
      Serial.println(F("------------------------------------"));
      Serial.println(F(""));
      delay(500);
    }

    /**************************************************************************/
    /*
        Configures the gain and integration time for the TSL2591
    */
    /**************************************************************************/
    void configureSensor(void)
    {
      // You can change the gain on the fly, to adapt to brighter/dimmer light situations
      //tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
      //tsl.setGain(TSL2591_GAIN_MED);      // 25x gain
      tsl.setGain(TSL2591_GAIN_HIGH);   // 428x gain

      // Changing the integration time gives you a longer time over which to sense light
      // longer timelines are slower, but are good in very low light situtations!
      //tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);  // shortest integration time (bright light)
      // tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
      // tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
      // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
      // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
      tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS);  // longest integration time (dim light)

      /* Display the gain and integration time for reference sake */
      Serial.println(F("------------------------------------"));
      Serial.print  (F("Gain:         "));
      tsl2591Gain_t gain = tsl.getGain();
      switch(gain)
      {
        case TSL2591_GAIN_LOW:
          Serial.println(F("1x (Low)"));
          break;
        case TSL2591_GAIN_MED:
          Serial.println(F("25x (Medium)"));
          break;
        case TSL2591_GAIN_HIGH:
          Serial.println(F("428x (High)"));
          break;
        case TSL2591_GAIN_MAX:
          Serial.println(F("9876x (Max)"));
          break;
      }
      Serial.print  (F("Timing:       "));
      Serial.print((tsl.getTiming() + 1) * 100, DEC);
      Serial.println(F(" ms"));
      Serial.println(F("------------------------------------"));
      Serial.println(F(""));
    }

    /**************************************************************************/
    /*
        Program entry point for the Arduino sketch
    */
    /**************************************************************************/
    void setup(void)
    {
      pinMode(IR850, OUTPUT);
      pinMode(IR940, OUTPUT);
      pinMode(RED, OUTPUT);
      pinMode(GREEN, OUTPUT);
      pinMode(BLUE, OUTPUT);
      digitalWrite(IR850, LOW);
      digitalWrite(IR940, LOW);
      digitalWrite(RED, LOW);
      digitalWrite(GREEN, LOW);
      digitalWrite(BLUE, LOW);
      Serial.begin(9600);

      Serial.println(F("Starting Adafruit TSL2591 Test!"));

      if (tsl.begin())
      {
        Serial.println(F("Found a TSL2591 sensor"));
      }
      else
      {
        Serial.println(F("No sensor found ... check your wiring?"));
        while (1);
      }

      /* Display some basic information on this sensor */
      displaySensorDetails();

      /* Configure the sensor */
      configureSensor();

      // Now we're ready to get readings ... move on to loop()!
    }

    /**************************************************************************/
    /*
        Shows how to perform a basic read on visible, full spectrum or
        infrared light (returns raw 16-bit ADC values)
    */
    /**************************************************************************/
    void simpleRead(void)
    {
      // Simple data read example. Just read the infrared, fullspecrtrum diode
      // or 'visible' (difference between the two) channels.
      // This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
      uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
      //uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
      //uint16_t x = tsl.getLuminosity(TSL2591_INFRARED);

      Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
      Serial.print(F("Luminosity: "));
      Serial.println(x, DEC);
    }

    /**************************************************************************/
    /*
        Show how to read IR and Full Spectrum at once and convert to lux
    */
    /**************************************************************************/
    uint16_t ir, full;
    void advancedRead(void)
    {
      // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
      // That way you can do whatever math and comparisons you want!
      uint32_t lum = tsl.getFullLuminosity();
      uint16_t ir, full;
      ir = lum >> 16;
      full = lum & 0xFFFF;
      Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
      Serial.print(F("IR: ")); Serial.print(ir);  Serial.print(F("  "));
      Serial.print(F("Full: ")); Serial.print(full); Serial.print(F("  "));
      Serial.print(F("Visible: ")); Serial.print(full - ir); Serial.print(F("  "));
      Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
    }

    /**************************************************************************/
    /*
        Performs a read using the Adafruit Unified Sensor API.
    */
    /**************************************************************************/
    void unifiedSensorAPIRead(void)
    {
      /* Get a new sensor event */
      sensors_event_t event;
      tsl.getEvent(&event);

      /* Display the results (light is measured in lux) */
      Serial.print(F("[ ")); Serial.print(event.timestamp); Serial.print(F(" ms ] "));
      if ((event.light == 0) |
          (event.light > 4294966000.0) |
          (event.light <-4294966000.0))
      {
        /* If event.light = 0 lux the sensor is probably saturated */
        /* and no reliable data could be generated! */
        /* if event.light is +/- 4294967040 there was a float over/underflow */
        Serial.println(F("Invalid data (adjust gain or timing)"));
      }
      else
      {
        Serial.print(event.light); Serial.println(F(" lux"));
      }
    }

    int lightvalue;
    int NDVIred;
    int NDVIinfrared;
    int NDVI;
    boolean (hasrun) = false;

    /**************************************************************************/
    /*
        Arduino loop function, called once 'setup' is complete (your own code
        should go here)
    */
    /**************************************************************************/
    void loop(void)
    {
      lightvalue = 255;
      //simpleRead();
      //advancedRead();
      //unifiedSensorAPIRead();
      if(hasrun==false){
      analogWrite(RED, lightvalue);
      advancedRead();
      NDVIred = full;
      delay(5000);
      analogWrite(IR940,lightvalue);
      advancedRead();
      NDVIinfrared=full;
      NDVI=(NDVIinfrared-NDVIred)/(NDVIinfrared+NDVIred);
      Serial.print("NDVI: "); Serial.write(NDVIred);
      delay(1000);
      exit(0);
      }
    }

title: Why is the serial monitor not printing a variable?

Answers: 1

body:
You wrote:
> ```c++
> Serial.print("NDVI: "); Serial.write(NDVIred);
> ```

You are misusing here the `Serial.write()` method. This method is meant
for sending raw bytes through the serial port. Since you are printing
text, you probably want the numeric value `NDVIred` to be printed out as
text, as a decimal number.

For printing text, use `Serial.print()` and `Serial.println()`:

```c++
Serial.print("NDVI: "); Serial.println(NDVIred);
```


body:
I was wondering what product would work best for my application. I need a web server interface to control several digital outputs connected to my board, and it needs to be as polished as it can be.

In the past I have extensively used ESP32 Dev boards with async web server and often used the integrated memory to save both html and image files to make the web server interface nicer. I was going to buy an ESP32 Dev board once again but then the uno R4 came out and now I am a bit confused on what to choose.
In short, my questions are:

 - can I load a source file alongside images and html files on the new uno like I did with the ESP32 (since from what I understand you could not do that in previous revisions of the uno)?
 - can I use the uno R4's ESP32 GPIO pins alongside the ones already provided on the uno?
- is there any real advantage of the uno R4 over the ESP32 Dev board for the application I described?
Thanks in advance and sorry if the question is ill posed, I am not really practical with some of the hardware concepts involved!

title: Arduino uno R4 vs ESP32 Dev board

Answers: 1

body:
I did not test the UNO R4 yet, so this is completely based on the technical documents.

For a polished web interface, you will need some space to save all the data. Remember you need some space for the code, too, so these numbers are an upper bound and free space for HTML, CSS and images is a good portion less.

* Standard ESP32 Dev Board: mostly 4 MB flash ROM (but can be 8 or 16).
* UNO R4: 256 kB Flash ROM on the main chip, 384 kB ROM on the ESP32-S3-Mini-1-N8 that is used for WiFi.

This suggests that you do have way more space on the ESP32 DevBoard, making it more future-proof.

Another point that may be of interest is interrupts. WiFi does not like to be blocked by interrupt handlers, so if your code relies on interrupts, you may like multiple cores: That way, your code is not hampered by transferring the website.

* The ESP32 has two cores, but you may need to keep an eye on which threads run on which cores. (I sometimes do have problems with time-critical applications like updating a string of WS2812b LEDs while loading the control website.)
* The UNO R4 has completely separate chips for your sketch and the WiFi stack, but to run the web interface completely from its ESP32-S3-Mini-1-N8, I assume that you have to re-flash it with your own sketch. This probably (again, I'm interpolating from datasheets) means that you have program the UNO R4 as if it has two completely separate chips on it; and you'd have to create their communication protocol by yourself.

For your needs, this sounds as if you're better off using ESP32 DevBoards; maybe two if you run into the same problem as me.

Now, to directly answer your questions:

* For serving files via webserver from Arduino UNO R4, I did not find much. Presumably the LittleFS filesystem works on Arduino UNO; and "just serving files" on ESP8266/ESP32 requires them to be in SPIFFS or LittleFS (to my knowledge). It may be that library support for this use case will improve with the release of the UNO R4, but for now, it looks like ESP32 is your best bet.
* You may be able to use the GPIOs of the ESP on the UNO R4, but I'd assume that you will have to provide your own sketch/firmware for the ESP. Also, keep in mind that the UNO itself has 5V GPIOs, while the ESP has 3.3V GPIOs _and you must not mix those voltages_.
* The only advantage of the UNO R4 over a ESP32 that I can see for you is: The GPIOs have 5V and you can run the board on 7-24V or USB. This makes the board more compatible with a lot of modules sold "for Arduino".

In the end, I probably would go for ESP32 and design every periphery on 3.3V or with level shifters; and add a second ESP32 if you run into the problem of the web interface interfering with your basic operation.


body:
Newbie here: I built a working binary clock with my Arduino UNO R3, see Picture 1. From my understanding the power supply for the Arduino itself is via USB, and I use the 5V output to supply power to the switch. Now, **I would like the Arduino to run on battery and keep using its 5V power output** - instead of only when it is connected to the PC.

[![setup powered via USB][1]][1]

From what I gathered on the internet, e.g. [this page][2], I can simply connect the + end of my battery to the Vin port and the - end to GND. However, none of the pages I found deal with what to do with the "surrounding power infrastructure". Can I just keep it as is and use the wiring as in Picture 2 (USB is disconnected), i.e. is it safe to connect my 9V battery now? Or is there a better alternative?

[![proposed setup running on battery][3]][3]

Sorry for the beginner question. I am having so much fun learning with the Arduino (blasted through half the starter kit project handbook in just two days -> this is my variant of the digital hourglass) and don't want it to go up in flames already.

UPDATE: After the answers suggested that my idea should work, I tried it and, indeed, it works OK. I am getting a lot of Arduino resets/restarts though. Thanks for the replies!

  [1]: https://i.stack.imgur.com/pzL7S.jpg
  [2]: https://www.instructables.com/Powering-Arduino-with-a-Battery/
  [3]: https://i.stack.imgur.com/Gw4Ma.jpg

title: Run Arduino Uno with battery AND use 5V output

Answers: 3

body:
Yes, that should work, albeit inefficiently: for every milliwatt of power
consumed by an LED, you will have roughly 0.7 mW dissipated in the
series resistor, and 1.3 mW dissipated in the Arduino's voltage
regulator. Given the low capacity of 9 V batteries, I doubt your
clock will run for very long.

body:
It is almost always better to add a schematic to your question. Backwards engineering from a picture can be confusing at times and lead to incorrect assumptions.

What you want to do appears to be possible. It looks like you are injecting 9 Volts positive at VIN (Pin 8 of the POWER header).  Examining the [Arduino Uno R3 schematic here][1] we see the VIN net connected to the input Pin 8 of the POWER header and also to the input side of the 5 Volt regulator (NCP1117ST50T3G).  This distributes the 5 Volts to the Atmel processor (appears to power the LED directly) and to the external switch which is assumed to be normally open but when closed connects to a 10Kohm resistor to ground.

The total current needed by external devices connected to the Arduino Uno R3 5 Volt regulator should be considered in such a design.  The [NCP1117ST50T3G data sheet here][2] state the regulator can handle in excess of 1 Amp (or 1000mA).

Assuming the LEDs take at most 20mA each and a worse case of all LED in the on state, that is 6 x 20mA or 120mA.  Also, when the switch is closed there is a current path from 5 Volts to ground through a 10Kohm resistor.  Using V = A x R we see that A = V / R = 5 / 10000 = 0.5mA when the switch is closed.  So the total current the external devices might use is likely no more than 120.5mA.  This is far less than 1000mA (the upper limit of the Arduino's 5 Volt regulator) so appears well withing safety margins.

However, an Alkaline 9 Volt battery only contains about 550mAh.  Ignoring the current it takes to run the Arduino Uno R3, we see that dividing the worst case external current demand of 120.5mAh into 550mAh we get 4.6 hours of use.  An Alkaline AA 1.5 Volt battery contains about 2000mAh.. You would need 6 AA 1.5 Volt batteries in series to generate 9 Volts. But they should last about 4 times longer.

  [1]: https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf
  [2]: https://www.mouser.com/pdfDocs/NCP1117-D.pdf

body:
You could certainly use a 9V battery into the VIN port on your Arduino, but the built-in power supply uses a "linear voltage regulator", which is quite inefficient. If your goal is long battery life you'd be much better off with a buck style power supply or a switching power supply. Those are a LOT more efficient.

You should be able to find modestly priced power supplies built for Adruino online that are a lot more efficient than the built-in supply.

(And as mentioned, 9V batteries have a very small capacity. 6 AA or even C batteries would last a lot longer.)


body:
I used to OTA sketches and data files using `ArduinoOTA` and `ESP32 sketch data Upload` tool and ESP32 devkit for example when using **Arduino IDE**.

**Versions:**
* Arduino IDE- 1.8.19
* ESP32 on Arduino IDE - 1.0.6
* ArduinoOTA 1.0.9

**Moving to PlatformIO-**

Started a new Project using ESP32 devkit, `ArduinoOTA` was added from registry to  project ( also 1.0.9 as on ArduinoIDE ).

And now - when tried to copy `BasicOTA` example from ArduinoIDE's `ArduinoOTA` example - compilation failed.

To make sure I don't have any library/ version issue, I checked:

1. `WiFi`, `ESPmDNS` is part of `builtin`.
2. `WiFiUdp` was not found not in`builtin`,`installed` nor `registry` - not shown in dependency graph during compilation -- ??
3. `ArduinoOTA` used from registry.

>     #include <WiFi.h>
>     #include <ESPmDNS.h>
>     #include <WiFiUdp.h>
>     #include <ArduinoOTA.h>
>
>     const char* ssid = "dvirz_iot";
>     const char* password = "GdSd13100301";
>
>     void setup() {
>       Serial.begin(115200);
>       Serial.println("Booting");
>       WiFi.mode(WIFI_STA);
>       WiFi.begin(ssid, password);
>       while (WiFi.waitForConnectResult() != WL_CONNECTED) {
>         Serial.println("Connection Failed! Rebooting...");
>         delay(5000);
>         ESP.restart();
>       }
>
>       // Port defaults to 3232
>       // ArduinoOTA.setPort(3232);
>
>       // Hostname defaults to esp3232-[MAC]
>       // ArduinoOTA.setHostname("myesp32");
>
>       // No authentication by default
>       // ArduinoOTA.setPassword("admin");
>
>       // Password can be set with it's md5 value as well
>       // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
>       // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
>
>       ArduinoOTA
>         .onStart([]() {
>           String type;
>           if (ArduinoOTA.getCommand() == U_FLASH)
>             type = "sketch";
>           else // U_SPIFFS
>             type = "filesystem";
>
>           // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
>           Serial.println("Start updating " + type);
>         })
>         .onEnd([]() {
>           Serial.println("\nEnd");
>         })
>         .onProgress([](unsigned int progress, unsigned int total) {
>           Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
>         })
>         .onError([](ota_error_t error) {
>           Serial.printf("Error[%u]: ", error);
>           if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
>           else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
>           else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
>           else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
>           else if (error == OTA_END_ERROR) Serial.println("End Failed");
>         });
>
>       ArduinoOTA.begin();
>
>       Serial.println("Ready");
>       Serial.print("IP address: ");
>       Serial.println(WiFi.localIP());
>     }
>
>     void loop() {
>       ArduinoOTA.handle();
>     }

and got this compilation error:

     *  Executing task in folder esp32_OTA_from_scratch: platformio run --environment esp32dev

    Processing esp32dev (platform: espressif32; board: esp32dev; framework: arduino)
    -------------------------------------------------------------------------------------------------------------------------------------------------
    Verbose mode can be enabled via `-v, --verbose` option
    CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
    PLATFORM: Espressif 32 (6.1.0) > Espressif ESP32 Dev Module
    HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
    DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
    PACKAGES:
     - framework-arduinoespressif32 @ 3.20007.0 (2.0.7)
     - tool-esptoolpy @ 1.40500.0 (4.5.0)
     - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
    LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
    LDF Modes: Finder ~ chain, Compatibility ~ soft
    Found 34 compatible libraries
    Scanning dependencies...
    Dependency Graph
    |-- ArduinoOTA @ 1.0.9
    |-- ESPmDNS @ 2.0.0
    |-- WiFi @ 2.0.0
    Building in release mode
    Compiling .pio/build/esp32dev/src/main.cpp.o
    Building .pio/build/esp32dev/bootloader.bin
    Generating partitions .pio/build/esp32dev/partitions.bin
    esptool.py v4.5
    Creating esp32 image...
    Merged 1 ELF section
    Successfully created esp32 image.
    Compiling .pio/build/esp32dev/lib8f4/Update/HttpsOTAUpdate.cpp.o
    Compiling .pio/build/esp32dev/lib8f4/Update/Updater.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFi.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiAP.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiClient.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiGeneric.cpp.o
    Archiving .pio/build/esp32dev/lib8f4/libUpdate.a
    Indexing .pio/build/esp32dev/lib8f4/libUpdate.a
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiMulti.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiSTA.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiScan.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiServer.cpp.o
    Compiling .pio/build/esp32dev/liba9d/WiFi/WiFiUdp.cpp.o
    Compiling .pio/build/esp32dev/libc4b/FS/FS.cpp.o
    Compiling .pio/build/esp32dev/libc4b/FS/vfs_api.cpp.o
    Compiling .pio/build/esp32dev/lib263/SPI/SPI.cpp.o
    Archiving .pio/build/esp32dev/liba9d/libWiFi.a
    Indexing .pio/build/esp32dev/liba9d/libWiFi.a
    Compiling .pio/build/esp32dev/lib494/SD/SD.cpp.o
    Archiving .pio/build/esp32dev/lib263/libSPI.a
    Indexing .pio/build/esp32dev/lib263/libSPI.a
    Compiling .pio/build/esp32dev/lib494/SD/sd_diskio.cpp.o
    Compiling .pio/build/esp32dev/lib494/SD/sd_diskio_crc.c.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorage.cpp.o
    Archiving .pio/build/esp32dev/libc4b/libFS.a
    Indexing .pio/build/esp32dev/libc4b/libFS.a
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageAVR.cpp.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageESP.cpp.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageRP2.cpp.o
    Archiving .pio/build/esp32dev/lib494/libSD.a
    Indexing .pio/build/esp32dev/lib494/libSD.a
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/InternalStorageSTM32.cpp.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/OTAStorage.cpp.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/WiFiOTA.cpp.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/utility/rp2_flash_boot.c.o
    Compiling .pio/build/esp32dev/lib624/ArduinoOTA/utility/stm32_flash_boot.c.o
    Compiling .pio/build/esp32dev/lib6d4/ESPmDNS/ESPmDNS.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/Esp.cpp.o
    Archiving .pio/build/esp32dev/lib624/libArduinoOTA.a
    Compiling .pio/build/esp32dev/FrameworkArduino/FirmwareMSC.cpp.o
    Indexing .pio/build/esp32dev/lib624/libArduinoOTA.a
    Compiling .pio/build/esp32dev/FrameworkArduino/FunctionalInterrupt.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/HWCDC.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/HardwareSerial.cpp.o
    Archiving .pio/build/esp32dev/lib6d4/libESPmDNS.a
    Indexing .pio/build/esp32dev/lib6d4/libESPmDNS.a
    Compiling .pio/build/esp32dev/FrameworkArduino/IPAddress.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/IPv6Address.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/MD5Builder.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/Print.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/Stream.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/StreamString.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/Tone.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/USB.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/USBCDC.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/USBMSC.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/WMath.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/WString.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/base64.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/cbuf.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-adc.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-bt.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-cpu.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-dac.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-gpio.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-i2c-slave.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-i2c.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-ledc.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-matrix.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-misc.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-psram.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-rgb-led.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-rmt.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-sigmadelta.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-spi.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-time.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-timer.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-tinyusb.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-touch.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/esp32-hal-uart.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/firmware_msc_fat.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/libb64/cdecode.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/libb64/cencode.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/main.cpp.o
    Compiling .pio/build/esp32dev/FrameworkArduino/stdlib_noniso.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/wiring_pulse.c.o
    Compiling .pio/build/esp32dev/FrameworkArduino/wiring_shift.c.o
    Archiving .pio/build/esp32dev/libFrameworkArduino.a
    Indexing .pio/build/esp32dev/libFrameworkArduino.a
    Linking .pio/build/esp32dev/firmware.elf
    Retrieving maximum program size .pio/build/esp32dev/firmware.elf
    Checking size .pio/build/esp32dev/firmware.elf
    Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
    RAM:   [=         ]   8.0% (used 26164 bytes from 327680 bytes)
    Flash: [==        ]  24.6% (used 322233 bytes from 1310720 bytes)
    Building .pio/build/esp32dev/firmware.bin
    esptool.py v4.5
    Creating esp32 image...
    Merged 2 ELF sections
    Successfully created esp32 image.
    ========================================================= [SUCCESS] Took 13.72 seconds =========================================================
     *  Terminal will be reused by tasks, press any key to close it.

     *  Executing task in folder esp32_OTA_from_scratch: platformio run --environment esp32dev

    Processing esp32dev (platform: espressif32; board: esp32dev; framework: arduino)
    -------------------------------------------------------------------------------------------------------------------------------------------------
    Verbose mode can be enabled via `-v, --verbose` option
    CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32dev.html
    PLATFORM: Espressif 32 (6.1.0) > Espressif ESP32 Dev Module
    HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
    DEBUG: Current (cmsis-dap) External (cmsis-dap, esp-bridge, esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
    PACKAGES:
     - framework-arduinoespressif32 @ 3.20007.0 (2.0.7)
     - tool-esptoolpy @ 1.40500.0 (4.5.0)
     - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5
    LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
    LDF Modes: Finder ~ chain, Compatibility ~ soft
    Found 34 compatible libraries
    Scanning dependencies...
    Dependency Graph
    |-- ArduinoOTA @ 1.0.9
    |-- ESPmDNS @ 2.0.0
    |-- WiFi @ 2.0.0
    Building in release mode
    Compiling .pio/build/esp32dev/src/main.cpp.o
    src/main.cpp: In lambda function:
    src/main.cpp:39:22: error: 'class ArduinoOTAMdnsClass<WiFiServer, WiFiClient, WiFiUDP>' has no member named 'getCommand'
           if (ArduinoOTA.getCommand() == U_FLASH)
                          ^~~~~~~~~~
    src/main.cpp:39:38: error: 'U_FLASH' was not declared in this scope
           if (ArduinoOTA.getCommand() == U_FLASH)
                                          ^~~~~~~
    src/main.cpp: In function 'void setup()':
    src/main.cpp:37:13: error: invalid use of 'void'
       ArduinoOTA
       ~~~~~~~~~~
         .onStart([]() {
         ~~~~~~~~^~~~~~~
           String type;
           ~~~~~~~~~~~~
           if (ArduinoOTA.getCommand() == U_FLASH)
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             type = "sketch";
             ~~~~~~~~~~~~~~~~
           else // U_SPIFFS
           ~~~~~~~~~~~~~~~~
             type = "filesystem";
             ~~~~~~~~~~~~~~~~~~~~

           // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           Serial.println("Start updating " + type);
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
         })
         ~~
    src/main.cpp:49:6: error: expected primary-expression before ')' token
         })
          ^
    src/main.cpp:52:6: error: expected primary-expression before ')' token
         })
          ^
    src/main.cpp:60:6: error: expected primary-expression before ')' token
         });
          ^
    src/main.cpp:62:20: error: no matching function for call to 'ArduinoOTAMdnsClass<WiFiServer, WiFiClient, WiFiUDP>::begin()'
       ArduinoOTA.begin();
                        ^
    In file included from src/main.cpp:5:
    .pio/libdeps/esp32dev/ArduinoOTA/src/ArduinoOTA.h:91:8: note: candidate: 'void ArduinoOTAMdnsClass<NetServer, NetClient, NetUDP>::begin(IPAddress, const char*, const char*, OTAStorage&) [with NetServer = WiFiServer; NetClient = WiFiClient; NetUDP = WiFiUDP]'
       void begin(IPAddress localIP, const char* name, const char* password, OTAStorage& storage) {
            ^~~~~
    .pio/libdeps/esp32dev/ArduinoOTA/src/ArduinoOTA.h:91:8: note:   candidate expects 4 arguments, 0 provided
    *** [.pio/build/esp32dev/src/main.cpp.o] Error 1
    ========================================================== [FAILED] Took 2.69 seconds ==========================================================

     *  The terminal process "platformio 'run', '--environment', 'esp32dev'" terminated with exit code: 1.
     *  Terminal will be reused by tasks, press any key to close it.

What may be the problem ??

Guy

title: ArduinoOTA - diff between ArduinoIDE and PlatfromIO

Answers: 1

body:
All I can see are three issues (plus possible some bonus ones)

1) You can't daisy chain callback setters like that, it returns void and it doesn't make any sense to have  void.onProgress... and those callbacks doesn't seems to fit current library, so you should just drop them completely.
2) There is no `begin()` without parameters. See [examples](https://github.com/JAndrassy/ArduinoOTA/blob/1.0.9/examples/SerialWiFiOTA/SerialWiFiOTA.ino#L54).
3) In the library I can see only callback setters: [`beforeApply`, `onError` and `onStart`](https://github.com/JAndrassy/ArduinoOTA/blob/1.0.9/src/WiFiOTA.h#L45)
4) You might be missing `#include <Arduino.h>` (it doesn't have any preprocessor like ArduinoIDE that adds this to the first line without you knowing it
5) You might be missing some defines (you can compare Arduino compile commands and Pio one)

Anyway you should take a look into the examples (at least begin is there). Callbacks looks like they are taken from who knows where (probably different library or so).

But they definitely must be complete like:

    ArduinoOTA.onStart([](){ /* started */ });
    ArduinoOTA.onBeforeApply([](){ /* before aply */ });

EDIT:

After some searching the ArduinoOTA library is directly in [esp32 core](https://github.com/espressif/arduino-esp32/blob/master/libraries/ArduinoOTA/src/ArduinoOTA.h) (google: "arduinoOTA onProgress esp32"), so you don't have to add any lib_deps for ArduinoOTA. Or more likely you shouldn't add any, and the correct library will be used then. If not, you'll have to copy (or download) correct library into lib/ subdirectory.


body:
I have an Arduino Uno WiFi Rev2 which I am trying to read data over the serial port from (using C#). The Arduino program periodically emits data to the serial port (for testing purposes). Whenever the Arduino writes to the serial, it also toggles the onboard LED to prove it is still running.

Everything seems to run fine. The LED periodically blinks and thus proves the loop runs as expected. Using the Serial Monitor on the Arduino IDE also correctly echoes the data that the Arduino emits.

Here is the program:
````
int keepAlive = 500;
unsigned long lastKeepAlive = 0;
char ledState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (millis() > lastKeepAlive + keepAlive) {
    lastKeepAlive = millis();
    Serial.println("Alive");
    if (ledState == 0) ledState = 1; else ledState = 0;
    digitalWrite(LED_BUILTIN, ledState);
  }
  delay(5);
}
````

Another reason why I know it works is because the TX LED on the Arduino blinks whenever it writes on the port.

However, once I close the IDE, the Arduino "stops" writing to the serial port. Maybe because it doesn't have to - there is no connection. Fine with me. Also: the TX-LED stops blinking while the onboard-LED keeps toggling on and off. So the loop still runs fine.

Now I'd like to read out the serial data via C#. For that I've written a simple program like so:
````
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
port.Write("123");
while (true)
{
  Console.WriteLine(port.BytesToRead);
  await Task.Delay(1000);
}
````

I expect this program to tell me how many bytes are waiting to be read. But it keeps printing `0` endlessly. Also: the TX-LED does not light up on the Arduino. On the other hand, note that little `port.Write` in the program - it's a test to verify the communication between the Arduino and C#. In fact: I can briefly see the RX-LED on the Arduino light up when my program sends the `123`. I reckon the port and it's settings are correct then.

When I close my program, and the open up the IDE again, the Arduino starts to emit serial data again, the TX-LED starts blinking again and data arrives in the Serial Monitor.

All the while the onboard-LED keeps toggling on and off merrily.

What am I doing wrong? Why is the Arduino talking to the IDE but not to my program? Do I have to initiate some kind of handshake?

title: Arduino Uno WiFi Rev2 is sending serial data to IDE, but not to C# program

Answers: 1

body:
I have solved the issue and @jsotola was correct in pointing out the problem lay with the C# program.

What mislead me was the fact that the TX and RX leds apparently only blink when data is *read* from the respective buffer, not when it is *written* to. In other words: the Arduino kept happily writing to the serial port (as expected) but the TX led did not light up because no one was reading what it wrote. I dind't know that.

For anyone else having this issue: I had to set `DtrEnable` to true. This is still a little confusing to me though. I am not new to programming in C# and with serial ports at all. Yet, I have never had to do this. Also, according to documentation this flag is used when using XOn/XOff or RTS handshake. None of which I am using.

I also tried with PuTTY. I did not configure anything aside from the port name and the baud rate and it worked right away. Investigating, I found that PuTTY apparently defaults to XOn/XOff.

So I'm guessing it really is XOn/XOff then ...

I updated my program like this:
````
var port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.DtrEnable = true;
port.Open();
...
````


body:
Let's suppose you've just created a new Arduino project using PlatformIO, or an IDE like Sloeber. You now have a file named "main.cpp" with two functions (methods?):
* void setup()
* void loop()

Now, suppose you follow Arduino coding norms, and stick something at the top like:

~~~
hd44780_I2Cexp lcd(0x27);
~~~

Is the hd44780_I2Cexp object instantiated by it static? Or is main.cpp #include'd into some class in a way that makes everything in it private or public members of that class?

If they're instance methods, is it absolutely 100% guaranteed that the instance is, and forever shall be, a singleton? Or is there any conceivable scenario where there could be two simultaneous instances of it (say, if you were using both cores of an ESP32)?

If it's an instance, but guaranteed to forever be singleton on any future platform that calls itself "Arduino", is there any *need* to care about the distinction between "instance member" and "static variable" (in the context of main.cpp)?

Should main.cpp "really" have a separate main.h file, and "official" `public:` and `private:` blocks for the sake of C++ linguistic purity, or would I just be creating real or potential problems for the sake of intellectual exercise and ideology?

title: Are variables declared in main.cpp static, instance, or...?

Answers: 2

body:
In the Arduino IDE, `setup` and `loop` are functions, not instances of anything.

There is a file included in the compilation sequence, main.cpp, which has the following code (slightly simplified here):

<!-- language: c++ -->

    #include <Arduino.h>

    int main(void)
    {
     init();

     setup();

     for (;;) {
      loop();
     }

     return 0;
    }

So you can see that this bit of "sugar" basically calls `setup` once and `loop` repeatedly.

The other function, `init`, initialises some hardware, like the timers, so that `millis()` and `delay()` work as documented.

 I can't speak for other IDEs but I assume they do similar things, in order to be compatible.

body:
Whatever you define outside of any function will be global, which is static - it lives for the duration of program execution - and visible to all compilation units that are bound into the eventual execution unit.

If you also include the 'static' declaration ahead of the type, the variable will be file-level static, meaning it will be visibile only within the current file.

This is standard C/C++ behavior for any data type - scalars; vectors, structs & arrays; and objects (C++ only, of course).


body:
I have a problem with my project, the problem is that my Firebase can't detect my DHT11 temperature and humidity sensor from the Arduino.

The code runs without an error but the Firebase can't read my sensor.
Here is my code

````
#include <FirebaseArduino.h>
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>

#define FIREBASE_HOST "*****-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "WE7YUKBpSMo07nUT8ZWYS*****"

#define WIFI_SSID "***"
#define WIFI_PASSWORD "****"

#define DHTPIN D5
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

bool light;
bool fan;

unsigned long previousMillis = 0;
const long interval = 10000;

void setup() {
  pinMode(D1, OUTPUT);
  Serial.begin(115200);
  delay(500);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.println("Connecting..");

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

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  dht.begin();

  delay(2000);

  if (Firebase.failed()) {
  Serial.print("Firebase connection failed: ");
  Serial.println(Firebase.error());
  return;
  }

}

void readDatas(){
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Serial.println(t);
  Serial.println(h);
  Firebase.setFloat("Data/Temperature:", t);
  Firebase.setFloat("Data/Humidity:", h);
}

void loop() {
  light = Firebase.getBool("LightStates/switch");
  Serial.println(light);
  if (light == true){
    digitalWrite(D6, HIGH);
  }
  if (light == false){
    digitalWrite(D6, LOW);
  }

  fan = Firebase.getBool("FanStates/switch");
  Serial.println(fan);
  if (fan == true){
    digitalWrite(D7, HIGH);
  }
  if (fan == false){
    digitalWrite(D7, LOW);
  }

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval){
    readDatas();
    previousMillis = currentMillis;
  }
}
````
Here is the screenshot of my Firebase for better understanding:

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

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

Temporarily, I am using dummy data for the temperature and humidity. Please if you guys know how to fix it, let me know. it will mean so much to me.

title: Arduino cant send DHT11 data to Firebase

Answers: 0


body:
I have an esp32 connected to an FPGA about 2 cm on a PCB. I am trying to send a constant data stream to the FPGA at a throughput of around 1.5 MB/s.

This is too fast for UART, I've been considering SPI but I don't really know how I can implement it in the FPGA.

Are there any other fast data communication protocols over wires available to me, or even a parallel protocol ?

title: Fast wired communication protocols

Answers: 0


body:
I receive the data I send from the Android phone via Bluetooth with Arduino. I want to run the animation that is selected as a result of the data I receive.

There is no problem when I call the animation normally in the loop method. But when I call it in the condition, the program hangs.

Here are the codes:

```
#include <Arduino.h>
#include <Adafruit_NeoPixel.h>
#include "BluetoothSerial.h"

#ifdef __AVR__
#include <avr/power.h>
#endif

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

#define neopixel_data_pin 4
#define led_count 60

Adafruit_NeoPixel strip = Adafruit_NeoPixel(led_count, neopixel_data_pin, NEO_GRB + NEO_KHZ800);

BluetoothSerial SerialBT;
String device_name = "ESP32 Test";
const int neopixel_power_pin = 13;
const int TRIG_PIN = 14;
const int ECHO_PIN = 18;

int neopixel_state;
String ledAnimationVal = "RainbowCycle";
String received_data = "";
bool isConnected = false;

float duration_us, distance_cm, temp_distance = 0;

void state_callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
  if (event == ESP_SPP_SRV_OPEN_EVT) {
    Serial.println("Client connected!");
    sendData("N " + String(neopixel_state));
    sendData("A " + ledAnimationVal);
    distance_change();
    isConnected = true;
  }
  if (event == ESP_SPP_CLOSE_EVT) {
    Serial.println("Client disconnected!");
    isConnected = false;
  }

  if (event == ESP_SPP_DATA_IND_EVT) {
    Serial.println(event);
    Serial.println("Received data!");
  }
}

void sendData(String data) {
  SerialBT.print(data);
  delay(500);
  Serial.println("Sended data! " + data);
  delay(1000);
  SerialBT.flush();
}

void setup() {
  Serial.begin(115200);
  SerialBT.register_callback(state_callback);
  SerialBT.begin(device_name);

  strip.begin();
  strip.setBrightness(255);
  strip.show();

  pinMode(neopixel_power_pin, OUTPUT);

  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  if (SerialBT.begin()) {
    Serial.println("Bluetooth initialized!");
  } else {
    Serial.println("Bluetooth failed to initialize!");
  }
#if defined(__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
#endif
}

void distance_change() {
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  duration_us = pulseIn(ECHO_PIN, HIGH);

  distance_cm = 0.017 * duration_us;

  if (distance_cm - temp_distance > 10.0 || temp_distance - distance_cm > 10.0) {
    temp_distance = distance_cm;
    sendData("T " + String(temp_distance));
  }
}

void animation_method(int ledAnimationVal) {
  switch (ledAnimationVal) {
    case 0:
      rainbow(50);
      break;
    case 1:
      rainbowCycle(50);
      break;
    case 2:
      colorWipe(strip.Color(255, 0, 0), 100);
      colorWipe(strip.Color(0, 255, 0), 100);
      colorWipe(strip.Color(0, 0, 255), 100);
      break;
    case 3:
      theaterChase(strip.Color(127, 127, 127), 50);
      break;
    case 4:
      theaterChaseRainbow(50);
    default:
      Serial.println("Unkown Command!");
      break;
  }
}

void loop() {
  if (isConnected) {
    distance_change();
  }

  if (SerialBT.available()) {
    received_data = SerialBT.readStringUntil('\n');
    received_data.remove(received_data.length() - 1, 1);

    if (received_data == "open") {
      neopixel_state = 1;
      digitalWrite(neopixel_power_pin, neopixel_state);
      sendData("N " + String(neopixel_state));
    } else if (received_data == "close") {
      neopixel_state = 0;
      digitalWrite(neopixel_power_pin, neopixel_state);
      sendData("N " + String(neopixel_state));

    } else if (received_data == "Rainbow") {
      ledAnimationVal = received_data;
      sendData("A " + ledAnimationVal);
      animation_method(0);
    } else if (received_data == "RainbowCycle") {
      ledAnimationVal = received_data;
      sendData("A " + ledAnimationVal);
      animation_method(1);
    } else if (received_data == "ColorWipe") {
      ledAnimationVal = received_data;
      sendData("A " + ledAnimationVal);
      animation_method(2);
    } else if (received_data == "TheaterChase") {
      ledAnimationVal = received_data;
      sendData("A " + ledAnimationVal);
      animation_method(3);
    } else if (received_data == "TheaterChaseRainbow") {
      ledAnimationVal = received_data;
      sendData("A " + ledAnimationVal);
      animation_method(4);
    } else {
      Serial.println("Unkown command!");
    }
  }
}

void colorWipe(uint32_t c, uint8_t wait) {
  for (uint16_t i = 0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for (j = 0; j < 256; j++) {
    for (i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for (j = 0; j < 256 * 5; j++) {  // 5 cycles of all colors on wheel
    for (i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

void theaterChase(uint32_t c, uint8_t wait) {
  for (int j = 0; j < 10; j++) {  //do 10 cycles of chasing
    for (int q = 0; q < 3; q++) {
      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, c);  //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, 0);  //turn every third pixel off
      }
    }
  }
}

void theaterChaseRainbow(uint8_t wait) {
  for (int j = 0; j < 256; j++) {  // cycle all 256 colors in the wheel
    for (int q = 0; q < 3; q++) {
      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, Wheel((i + j) % 255));  //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i = 0; i < strip.numPixels(); i = i + 3) {
        strip.setPixelColor(i + q, 0);  //turn every third pixel off
      }
    }
  }
}

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

 ```

title: Ws2812 Arduino Program stops

Answers: 0


body:
I want to check for specific string (like "RecordStart") in a UART stream (115 200 baud 8N1) from a [camera][1], to know when it is recording or not/if there is an SD. I am using an ESP32-WROOM-32UE with 16MB flash. I wired the Tx from the camera to one of the pin of the ESP. The ESP32 is programmed with VsCode (platformIO) through Arduino framework. I am using freeRTOS.

The thing is, "RecordStart" or "RecordStop" or other strings, appear just one time. Sometimes (when the camera is powering on), there are many many strings sended, very fast. So, from time to time, I lose some bytes and I can't find the strings I am looking for. I would like to optimize my code to never miss a string.

*How the code works ?*
If there is at least 1 byte in the serial buffer, the *taskUART* priority is set to 2 (while other tasks are priority 1. If a null character is detected, the *message_UARTcam* buffer starts to be filled. Then, each time a byte enters the buffer, I am checking if the buffer contains the strings I am looking for. It is working quite well but sometimes, I lose some bytes and the strings are not detected. I think It is because many other tasks are running and the serial buffer fills up faster than it empties. Increase temporarily the priority of the UART task improves the detection but I am still missing some bytes.

*The code:*
```
void taskUART(void *parameter)
{
  while (1)
  {
    if (SerialPortCam.available() > 0)
    {
      vTaskPrioritySet(nullptr, 2);
      char incomingChar = SerialPortCam.read();
      // Serial.write(incomingChar);

      if (flagNullChar == 1 || bufferIndex_UARTcam > 0 && bufferIndex_UARTcam < BUFFER_LEN_UART_CAM)
      {
        message_UARTcam += incomingChar;
        // Serial.println(message);

        if (message_UARTcam.indexOf(stringStart_app) != -1 || message_UARTcam.indexOf(stringStart_button) != -1)
        {
          // Serial.println("Start recording");
          SD_UARTcam = 1;
          record_UARTcam = 1;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringStop) != -1)
        {
          // Serial.println("Stop recording");
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdError) != -1)
        {
          // Serial.println("SD error");
          SD_UARTcam = 0;
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdInitOk) != -1)
        {
          // Serial.println("SD init OK");
          SD_UARTcam = 1;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }
        else if (message_UARTcam.indexOf(stringSdRemoved) != -1)
        {
          // Serial.println("SD removed");
          SD_UARTcam = 0;
          record_UARTcam = 0;
          bufferIndex_UARTcam = 0;
          message_UARTcam = "";
        }

        bufferIndex_UARTcam++;
        flagNullChar = 0;
      }

      if (incomingChar == 0x00)
      {
        flagNullChar = 1;
        message_UARTcam = "";
        bufferIndex_UARTcam = 0;
      }
    }
    else
    {
      vTaskPrioritySet(nullptr, 1);
    }
  }
}
```
*Camera output example:*
```
␛[0;36m[00105849][CA9] ␀[App - Connected] <OnMessage> Received msg: 0xE001000C (param1 = 0x0 / param2 = 0x0)␛[0m
␛[0m[00105849][CA9] ␀RecCapState:0 RecCurrMode:0 RecNextMode:0 GFlags:0X7 Flags:0 StreamType:0␛[0m
␛[0m[00105849][CA9] ␀[App - Widget] <Off> widgetId: -1␛[0m
␛[0;33m[00105849][CA9] ␀[App_Glob_PWM_Buzzer] PWM Buzzer : 2␛[0m
␛[0m[00105849][CA9] ␀[App - ButtonOp] <MgrTask> Received msg: 0x0 (Param1 = 0x0 / Param2 = 0x0)␛[0m
␛[0m[00105849][CA9] ␀[App - ButtonOp] <MgrTask> Received msg: 0x1 (Param1 = 0x0 / Param2 = 0x0)␛[0m
␛[0m[00105899][CA9] ␀[rec_connected_cam_record_start] Start␛[0m
␛[0m[00105899][CA9] ␀[App - Connected] <RecordStart> REC_CONNECTED_CAM_RECORD_START␛[0m
␛[0m[00105899][CA9] ␀Dechi.motion_detec: 0␛[0m
␛[0m[00105899][CA9] ␀[Applib - ExtendEnc] <_ExtendEnc_SetEnableStatus> Enable flag: 0␛[0m
␛[0m[00105899][CA9] ␀[AppLib - MuxMp4] <SetTrickRecDivisor> Cur TrickRecDivisor: 1, New TrickRecDivisor: 1␛[0m
␛[0;34m[00105899][CA9] ␀[App - Sensor] <GetVinMode> Vin Mode = 11␛[0m
```

  [1]: https://www.foxeer.com/foxeer-4k-ambarella-a12-hd-camera-uav-pwm-remote-control-wifi-distortionless-lens-tv-out-micro-hdmi-g-220

title: How to optimize checking for specific string in a UART stream

Answers: 1

body:
Here is an idea that _may_ work: instead of buffering the input stream
and comparing the buffer with the search string, you could do the
comparison on the fly, as you receive the characters. Then you have no
buffering at all, and no time spent in scanning through the buffer.

Below is a function that searches for the `"RecordStart"` marker, while
being fed one character at a time. This function remembers how many
correct characters it has received so far (this is the static variable
`pos`), and updates this count on each received character. It returns
`true` when it has just detected the marker, and `false` otherwise:

```c++
bool marker_found(int c) {
    const char marker[] = "RecordStart";  // search string
    static int pos = 0;  // correct characters received so far
    if (c == -1) return false;  // shortcut for a common case
    if (c == marker[pos]) {
        pos++;                      // count a correct character
        if (marker[pos] == '\0') {  // we got the complete string
            pos = 0;                // reset for next time
            return true;            // report success
        }
    } else if (c == marker[0]) {
        pos = 1;        // we have the initial character again
    } else {
        pos = 0;        // we received a wrong character
    }
    return false;
}
```

You would use it like this:

```c++
if (marker_found(SerialPortCam.read())) {
    // handle the incoming record
}
```

Note that you do not need to test for `SerialPortCam.available() > 0`,
as this is already handled by `marker_found()`.


body:
I'm a total beginner, so I've been talking with Chatgpt regarding the capabilities of the **Attiny85** microcontroller. But the AI would hallucinate a lot and give only partially right answers (because it relies on patterns and knowledge from its training data or something). So I came here to ask for some guidance and insights on the following questions:

1. How much readable text can the Attiny85 accommodate considering variables such as the programs, libraries, and fonts?
2. Is it possible to create a mini text reader using an Attiny85 and a 0.91-inch OLED display, where the text can be scrolled and read like a booklet?

I understand that the Attiny85 has 8kb of flash memory, but I'm unsure about the actual capacity for storing and displaying text, especially considering the potential impact of the compression of the code.

Any advice, experiences, or suggestions on how to optimize the usage of the Attiny85 and the OLED display for this purpose would be greatly appreciated.

Note: Feel free to correct any misconceptions or assumptions I may have made in my questions due to my limited knowledge in this field.

title: How much readable text can fit inside an ATTINY85? Feasibility of scrolling a booklet on a 0.91-inch OLED display

Answers: 2

body:
The AtTiny85 has 8KB of program memory, which you could store strings in. The more data you store, the less room you have for program code and vice-versa.

For only slightly more money you could use an Atmega328P which has 32KB of program memory, giving you somewhat more scope for storing data.

For some kind of text reader you might want to consider an external disk (like, a micro-SD card) which can be easily attached with a modest amount of extra hardware. The hardware might be a couple of voltage-level converters, if you are going to run the processor at 5V rather than 3.3V.

The code to interface to the SD card might be too large to fit into 8KB of memory (I'm not sure about that) but certainly would fit into 32KB.

You also need the code to interface with the OLED — I'm not sure how much program space that would take up.

You might do it with the AtTiny85, with no external disk, but you would probably only get a couple of K of text, once you had your code and your OLED interface. You could compress the text, but then you need code to decompress it, which might outweigh the advantage of compressing it.

For some sort of "booklet" I think the external disk is the most practical solution. This is what one looks like, with its voltage-level converter, hooked up to my Uno:

[![Micro-SD card][1]][1]

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

body: I will take a SWAG, the approach I would use would be to add external memory such as I2C FRAM. It is not expensive and will work just fine with the I2C bus. I use the 32K x 8 devices. You could connect 8 of them. FRAM can be acquired in SPI as well. I have assumed you are using the I2C for the display so no additional pins on the processor will be needed.


body:
I can't seem to figure out what the problem is here. I am trying to upload this code to Arduino Uno but it keeps telling me that the library is not found. I did download the library for the MHZ sensors but it doesn't like it.
I am somewhat new to Arduino.
Please help!
This is the code:

    // Libraries
    #include <DHT.h>
    #include <SD.h>
    #include <SoftwareSerial.h>
    #include <MHZ19B.h>

    // Constants
    const int chipSelect = 10;   // SD card chip select pin
    #define DHTPIN 7             // DHT sensor pin
    #define DHTTYPE DHT22        // DHT sensor type
    #define MHZ19B_TX_PIN 8      // MHZ19B sensor TX pin
    #define MHZ19B_RX_PIN 9      // MHZ19B sensor RX pin

    // Variables
    DHT dht(DHTPIN, DHTTYPE);
    File dataFile;

    MHZ19B mhz19b;
    float hum;      // Humidity value
    float temp;     // Temperature value
    int lightVal;   // Light sensor value
    int co2;        // CO2 concentration

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

      Serial.print("Initializing SD card...");
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        while (1);
      }
      Serial.println("card initialized.");

      Serial.print("Initializing MHZ19B sensor...");
      mhz19b.begin(MHZ19B_TX_PIN, MHZ19B_RX_PIN);
      Serial.println("MHZ19B sensor initialized.");
    }

    void loop()
    {
      lightVal = analogRead(A1);
      Serial.print("Light Value: ");
      Serial.println(lightVal);
      delay(50);

      hum = dht.readHumidity();
      temp = dht.readTemperature();
      Serial.print("Humidity: ");
      Serial.print(hum);
      Serial.print(" %, Temp: ");
      Serial.print(temp);
      Serial.println(" Celsius");
      delay(5);

      co2 = mhz19b.getCO2();
      Serial.print("CO2 Concentration: ");
      Serial.print(co2);
      Serial.println(" ppm");

      dataFile = SD.open("datalog.txt", FILE_WRITE);

      if (dataFile) {
        dataFile.println("Light Value: ");
        dataFile.println(lightVal);
        delay(50);

        hum = dht.readHumidity();
        temp = dht.readTemperature();
        dataFile.print("Humidity: ");
        dataFile.println(hum);
        dataFile.print(" %, Temp: ");
        dataFile.println(temp);
        dataFile.println(" Celsius");

        co2 = mhz19b.getCO2();
        dataFile.print("CO2 Concentration: ");
        dataFile.print(co2);
        dataFile.println(" ppm");

        delay(5000);
        dataFile.close();
      }
      else {
        Serial.println("Error opening datalog.txt");
      }

      delay(1000);
    }

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

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

title: MHZ19B Sensor - Library not found- Please Help!

Answers: 1

body:
That's because it should be either `#include <MHZ.h>` for the MH-Z CO2 Sensors library or `#include <MHZCO2.h>` for the MHZCO2 one.

How do you typically include the libraries you download? Thru the library manager? The way you can do it in Arduino IDE 2.0 is going  thru *Sketch* -> *Include Library* -> the library you want to include -- that should include the correct header.


body: I have an SMD ATTINY that I'm using for a project. Attached to it are 3 I2C devices. When programming it using an Arduino as an ISP, can I have those devices attached? Ie, do I have to program the ATTINY and then solder it on my board or can I solder it and the program (and re-program if necessary).

title: Can I program ATTINY using Arduino as ISP whilst having other I2C devices connected?

Answers: 1

body: Yes, the slave devices shouldn't respond unless addressed. When programming, data will obviously be on the lines however the probability of this data accidentally containing the right sequence to correctly query a slave is minimal.


body:
I built my own atmega32u4 board. I wish to use it as "arduino" so I need to upload first the arduino bootloader.

Now, to do that I need another arduino but I don't have it currently.

However I have an AVR Dragon, which was the way to program these chips years back. So: how the heck can I burn the arduino bootloader to the mega32u4 with avr dragon?

Note: I can use AVR Dragon, and it can see the mega. Just I have NO clue on where this ** arduino stores it's bootloader hex file.

title: Initialize ATMEGA32U4 with arduino bootloader with AVR Dragon?

Answers: 2

body:
See <https://github.com/arduino/ArduinoCore-avr/tree/master/bootloaders/caterina>

The file you probably want would be `Leonardo-prod-firmware-2012-12-10.hex` in that folder.

Those files will be in your Arduino installation, in a folder called "bootloaders".

body:
You don't need another Arduino if you have a programmer, but there is [some problem][1] with the AVR Dargon programmer and avrdude so the Arduino boards package and the MiniCore boards package don't have it configured.

With a supported programmer you can burn the bootloader with Arduino IDE. In Tools menu you select the board most similar to your custom board, then you select in Tools menu the programmer and then you select "Burn bootloader".

[![enter image description here][2]][2]

  [1]: https://github.com/MCUdude/MightyCore/pull/14#issuecomment-191285915
  [2]: https://i.stack.imgur.com/KPLFW.png


body: Just already finished writing the program in arduino ide, but were just thinking if i could use flash encryption in esp32 using arduino ide for commercial use? Cause i am still new to this esp-idf stuffs and wondering if i could set some security config using arduino ide.

title: Is it possible to use flash encryption in esp32 in Arduino ide

Answers: 0