text:
OTA framework update by GitHub server Connection fail error
I have tried to use some OTA programming method by website servers like this method which was not successful and asked here. So I have tried the own Arduino library shown below:
and changed the ESP OTA GitHub Library example code :

to this kind :
/*
  GitHub_Upgrade.ino - Example for ESP library for auto updating code from GitHub releases.
  Created by Gavin Smalley, November 13th 2019.
  Released under the LGPL v2.1.
  It is the author's intention that this work may be used freely for private
  and commercial use so long as any changes/improvements are freely shared with
  the community under the same terms.
*/

#include <ESP8266WiFi.h>
#include <FS.h>

#ifndef STASSID
#define STASSID "Adsl momo"
#define STAPSK  "xxxxxx"
#endif

// A single, global CertStore which can be used by all
// connections.  Needs to stay live the entire time any of
// the WiFiClientBearSSLs are present.
#include <CertStoreBearSSL.h>
BearSSL::CertStore certStore;

/* Set up values for your repository and binary names */
#define GHOTA_USER "soheilpaper" //"username"
#define GHOTA_REPO "ota_github_blink" //"repository"
#define GHOTA_CURRENT_TAG "2.0"
#define GHOTA_BIN_FILE "BlinkWithoutDelay_ino_esp8285.bin"//"sketchname.ino.d1_mini.bin"
#define GHOTA_ACCEPT_PRERELEASE 2

#include <ESP_OTA_GitHub.h>

void handle_upgade() {
    // Initialise Update Code
    //We do this locally so that the memory used is freed when the function exists.
    ESPOTAGitHub ESPOTAGitHub(&certStore, GHOTA_USER, GHOTA_REPO, GHOTA_CURRENT_TAG, GHOTA_BIN_FILE, GHOTA_ACCEPT_PRERELEASE);

    Serial.println("Checking for update...");
    if (ESPOTAGitHub.checkUpgrade()) {
        Serial.print("Upgrade found at: ");
        Serial.println(ESPOTAGitHub.getUpgradeURL());
        if (ESPOTAGitHub.doUpgrade()) {
            Serial.println("Upgrade complete."); //This should never be seen as the device should restart on successful upgrade.
        } else {
            Serial.print("Unable to upgrade: ");
            Serial.println(ESPOTAGitHub.getLastError());
        }
    } else {
        Serial.print("Not proceeding to upgrade: ");
        Serial.println(ESPOTAGitHub.getLastError());
    }
}

void setup() {
    // Start serial for debugging (not used by library, just this sketch).
    Serial.begin(115200);

    // Start SPIFFS and retrieve certificates.
    SPIFFS.begin();
    int numCerts = certStore.initCertStore(SPIFFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
    Serial.print(F("Number of CA certs read: "));
    Serial.println(numCerts);
    if (numCerts == 0) {
        Serial.println(F("No certs found. Did you run certs-from-mozill.py and upload the SPIFFS directory before running?"));
        return; // Can't connect to anything w/o certs!
    }

    // Connect to WiFi
    Serial.print("Connecting to WiFi... ");
    WiFi.mode(WIFI_STA);
    WiFi.begin(STASSID, STAPSK);
    if ((WiFi.status() != WL_CONNECTED)) {
        Serial.print("... ");
    }
    Serial.println();

    /* This is the actual code to check and upgrade */
    handle_upgade();
    /* End of check and upgrade code */

    // Your setup code goes here

}

void loop () {
    // Your loop code goes here
Serial.println("main loop");
delay (1000);
Serial.println("handle_upgade starting: ...");

 handle_upgade();

 Serial.println("handle_upgade ednded: ...");

 delay (1000);

}

but I get the connection error:
checking for update...
Not proceeding to upgrade: Connection failed
handle_upgade ednded: ...

Again, I get some connection similar error like my previous question.
So I asked it to find some instruction for fixing it, if possible.
Thanks.

I don't fully understand this, but I haven't read through it completely either.  Given your apparent success in your other question about "Error 101 Server Did Not Report Size" is it fair to say that you got past whatever problem you were having here and that this question can be closed?


text:
Not able to upload code to NodeMCU
Im now working on a Node MCU based project but the problem is that i cannot upload the code to the board. Further more whenever i connect the usb to the NodeMCU my keyboard stops working and only works again after i turn off and on my pc this happens whenever i disconnect and connect the Node MCU. The error is COM port is not found or board is not connected and sometimes after i disconnect the Node MCU my system gives a message The Last USB device malfunctioned
Can anyone help I'm using a basic NodeMCU 12E CP2021??

I'd check 3 things:

If it's a specific USB port/cable problem, not related to the NodeMCU itself (your said it interacted with your USB keyboard, what makes sense if it's a computer-usb issue). Try to connect the NodeMCU to a different USB port/hub in your computer using another USB cable.

Of course it could be a USB-Serial driver issue. Please make sure what chip is used on your NodeMCU (CH340 or CP1202) and make sure the correct driver is installed.

Most important - you must make sure your Serial pins on the NodeMCU (TX, RX) are not connected to anything during program upload. They are bridged to the Serial connection that is coming from the computer (through the USB-to-Serial chip) and interact and interfere with them.

Good luck!

Thank you apparently its y breadboard which had a problem as it made a connextion between the rx and tx

source: Stack Exchange

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

sort: votes


text:
Problem with sending sound sensor data to app using ESP32 over BLE_UART
I was working on Adafruit Electret Microphone Amplifier - MAX4466 with Adjustable Gain
and ESP32.
I want to send data to an app using BLE UART
I have printed data to the serial monitor or serial Plotter using the following example  code
/*
    Video: https://www.youtube.com/watch?v=oCMOYS71NIU
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
    Ported to Arduino ESP32 by Evandro Copercini

   Create a BLE server that, once we receive a connection, will send periodic notifications.
   The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E
   Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE"
   Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with  "NOTIFY"

   The design of creating the BLE server is:
   1. Create a BLE Server
   2. Create a BLE Service
   3. Create a BLE Characteristic on the Service
   4. Create a BLE Descriptor on the characteristic
   5. Start the service.
   6. Start advertising.

   In this example rxValue is the data received (only accessible inside that function).
   And txValue is the data to be sent, in this example just a byte incremented every second.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
float AnalogValue;
BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
BLECharacteristic * pTEMPCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint16_t  txValue;
uint16_t  TEMPValue;

static String Received_Char;

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TEMP "6E400004-B5A3-F393-E0A9-E50E24DCCA9E"

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++)
        {
          Serial.print(rxValue[i]);
          Received_Char=rxValue[i];
        }
        Serial.println();
        Serial.println("*********");

      }
      Serial.println(Received_Char);
    }
};

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

  // Create the BLE Device
  BLEDevice::init("Lungs Monitoring");

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pTxCharacteristic = pService->createCharacteristic(
                        CHARACTERISTIC_UUID_TX,
                        BLECharacteristic::PROPERTY_NOTIFY
                      );

  pTxCharacteristic->addDescriptor(new BLE2902());

    pTEMPCharacteristic = pService->createCharacteristic(
                        CHARACTERISTIC_UUID_TEMP,
                        BLECharacteristic::PROPERTY_NOTIFY
                      );

  pTEMPCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
      CHARACTERISTIC_UUID_RX,
      BLECharacteristic::PROPERTY_WRITE
                                          );

  pRxCharacteristic->setCallbacks(new MyCallbacks());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {

  if (deviceConnected) {
    if(Received_Char=="S"){
    txValue = analogRead(A0);//=AnalogValue.toInt();
    pTxCharacteristic->setValue(txValue);
    pTxCharacteristic->notify();
    //txValue++;
    Serial.println(txValue);
    delay(10); // bluetooth stack will go into congestion, if too many packets are sent
  }
  else if(Received_Char=="T");
  }
  // disconnecting
  if (!deviceConnected && oldDeviceConnected) {
    delay(500); // give the bluetooth stack the chance to get things ready
    pServer->startAdvertising(); // restart advertising
    Serial.println("start advertising");
    oldDeviceConnected = deviceConnected;
  }
  // connecting
  if (deviceConnected && !oldDeviceConnected) {
    // do stuff here on connecting
    oldDeviceConnected = deviceConnected;
  }
}

But the data is transferring at a very high speed and the app is not able to get it properly.
Can anyone help me with how to take samples of the audio sensor and store them in a byte array and send it to the app?
Thank you in advance.

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


text:
fixing communication port errors
the communication port (com11) is yellowed with exclamation marks in device manager and I am unable to run arduino on my computer. how to get rid of the yellow exclamation mark on the com 11?

I guess you are using Windows? You might need to install the correct driver. Do you have a genuine Arduino, or one of the cheap clones? (They use different USB to Serial chips)

how do I know if it is genuine or clone in the first place?

It's written on it or on the box it came in.

Provide a link to the actual thing you bought.


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

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

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

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

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


text:
Cannot display a chr string using Wire.read() and u8g2.drawStr()
I'm still getting myself acquainted with C++, so I expect this is a very basic issue I'm facing. I've got an OLED screen connected to a Teensy LC and can display text on it just fine. The Teensy receives bytes via I2C, and I want to reassemble those bytes into strings and display them on the OLED.
My relevant code:
#define I2C_ADDRESS 4
char buf[16];

void setup(void) {
  Serial.begin(9600);
  Wire.begin(I2C_ADDRESS);
  Wire.onReceive(receiveData);
  u8g2.begin();
}
void loop(void) {
  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, buf);
  // This line does:
  u8g2.drawStr(0, 20, "Foobar!");
  u8g2.sendBuffer();
  delay(1000);
}

void receiveData(int byteCount){
  Serial.print("Data received: ");
  int i;
  for (i=0; i<byteCount; i++)
  {
    buf[i] = Wire.read();
    Serial.println(buf[i]);
  }
  buf[i] = '\0';
  Serial.println(buf);
}

In the receiveData() function, the Serial.println() within the for loop prints out each letter of the payload as it's received, one after the other - but the Serial.println() below the for loop, which in my estimation should print out the whole message, prints out a blank line. I presume that's related to the fact that the received string doesn't show up on the OLED display.

Add a Serial.print(byteCount); as first line of receiveData . Perhaps that gives a hint.

This is kind of convoluted to put as a comment and it is sort of an answer, so I'm making it an answer.  Just to warn you, I have not tried to compile any of the code snippets here.
Wire.onReceive(receiveData); registers your function so that it can be later called back in the context of the interrupt service routine used for handling I2C ("Wire") data.  Or at least this is how it usually works.  So when your receiveData function is running you are in the middle of handling an interrupt associated with the I2C peripheral.
Using Serial.print(), .println(), .write(), and many other things, including non-serial related things like delay() inside of an interrupt service is usually a no-no.  On the AVR Arduino core, if the outbound serial buffer happens to fill, your code will deadlock with the underlying .write() waiting for there to be room in the outbound serial buffer and the serial transmit interrupt waiting for .write() to get done waiting for it.  I don't know how the Teensy LC and its MCU are configured, whether or not it prioritizes interrupts, etc, but it is likely that you're still not supposed to call functions like these inside the interrupt context.
There's really not a lot you're supposed to do in an ISR except:

communicate with hardware (which is being done for you here)
manage the non-volatile variables that belong to the ISR itself.
set global volatile qualified variables to communicate with the main line of execution.
call functions that have no shared state with the main line of execution.
call functions that have shared state but are carefully designed to be called from both ISR contexts and main line of execution.

That said, I don't know precisely why you're seeing what you're seeing, but I'm not overly surprised either.  The above may be related to it, but I haven't drawn that connection yet.
The way you currently have receiveData, it may overflow buf.  All that's required for that is for the sending side to send more than 15 bytes.  Any number of weird things can happen if you manage to overflow.  Is it related? Maybe.
For communicating between the receiveData running in the ISR context and the main line of execution in loop, buf should be volatile qualified.  Without that the main line of execution can behave as though buf never changes after it is first seen.  Because of how you're using it and familiarity with the compiler, I'm going to guess that this isn't manifesting as a bug, but I don't know that; it could be related.
So I'd recommend updating something like your buf declaration to volatile qualified and removing the Serial print calls from the receiveData function, and preventing overflow:
volatile char buf[16];

/// ...

void receiveData(int byteCount){
  static const size_t room_for_non_null_chars = sizeof buf - 1;
  const size_t read_amount = min(byteCount, room_for_non_null_chars);

  int i;
  for (i = 0; i < read_amount; ++i) {
    buf[i] = Wire.read();
  }

  buf[i] = '\0';
}

If it weren't for the fact that we need to read into something volatile qualified the above loop could really just be a read call taking the buffer and size.  You can see that's updated to prevent overflow.
Part of loop would then become something like:
void loop() {
  char non_volatile_buf[sizeof buf];
  size_t write_index = 0;

  noInterrupts();
  for (char c: buf) {
    non_volatile_buf[write_index++] = c;
  }
  interrupts();

  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, non_volatile_buf);

  // ...

We're turning off interrupts while copying the data into a local buffer so that the onReceive handler cannot interrupt the use of the buf, updating while you're in the middle of using it in drawStr.
If you care about losing messages there's more that would need to be done.  Surrounding what to do if you've got a call to receiveData while there's a message currently in buf.  The way the above is written it just drops whatever is in there whether it's been seen by loop() or not.

I didn't get a load of sleep last night but I finally figured it out, thanks to timemage's post. I'm concerned that my solution is hyper-specific, but I'd rather share it to save someone the trouble in future.

timemage was right in that the buffer should really be volatile qualified and that as little processing as possible should happen in what I now understand is an ISR. I couldn't get their code to work, but I eventually stumbled on i2c_t3, an enhanced I2C library specifically for Teensy 3.0/3.1/LC. Looking at the library's code and especially its basic peripheral example, it looks like it implements similar techniques to those timemage recommended.
The other thing I didn't consider was the way the controller was communicating. I was using the smsbus2 Python library, and at one point I changed the address offset from 0x00 to 0x01. This mysteriously seemed to make the Teensy code work, but I don't know why!

data = [1, 2, 3, 4, 5, 6, 7, 8]
bus.write_i2c_block_data(0x21, 0x01, data)

Lastly, from reading forum posts about saving data to variables from I2C, it looks like a lot of quite simple code that does work on other Arduino devices doesn't work on the Teensy.1 I'd have to get an Arduino device to test this theory, though.

Because I'm a bad scientist, I haven't checked whether any of my original code or timemage's improved code works when I offset the address in the smbus2 code. But for what it's worth, these are the things I did to solve my problem!

See for example: https://forum.arduino.cc/index.php?topic=570597.0; https://forum.arduino.cc/index.php?topic=619902.0.


text:
7-segment displays are not working

/*
MODIFIED TRAFFIC LIGHT SYSTEM W/ A COUNTDOWN TIMER FUNCTION
BY JOHN SEONG

THIS IS A QUITE ACCURATE SIMULATION OF TORONTO'S TRAFFIC LIGHT SYSTEM
WHICH INCLUDES TWO 7-SEGMENT DISPLAYS THAT SHOW THE SECONDS LEFT
TILL THE PEDESTRIAN LIGHT SWITCHES BACK TO RED.

ENJOY!
*/

const int redLED = 4;
const int yellowLED = 5;
const int greenLED = 6;
const int pedestrianRedLED = 13;
const int pedestrianGreenLED = A5;
const int buzzer = 12;
const int button = 7;

int segmentPins[] = {11, 10, 9, 8};

int buttonHitCount = 0;

void setup() {

  Serial.begin(9600);

  // Car Traffic LEDs
  pinMode(redLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);
  pinMode(greenLED, OUTPUT);

  // Pedestrian Traffic LEDs
  pinMode(pedestrianRedLED, OUTPUT);
  pinMode(pedestrianGreenLED, OUTPUT);

  // 7-Segment Display Pins
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);

  // Piezo Speaker Pin
  pinMode(buzzer, OUTPUT);

  // Pedestrian Push Button
  pinMode(button, INPUT_PULLUP);

  displayNumber(9, 2);
  displayNumber(9, 3);
}

void loop() {

  // Read the state of the button
  int buttonState = digitalRead(button);

  Serial.println(buttonState);

  if (buttonState == LOW) {
    buttonHitCount = 1;
  }

  if (buttonHitCount == 1) {
    switchToRed();

  } else if (buttonHitCount == 0) {
    defaultState();
  }
}

void displayNumber(int num, int displayPin) {

  bool binaryValue[][4] = {
    {0, 0, 0, 0}, // 0
    {0, 0, 0, 1}, // 1
    {0, 0, 1, 0}, // 2
    {0, 0, 1, 1}, // 3
    {0, 1, 0, 0}, // 4
    {0, 1, 0, 1}, // 5
    {0, 1, 1, 0}, // 6
    {0, 1, 1, 1}, // 7
    {1, 0, 0, 0}, // 8
    {1, 0, 0, 1}, // 9
  };

  for(int i = 0; i < 4; i++) {
    digitalWrite(segmentPins[i], binaryValue[num][i]);
  }

  digitalWrite(displayPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(displayPin, LOW);
}

void switchToRed() {

  delay(5000);

  // YELLOW
  digitalWrite(yellowLED, HIGH);
  digitalWrite(redLED, LOW);
  digitalWrite(greenLED, LOW);
  delay(2000);

  // RED
  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, LOW);
  digitalWrite(yellowLED, LOW);

  // GREEN
  digitalWrite(pedestrianGreenLED, HIGH);
  digitalWrite(pedestrianRedLED, LOW);

  switchToGreen();
}

void switchToGreen() {

  // 15
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(5, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 14
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(4, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 13
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(3, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 12
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(2, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 11
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(1, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 10
  noTone(buzzer);
  displayNumber(1, 2);
  displayNumber(0, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 9
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(9, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 8
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(8, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 7
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(7, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 6
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(6, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 5
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(5, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 4
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(4, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 3
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(3, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 2
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(2, 3);
  tone(buzzer, 1000);
  delay(1000);

  // 1
  noTone(buzzer);
  displayNumber(0, 2);
  displayNumber(1, 3);
  tone(buzzer, 1000);
  delay(1000);

  noTone(buzzer);

  // YELLOW
  digitalWrite(yellowLED, HIGH);
  digitalWrite(redLED, LOW);
  digitalWrite(greenLED, LOW);
  delay(2000);

  // GREEN
  digitalWrite(redLED, LOW);
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, LOW);

  // PEDESTRIAN - RED
  digitalWrite(pedestrianGreenLED, LOW);
  digitalWrite(pedestrianRedLED, HIGH);

  // Reset the value
  buttonHitCount = 0;
}

void defaultState() {

    // GREEN
    digitalWrite(greenLED, HIGH);
    digitalWrite(yellowLED, LOW);
    digitalWrite(redLED, LOW);

    // PEDESTRIAN - RED
    digitalWrite(pedestrianRedLED, HIGH);
    digitalWrite(pedestrianGreenLED, LOW);
}

Clearly something is wrong with my code and the 7-segment displays are off the whole time the program is running. I also posted a link below which directs to the tinkercad project I made.
https://www.tinkercad.com/things/7pnnbXoaqrG-improved-stop-light-john-seong/editel?sharecode=jR86i_srV7QgP11u1CxOFzeVwehzjIRr8wCC7vbbLaY

Please try to color code the wires more. With nearly all wires being green and overlapping at many places it is really difficult to follow the wiring diagram. Also you have some more components besides the 7-segment displays, that aren't really relevant here. It is a common debug method to remove all code and components, that aren't relevant to a specific problem, then getting the relevant problem solved and then add the rest of the code and components one by one, always checking for errors inbetween. You could try building the circuit for only the displays and check again

I debugged; which turns out, all the connections are right however when I press the button the segment displays turn off.

You are never touching the segment display anywhere in your loop() function. So if does something (like going off) but none of the LEDs act as intended (i.e. switching from green to red), then something in your wiring must be wrong or the pin numbers in the code don't match.

It's supposed to multiplex^

You could make it easier for anyone trying to help you by structuring the wires in a more logical manner (for example don't let wires of the same color overlap) and maybe enlarging the schematic (so that pin numbers are readable for example). It's very hard to understand at the moment.

displayNumber only show the number for 10µs. So you need to call this function a lot more times per second for you eyes to notice. You could also use a timer to periodically change between segments, but fast enough that it appears all two displays are lit at the same time.

Why not convert it to a schematic as you have wired it, we would understand that a lot easier. It is also much easier to follow your logic in that format. You can download several schematic capture programs for free. I use KiCad. Schematics are part of the basic language in electronics.

How about an annotated schematic, the language of electronics.

Not really a solution, but changing the code for the displayNumber function as shown below, will make it more apparent where the real problem is.
void displayNumber(int num, int displayPin) {

  bool binaryValue[][4] = {
    {0, 0, 0, 0}, // 0
    {0, 0, 0, 1}, // 1
    {0, 0, 1, 0}, // 2
    {0, 0, 1, 1}, // 3
    {0, 1, 0, 0}, // 4
    {0, 1, 0, 1}, // 5
    {0, 1, 1, 0}, // 6
    {0, 1, 1, 1}, // 7
    {1, 0, 0, 0}, // 8
    {1, 0, 0, 1}, // 9
  };

  // turn off both displays
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);

  for(int i = 0; i < 4; i++) {
    digitalWrite(segmentPins[i], binaryValue[num][i]);
  }

  digitalWrite(displayPin, HIGH);
  /* // remove these two lines
  delayMicroseconds(10);
  digitalWrite(displayPin, LOW);
  */
}


text:
Push button restarts the arduino
I have linked an external push red colored button to my arduino but when I press it, instead of giving me HIGH or LOW, it resets the arduino. I am a beginner to this stuff so could someone help?

It is odd that you omitted your code and a schematic or image or even description of your wiring but made sure to let us know that the button is red =)

Yes. Change it to a green button and all will be well :P

Why don’t you show (or at least describe) how you’ve connected the button so we don’t have to guess? There are very many ways to connect an external red button to an Arduino.

If your button creates a short circuit between 5V and GND pins... it will certainly act like a RESET.  Let's try to make sure you are not creating a dead short on an Arduino pin so you avoid prematurely killing your controller.

Thank you. Changing it to 3.3 V also does the trick

@SiddharthAgrawal please fix the real issue. Creating a short on 3.3V maybe doesn't reset the Arduino, but in general, shorts are to be avoided. Unless you like fire, sparks,  and/or broken electronics.

Ok I'll add the resistance. Thanks


text:
Can we have 2 HC12 on a single Arduino (1 to receive and other to transmit)?
I'm working on a project and I need to send 2 datas and receive them at the same time.
My question is: Is it possible to have 2 Arduinos both have 2 HC12 (total 4), because I want each Arduino to send and receive data at the same time.
It's hard for me to have 4 Arduinos.

You may have to provide a link to this HC12 thing you have.  If you're trying to use a particular library with them you should mention that library also.

Why do you want 2 HC-12s? I thought, that they are already working duplex

It would be good to know what is meant by "two datas".  Two connections? Two items? etc.

i'm using the arduino for a motor in an RC plane (1 arduino in the sky the other is on the ground), i want to control it's speed from the ground by an HC12 (send from ground and recive in the sky)  the other is to send me back number of rotations of the motor (sends from sky and receive from ground) so total 4 HC12 and 2 arduinos

@chrisl The HC-12 is actually half duplex but with a small buffer. For true full duplex you need two pairs of modules.

how can i know if mine is half or full duplex

Yes you can - one on Serial pins 0/1 and the other using SoftwareSerial on any other pins. Note that the one on SoftwareSerial will interfere with the one on Serial as it disables interrupts while sending or receiving.
It may be better to use an Arduino which has multiple hardware serial ports. Maybe one of the Teensy boards would be better for your needs.
Alternatively if (and I am not familiar with the modules enough to know if this is right or not) they operate as a transparent serial bridge then you could connect one module to the TX pin for transmission and the other to the RX pin for reception - reading from serial receives from one, and writing to serial transmits through the other.
Also note that you will have to ensure that both pairs of modules are running on different channels to prevent interference between them.

thank you so much, this is really helpful! can i know if you have any codes that may be helpful

@shamsaalb No. As I say I'm not familiar with the modules. However they look like a transparent serial bridge, so whatever you Serial.print from one end will appear at the other end.

Yes, you just need to connect your TX pin on the RX pin of one HC-12, and your RX pin on the TX pin of the other HC-12, and use separate channels for both HC-12. And then you do the same thing on the otherside, but you need of course, to reverse the channels - Et voila.
However, you might need to take precautions (distancing / shielding) to avoid your emitting HC-12 to parasite the channel of the nearby receiver.
By the way, it seems that one should refrain as much as possible to use SoftwareSerial, which is not robust enough for high speed and seems to cause data distortion.


text:
How to add the previous value to current value from sensor
const byte interruptPin = 4;
void ICACHE_RAM_ATTR count();
void setup() {
  Serial.begin(115200);

  // Set up our digital pin as an interrupt
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), count, RISING);
}

void loop() {

}

void count() {
  volatile float rainrate = 3;
  volatile float rate;
  volatile float total;

  rate = rainrate * 0.1;
  Serial.println(rate);

Every time it tips, it returns 0.3.  How do I add the previous value(0.3) to a new tip, to make it 0.6, and save it into a variable.
Thanks!

hello, no it should be like, if it becomes 0.6 from 0.3, the next tip will be 0.9 and so on.

It may be just me, but I have no idea what you mean by "tip".  Not that it matters, I think you have an effective answer to your question anyway.

Btw, you can make the volatile variables global, by putting them above void Setup.
To put the total (new) value, use:
total += <sensorValue>;

where <sensorValue> is a call to get the sensorValue (or the value that has the sensor value stored in it), but I cannot see that in your sketch.
total += 0.3;

is the same as writing:
total = total + 0.3;

The value right of the '='sign is copied (assigned) to the left part of the '=' sign.

Hello, its working. but I think there's somethings wrong with my code because it outputs as double value. when I tip my tipping bucket reed switch, it outputs as 0.3, 0.6 then stop, next tip will be 0.9, 1.20.

An Arduino does not make a difference between double or float. I'm not sure what you mean it stops at 0.6. The variable total should be increased every time it is (what you call) 'tipping'.

@Giddsec I suspect you are suffering from "button bounce" - google "arduino debounce" for help.

Got it all working, thank you very much! :)

You're welcome; if it helped you, please upvote the answer, if the answer gave the best response, accept it (by using the check mark next to the question). Success with your project.

Why bother doing that arithmetic at every tip, when you could just count tips, and multiply the count by 0.3 whenever a result is needed?
tips += 1;                    // each time the bucket tips.
and
Serial.println(0.3 * tips);   // each time you want a result

Just to add context to this answer: floating point arithmetics can be orders of magnitude slower than integer arithmetics on FPU-less devices (like many Arduinos).


text:
How to make an arduino webserver over USB? without ethernet shield nor wifi chip
I would like to begin to understand ethernet handshakes by integrating an Ethernet over USB protocol within an arduino mega or nano. Is there something about the ethernet protocol that requires more  components? I know that USB to ethernet adapters exist. In this scenario, it would be more like a USB to arduino webserver experiment, except the arduino webserver would also be providing the IP address to the laptop during the initial handshake.
Shouldnt it be possible to create a simple router from an ATMega2560, where you plug in an arduino to a computer, and the computer is assigned an IP address on the ATMega's network?
Likewise, couldnt you then serve small files from the ATMega to a web browser through this IP connection?
I know this sounds dumb and like over engineering. But i promise i am not crazy and that this could be useful. USB to Ethernet adapters and drivers exist, so i am not sure that there is a hardware limitation. In other words, while ethernet normally requires 4 data lines and USB 2.0 has only 2 data lines, there are still kernel drivers that allow USB to work fine in this way. Likewise the ATMega has only 2 available data lines. So couldnt you begin by simulating a USB to Ethernet device firmware using the ATMega?
A new avenue here that isnt available with Serial connections would be that you could access the ATMega from a web browser, whereas in other driver modes the browser doesnt have the permission to communicate with the Mega.
Why or why not? / How could this be done?

it is unclear what you are talking about ... where would the USB ethernet adapter plug in?

the computer is assigned an IP address on the ATMega's network? This requires that the Arduino also be running a DHCP server. If all you want is to serve small files, why not emulate a USB storage device?

@jsotola There is no Ethernet port nor USB ethernet adapter. There is one connection, from the USB line to the AT Mega.

@Reinderien Yes a DHCP server would be needed, except the server would only have one client. I want the files to be html/javascript, executed through a web browser like chrome or firefox

i guess web browsers can still access File URIs. Still, i am wondering how to do this for learning purposes and other reasons, like is a shield needed? Or can you do it all without one?

https://playground.arduino.cc/Code/SerialIP/

You cannot change what the Arduino's USB does. The USB is not provided by the ATMega2560, but by the USB to UART interface chip.
On a genuine Arduino that may be an ATMega16U2 which could be reprogrammed, but on Chinese clones it most often isn't.
You would need to start with a board that has a real "native" USB connection, such as the Arduino Leonardo (ATMega32U4) or the much more capable (though deprecated) Arduino Due.
Then you would need to create not only the USB "CDC/ECM" device profile, but also the IP stack on top of it to handle the IP data, then a TCP later on top of that to handle the socket data.
The actual CDC/ECM device itself is very simple - much like the CDC/ACM (USB serial) device it's really just a dumb pipe that sends and receives raw Ethernet frames. Interpreting those frames and managing TCP/IP sessions and streams is a far more involved process and would be the bulk of the work. You'd probably want to take an existing standalone IP stack implementation and replace the existing layer 2 code with the CDC/ECM interface instead.
An alternative, as advocated by @Juraj, is to use IP over Serial. This uses a serial protocol (SLIP) to encapsulate the IP frames and has a rudimentary cut-down IP stack in it. However this is old technology and is not well supported by operating systems any more. For example the home versions of Windows no longer have any SLIP support (it used to be provided through "DUNS" - the Dial UP Network Server - which no longer exists).

Try the Web Serial API instead. Example usage.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

More information is needed. For example, please provide a link to the Web Serial API webpage and then provide a summary of what this API does and how it solves the problem the OP is asking.

I do not see any way using the Web serial API would help the question asker with their goal of  understanding Ethernet handshakes


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@EdgarBonet So it is...

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

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

Thanks! it worked :)


text:
INA219 with L298N POWER LOGGER
I Have been working on a power logger with INA219 and L298N
the thing is, the voltage and current displayed on Serial Monitor is not the same on my multimeter.
the Arduino is connected to the pc to view the result on the serial
#include <Wire.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

//Adafruit_INA219 ina219_A;
//Adafruit_INA219 ina219_B(0x41);

void setup(void)
{
  Serial.begin(115200);
  while (!Serial) {
      // will pause Zero, Leonardo, etc until serial console opens
      delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  if (! ina219.begin()) {
    Serial.println("Failed to find INA219 chip");
    while (1) { delay(10); }
  }
  ina219.setCalibration_32V_1A();

  Serial.println("Measuring voltage and current with INA219 ...");
}

void data(void)
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;
  float power_mW = 0;
    delay(2000);
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

  Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
  Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
  Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
  Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
  Serial.print("Power:         "); Serial.print(power_mW); Serial.println(" mW");
  Serial.println("");

  delay(2000);
}

void loop() {

    analogWrite(9, 245); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 200); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 150); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 0); //ENA pin
    digitalWrite(8, LOW);
    digitalWrite(7, LOW);
    data();
    delay(5000);

}

not the same on my multimeter What sort of difference are you seeing?

The INA219 gives you the instantaneous current and voltage at a given moment in time, whereas your DMM shows you the average over a period.
The L298N is giving out a PWM waveform that is rapidly being turned on and off.
You see where this is going?
Your Arduino detection will be giving you either full power or no power (or somewhere in between owing to the low-pass filter effect of the motor), pretty much randomly, whereas the DMM will give you the average over a number of samples.
You would need to rapidly sample the PWM signal over a period of time and calculate the average to get an idea of what the current and voltage might be.

Thank you sir, but do you think there is something wrong with the connection or i will just add code for DMM somewhere?

You need to add code to create an average over time of the values.

Unless I missed something, I didn't see where the control pins (7,8,9) were initialized properly.  There should be some 'pinMode()' statements in setup().  Am I missing something?


text:
Powering Arduino by USB
The USB cable that came with the Arduino board is not easily recognized by the computer for selecting the appropriate COM port,
For powering the Arduino it works fine (the board will light up when plugged), so why it is not easily recognized by the computer in the device manager?

What do you mean with "is not easy"? Does is work or doesn't it work?

it requires you holding it to be detected in the device manager

Mhh, that should not happen. When something only works, when you touch it, it is often because of a grounding issue. Can you please try a different cable? Maybe the one, that you got with the Arduino, is broken.

It sounds like you're describing a board with a micro-usb connector.  Is that what you have?


text:
Built-in LED lighs up spontaneously
I'm trying to connect my ESP32 to this CO2 measurement device. I admit I am clueless about connecting devices with independent power sources to one another.
I connected ground to ground and CLK to PIN2. Just to be on the safe side, I put a resistor between CLK and PIN2.
I started with 4.8KOhm of resistance. ESP's ADC measured 2.1V and it seemed fine. But when I switched to 1K resistor, trying to get closer to the level of "logical 1" (the way I understand it), something unexpected happened. ADC measured 2.65V, which is still beyond 3.3V ESP should be able to handle, and the built-in LED lit up, although nothing in my sketch called for it.
Though the configuration worked stably for some minutes while I was testing it, and no smoke appeared, I am afraid the LED lighting spontaneously might be a sign of an electrical breakdown.
The both devices are sitting on the same USB hub.
Here is the sketch I am using:
#define PIN_CLOCK  2

void setup() {
  pinMode(PIN_CLOCK, INPUT);
  Serial.begin(4800);
}

bool last = 0;

void loop() {
  int x = analogRead(PIN_CLOCK);
  bool val = x > 1500;
  if (last != val)
    Serial.println(x*3.3/4095);
    last = val;
  }

Can someone explain why the LED lights up?
Can someone recommend a good article/video on basic rules about interconnecting such devices?

You do not need a resistor in the circuit. Just connect the devices together directly as shown in the tutorial you link to. They are both 3.3V devices and operate perfectly together with no additional components.
Reading an analog value from a clock signal is pretty meaningless anyway, so there's really no point in your experiments at the moment. They prove nothing.
As to why the light came on - that is most likely because the ESP is configured to use that LED to indicate the WiFi status or something similar.  The thing with an ESP32 is there is a whole lot more going on than just your code. Your code is just one thread in a complex system.

The clock pin is an output from the ESP to the nRF24L01. Could you expand on that? I have probably misled you, by calling it "CLK". I meant I connected what in the tutorial called ZG-C to D2. nRF24L01 is a part of a different setup. Still the question is: "why the built-in led"?

Ah, so you're using section 3.2 of the tutorial? It still stands that you don't want a resistor in there. As to the internal LED - that may be being controlled by the WiFi code and have nothing to do with what you are doing.

A schematic would be a big help and maybe links to the particular modules your using and there data sheets.


text:
Is this class declaration wrong? " Declaration has no storage class or type specifier" error
While trying to setup  an ESP32 as mqtt publisher I am getting strange errors. Here is my code:
#include "mqttSetup.h"
#include <WiFi.h>
#include <PubSubClient.h>

static byte httpFailCounter = 0;
byte counter = 0;

const char *ssid = "SSID";
// const char *password = "xxxxx";
const char *passphrase = "xxxxx";

WiFiClient espClient;

const char *mqtt_server = "192.168.1.39";
const int mqttPort = 1883;
const char *mqttUser = "xxxx";
const char *mqttPassword = "xxxxx";

PubSubClient pubClient(espClient);

pubClient.setServer(mqtt_server, mqttPort);

void checkConnection()
{
    if (WiFi.status() == WL_CONNECTED)
    {
        counter = 0; //reset counter
    }
    else if (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, passphrase);
    }
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");

        counter++;
        if (counter >= 60)
        {
            ESP.restart();
        }
    }
}

void reconnect()
{

    while (!pubClient.connected())
    {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        const char *clientID = "ESP32D-MQTT";
        // Attempt to connect
        if (pubClient.connect(clientID))
        {
            Serial.println("connected");
            // Once connected, publish an announcement...
            pubClient.publish("outTopic", "Hello from ESP");
            // ... and resubscribe
            //   client.subscribe("inTopic");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(pubClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

I don't understand why the compiler is spitting out the following two errors:
this declaration has no storage class or type specifier (referring to my pubClient declaration)

expected a ';'

It doesn't have any issue when I declare the pubClient but at the line :
pubClient.setServer(mqtt_server, mqttPort);
where I use the pubClient it gives the error.
Besides I don't see any ; missing in the code.
Could you please help me figure out the source of error?

Header file for this code chunk
#ifndef MQTTSETUP_H
#define MQTTSETUP_H

void checkConnection();
void reconnect();

#endif

------------ Main sketch---------
#include <Arduino.h>
#include "Wire.h"
#include "tempSensor.h"
#include "mqttSetup.h"

void setup()
{
  Wire.begin();

  Serial.begin(115200);
  while (!Serial)
    ;

  shtBegin();
  checkConnection();
}

void loop()
{
  uint32_t newTime = millis();
  static uint32_t oldTime = 0;
  static uint32_t t2 = 0;

  float temp = 0.0;
  float humid = 0.0;

  char senVals[50];

  if (newTime - oldTime >= 10000)
  {
    oldTime = newTime;

    readsht(temp, humid);
    snprintf(senVals, 50, "Temp: %.2f Humid: %.2f", temp, humid);
    Serial.println(senVals);

  }
}

Code goes in functions, not the global scope.
Your line
pubClient.setServer(mqtt_server, mqttPort);

should be inside a function. Most probably setup() so it gets called when your program starts.
Incidentally - where are setup() and loop() - the two functions that are required by Arduino code?

This code chunk is contained in a separate .cpp file. I was trying to keep the main sketch clean from setup and function definitions for different components. That's why you don't see the main sketch. I intended to call only a publish function(not yet implemented in my code) in the main sketch. I will update my post with the header file and the main sketch

@Zaffresky Then you should wrap that line in a function which you can then call from setup().

I have updated my post with main sketch and the relevant header file. I don't fully understand why I should put the line  "PubClient.setServer(mqtt_server, mqttPort);"  in a new function. My understanding was that the PubClinet.serServer function is already defined in the PubSubClient library and in my separate mqttSetup.cpp file I was calling this function so that this file would be self-contained and I wouldn't need to call any PubSubClient library functions directly in the main sketch. Rather I would only call my function publishMQTT() in the main sketch. Is this approach wrong?

@Zaffresky Because code goes in functions not in the global scope.  Anything you call during the sequence of the execution of your program must go in a function. The only things that can go in the global scope are variable declarations (with or without an immediate assignment).

I see it now. I was not considering the scope in that seperate .cpp file. I mistakenly assumed that the concept of scope was applicable only to the main sketch. Thanks for clarifying


text:
What is the best way to power the ESP32 from a battery?
I am making a temperature sensor that can go in a freezer and I am trying to figure out what the best method is.
My research has taken me all over the place an I can't seem to find a straight answer. Some sites recommend using LiFePo4, while others say absolutely not, because it needs to be regulated.
One question I have is: could I use more voltage, say 6V from a series of batteries and connect it to the 5V pin since it is regulated, or is it better to go with an external regulator for the 3.3V pin with less voltage?

For battery operation always use an external switching regulator (not an LDO regulator) to 3.3V. It will double your battery life over using the 5V pin. Also: will the whole thing be in the freezer? What temperature freezer?

Which ESP32 unit are you considering? Does it have an internal voltage regulator?

@Majenko, yes it is meant to be entirely in the freezer and the temp has been a consideration as well.

@DuncanC, I am using the ESP32 Dev KitC V4.  It has an internal voltage regulator on the 5V pin, not the 3.3V, which is why I was wondering if it would be easier to use the 5V rather than messing with the 3.3V pin and needing a regulator

Before you get too carried away figuring out how you're going to power it with batteries you might see if you can even get a signal through your freezer walls at all.  If you can't, it means your running wires anyway, maybe just a thermocouple wire.  So far as I can tell, you are basically asking about putting a wireless device inside of a Faraday cage.

@timemage, signal is a concern and wiring is the backup option, but I still want to find the best way to power it.  That was how we were planning to test it.

I appreciate that you may still like an answer to the question irrespective, but I don't believe you need a battery to effectively test how well your signal will travel through the walls of your freezer.  Besides just snaking in a power cable to do that test, you will know the answer to this rather quickly, to the point where you could plug it into a laptop and place the show inside the freezer for long enough (30 seconds, if that) to know how well (or not) the signal passes.  I mention the laptop to just point out that you don't even need so much as a USB/phone charger type battery pack.

I'm betting you won't get any radio signals through the walls of a metal freezer. As time mage says, it's basically a Faraday cage. Now if you put an antenna on the inside and one on the outside, connected with a piece of coax, that would carry radio signals through.

Since it is a freezer (operating temperature unknown) I am assuming it is connected to the mains why not do the same with the electronics. This will save you a lot work and time and when you find out it will not work in a  Faraday cage as stated by timemage.  Leave the sensor wire long enough to mount the electronics outside just in case. Also consider packaging, it will be cold, possibly below the operating range of some of the components requiring you to keep them warm (above minimum temperature). I would assume your freezer like ours has moisture concerns as ice will form when opened then removed by a defrost cycle. You will also have to protect for that. Then there is the operating temperature range of the batteries, are they capable of operating at your freezer temperatures. I would suggest you redefine your problem before starting the design, this process saves me a lot of grief.

Just wanted to let everyone know that I tested the signal and we had NO issues connecting to the WiFi from inside the freezer!  Still looking for advice for a battery solution.....

I would recommended that the best type of battery for the freezer are the lithium variety. Keep in mind these are 100% disposable. So as much as I normally recommend rechargeable batteries for just about EVERY application, these are better for use in very cold sub zero temperatures.


text:
Sending a JPEG from one Arduino to another
I've got an Arducam OV2640 which takes a picture as a JPEG that I'd like to send to another Arduino using a pair of nRF24L01 wireless transceivers to eventually display it on an SSD1351 OLED.
Unfortunately, because the JPEG data is so large, it's being handled in a way I'm unfamiliar with, and I've also never really tried sending any data between Arduinos, let alone a JPEG, but I'm hoping that won't stop me.
The code I've posted below for the camera seems to be reading from a FIFO buffer that I'm assuming is on the camera module itself. Based on how it's saving it to the SD card, I know when I send it to the Arduino I have to send it in chunks and tell it how many chunks, when to start, and when to stop, but I'm having trouble finding good resources on how exactly to do that.
Currently, the code saves it to an SD card. My plan was to send the data to the second Arduino, have it save it to the SD card, and then display the JPEG from the SD card onto the OLED, but if I could skip the SD read/write that'd be preferable.
Camera code:
#include <ArduCAM.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "memorysaver.h"

#define SD_CS 10

const int SPI_CS = 7;

ArduCAM myCAM( OV2640, SPI_CS );

void setup() {
  uint8_t vid, pid;
  uint8_t temp;

  Wire.begin();
  Serial.begin(9600);
  Serial.println(F("ArduCAM Start!"));

  // set the CS as an output:
  pinMode(SPI_CS, OUTPUT);
  digitalWrite(SPI_CS, HIGH);

  // initialize SPI:
  SPI.begin();

  // Reset the CPLD
  myCAM.write_reg(0x07, 0x80);
  delay(100);
  myCAM.write_reg(0x07, 0x00);
  delay(100);

  while(1) {
    //Check if the ArduCAM SPI bus is OK
    myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
    temp = myCAM.read_reg(ARDUCHIP_TEST1);

    if (temp != 0x55) {
      Serial.println(F("SPI interface Error!"));
      delay(1000);
      continue;
    } else {
      Serial.println(F("SPI interface OK."));
      break;
    }
  }

  //Initialize SD Card
  while (!SD.begin(SD_CS)) {
    Serial.println(F("SD Card Error!"));
    delay(1000);
  }
  Serial.println(F("SD Card detected."));

  while(1) {
    //Check if the camera module type is OV2640
    myCAM.wrSensorReg8_8(0xff, 0x01);
    myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
    myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
    if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 ))) {
      Serial.println(F("Can't find OV2640 module!"));
      delay(1000);
      continue;
    } else {
      Serial.println(F("OV2640 detected."));
      break;
    }
  }
  myCAM.set_format(JPEG);
  myCAM.InitCAM();
  myCAM.OV2640_set_JPEG_size(OV2640_320x240);
  delay(1000);
}

void loop() {
  myCAMSaveToSDFile();
  delay(5000);
}

void myCAMSaveToSDFile() {
  char str[8];
  byte buf[256];
  static int i = 0;
  static int k = 0;
  uint8_t temp = 0, temp_last=0;
  uint32_t length = 0;
  bool is_header = false;
  File outFile;

  // Flush the FIFO
  myCAM.flush_fifo();

  // Clear the capture done flag
  myCAM.clear_fifo_flag();

  // Start capture
  myCAM.start_capture();
  Serial.println(F("start Capture"));
  while(!myCAM.get_bit(ARDUCHIP_TRIG , CAP_DONE_MASK));
  Serial.println(F("Capture Done."));

  length = myCAM.read_fifo_length();
  Serial.print(F("The fifo length is :"));
  Serial.println(length, DEC);
  if (length >= MAX_FIFO_SIZE) { // 384K
    Serial.println(F("Over size."));
    return;
  }
  if (length == 0 ) { // 0 kb
    Serial.println(F("Size is 0."));
    return ;
  }

  // Construct a file name
  k = k + 1;
  itoa(k, str, 10);
  strcat(str, ".jpg");

  //Open the new file
  outFile = SD.open(str, O_WRITE | O_CREAT | O_TRUNC);
  if (!outFile) {
    Serial.println(F("File open faild"));
    return;
  }
  myCAM.CS_LOW();
  myCAM.set_fifo_burst();
  while (length--) {
    temp_last = temp;
    temp =  SPI.transfer(0x00);
    //Read JPEG data from FIFO
    if ((temp == 0xD9) && (temp_last == 0xFF)) { // If find the end, break while
      buf[i++] = temp;  // save the last 0XD9

      // Write the remain bytes in the buffer
      myCAM.CS_HIGH();
      outFile.write(buf, i);

      // Close the file
      outFile.close();
      Serial.println(F("Image save OK."));
      is_header = false;
      i = 0;
    }
    if (is_header == true) {
      // Write image data to buffer if not full
      if (i < 256)
        buf[i++] = temp;
      else {
        // Write 256 bytes image data to file
        myCAM.CS_HIGH();
        outFile.write(buf, 256);
        i = 0;
        buf[i++] = temp;
        myCAM.CS_LOW();
        myCAM.set_fifo_burst();
      }
    } else if ((temp == 0xD8) & (temp_last == 0xFF)) {
      is_header = true;
      buf[i++] = temp_last;
      buf[i++] = temp;
    }
  }
}

Transmitter Code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

Receiver Code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

So I know the JPEG is too big to be saved to a variable, so I can't just Radio.write it out and I have to hijack the loop being done in the SD card saving code.
I'm just so unfamiliar with this part of Arduino, I could really use some advice on how to make it work.

I think, even if you manage to transfer the data, decoding and displaying a JPEG on an Arduino will be a non-starter.

@Majenko I can also choose to send it in Bitmap form if that matters, but I don't have a great example of that code.

I did find https://www.arduino.cc/reference/en/libraries/jpegdecoder/ and https://www.arduino.cc/reference/en/libraries/jpegdec/ that may possibly be able to handle it, I obviously haven't tested it haha.

the filetype is irrelevant to the question ... the file is simply a collection of bytes ... what those bytes represent makes no difference to the problem of transmitting them

There are a couple of discussions out there on similar issues. Answer seems to be to block up the data into 32 byte chuncks (a limitation of the NRF24L01) and stitch them together at the receiver. https://forum.arduino.cc/index.php?topic=254713.0
https://forum.arduino.cc/index.php?topic=479587.0

Do you have a sample that would display such a jpeg from SD card to your display?
If yes, it should be possible to bypass SD by a serial connection, either with direct serial wiring or via  your nRF24L01 link.

Consider the basics first: how big (in bytes) an image do you wish/need to have?  What can store (buffer) that image on each end?  A lot of the implementation should get clearer as you further constrain your needs and run into constraints.


text:
ESP8266 wakeup from deep sleep, both by timer and by button
In a project powered by batteries, the ESP8266 should go to deep sleep for a long time, having RF disabled. After some number of sleep cycles, it should restart with RF enabled, synchronize time via NTP, and again go to sleep. I think this could work with a counter saved in RTC Memory or SPIFFS.
Additionally, s.o. should be able to wake up via push button (at any time), which should result in different behaviour (running as WiFi AP, allowing for configuration of new WiFi credentials).
The question is: Is it possible to find out what did wake the ESP (timer or pushbutton)?
Using external circuitry this might be possible. To avoid this, we switch to ESP32, which is overkill for the project, but easy to find out the source of the wakeup (and with the possibility to use touch sensors). Additionally, ESP32 allows for easy use of "Preferences" in NVR and variables in RTC memory (when using the Arduino IDE), which will survive deep sleep (RTC) and even reset/power loss (NVR).

Does this answer your question? Wake up ESP8266 from deepSleep with a button

Well, not really. Resetting the ESP with a button is not the problem; in both cases /by button/by timer the ESP will be reset, running through setup() code. But how to know why it was reset? I read something about rtc_get_reset_reason() and ESP.getResetReason(); will try that and report on success.

In case of wakeup from deep sleep, rtc_get_reset_reason() always responds with "wakeup from deep sleep" - that is correct, but does not help here.

it is the same reset with button and with io 16. the software can't distinguish it. the reset with io 16 is a workaround for a bug in ROM code of the esp8266

Place a capacitor on the ESP side of the button to one power rail or the other (my preference is to ground, but either should work), and have the setup() routine read the state of the pushbutton switch as its first instruction.  You probably don't even need the capacitor, but if you don't have it, you'll have to read the switch state multiple times to account for possible contact bounce.
If the ESP wakes up due to a timer, there will be no activity on the PB line; if it wakes up due to the PB being pressed, there will be activity on the PB line for several 10s of millisecinds no matter how quickly it is pressed and released.

The only button I know to wakeup an ESP8266 is the reset button - and this one as well has to be used by the timer. Or am I mistaken?

Ah, I thought the OP was referring to an external button.  This solution still might work if the state of the reset button can be read programmatically during setup().

The capacitor solution works, but I wanted to expand on what I did in particular and why I found it beneficial. Here's my circuit:

At wakeup, the first thing I do is read D1. After that, I then set D1 to an output and set it high to keep the capacitor charged. That prevents a second button press from resetting the ESP.
Then, when going to sleep, I set the pin low for a few ms to discharge the capacitor.
I picked the smallest capacitor possible because there's no downside to charging quickly.
Note that the ESP will reset as the button is pressed down - the pin will go low, and soon after go high as the capacitor charges, all before the button is released. This is ideal in circumstances where you want the act of pushing the button to cause the wake up, not the release.

If D0 is positive and D1 is negative, your shorting the power, BAD.... That will reset the chip all right, but burn the chip up... I would simply use an "and gate" like the MC74VHC1G08... I have not tried your Idea, But connecting 2 chip outputs together is never a good idea...

it is just TTL. It is how TTL works.


text:
How to shorten this code (because my sensor reads slowly)?
I'm making a fare meter for our school project. I have too much lcd.print code. This code is not finished yet. My only concern is how to minimize the usage of lcd.print. I think it's the one that makes my sensor reading slow.
I'm new at Arduino; sorry if I have too many mistakes. I appreciate any of your answers. Thank you!
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <virtuabotixRTC.h>

virtuabotixRTC myRTC(6, 7, 8);
float d[4] = {};
int x = 0;
int f = 0;
int dis = 0;
const uint8_t disBut = 13;
int input = A0;
int state = 0;
int disF = 0;
int buttonstate = 0;
LiquidCrystal_I2C lcd(0x27, 20, 4);
LiquidCrystal_I2C lcd1(0x26, 20, 4);

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  lcd1.init();
  lcd1.backlight();
  pinMode(disBut, INPUT);
  pinMode(buttonstate, OUTPUT);
}

void loop() {
  myRTC.setDS1302Time(18, 10, 10, 7, 18, 9, 2020);

  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth);
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print("  ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  delay(500);

  d[0] = (x * 1.73);
  d[1] = (x * 1.73);
  d[2] = (x * 1.73);
  d[3] = (x * 1.73);

  lcd.setCursor(8, 0);
  lcd.print(d[0]);
  lcd.setCursor(8, 1);
  lcd.print(d[1]);
  lcd.setCursor(8, 2);
  lcd.print(d[2]);
  lcd.setCursor(8, 3);
  lcd.print(d[3]);

  lcd.setCursor(0, 0);
  lcd.print(F("P1"));
  lcd.setCursor(0, 1);
  lcd.print(F("P1"));
  lcd.setCursor(0, 2);
  lcd.print(F("P1"));
  lcd.setCursor(0, 3);
  lcd.print(F("P1"));

  lcd.setCursor(6, 0);
  lcd.print(F("D="));
  lcd.setCursor(6, 1);
  lcd.print(F("D="));
  lcd.setCursor(6, 2);
  lcd.print(F("D="));
  lcd.setCursor(6, 3);
  lcd.print(F("D="));

  lcd1.setCursor(0, 0);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 1);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 2);
  lcd1.print(F("W="));
  lcd1.setCursor(0, 3);
  lcd1.print(F("W="));

  lcd1.setCursor(6, 0);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 1);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 2);
  lcd1.print(F("dscnt="));
  lcd1.setCursor(6, 3);
  lcd1.print(F("dscnt="));

  lcd1.setCursor(15, 0);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 1);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 2);
  lcd1.print(F("F="));
  lcd1.setCursor(15, 3);
  lcd1.print(F("F="));

  int counter=digitalRead(A0);
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        lcd.setCursor(11, 0);
        x = x + 1; lcd.print(x);
        break;
      case 0:
        state = 0;
        break;
    }
  }

  if (counter == LOW)
    state = 0;
  if (state == 0) {
    switch (counter) {
      case 1:
        state = 1;
        x = x + 1;
        break;
      case 0:
        state = 0;
        break;
    }
  }

 if (counter == LOW)
   state = 0;
}

remove the Serial prints or at least use a higher baud rate

Why do you think the sensor reading is slow? Do the measurement values update to slowly? How fast do you need it? Note that if the display updates too fast, you cannot read it.

Only print to the display things that change. Put in the static text once and once only in setup, and only display the changing values when they actually change, rather than every single iteration of loop.

Your slowness is because on every single iteration of loop() you are updating the entirety of the display.  That's bad and wasteful.
You need to do two things:

Only display static information (the labels) once. Do that in setup().
Only display the variable data if it actually changes.

The first is simple: move any static text to setup(). That means things like lcd1.print(F("dscnt="));. It never changes, and the display doesn't "forget" it, so doesn't need constantly reminding.
The second is slightly harder. You need to keep two copies of the data. One that is the data at this moment, and one that is the data that is being displayed. Then you compare one with the other and for any items where they differ display them and update your saved copy.
So something like:
if (d[0] != d_saved[0]) {
    d_saved[0] = d[0];
    lcd.setCursor(8, 0);
    lcd.print(d[0]);
}

You can of course make that easier to program with a loop:
for (uint8_t i = 0; i < 4; i++) {
    if (d[i] != d_saved[i]) {
        d_saved[i] = d[i];
        lcd.setCursor(8, i);
        lcd.print(d[i]);
    }
}

Of course d_saved[4] needs creating in either the global scope or as a local static variable and initialising with some suitable "can never be" values (like -1 or something) so that the first time through it will always be different from the real values and display everything properly.


text:
How to remove Arduino Due and Mega shields without bending pins?
What's your suggested technique for reliably removing Arduino Due and Mega shields while minimizing the chance of bending the strip header pins?
For example, there's a similar discussion here where the asker ended up building a jig to keep everything parallel, but the main PCB was screwed down into the jig (a disadvantage). There is a heap of PCB Pullers/Extractors on the web, but they all seem to relate to edge connected cards.
I'm hoping for multiple answers / techniques. Interested to hear how you do it, or for you to upvote an answer you like. Maybe everybody is just doing the best they can with finger wriggling and manual pin straightening?

I use the handle of one of the toothbrushes I use to clean PCBs. Anything long, solid, and above all non-metallic, makes a good lever.

A non-conductive pair of reverse pliers might be useful, but I'm not sure they exist. https://www.expandingpliers.com/

slowly. one corner a little, second corner a little, ... and repeat

Thanks @Juraj, yes I suspect that's the most common approach and certainly what I have been doing, but I always seem to need to straighten pins afterwards.

I think I've found a nearly perfect tool in Knipex 45 10 170 reverse pliers. The only downside I can currently see is that they're conductive. The (unmodified) wooden clothes peg idea I found did not have enough grip or leverage.

To make them non-conductive (and add some protection for the boards as well), you might try a couple of plier-tip sleeves cut from plastic- or surgical rubber- tubing. Thanks for the tip on the pliers!

You could modify a couple of wooden clothes pegs to act as reverse pliers.

(source: niceshops.com)

Here's the easiest solution. Spend $10 on Amazon and buy one of these "hose pliers".  Put the tips on the double pin end. Gently squeeze. Simple!
https://www.amazon.com/dp/B07G5QSQFQ?ref_=cm_sw_r_apan_dp_Q2FM8GDW6EPGVSNA5XDZ_1

It's an indirect answer to my original question, but having made a number of Due/Mega shields over the year or so since then, I've started making the side pins ~3mm longer than the double row end pins. This helps.

@Majenko's comment suggesting using a toothbrush handle as a lever reminded me of auto trim levers. I remembered I had some, and have done some quick testing. They give a little more strength I would say, but not much (if any) more control than using fingers.


text:
ESP32: interrupt error (The following tasks did not reset the watchdog in time)
My system includes 2 ESP32 devices, communicating over ESPnow protocol. The slave device (connected to a Joystick)  is transmitting only when a changes occur, yet there can be several changes in a short time. The Master receives the transmission and executes upon. It starts running OK, but from time to time the master gets the following error and reset:
6429) task_wdt: Task watchdog got triggered. The following tasks did not reset the watchdog in time:
The master loop is empty, so to my understanding it runs endlessly (like NOP?) until an interrupt is received. However, the function registered with
esp_now_register_recv_cb(OnDataRecv);

is not very short. So perhaps this is the cause for the error.
I guess I could use a handling routing to collect the messages from the slave, but in this case it doesn't matter if a packet of data will be lost from time to time. I prefer losing old data rather than responding to it late.
Any ideas how to solve this problem? perhaps stop registration of the OnDataRecv when the master is working on the service routine? and re-register it when ready?
the relevant code:
struct_message myData;
// callback function that will be executed when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&myData, incomingData, sizeof(myData));
my_tank.tank_go_vector(myData.x_val,myData.y_val,myData.button_state,range);
} // of OnDataRecv()
The registration within setup:
esp_now_register_recv_cb(OnDataRecv);

The routine that executes:
void tank_go_vector(int _x, int _y,int _button,int _range) {

    Serial.print("  >> in tank_go_vector: x/y/button/range ");
    Serial.print(_x);
    Serial.print("..  ");
    Serial.print(_y);
    Serial.print("..  ");
    Serial.print(_button);
    Serial.print("..  ");
    Serial.print(_range);
    Serial.print("..  ");

    // go by vector recieved from joystick;

    int x_speed = abs(_x);
    int y_speed = abs(_y);

    x_speed = map(x_speed,0,_range,0,SERVO_RANGE); // 255 for 8 bits
    y_speed = map(y_speed,0,_range,0,SERVO_RANGE);

    Serial.print("   x_speed / y_speed: x/y ");
    Serial.print(x_speed);
    Serial.print("..");
    Serial.print(y_speed);

    if (_x==0 && _y==0) {
      Serial.println("  stop");
      left_motor.stop();
      right_motor.stop();
      return;
    }

    if (_x==0 && _y>0) {
      Serial.println("  forward");
      Tank_forward(y_speed);
      return;
    }

    if (_x==0 && _y<0) {
      Serial.println("  backward");
      Tank_backward(y_speed);
      return;
    }

    if (_x>0 && _y==0) {
      Serial.println("  Right Pivot");
      Tank_right_pivot(x_speed);
      return;
    }

    if (_x<0 && _y==0) {
      Serial.println("  Left Pivot");
      Tank_left_pivot(x_speed);
      return;
    }

  // now deal with vector moves TBD

  } // of tank_go_vector

Or maybe just kick the dog during long looping operations. Without your code it's impossible for us to help you.

@Majenko I added the code.

I did some trials and found out that if the number of transmissions is reduced, the system is working well. Since it is OK to lose some packages, as long as the master is handling the latest package, How can I program the ESP32 master to stop receiving ESPnow messages while handling the current message? and enable it afterwards?


text:
Play audio on an ESP32 or an Arduino
I am in the process of making a talking robot and I have linked my ESP32 to a Google text-to-speech service. The service returns me a base64 8-bit audio response.
I need to play this audio and I can't figure out how to do it. I know that an audio playing library exist for PCM but the data that it requires is not base64.

Base64 is just an encoding to encapsulate 8 bit data into ASCII text. It has nothing to do with audio. Decode it first into your binary data then use a suitable library for your hardware to play it.

On the esp, there is also an offline version of text to speech. Just if you want to try it...

I don't know weather this will help you there is a guy who makes cool stuff in GitHub text to speech in esp8266 hope it will work in esp32 too https://github.com/earlephilhower/ESP8266SAM

Base64 has nothing to do with audio. It is merely a way of encapsulating binary data into ASCII text so that it can safely be included in text-based structures like JSON, or transmitted over a text-based communication channel.
There is no library to "play" base64 simply because base64 is not something you play.
First you decode the base64 text into raw 8-bit binary. It's then that data that you play through whatever library is most suitable for your hardware.
For example on the ESP32 you have the function base64_decode() available. You can read up on how to use it in this tutorial.


text:
Need help with millis () function for two linear actuators
Last week I was grateful to receive help programming the Arduino to control two linear actuators.
I need help re-writing the code using the millis () function. I am more than happy to reimburse for time spent on this project. This is my first experience with Arduino and millis () is too involved for me.
The actuators control a set of barn doors in my house. The actuators are programmed to open and close with the push of a button (z-wave relay programmed as 6 second momentary switch). The actuators do not give feedback, so the program is used to control the speed from 0-255 using the PWM ports to make the actuators appear somewhat in sync. They move at three different speeds so that they don't slam when opening and closing. This is where millis () comes in. Right now I am using a delay to control the speed for various amounts of time, but using a delay creates a safety issue since the Arduino cannot do anything during this time.
The reason I need to utilize the millis () function is that I need to be able to make the doors stop and reverse in the event that there is something blocking their path. To accomplish this I will be using a garage door electric eye wired through a homemade circuit board. The output will go low any time the beam is broken and otherwise it will remain high. I'd like the Arduino program to utilize this signal any time the doors are closing and if the beam is broken - make the actuators reverse direction. I realize that without feedback I cannot make the doors open all the way depending on when the beam is broken. I am really not too concerned about that. As long as they stop and reverse for at least a little bit I will be happy. I don't want to crush my kids or pets.
Again, I am more than happy to reimburse anyone willing to help write the code for this. Here is the code I am using now which utilizes the delay function. I'd like this code to be changed to utilize the millis function and also add in programming for the sensor as described above.
/* Program enables momentary direction control of actuator using push button
 */

int RPWM = 10; //connect Arduino pin 10 to IBT-2 pin RPWM
int LPWM = 11; //connect Arduino pin 11 to IBT-2 pin LPWM
int RPWM2 = 5; //connect Arduino pin 5 to IBT-2 pin RPWM
int LPWM2 = 6; //connect Arduino pin 6 to IBT-2 pin LPWM
int downPin = 12;
int upPin = 13;
int speed1 = 0; // Top speed you can change it between [0-255]
int speed2 = 0; // Low speed you can change it between [0-255]
int speed3 = 0; // Low speed you can change it between [0-255]

void setup() {
  pinMode(RPWM, OUTPUT);
  pinMode(LPWM, OUTPUT);
  pinMode(RPWM2, OUTPUT);
  pinMode(LPWM2, OUTPUT);
  pinMode(downPin, INPUT_PULLUP);
  pinMode(upPin, INPUT_PULLUP);
}

void loop() {
  if(digitalRead(upPin)==LOW){ //check if extension button is pressed
    analogWrite(RPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM, 255); // rotate motor with top speed
    analogWrite(LPWM2, 245); // rotate motor with top speed
    delay(3000);               // wait for x sec
    analogWrite(LPWM, 180); // rotate motor with low speed
    analogWrite(LPWM2, 176); // rotate motor with low speed
    delay(1500);               // wait for x sec
    analogWrite(LPWM, 80); // rotate motor with low speed
    analogWrite(LPWM2, 80); // rotate motor with low speed
    delay(1500);               // wait for x sec
    analogWrite(LPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(LPWM2, 0);     // uncomment if you want to stop motor now
  }

  else if(digitalRead(downPin)==LOW){ //check if retraction button is pressed
    analogWrite(LPWM, 0);
    analogWrite(LPWM2, 0);
    analogWrite(RPWM, 250); // rotate motor with top speed
    analogWrite(RPWM2, 255); // rotate motor with top speed
    delay(3000);               // wait for x sec
    analogWrite(RPWM, 165); // rotate motor with low speed
    analogWrite(RPWM2, 165); // rotate motor with low speed
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 80); // rotate motor with low speed
    analogWrite(RPWM2, 80); // rotate motor with low speed
    delay(1500);               // wait for x sec
    analogWrite(RPWM, 0);     // uncomment if you want to stop motor now
    analogWrite(RPWM2, 0);     // uncomment if you want to stop motor now
  }

  else{ //if no button is pushed, remain stationary
    analogWrite(RPWM, 0);
    analogWrite(LPWM, 0);
    analogWrite(RPWM2, 0);
    analogWrite(LPWM2, 0);
  }
}

You should not rely on Arduino code at all, millis or otherwise, for your safety features.  More broadly you should not rely on software at all when it comes to not crushing your kids or pets.

Definitely open to other suggestions.... The actuators are only rated 20lbs. I’ve let the doors close on me and it is not bad at all... but, still would prefer the doors not close on things.

I'm not sure I'm all that comfortable advising you on this.  But, if your actuators are responsible for different directions, it seems at a minimum the door closing on something should mechanically interrupt the power going to the actuator that closes the door and it should probably latch into this interrupted position such that it manual intervention is required to make it operate again.

Each actuator has adjustable overcurrent protection. It works ok to cut power to the actuators if the doors bump into something, but I’m hoping to actually have the doors reverse before bumping into anything. After-all don’t our garage doors rely on software for the same type of safety function?

Also note - My backup plan if I can’t get this working with the Arduino is to connect the electric eye to a couple of relays that would reverse polarity to the actuators in the event the beam is blocked - causing the doors to reverse direction. This would be one method that avoids using software. Could also cause the doors to close on something if the beam is blocked while the doors are opening... so not ideal!

You've come to the requirement called non-blocking programming. The gist of it is that your loop() function does little other than call a number of "maybe-do" functions - my name for functions that assess the need to act, and act or not, and return, as quickly as possible. So in pseudo-code, your loop might look something like:
void loop(){
   maybeStartMotor1();
   maybeSlowMotor1();
   maybeStartMotor2();
   maybeSlowMotor2();
   maybeStopMotor1();
   maybeStopMotor2();
   // Call maybe-do()s for ... whatever else might need to happen
}

Your maybe functions would probably look like, e.g.:
maybeSlowMotor1(){
if( millis() - millis_at_motor1_start > DECELTIME2 )
set motor1 to slow speed;
else if( millis() - millis_at_motor1_start > DECELTIME1 )
set motor1 to medium speed;
return;
}
Note that my understanding of your mechanical system is limited and the above is meant to describe a software technique, not a solution.
Also note my complete agreement with @timemage's caution against depending on software for your safety interlocks. Your 3rd comment under your question - to directly reverse the doors with photocells and relays - in addition to the software detection and control - provides a necessary redundancy.
I'd also like to refer you to this somewhat more complete description I wrote to answer another, similar, question.

Thank you for your answer. I am just a total noob to Arduino and this is outside my wheelhouse. Perhaps the simplest solution for me would be to use the electric eye to simply cut power to the actuators in the event the beam is blocked. Reversing direction would be nice, but to have it function properly would require software/programming.

Use the electric eye / stop actuators first. Then you can work on the software, a little at a time, and not have to do the "would be nice" parts of it up front. With the worst-case covered, you can experiment with the software a little at a time without being able to leave any glaring safety issues.

That’s what I’ll do. I’d still be more than happy to pay someone to do the programming for me if there are any takers! If I just had something to work with I bet I could get it functioning properly.

@ChrisGroat, get in touch w/me through my profile.


text:
Problem with sending IR with at ATMega328P-PU
I have a sketch that sends an IR code every second. It works fine (the correct code is received by my receiving Arduino next to it) on the Arduino but when I try to move the sketch to an ATMega328P-PU, the IR no longer sends (the serial monitor output still works).
I have used a camera to look at the IR LED and it just doesn't flash on the ATMega328 but does on the Arduino (and I have tested my LED, it does work). It uses pin 3 on the Arduino, so I use pin 5 on the ATMega328.
Are there extra components that are needed to make PWM work without the Arduino board? I am honestly stumped so any help would be appreciated. Thanks in advance.
Sketch:
#include <IRremote.h>

IRsend irsend; //Setup the IR transmitter

int codeToSend;
int team = 1;
int damage = 0;

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

void loop()
{
    team++;
    if (team > 8) team = 1;
    damage++;
    if (damage > 99) damage = 0;

    if (damage > 9) codeToSend = (String(team) + String(damage)).toInt();
    else codeToSend = (String(team) + "0" + String(damage)).toInt();

    Serial.println("sent");
    irsend.sendNEC(codeToSend, 32);
    delay(500);
}

If I take your question literally, "no".  However, I'm guessing you actually want to know why this isn't working on a breadboard.  For that, it would be helpful to have in-focus picture(s) of your board's actual wiring, in one frame if that's possible.

I added a photo, sorry the wiring is messy, I only have small breadboards. Far left is ground, front left is 5v. You can't see but the capacitor connects the ground and 5v rows and the resistor connects pin 1 to 5v (10Kohms).

NOTE: The following comment was left on this answer (below) and indicates the principal problem the original poster was having above and beyond not having a resistor, etc.

SOLVED - my breadboard was broken on that rail. :/

Current limiting
What you have pictured looks alright for the most part with the exception of there appearing to be no current limiting resistor for the IRED.  It is possible that you've damaged the IRED by setting the pin HIGH for an extended period of time.  It is also technically possible to have damaged the AVR (or just the one pin) by doing that, though this wouldn't be my first guess.
Typical forward voltages for an IRED around around a volt.  An AVR pin's maximum rating current is 40mA.  To get proper logical levels out of it, it should be less than 20mA.  You could perhaps operate near 30mA, since you're not doing much else with the AVR's ports and you're not trying to get logic level voltages out of the pin.  For that you'd need a resistor in series with the IRED that is something like  (5V - 1V) / 0.030A, approximately 133 ohms.

Transistors
When people use IRED to make remotes, it is normal to use a transistor to offload the current requirement from the MCU.  And also to operate the IRED above its continuous operation current, closer to it's rated peak/pulse current.  Operating in the low tens of mA often only gets you a meter or so.
That arrangement might look something like the following for higher current pulses around 80mA:

Asides

I'm not able to read your reset resistor well.  If you're not, do measure it to make sure it's 10K.  If in doubt, remove it.  There is a weaker internal pullup on the AVR reset and it's usually enough.  If you wanted you could wire the reset signal over to the UNO reset pin to take advantage of the external pullup, reset switch, and DTR reset mechanism of the UNO itself.

You may want to add .1uF capacitors from your VCC and AVCC pins to ground.  You can often go without while experimenting, but when you're switching higher currents they'll become more important.

I have a bunch of those jumpers with the rounded (cylindrical) ends.  They often don't make good connections on breadboard.  You can save some trouble sometimes with "Dupont" type jumpers or just making your own out of solid 22awg hookup wire.

When I put the IRLED into my other Arduino with the same circuit and sketch set up, the IRLED works, so I don't think it's damaged. I have added a 133ohm resistor (100+33) as you said and tried again with a different 328p-pu but still no luck. The resistor on my reset is definitely 10kohm as I tested it with a multimeter

I'll look over the image some more, but I don't know what expect to find.  The fact that it's still operating over serial rules out a lot of ideas.  With respect to the current limiting, that's good to hear, because you should have that no matter what else is going on.

It would appear that digital pin 3 (pin 5 of 328) doesn't work at all without the board. I uploaded a simple led blink sketch to the MCU and that worked fine using pin 2 (pin 4 of 328), but not 3 (pin 5 of the 328). This would suggest that pin 5 of the 328 doesn't work at all, but it must do as the sketch works with the chip in the Arduino board using pin 3. This goes to both my 328 chips and boards. Any ideas?

On an official UNO PD3 doesn't go anywhere except the header.  I expect no difference on any normal clone.  It's my suspicion that if you put it back into the board it will continue to fail to work there.  If not that, then perhaps one of those jumpers is not making very good contact.

"On an official UNO PD3 doesn't go anywhere except the header." - I think you mean the pin on the Arduino doesn't go anywhere except for pin 5 on the 328?

SOLVED - my breadboard was broken on that rail. :/  Thank you so much for your time and help.

PD3 is the signal on DIP pin package no. 5, or Arduino digital pin no. 3.  So what I mean is that signal goes straight from the AVR to the header.  It is not connected to anything else on the board.