text:
How to power Arduino Uno from L298N motor driver's 5v terminal?
I am trying to setup L298N motor driver controller with my Arduino. Different online schematics about how to connect them are mostly similar - but they differ in powering the Arduino from the drive controller's 5v pin.
I am connecting 7.5v to the Vin and Gnd to the motor driver controller screw terminal , and I wish the power the Arduino from the 5v screw terminal. Since I am planning to use the 5v screw terminal as output I am choosing to leave the 5v jumper on.
Here are 3 of the schematics I've found online,

Source Homemade-circuits:

This is what I was expecting to see. But from Arduino Uno Rev3 Faq,
Vin -- The input voltage to the Arduino board when it's using an external power source (as opposed to 5
volts from the USB connection or other regulated power source). You can supply voltage through this pin,
or, if supplying voltage via the power jack, access it through this pin.

5V -- This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power
either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).
Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

This one looks wrong to me. I am under the assumption that Vin pin is expecting 7-12V because it's connected to voltage regulator which will cause a 2v drop. Which mean I should not connect 5v from the motor controller to Vin - making this schematic incorrect. Is my analysis correct? Here is an answer that says I can not use the 5v pin to power an Arduino since it an input pin and not an output pin.

Source teachmemicro:

This one looks ok to me since the 5v source at motor controller is a regulated source and that's what exactly Arduino is expecting on 5v pin based on aforementioned FAQ. Can I implement is safely?

Source Instructables:

I do not know if it's correct or not. Notice that the 5v screw terminal is not connected to Arduino in any way. Is it setup going to work? I am wondering where the Arduino is getting its power from?
I am wondering which schematic should I follow. I am hesitant to hook up my L298N motor driver and Arduino without without understanding why each schematic is choosing to power the Arduino differently.

Clearly, your design (last image) won't work, because as you expected, the Arduino won't have power. It is a feasible design however, if you use it while still developing and you have the USB cable connected. Because then the Arduino will draw the power for itself from there.
Vin expects 7-12V, but allows an unregulated input (which is fine for connecting a battery). You can use the 5V pin to supply power from a regulated output as well. Since (pressumably) the output of the motor driver is regulated, that could work, however I would not advise it and directly connect the battery to the VIn pin.
Connecting the 5V output of the motor driver to the VIn pin might work. While this will likely not destroy anything, it may be to low to drive the internal regulator, which might cause the Arduino to run on undervoltage levels. You might see weird behavior in that case (pins not correctly recognizing high from low, incorrect measurements on analog inputs or even software crashes).

If I understood it correctly, you are suggesting a 4th options which is connecting the motor drive controller and Arduino(using Vin and Gnd) in parallel to the 7.5v battery?

Yes, I would directly connect the Arduino to the battery.

Thanks! Also why you advise against connecting 5v regulated motor controller pin to Arduino 5v pin?

I should have said that it would be my second choice. The quality of the power output of the motor controler may vary, while the one on the Arduino is known to be built for it. Also, a motor controller is subject (from the motors) to severe interferences, which I would try to avoid by reducing the connections to it to the required minimum.

What are the things I should watch out for when connecting Arduino and other loads in parallel with the power source? Do I need to make sure that the resistance of the load is strictly greater than Arduino to ensure most current do not go through the load?

You do not normally have to worry about that, since the loads that require external power (such as a motor driver) are designed already to have a very high resistance input and drive the output trough a series of transistors. If you were to build your own motor driver, you would need to ensure this yourself, though.

If you connect 5V from the motor board to the 5V pin on the Arduino, the varying loads on the motor controller's 5V line could cause the 5V input to the Arudino to bobble around (Even a regulated output fluctuates some under varying loads). That is an argument against that approach. You might want to add a filter capacitor between 5V and ground and close to the Arduino if you use that approach. It will even out the noise on the 5V line caused by changing loads.

I was facing same problem but I solved it by attaching L298 power pins to icsp power pins

Remember the voltage should be constant and there should not be any fluctuation other wise atmega will go in programming mode

I happened to just set up a similar circuit yesterday on a RC car. L298 is powered through a 3S lipo batterie, Uno is powered through the 5v output which also powers a servo. Uno powers a rc receiver. I burnt an Uno trying to power both servo and receiver.

Please note the picture is the very first version when servo was powered from receiver and receiver from uno. Not a good option, sketchy servo behavior


text:
Is it possible to generate an exact 15 kHz clock pulse using an Arduino?
I want to generate a 15 kHz pulse with an Arduino using Timer1, but the problem is that if we want a 15000 Hz clock we need to initialize the timer with 1/15000 seconds or 66.66 microseconds, but we can only pass integers without any decimal precision in the Timer1.initialize(66); function which generates a frequency of 15155 Hz.
So is it possible by any other means to generate an exact 15000 Hz or frequencies between 15000 Hz - 15155 Hz?
#include <TimerOne.h>

void setup() {
  pinMode(9,OUTPUT);
  Timer1.initialize(66);  // Frequency, 100 µs = 10 kHz
  Timer1.pwm(9,255);
}

void loop() {}

No you can't, at least not with a standard Arduino Uno and no other components. Trouble is, an Arduino Uno runs at 16MHz, which is not evenly divisible by 15,000Hz. You can only ever get an approximation using internal timers (which are all based on the main clock or some fraction of it).

any external component which can solve my problem? or any other microcontroller in which I can at least initialize my timer at 66.6 microseconds

Using a PIC32MX1xx or 2xx series running at 40MHz it's possible to generate 14999.992675785Hz using the reference clock output - that is, the system clock divided by (2*(1333+(171/512))).

If you can change xtal to 12MHz (bootloader for that xtal too), than it's easy :D

The LTC6903 can generate 14998.217Hz - is that close enough for you?

@StarCat while technically correct, it's kind of misleading, as I double OP will care if it's only a very tiny bit of. Dividing 16Mhz by 1067 would give you 14995Hz. Which is only 0.03% off. The 16Mhz crystal on the UNO probably has a higher error than that.

@Gerben, I realized that the OP was interested in a close(r) approximation after I'd already typed my comment. It was not meant to be misleading.

There is no such thing as "exact", only "to within tolerance", which you haven't really specified (unless you mean 15077.5±77.5).

No. Read the specification for the part you're using.  There is no such thing as an EXACT clock.  Even high-end microprocessors using PLLs have clock and phase jitter.

In practice, different oscillators will have different errors, and pretty much all oscillators are affected by the temperature, so you will obviously never get perfect, atomic-clock-grade 15kHz, even if you have a 15MHz oscillator. But after taking that into account, it boils down to the compromise: do you want 15000 ticks per second on average, or do you need the pulses to be equally spaced? With a 16MHz oscillator, you can have relatively fine adjustments of the interval in order to keep the average frequency close to 15kHz.

@chrylis-cautiouslyoptimistic-: I believe what is meant is "as exact as the source clock"

You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:
F_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles
If you round this to the nearest integer, you get
F_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz
This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.
Here is my attempt at this. I have tested it.
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}

What is the accuracy of the ceramic resonator? 0.5%?

@PeterMortensen: Typical tolerance is 0.5%. The tolerance is the worst-case frequency error. Typical error is more like 0.1%.

@PeterMortensen: If you calibrate the frequency error, you can adjust PERIOD to compensate for it. You then have about 0.1% resolution in the calibrated frequency.

Since the timer1 library only accepts whole numbers for the µs parameter you get a error. You could skip using the library and configure the timer directly. Or you could have a look at the source code of the library, and see that you can kind of bypass the limitation it has by only calculating a more accurate value for the ICR1 register.
Look at cycles = ((F_CPU/100000 * microseconds) / 20);. If you were to insert your 66.66666µs into this, instead of 66µs, you'd get 533 instead of 528.
This value is then used to set the PWM frequency in line 213. So you'd need to overwrite the ICR1 register with the more accurate value.
Your final code should look like:
pinMode(9,OUTPUT);
Timer1.initialize(66);
ICR1 = 533;
Timer1.pwm(9,255);

PS you might need to tweak this 533 value to get an even more accurate resulting frequency.

Can you please describe the role of ICR1 register here? I need to know how is it working with timer1.

Timer one keeps incrementing it counter (TCNT1) till it reaches ICR1. By increasing ICR1 by 5 is will take a bit longer to count to that, and thus give you a slightly lower frequency, than the 15155Hz you were getting. Hope that explains it a bit better. If not, feel free to let me know.

A better way to do the above average 15 kHz (or any other frequency) is with a phase accumulator scheme.  There are no IF tests; on each tick of an interrupt, you add a step to an accumulator and output the state of its MSB.  This can give incredible resolution, and is probably the best you can do.  But though the average frequency will be dead-on, the jitter can be terrible.  I use this method in my open-source DaqPort sketch
https://www.daqarta.com/dw_rraa.htm#00ff, which is used by DaquinOscope
https://www.daqarta.com/dw_rroo.htm and Arduino_Oscillators https://www.daqarta.com/dw_rrss.htm mini-apps running in Daqarta.  There's also a Jitter_Tbl macro to compute the jitter for arbitrary sample rates and output frequencies.  Although not relevant here, this phase accumulator method can also go to exceptionally low frequencies, into the micro-hertz range, and the jitter is extremely small there.

I can get within 5 Hz of 15,000 using a 16 MHz clock on a Nano, Uno or 2560. Here is the code...
// RTM_TimerCalc 1.20
// Timer-1 Mode_14_16Bit_Fast_TOP_is_ICR

TCCR1B = 0x18; // 0001 1000, Disable Timer Clock
TCCR1A = 0xA2; // 1010 0010

ICR1 = 1067-1;
OCR1A = (int) (ICR1 * 0.25);
OCR1B = (int) (ICR1 * 0.50);
TCNT1=0x0;

// UnComment following lines for UNO-NANO Timer-1 Pins
// pinMode(9, OUTPUT);  // OC1a
// pinMode(10, OUTPUT); // OC1b

// UnComment following lines for 2560 Timer-1 Pins
// pinMode(11, OUTPUT);  // OC1a
// pinMode(12, OUTPUT);  // OC1b

TCCR1B |= 1; // Prescale=1, Enable Timer Clock

Here is the Error Results...
ASK:        15,000 Hz
CALC:       14,995.3139643861 Hz
OFFSET:     -4.6860356139 Hz
hth

In answer to a comment from the OP asking for another microcontroller that can do this, and in addition to Majenko's reply comment:
A SAMD21G running at 48 MHz (as seen on some Arduinos) can make 15 kHz, in several ways.
Note that this assumes that the clock is exactly 48 MHz, and stable, and both assumptions could well be wrong, unfortunately. It helps if the clock is derived from a crystal; not all SAMD21G-based Arduinos do that, if any. This possible lack of clock precision and stability applies to all MCUs.
The SAMD21G does have a fractional PLL, and you can of course adjust the PER register, so some fine-tuning is possible if you have the equipment to measure the actual output frequency.
If you decide to go with one of the SAMD21G-based Arduinos: there is a PWM library for those (I know it well, as I wrote it) that will let you set a clock divider, a prescaler, and a resolution, which should make it easy enough to arrive at a (nominal) 15 kHz. There's a frequency table under "extras".

"It helps if the clock is derived from a crystal" are you saying that not all Arduino have crystal closk?

Yes, I am; there are also some that use a ceramic resonator, and some use the MCU's internal RC oscillator.

@JhonnyS: The Arduino Uno (and its many clones) uses a 0.5% ceramic resonator (there is a crystal on the PCB, but it is only used for the USB part). The official pages about Arduino Uno are quite misleading (by omission, wilful or not). They don't technically lie, but it is close. See Does the Arduino Uno have two crystals?. From the question: " the "big silvery" thing on the board (red) is the famous 16 MHz crystal of the Arduino. That's what I've believed until very recently."

@PeterMortensen thanks for the reference! It makes so much sense now! So three are two clock sources in Arduino! Was just wondering if these are synchronous in nature.

Yes, you can. Sort of...
A 66.6 µs delay means one delay of 66 µs and then two delays of 67 µs.
You could keep a close loop that calculates the micros() divided by 66 and modulo by 2 for every iteration. This will give you an alternating 1 and 0. Save the previous value to check this value for a change and digitalWrite HIGH or LOW.
I have no means at the moment to test the code, but in (semi-pseudo) code this would look something like:
void loop()
{
  int freq=15000;
  float interval = ((float)1000000/(float)freq)/2;//33.333333
  byte state=0;
  byte previousState=0;
  while (1)
  {
    unsigned long currentMicros=micros();
    previousState=state;
    state = (unsigned long)((float)currentMicros / interval) % 2;
    if (state==1 && previousState==0) digitalWrite(9,HIGH);
    if (state==0 && previousState==1) digitalWrite(9,LOW);
  }
}

This method will guarantee that after one second exactly 15000 periods have passed. The timing of the individual periods, however, might vary a little.

Note that this will provide a output that AVERAGES very close to 15KHz but will alternate between 1 cycle of 15.15 kHz and 2 cycles of 14.92 kHz.  That may or may not be acceptable depending on the use-case.

I guess that listening to the tone produced by this method will sound horrible.

I fixed the obvious errors (missing parentheses after micros, missing factor 2 in interval, state variable shadowing a previous declaration) and tested it on an Uno. Not only is the jitter huge, but the average frequency is wrong: about 8.5 kHz. The floating point calculations make the code so slow that it misses pulses.

I'd guess the frequency would be 7.5 kHz, but your factor 2 should have fixed that. I guess that the digitalWrite() take several clock cycles to execute. Too bad, because in theory this could have worked.

digitalWrite() is not that bad, the problem is the use of floats. I programmed something similar to your logic (timing with micros() and digitalWrite()) with integer-only arithmetics. The output does have some jitter visible on the scope, but is far from being as bad as this float-based version. And, as it does not miss pulses, it has an average frequency of 15 kHz.

@EdgarBonet this is awesome explanation so in micro-controllers we should avoid floating-point calculations if possible right? also what causes jitter in your case, despite using integer-only arithmetic?

@JhonnyS: Re “avoid floating point”: if you need to be fast, yes. If you have lots of time, or a microcontroller with an FPU, then floating point is fine. Re “what causes jitter in your case”: I guess it is mostly the resolution of micros(), which is 4 µs.

Re "I have no means at the moment to test the code": Can you update your answer when you have?

Edgar Bonet has fixed the typos and updated my code. See the second comment for his concerns.

source: Stack Exchange

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

sort: votes


text:
Hall Sensor (Fluid Flow) "Noise"
Kind of a fringe question here, but could not find anything concrete so figured I would throw it to this great community.
I have 2 DS80 flow meters (Hall Effect Sensor type flow meters - nothing special about them except they are bigger for 3" pipes), and they work fine, wired, code, etc and get decent readings and all that so no issues there.
During my bench prototyping, I noticed that sometimes, in spite of no "flow", I would detect "pulses" from the sensor. Because they are sitting on a workbench, with no pipes connected, I assume this is either:

Random transient voltage, maybe bleed from its neighbors in the wiring or what not
Maybe the magnet on one fin is parked at the sensor and vibration is causing it to bounce

The second one is what it is, but the first one feels like something I could iron out. The question is, should I have a cap/resistor/something on the data line from the sensor to smooth out readings? Because it is PWM I do not know what to put there that wouldn't interfere with the signal itself (if anything). Absolutely NOT critical, as I said it works fine under load and I do not need hyper-accurate readings. More of a "could I do this better" question.

this is not a question about an arduino

I can't find any clear results when trying to search for those meters. Could you provide a link, and a more specific part nr. and/or manufacturer name?

Is there any electrical equipment nearby? Flowing electricity can create magnetic fields that could interfere with the hall effect sensor.

@Gerben - Other than the other sensor nothing else nearby, although good to check that too. As for the part number, it came from Ali Express and I have never been able to find it anywhere but there. The "data sheet" as it is is pretty terrible and contradictory and it is possible it is just slightly flaky.
jsotola - you are correct! I am using arduinio for the MCU and since there is not a "sensors" Stack Exchange, I posted here. I will happily edit the question to say that it is taking readings from an Arduino if it will make you feel better about it being here?

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


text:
Time signal. Determine the presence of pulses and their duration
I want to detect the exact time signal from an FM radio station. The signal is transmitted in the form of 5 short pulses and one long one. My task is to determine the presence of a pulse in the audio data stream and its duration.
It is understood that the signal is received by the radio receiver and then the audio signal is fed to the atmega microcontroller.
The pulse duration varies in the range of 100 ... 560 ms
How can you control the appearance of these pulses using a microcontroller, and also determine their duration? Below is an example of computer processing. The same is required to be implemented on a microcontroller.

I have a reference recorded signal in WAV format.
This recorded signal from the output of the radio receiver contains both the speaker's speech, music, and the exact time signal:

I know the time signal is centered at 1 kHz, so
apply filtering to this signal. The filter has the following frequency response:

The signal after the filter looks like:

It remains to apply the threshold device and duration selection.
However, I do all this in an audio editor to understand the ongoing processes. In fact, I need to implement this on an arduino, so I really hope for your tips, because I don't know how to implement a filter on an arduino for one frequency, and I also don't know how to make a pulse detector and a meter for its parameters.

Below is the result of homodyne, the method suggested in the comments. On the test signal, the algorithm was able to identify the required pulses! It remains to write a sketch where there is a detection threshold and definition of the duration!
I was able to write a condition, when the threshold is exceeded, the LED turns on, and turns off otherwise. But I don't know how to make the definition of duration yet ...
Added after a few days:
I was able to assemble the entire structure, the sketch below does the following:

Listens to the audio signal coming to the analog input of the arduino from the radio receiver on the RDA5807M microcircuit, through an amplifier on one transistor, which provides signal amplification and offset to the positive range.

Performs homodyne processing: selects only the signal with a frequency of 1 kHz, all other frequencies are suppressed

Selects the optimal detection threshold for finding the exact time signal of 1 kHz frequency at the background level.

Calculates the duration of each pulse

Finds the exact time by the last impulse using the recalculation formula.

Thus, at the moment I get the exact time digit in the serial port monitor.
But the end result I want to get is setting the resulting digit on a seven-segment display. Having looked at the sketches of his work, I found that the values in the loop are constantly processed there, which again slows down the microcontroller, but for me this is unacceptable. As I understand it, you need to write a separate function into which you pass the value of the hour and set this value on the indicator only once an hour. But I don’t know how to implement it. I ask for help!
/ * Last edited on January 25, 2021.
   1 kHz homodyne signal detection

  This program continuously samples analog input A0 and uses a homodyne
  detection circuitry for signal identification at 1 kHz (+/- 24 Hz at -3 dB).

  The A / D converter is set to "free running mode" and takes one sample every 104 µs.
  The samples are multiplied by two generated 1 kHz signals ("local oscillator") in quadrature to each other.
  The products are then low-pass filtered with a time constant of 64 sampling periods (6.656 ms),
  which gives (I, Q) signals with a bandwidth of 24 Hz.
  Finally, the signal strength is calculated as I ^ 2 + Q ^ 2.

  The program is designed for Arduino Uno and will probably work on any AVR based Arduino,
  having an ADC and operating at a frequency of 16 MHz.

  For a detailed explanation, see
  http://arduino.stackexchange.com/a/21175

  Posted by: 2016 Edgar Bonet Orozco.
* /

// Here is everything related to the parameters of the RDA5807M receiver:
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
#define RDA5807M_REG_RSSI 0x0B
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word (0x0001)
#define RDA5807M_FLG_TUNE word (0x0010)
// masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word (0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

uint8_t volume = 7; // 0..15
uint16_t freq = 938; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;
// Receiver end

unsigned long startTime; // Turn on two timers, this
unsigned long elapsedTime; // and this one
int threshold = 300; // Set the maximum noise level
boolean timing = false; // I do not know...

#include <util / atomic.h>

// The analog input used must be between A0 and A5.
const uint8_t analog_in = 0;

// The frequency we want to define, in Hz.
const float SIGNAL_FREQ = 1000.0;

// Time bits.
const float SAMPLING_FREQ = F_CPU / (128 * 13.0); // 9.615 kHz
const long PHASE_INC = round (SIGNAL_FREQ / SAMPLING_FREQ * (1L << 16));
const int LOG_TAU = 6; // tau = 64 / SAMPLING_FREQ = 6.656 ms

// Set the ADC to constant conversion mode "free running mode"
static void configure_adc ()
{
  ADMUX = _BV (REFS0) // ref = AVCC
           | _BV (ADLAR) // left adjust result
           | analog_in; // input channel
  ADCSRB = 0; // free running mode
  ADCSRA = _BV (ADEN) // enable
           | _BV (ADSC) // start conversion
           | _BV (ADATE) // auto trigger enable
           | _BV (ADIF) // clear interrupt flag
           | _BV (ADIE) // interrupt enable
           | 7; // prescaler = 128
}

// Demodulated (I, Q) amplitudes.
volatile int16_t signal_I, signal_Q;

// Interrupt handler is called every time the ADC is ready to read.
ISR (ADC_vect)
{
  // Read the ADC and convert to a signed number.
  int8_t sample = ADCH - 128;

  // Update the phase of the local oscillator.
  static uint16_t phase;
  phase + = PHASE_INC;

  // Multiply samples by square waves in quadrature.
  int8_t x = sample;
  if (((phase >> 8) + 0x00) & 0x80) x = -1 - x;
  int8_t y = sample;
  if (((phase >> 8) + 0x40) & 0x80) y = -1 - y;

  // First order low pass filter.
  signal_I + = x - (signal_I >> LOG_TAU);
  signal_Q + = y - (signal_Q >> LOG_TAU);
}

/ * Return the power reading. * /
static uint16_t get_power_reading ()
{
  int16_t I, Q;
  ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
    I = signal_I;
    Q = signal_Q;
  }
  return sq ((int8_t) (I >> LOG_TAU)) + sq ((int8_t) (Q >> LOG_TAU));
}

// *********************************************** ***********************
void setup ()
{
  configure_adc ();
  Serial.begin (9600);

  // Receiver start:
  Serial.begin (9600);
  Wire.begin ();
  // Register 02h - enable, settings
  reg02h = RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // And then we decided to further strengthen the bass: (I don't need this, I need to somehow remove it)
  reg02h | = RDA5807M_FLG_BASS;
  setRegister (RDA5807M_REG_CONFIG, reg02h);

  // Register 03h - select radio station
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister (RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);
// Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister (RDA5807M_REG_VOLUME); // Read the current value
  reg05h & = ~ RDA5807M_VOLUME_MASK; // Reset the VOLUME bits
  reg05h | = volume << RDA5807M_VOLUME_SHIFT; // Set a new volume
  setRegister (RDA5807M_REG_VOLUME, reg05h);
  // Receiver end:
}

void loop ()
{
  // Print power readings every 8ms.
  static const uint16_t print_period = 8;
  static uint16_t last_print;
  uint16_t now = millis ();
  if (now - last_print> = print_period) {
    //Serial.println (get_power_reading ()); // Build a graph by which you can determine the optimal threshold
    // If the signal has exceeded the threshold, start timing:
    if (get_power_reading ()> threshold &&! timing)
    {
      startTime = millis ();
      timing = true;
    }
    // If the signal is below the threshold, stop the countdown and display the amount of time passed - the pulse duration:
    if (get_power_reading () <= threshold && timing)
    {
      elapsedTime = millis () - startTime;
      timing = false;
      //Serial.println(elapsedTime);
      if (elapsedTime> = 80 && elapsedTime <= 580)
      {
        int h = floor ((elapsedTime - 100) / 20); // Get the time in hours, but there are 6 pulses, but only the last one is needed.
        //Serial.println(h);
        // "valround" --- Round to the nearest integer,
        // "floor (x)" --- Round down to integer
        if (h> = 1 && h <= 24) // If the time is defined as abnormal, beyond reasonable limits, then simply forget it:
        {
          Serial.println ("Exact time:");
          Serial.print (h);
          Serial.println (": 00");
        }
      }
    }
    last_print + = print_period;
  }
}

// Receiver start:
void setRegister (uint8_t reg, const uint16_t value) {
  Wire.beginTransmission (0x11);
  Wire.write (reg);
  Wire.write (highByte (value));
  Wire.write (lowByte (value));
  Wire.endTransmission (true);
}

uint16_t getRegister (uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission (RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write (reg);
  Wire.endTransmission (false);
  Wire.requestFrom (0x11, 2, true);
  result = (uint16_t) Wire.read () << 8;
  result | = Wire.read ();
  return result;
}
// receiver end

Start by conditioning the signal to a voltage within 0 – 1.5 V (no pulse) or 3 – 5 V (during the pulse). Capture that on a scope and post the trace here. It should be way easier to help you if we can see what the conditioned signal really looks like.

can you actually hear the time signal on the radio? ... how often is it transmitted? ... if you can hear it, then what does it sound like?

Are you referring to the WWV/WWVH time broadcast signal?

or to the 1 kHz beeps

I am receiving a signal from a broadcasting station, and the time pulses sound at an audio frequency of 1 kHz. There are 6 of them, sometimes 5, when there are overlays on the presenter's broadcasting. The signal is transmitted at the end of every hour. Is not WWV/WWVH

Your last plot shows a signal intensity around 40 which, for a sine wave, implies an amplitude of π√(40÷8)≈7 on the ADC in 8-bit mode. This is using less than 6% of the range of the ADC. Also, the strong residual oscillations hint that the average voltage may be far from 2.5 V. You may want to fine tune your signal conditioning in order to fix these issues. You can also add a layer of smoothing on the decimated intensity.

If the voice and music are superimposed on top of the signal you are
looking for, that will make matters quite difficult. The first thing you
have to do is filter out all the unwanted sound. The limit on how
aggressively you can filter is given by the width of the pulses. If you
want to detect 100 ms pulses, your filter width should probably be more
than 10 Hz. The filter you used in your test is way larger than that.
Given the limited processing power of your typical Arduino, it may be
preferable to do all the signal conditioning in the analog domain, prior
to digitizing it on the Arduino. If you really have to do everything in
the Arduino, you will still have to adjust the amplitude and the offset
of the signal in the analog domain so that it fits the range of the ADC.
For implementing a narrow-band filter on the Arduino itself, I generally
recommend to use an homodyne detection scheme. This can give
you very narrow filters at a minimal processing cost. See this other
answer where I discuss the working of the scheme, and provide a
link to an implementation.
If you have something similar to an Uno, you should be able to load that
sketch directly, although you may want to tweak the time constant in
order to make the filter narrower. You can then send it your test
signal, collect back the power readings sent by the sketch through the
serial port, and plot those. This should give you a new test signal for
prototyping the next stages of your processing pipeline. If all goes
well, you would just have to set a threshold for detecting the pulses,
and then have some condition on the length of the detected pulses to
sort out spurious pulses from legit ones.
Edit: I suggested using a threshold on the detected power for
deciding when there is a pulse and when there is not. However, if the
power signal is noisy, this simple scheme may not be good enough.
One possible way to reduce the noise is to increase the time constant of
the filter by increasing LOG_TAU. Do not set it above 8,
otherwise it may overflow some variables. Also note that, the larger the
time constant, the lower the bandwidth, which can be an issue if the
frequencies are not very accurate.
Another option is to low-pass filter the power readings. This can be
done on a sub-sampled signal in order to lower the processing cost.
Finally, for deciding whether there is a pulse or not, it can be useful
to add some hysteresis to the detection, basically simulating a Schmitt
trigger. This is simply accomplished by replacing the detection
threshold with two distinct thresholds: a high one for the “no pulse” →
“pulse” transition, and a lower one for the reverse transition:
const uint16_t LOW_THRESHOLD  = ...;
const uint16_t HIGH_THRESHOLD = ...;

// within loop:
static enum { NO_PULSE, PULSE } state = NO_PULSE;
uint16_t power = get_power_reading();
if (state == NO_PULSE && power >= HIGH_THRESHOLD) {
    state = PULSE;
    register_pulse_start();
}
if (state == PULSE && power < LOW_THRESHOLD) {
    state = NO_PULSE;
    register_pulse_end();
}

Thank you! I used your code unchanged and it works! Only I used the signal from the generator, since I do not yet have an amplified signal after the receiver. Now output the result to the serial port. I only see huge numbers when I apply 1 kHz!
Tell me what can I do next? After all, the survey is carried out quite rarely.

@Антон: Next step would be to define a threshold for pulse detection, but you cannot do that without a realistic test signal (with realistic amplitude): send the test signal to the Arduino, plot the numbers that come out, and select a threshold in between the lowest pulse level and the highest non-pulse level.

I ran a test, this time using a signal from the phone generator. I changed the frequency of the signal and watched the result. I think the optimal threshold is 25.
I cannot give a test signal because Arduino rarely plots points and my short impulses simply does not fix.
I attached the graph in the post above

I increased the sampling rate to 115200 baud, but it is not always possible to detect a 200ms signal ... Is it possible to increase the sampling rate further?

@Антон: A sampling rate of “115200 baud” does not make sense. A sampling rate of 155200 samples per second is more than what the Arduino can handle: processing the samples would require 127% of the available CPU power. You can increase the sampling rate, but that will not help detecting short pulses. You instead have to increase the rate at which samples are printed to the serial port, i.e. decrease print_period. Increasing the baud rate will be needed only if you set print_period to less than 8 ms, which is unlikely to be useful.

How can the values be smoothed without getting a signal lag? I noticed that the signal is very jagged and the time is not always accurate.

@Антон: Every low-pass filter I know about introduces some lag. But the lag is the same for the rising and falling edges of a pulse, so it does not interfere with the pulse length measurement. Re “the signal is very jagged”: see amended answer.

Hello! Your code helped me a lot.
But now my task is to detect rectangular pulses with a duration of 460 μs. Can this be done with the help of your code? What needs to change in it?
I have created a new question on this site, and I would very much like to hear your instructions, as I really liked your solution to the previous problem. Thank you!


text:
"SparkFun SAMD21 Mini Breakout" 'Serial1' was not declared in this scope
I recently switched computers and installed Arduino IDE, Added SAMD21 to the boards manager and installed drivers.
My sketch previously ran on my laptop with no problems.  Now when I try to compile for the SAMD21 Mini, I get a 'Serial1' was not declared in this scope error.
If I try to compile it for Mega, there are no problems.
I have tried sample code with Serial1 for SAMD21 and it compiled and uploaded with no problems.

The samd21g serial options are more configurable than for an AVR.  Much of this is left to the variant definition.  So which board do you have selected?

I selected "SparkFun SAMD21 Mini Breakout".  I got it working see below :)

Given that you're now liable to be the only person to answer the question, you may want to just edit the question and answer to make a good read for whomever comes across it in the future.  E.g. the question doesn't mention that you're not working in an .ino file.

Ahhhh, I figured it out.  I had to add #include "Arduino.h" to the .cpp file.


text:
Sending variable over serial
I have an LCD keypad shield that I'm using to control a Catalex serial MP3 module and I have an int variable that has the volume setting which can go from 1 to 30. I'm trying to send the variable to the module but it's not working. Here's the code for the serial request:
void SetAttractVolume() {
  SerialString = SerialString2 + AttractVolume;
  delay(20);
  Send_buf[0] = 0x7e; // starting byte
  Send_buf[1] = 0xff; // version
  Send_buf[2] = 0x06; // the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = 0x06; //
  Send_buf[4] = 0x00; // 0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = 0x00;
  Send_buf[6] = 0x12;
  Send_buf[7] = 0xef; //ending byte
  for (uint8_t i=0; i<8; i++) {
    mySerial.write(Send_buf[i]); // send bit to serial mp3
    Serial.print(Send_buf[i], HEX); // send bit to serial monitor in pc
  }
  Serial.println();
}

"0x12" is the volume control, you set the 12 to any number from 1 to 30 to change it, I thought I could just put my variable in there, like this:
void SetAttractVolume() {
  SerialString = SerialString2 + AttractVolume;
  delay(20);
  Send_buf[0] = 0x7e; // starting byte
  Send_buf[1] = 0xff; // version
  Send_buf[2] = 0x06; // the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = 0x06; //
  Send_buf[4] = 0x00; // 0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = 0x00;
  Send_buf[6] = 0xAttractVolume;
  Send_buf[7] = 0xef; //ending byte
  for (uint8_t i=0; i<8; i++) {
    mySerial.write(Send_buf[i]) ;//send bit to serial mp3
    Serial.print(Send_buf[i],HEX);//send bit to serial monitor in pc
  }
  Serial.println();
}

This doesn't compile, I know it's not the correct way to do it, but I want to know how to do it right.
Thanks in advance.

This doesn't compile  ... you did not present the complete code amd you fid not say anything about any errors ... i suggest that you learn some programming ... at least examine some of the example sketches in the arduino IDE

Send_buf[6] = 0xAttractVolume; makes no sense; 0x is used to indicate a hex number follows; you can't just stick a variable name to it. Try Send_buf[6] = AttractVolume; and see what happens.


text:
esp32-cam stuck in repeat boot
I am trying to bring the esp32 example code live. I am able to upload the image error free but when I remove the jumper and then press the reset switch, instead of seeing it logon to my network via serial monitor, I just get this repeating over and over and over again.
rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8

Brownout detector was triggered

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:9720
ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8
ets Jun  8 2016 00:22:57

How do I boot an esp32-cam correctly?
code:
#include "esp_camera.h"
#include <WiFi.h>

//
// WARNING!!! Make sure that you have either selected ESP32 Wrover Module,
//            or another board which has PSRAM enabled
//

// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
//#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
#define CAMERA_MODEL_AI_THINKER

#include "camera_pins.h"

const char* ssid = "getAjobFool";
const char* password = "andreasd1";

void startCameraServer();

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }

#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  //initial sensors are flipped vertically and colors are a bit saturated
  if (s->id.PID == OV3660_PID) {
    s->set_vflip(s, 1);//flip it back
    s->set_brightness(s, 1);//up the blightness just a bit
    s->set_saturation(s, -2);//lower the saturation
  }
  //drop down frame size for higher initial frame rate
  s->set_framesize(s, FRAMESIZE_QVGA);

#if defined(CAMERA_MODEL_M5STACK_WIDE)
  s->set_vflip(s, 1);
  s->set_hmirror(s, 1);
#endif

  WiFi.begin(ssid, password);

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

  startCameraServer();

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
}

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

Brownout detector was triggered Did you look into what the brownout detector is?

The message:

Brownout detector was triggered

is being generated by your ESP32 because there is a problem with the Vcc power to the module.
Check the following:

Your USB cable.  Some cables are just plain cheap and can't supply the power the ESP32 needs.  Get a better one.

Some PCs are not able to supply enough power from their USB ports to supply the ESP32, try a powered USB hub and/or a different PC.

Some ESP32 modules are poorly made and may have bad solder joints or low quality components.  Your only real option here is to buy a better ESP32.

If you are powering other components from the ESP32's power supply, stop it.  Power any accessories separately.

I am connecting to the esp32 directly via ftdi. I tried both 3.3v and 5v and tried putting a 470uf capacitor right next to the vcc thinking it needed a bypass. I got zero change. The ftdi device is connected to a powered USB hub. I am not trying to power any other components. Joints look fine.

For... here, I'll vote it up.

"Directly" is not the word I'd have used with an FTDI but where is the power for the ESP32 coming from?  Via USB through the FTDI.  So everywhere I said "USB" you can change to "FTDI".  It's still via USB.  Try powering the ESP32 directly, that is with a known good power supply.  And the part about having a bad ESP32 still applies too.  Many of these are poorly made.

I've come across this issue and I've had good results with a 10-100uF capacitor directly between the GND and 3.3V pins on the ESP32Cam board. It stopped random reboots.

I used a different ftdi and it worked. You were dead on it. Thank you.

@brad Glad to help.


text:
When I start running the Brushless motors with MPU6050 in my quadrocopter, there is a sudden spike in the data of Gyro X-axis and Gyro Y-axis
I am using the MPU6050_light library for getting the data for my quad-copter. When I am obtaining the gyro values from the MPU6050 without running the motors, its giving correct values but on running the motors and getting the values, I am getting a huge spike on both axes. I am a newbie and a tenth-grader so i don't know so much about electronics. I tried using a Kalman filter but could not find any code which can help me and the Kalman Library was too complex. I think if I apply some kind of filter the problem will be solved. If any one knows any other filter and its code, if you can share it, it would be of great help.
The code is as follows:
#include <SoftwareSerial.h>
#include <Servo.h>
#include <MPU6050_light.h>
#include <Wire.h>

double x = 0.0, y = 0.0, z = 0.0;
int c=0;

SoftwareSerial Slave(5,6);
Servo m1, m2, m3, m4, l;
MPU6050 mpu(Wire);

int throttle = 0;
int t1 = 0, t2 = 0, t3 = 0, t4 = 0;
unsigned long timer;
int of = 0;

void setup()
{
  Slave.begin(9600);
  Serial.begin(9600);
  Wire.begin();
  byte stat = mpu.begin();
  del(1000);
  mpu.calcOffsets();
  del(2000);
  m1.attach(3, 800, 2000);
  m2.attach(9, 800, 2000);
  m3.attach(10, 800, 2000);
  m4.attach(11, 800, 2000);
  l.attach(12, 800, 2000);
  throttle = 0;
  normal();
  del(10000);
  l.detach();
  while (of == 0)
  {debug();}
}

void loop()
{
  normal();
  debug();

  if (of == 0)
  {
    safe_land();
  }

  getxyz();

  if (x < -5.0)
  {
    t1 = t1 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (x > 5.0)
  {
    t2 = t2 + 1;
    t4 = t4 + 1;
    debug();
    normal();
    getxyz();
  }
  if (y < -5.0)
  {
    t4 = t4 + 1;
    t3 = t3 + 1;
    debug();
    normal();
    getxyz();
  }

  if (y > 5.0)
  {
    t2 = t2 + 1;
    t1 = t1 + 1;
    debug();
    normal();
    getxyz();
  }

}
void normal()
{
  m1.write(throttle + t1);
  m2.write(throttle + t2);
  m3.write(throttle + t3);
  m4.write(throttle + t4);

}
void safe_land()
{
  throttle = 0;
  t1 = 0;
  t2 = 0;
  t3 = 0;
  t4 = 0;
  normal();
  off();
}
void off()
{
  m1.detach();
  m2.detach();
  m3.detach();
  m4.detach();
  while (true);
}
void del(int tii)
{
  unsigned long tim = (unsigned long)(tii);
  unsigned long t = millis();
  while (millis() - t <= tim);
}
void getxyz()
{
  mpu.update();
  x = (double)(mpu.getAngleX());
  Serial.print("X:");
  Serial.println(x);
  y = (double)(mpu.getAngleY());
  Serial.print("Y:");
  Serial.println(y);
  //z = (double)(mpu.getAngleZ());
}

void debug()
{

  if (Slave.available())
  {
   c=(int)(Slave.read());
  }
   if(c<=180)
   {
    throttle=c;
   }
   if(c==200 || c==201)
   {
    of=c-200;
   }
}

I am also using two Arduino UNOs, hence the software serial...

what is your question? ... have you tried ignoring gyro data when the motors start up?

@jsotola I can't make the drone balance itself because the mpu6050 values are coming wrong when i am starting the motors... the gyro data at start should be 0.0 both x and y because they are on the ground but they are coming x:10 and y:-12 and not 0.0

that's why I said to ignore the the gyro when you are starting the motors .... try reading the gyro data after the motors started

@jsotola thnx will try and say


text:
I'm working on a NodeMCU project and have a small doubt about LEDs and resistors
In my NodeMCU I want a statement to turn on an LED, which is easy, just use pinnumber, HIGH. But, what I'm trying to do here is connect multiple LEDs to one pin like this:
I just wanted to know if this will work and whether all the LEDs will turn on by one command write (pinnumber, high) or do I have to do something else to this circuit?
Please help I'm a noob to electronics.
And also, is the resistor correct(1k ohm) or is it 220ohm, because different places suggest different things.

No! Most likely it will not work.
An LED lights up if the Voltage between the Anode (one side of the LED) and cathode (the other leg) exceeds a so called forward voltage (Vf).
This Vf depends on the creation process and differs between different colors. Vf can be between abt. 1.8 Volt (red LEDs) and abt. 4.2 Volt (blue LEDs). Even if the LEDs would have the same color, they might have different forward voltages. If you arrage 4 LEDs in parallel, like you did above, the Voltage over the 4 LEDS is as low as the Vf of the LED with the lowest Vf among the four. If the four LED would not have equal (Vf)s, only one LED will light up and all others stay dark or just glow a little bit.
The sum of the current that flows through the 4 LEDs must also flow through the resistor. So the resistor must let pass 4 times the current that is required for one LED. An normal 3mm or 5mm LED works best at about 10mA to 20mA. Let's say the LEDs have all the same Vf = abt. 2 Volts, and you choose to drive them with 15 mA.
You need 60 mA in sum for the 4 LEDs, that must pass the resistor. You can compute the required resistance with  Ohms law. R = U / I.

R is the resistance in Ohms.

U is the voltage over the resistor in Volts.

I is the current through the resistor in Ampere.
U = Voltage of the ESP (3.3 Volt) minus
the lowest forward voltage of the LEDs (2 Volt)
I = the wanted current 60mA = 0.06 Ampere
R = (3.3-2) / 0.06 = 140 / 6 = abt. 23 Ohm
(27 Ohm resistors should be available.)

The resistor depends on the Voltage of the ESP, the kind of the LED and the amount of current you need to reliably light up the LEDs. You can not just take values from schematics or discussions the internet. Also 60 mA is very much current for the ESP pin. That might be a problem.
The best way the Light up 4 LEDs from one pin would be to use one resistor for each LED and a MOS FET Transistor that is connected to 5 Volts with its Drain pin, the parallel LED resistor pairs with its Source and to the ESP pin with its Gate. You should also be sure that the MOS FET you use is able to switch with a 3.3 V voltage from the ESP on its Gate.
If you did not understand what I have written, I advice you to learn the basics before experimenting further. The values above are all useless if the conditions change.

Yes, technically your circuit works. But don't do like this.
TLDR;
This applies only to what you are doing

LED is current device. We control brightness by control current flow through it.
Each IO pin (of ESP8266) has current drive capable (source/sink) 12mA only, so calculate it wisely or you risk killing it.
Simplest way to control current of LED is using current limiter or just a resistor in series
Voltage drop across red LED (Vf) is 1.8v
4 LEDs in parallel work just like 1 LED, assuming the same kind, but of course 4 times dimmer
Current goes through each LED = 1/4 of current goes through resistor (kirchhoff law of current)
Equation: 3v3 = 1.8v + V_R hence , V_R = 1.5v
Current goes through resistor I_R = V_R / R
5mm LED has nominal current of 20mA to be considered brightest that last VERY long time.
BUT ESP8266 can only do 12mA. You go 20mA, ESP8266 goes bye bye.
So choose 10mA to be on safe side. Plug 10mA into #8, hence R = 1.5v / 10mA = 150 ohm
You can choose resistor value from 220R up to 1K, no problem. Higher resistance, less current.
You can do rough calculation, ignore voltage drop across LED, just use 3v3 / 10mA = 330R. Hence you will see people usually use resistor 330 ohm regardless 3v3 or 5v, red LED or green LED. Because at 5v it is 15mA, red or green makes only 0.3mA different. Nothing to worry.
But your circuit has 4 LEDs in parallel, hence current through each LED = 10mA/4 = 2.5mA
Fact: Even as low as 0.15mA (R=10k with 3v3 power supply), RED and GREEN LEDs are still bright enough for indication.

Note:

My guess is, you are using LEDs like a torch. More LEDs = more brightness, right? Unfortunately, it won't work like that. You want to use transistor (BJT) or mosfet as a switch to turn on power supply for LED instead of driving LED from IO pin. Google high side switch or low side switch for that matter. Better solution is to use LED driver IC.
Normally for simple indicator, I just whack a 470R resistor in series of a LED regardless voltage to drive it (5v or 3v3). It still gives quite intense brightness when you stare directly on it. Sometime you want to use 1k ohm just to reduce the brightness further or even sanding the LED from crystal clear into translucent white.


text:
How to implement brown out detector arduino ESP32?
We are using ESP32 with arduino sdk for developing our application. In our application we need to implement BOD to detect with specific voltage level.
Basically we want to set specific voltage level and when device goes to power off it will detect and trigger interrupt. How I can set interrupt for brown out detect?
we have only this code:
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"

void setup() {
  Serial.begin(115200);
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 1); //enable brownout detector
}

void loop() {
  Serial.println("Start BOD");
  delay(1000);
}

You need to explain a bit better what you're trying to do. Do you want to execute some code when the power fails? Without additional hardware, that could be difficult, since when the power is off, the board is off, too.

The ESP32's on-board BOD is mainly intended to inhibit operations that might cause corruption if they happened with too low a voltage.  There is a very unpredictable amount of time for the code in the ESP32 to do anything but effectively halt.
If that's what you want, then you have enabled it in your code above.
If you want to detect a power outage, for example, and log something, then you need two things:

A reliable detector that the power has failed.
A battery or capacitor-based circuit that will continue the ESP32's power for long enough for you to do what you need to do.

So when "1" happens you set a GPIO pin on the ESP32 which triggers your interrupt and you do what you need to do while the power remains stable.

Are you talking mains power or some other source of power (AC or DC)? Is the ESP powered from that source or another source? How much time will be left from when the power browns out until you lose control? Do you plan on using the A/D or an external comparator?


text:
When is following code is dumped into Arduino NANO the output is not as expected after few trials
I'm a beginner of Arduino programming,  when I dumped the following code into Arduino NANO board, at the first the output is as expected. But After few trials the 16*2 LCD display is getting off and DC motor pump is running continuously.
      #include <Wire.h>
      #include <Adafruit_MLX90614.h>
      #include <LiquidCrystal_I2C.h>
      LiquidCrystal_I2C lcd(0x27, 16,2);

      char *typeName[]={"Object","Ambient"};

      Adafruit_MLX90614 mlx = Adafruit_MLX90614();

      const int trigPin = 13;
      const int echoPin = 12;
      #define DCwater_pump 11

      long duration;
      int distance;

     void setup()
     {
          Serial.begin(9600);
          Serial.println("S.O.A.P. DISPENS");

          Serial.print("Ambient = ");
          Serial.print(mlx.readAmbientTempF());
          Serial.print("*F\tObject = ");
          Serial.print(mlx.readObjectTempF());
          Serial.print("*F");

          Serial.println();

          delay(500);

          if (!mlx.begin())
          {
              lcd.print("MLX90614 Failed");
              lcd.setCursor(0,1);
              lcd.print("check wiring!");
              while (1)
              ;
          }
          Wire.begin();
          lcd.begin(16,2);
          lcd.backlight();
          lcd.print("S.O.A.P.D. Temp");
          lcd.setCursor(0,1);
          lcd.print("S.O.A.P.D. Temp");
          delay(500);
          clearCharacters(2-1,0, 16-1);

          pinMode(trigPin, OUTPUT);
          pinMode(echoPin, INPUT);
          pinMode(DCwater_pump, OUTPUT);

    }

void loop()
{

        printTemp('C');
        delay(1000);

        printTemp('D');
        delay(1500);

}

float getTemp(char type)
{

  float value;
    float tempObjec = mlx.readObjectTempC();
    float tempAmbient = mlx.readAmbientTempC();

   if(type =='C')
   {
    value = tempObjec;
   }
   else if(type =='D')
   {
    value = tempAmbient;
   }
   return value;

}

            void printTemp(char type)
  {
            clearCharacters(1,0, 16-1 );
            float TmpC =getTemp(type);
            float TemF;
            TemF = (TmpC*1.8)+32;
            lcd.setCursor(0,1);
            if(type =='C')

              {
                lcd.print(typeName[0]);
                lcd.print(" ");
                lcd.print(TemF);
                lcd.print((char)223);
                lcd.print("F");
               }

                  else if(type =='D')
                  {
                    lcd.print(typeName[1]);
                    lcd.print(" ");
                    lcd.print(TemF);
                    lcd.print((char)223);
                    lcd.print("F");
                  }

  }

void clearCharacters(uint8_t row,uint8_t start, uint8_t stop )
{
    for (int i=start; i<=stop; i++)
    {
    lcd.setCursor (i,row);
    lcd.write(254);
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance= duration*0.034/2;

    Serial.print("Distance: ");
    Serial.println(distance);

           if (distance < 30)
          {
           digitalWrite(DCwater_pump,HIGH);
           Serial.println("DC Pump is ON Now!!");
           delay(500);
          }
          else
          {
           digitalWrite(DCwater_pump,LOW);
           Serial.println("DC Pump is OFF Now!!");
           delay(500);
          }

}

Try to fix the formatting of your code first. This is very hard to read.

Your code is very confusingly organized. You clearCharacters function, which suposedly should clear the display, does a distance measurement (using an HSR-04 module?) and enables/disables the water pump as a side effect.

How is the pump motor connected? Do you have a flyback diode? Did you try using external pullups in the range of 4.7kOhm at the I2C lines (they might get problems with the motor generated noise, when you only use the internal pullups)?

I connected DC pump using a relay.


text:
error ph meter cant show the data
im using ph meter DFROBOT v1.0 at i compiled the code from the DFROBOT web this is the code
*
 # This sample code is used to test the pH meter V1.0.
 # Editor : YouYou
 # Ver    : 1.0
 # Product: analog pH meter
 # SKU    : SEN0161
*/
#define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
#define Offset 0.00            //deviation compensate
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex=0;
void setup(void)
{
  pinMode(LED,OUTPUT);
  Serial.begin(9600);
  Serial.println("pH meter experiment!");    //Test the serial monitor
}
void loop(void)
{
  static unsigned long samplingTime = millis();
  static unsigned long printTime = millis();
  static float pHValue,voltage;
  if(millis()-samplingTime > samplingInterval)
  {
      pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();
  }
  if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
  {
    Serial.print("Voltage:");
        Serial.print(voltage,2);
        Serial.print("    pH value: ");
    Serial.println(pHValue,2);
        digitalWrite(LED,digitalRead(LED)^1);
        printTime=millis();
  }
}
double avergearray(int* arr, int number){
  int i;
  int max,min;
  double avg;
  long amount=0;
  if(number<=0){
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  if(number<5){   //less than 5, calculated directly statistics
    for(i=0;i<number;i++){
      amount+=arr[i];
    }
    avg = amount/number;
    return avg;
  }else{
    if(arr[0]<arr[1]){
      min = arr[0];max=arr[1];
    }
    else{
      min=arr[1];max=arr[0];
    }
    for(i=2;i<number;i++){
      if(arr[i]<min){
        amount+=min;        //arr<min
        min=arr[i];
      }else {
        if(arr[i]>max){
          amount+=max;    //arr>max
          max=arr[i];
        }else{
          amount+=arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount/(number-2);
  }//if
  return avg;
}

and its work, untill i want to combine thats code to my code, the ph value = 0.00
im just copy paste the code from the website in to my code and its not working what should i do
void loop()
{
  //-------------Read Function sensor-----------
//  PPM----
    gravityTds.setTemperature(temperature);  // set the temperature and execute temperature compensation
    gravityTds.update();  //sample and calculate

    tdsValue = gravityTds.getTdsValue();
    tdsValue=(tdsValue *2)/1000;// then get EC the value
    Serial.print(tdsValue,5);
    Serial.println("ppm");

    hasilec = (ppmcensor - inputec );
    Serial.print("Eror EC : ");
    Serial.println(hasilec,6);

// ph-----
  if(millis()-samplingTime > samplingInterval)
  {
      pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();
  }
  Serial.print("Nilai pH :");
  Serial.println(voltage,2);

//  ph = (phcensor - inputph);

//  hasilec = random(-200, 0) / 100.0;
//  ph = random(-200, 200) / 100.0;
  ph = 130/100.0;

  unsigned long now = millis();

  SerialMon.print("EROOR pH    ");
  SerialMon.print(ph);
  SerialMon.print("  ");
  SerialMon.print("ERORR EC ");
  SerialMon.print(hasilec);
  SerialMon.println("");
  SerialMon.print(ph);  Serial.print(" ");
  SerialMon.print(hasilec);   Serial.print(" ");
  SerialMon.println(" ");

  fuzzy->setInput(2, hasilec);
  fuzzy->setInput(1, ph);
  fuzzy->fuzzify();

  float pompa01 = fuzzy->defuzzify(1);//pHDOWN
  float pompa02 = fuzzy->defuzzify(2);//pHUP
  float pompa03 = fuzzy->defuzzify(3);//ABMIX

  SerialMon.println("Result= ");
  SerialMon.println("");
  SerialMon.print(" Pompa1 pHDOWN: ");
  SerialMon.println(pompa01);
  SerialMon.print(" pompa2 phUP  : ");
  SerialMon.println(pompa02);
  SerialMon.print(" pompa3 ABMIX : ");
  SerialMon.println(pompa03);
  SerialMon.println("");
  SerialMon.println("");
  SerialMon.println("");

  delay (2000);

  long int pompa1 = pompa01*1000;
  long int pompa2 = pompa02*1000;
  long int pompa3 = pompa03*1000;

  pump_periods[0] = pompa1; //PHdown
  pump_periods[1] = pompa2; //PHup
  pump_periods[2] = pompa3; //ABMIX

//  for (int i = 0; i < jml_pump; i++) {
//      if (now - pump_last_actuations[i] >= pump_periods[i]) {
//          pump_states[i] = (pump_states[i] == LOW) ? HIGH : LOW;

//          digitalWrite(pump_pins[i], pump_states[i]);
//          pump_last_actuations[i] = now;
//      }
//  }

  for (int i = 0; i < jml_pump; i++) {
  digitalWrite(pump_pins[i], LOW);     // Start pump i
  delay(pump_periods[i]);            // nyala waktu dalam pompa[i] ms
  digitalWrite(pump_pins[i], HIGH);     // Stop pump i
  }
  delay(100000);
}
double avergearray(int* arr, int number){
  int i;
  int max,min;
  double avg;
  long amount=0;
  if(number<=0){
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  if(number<5){   //less than 5, calculated directly statistics
    for(i=0;i<number;i++){
      amount+=arr[i];
    }
    avg = amount/number;
    return avg;
  }else{
    if(arr[0]<arr[1]){
      min = arr[0];max=arr[1];
    }
    else{
      min=arr[1];max=arr[0];
    }
    for(i=2;i<number;i++){
      if(arr[i]<min){
        amount+=min;        //arr<min
        min=arr[i];
      }else {
        if(arr[i]>max){
          amount+=max;    //arr>max
          max=arr[i];
        }else{
          amount+=arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount/(number-2);
  }//if
  return avg;
}

What exactly do you mean by copy&pasting the code into your code? You cannot simply do that, because you can only have 1 void loop() function and 1 void setup() function

the first code its from https://wiki.dfrobot.com/Gravity__Analog_pH_Sensor_Meter_Kit_V2_SKU_SEN0161-V2
and i add that code to my code

As I wrote, you cannot simply do that. Combining two codes is more complex than that

yep thx for helping me


text:
Connecting the cathode of a diode to the output of a multiplexer
From the image, the diodes share the same anode which is driven by 'Do Something'. My question is: through using Arduino IDE, what code should I write that connects the output of the multiplexer (Z) to a specific diode's cathode (Y0 or Y1 or ... or Y7), which in turn is connected to 'Do Something' that drives the cathode probably? In this code, I want the ESP32 microcontroller to connect this cathode to 'Do Something' for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds [where no diodes' cathodes are connected to Z]       (and so on: in a continuous loop).
Here some code I found online but not sure what needs to be added to get the proper functionality:
int outputs[4] = {4,0,2}; // pins for selecting LED
int inhibit_pin = 15; // pin for turning off all LEDs

void setup() {
  for(int i;i<3;i++){
    pinMode(outputs[i],OUTPUT); // output selection for LED control
  }
  pinMode(inhibit_pin,OUTPUT);
  digitalWrite(inhibit_pin,LOW); // raise high to disable all

}

void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){
    // turn on LEDs based on bit conversion
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    delay(100); // delay .1 sec
  }
}

I don't think that "digitalWrite(outputs,bitRead(j,i));" is actually needed and I am not quite sure of what it does.

bitRead(j,i) reads the i-th bit from a bitstring. e.g The number 6 has the binary representation 110. bitRead(6,2) reads a 1 as it starts from right bit0 = 0, bit1 = 1, bit2 = 1. In your program this code is written to the output pins which control the multiplexer to use Y6. That's all. The program should work as it is. BTW: You will only see an effect if the diodes in the schematic/picture are LEDs, and "Do Somethig" does something i.e provides a constant or fast pulsing voltage.

What is the MUX?

for say 3 seconds and then switch to the next diode's cathode with a delay of 0.1 seconds If you mean you want none of the eight outputs to be driven during the 0.1 second period, you should update your question to clarify.  As is, that is not something your code is doing.

what kind of diodes are you using? ... why do you even need them?

My idea is to use the microcontroller for only controlling the MUX (each time, one Y0 is connected to Z). The 'Do something' Block continuously provides appropriate signals for driving the anode of a diode and Z (cathode of a diode). The diagram only shows a small part of my project, and the 'Do Something' is a very complicated system. It works nicely when one diode is connected directly [without the MUX] to 'Do Something', but now I want 8 diodes, each time one diode gets connected to 'Do Something'.

Why not use 1 diode on Z, and remove the 8 diodes between pins Y0...Y7 of your MUX and  your Do Something block? That would only allow current to flow one way between Yx and Z, using one diode instead of 8.

I rolled-back your latest edit because you deleted the URL for the image but left the image tag in and also the content of your question makes reference to this image.  If you have good reason to get of the image, and it's not clear that you do, remove both the tag and URL and references to it.

Your "do something" common anode input should probably have a pullup to avoid a floating condition.

You should edit your question and put the image back. Without it your description is going to be very hard to follow.

The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.
Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.
One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your for(int i=0;i<3;i++) loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit_pin to HIGH (disabling the mux before entering your for(int i=0;i<3;i++) loop, and then set it to LOW again at the end of the i loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)
Your description is a little hard to follow, but it sounds like that is what you want.
If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}

Thank you very much!! Out of curiosity, if I had two identical MUXs [same pins] and 16 diodes, then how would the code be changed to connect each of the 8 pins to Z of both MUXs at the same order/time [i.e. Y0 to Z of MUX1 and Y0 to Z of MUX2, then Y1 to Z of MUX1 and Y1 to Z of MUX2, and so on]? Excuse the wording of my question as I am trouble in putting my thoughts into words.

You could drive 2 MUXs with your Arduino, or better yet get a 16 channel MUX (altough with 1 16-channel MUX you could only select one channel at a time.) If you used 2 MUXs your tie their Z pins together, and use 3 different Arduino pins for the channel selector on each MUX. I'd write a channel-selecting function that took a MUX number as input (MUX 1 or MUX 2, say) and used that to look up the pin numbers to select and enable a channel for that MUX, and then my loop would call the function for each MUX in turn.

It looks like you need 4 unique pins for each MUX (3 channel select pins and an enable pin.) You could lower that to 3 unique pins and a shared enable pin if you wrote your code to disable both MUXs, do the channel selection, and then enable both at the same time.

I initially thought that since the two MUXs are to be operated in the same manner, then the code can be used as it is. But since I haven't used Arduino IDE much nor hardware programming in general, I wrote my initial comment to double check and as you said that I need a function to call each of the MUX. Yes, I agree that the two MUXs can share the enable signal, VCC, etc except for Y0-Y7 and Z.

if you are aware of any relevant web pages, please share them with me

If you always want MUX1 and MUX2 to connect their same pins at the same time, you could just split the Arduino outputs and drive both MUXes with the same 4 control pins.


text:
Grove Base Kit Multiple I2C Connection
I tried to connect two modules that require I2C connection and they won't work at the same time.
I used the Arduino Sensor Kit - Base. This kit does not need any connection, you just have to code to get your desired output. I wanted to display the Air Pressure (BMP280) module values to the 0.96" OLED Display, however, it is refusing to run both the air pressire and the OLED display at the same time. Only running one module (either Air pressure or OLED) at a time makes it work. Does it have something to do with how the I2C connection is wired on the board?
#include "Arduino_SensorKit.h"

void setup() {
  // put your setup code here, to run once:
  Oled.begin();
  Oled.setFlipMode(true);
  Oled.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

void loop() {
  // put your main code here, to run repeatedly:
  Oled.clear();

  Oled.setCursor(0, 10);
  Oled.print("Temp: ");
  Oled.print(Pressure.readTemperature());
  Oled.print(" C");
  Oled.setCursor(0, 20);
  Oled.print("Pres: ");
  Oled.print(Pressure.readPressure());
  Oled.print(" Pa");
  Oled.setCursor(0, 30);
  Oled.print("Alti: ");
  Oled.print(Pressure.readAltitude());
  Oled.print(" m");

  delay(1000);
}

What I did:

Test to see if Air Pressure will still work while both Air Pressure and OLED is connected by using Serial.begin(). Now I know that only the OLED does not work when both modules are connected.
Changed order of initialization. Same result: Air Pressure works but not OLED

"it is refusing to do so" means what? It's printing nothing to the OLED? It's printing things but getting the values wrong? Please be more specific.

it has nothing to do with how the I2C connection is wired on the Base shield. run the I2C scanner sketch to see the devices I2C addresses

@Majenko The OLED is not working at all. Air pressure works (tested with Serial.print())

You tested the pressure using Serial.print() while the OLED code was there?

@Juraj The OLED has the address 0x3C and the Air Pressure has the address 0x77. Was also able to confirm it on their site: wiki.seeedstudio.com/I2C_And_I2C_Address_of_Seeed_Product/

@Majenko Yes I did

try to swap the initialization order

@Juraj Still the same output. OLED won't work :(

Perhaps it is something simple like: If you print the float pressure value (like 920.2773), the OLED line might overflow and cause and error/reset in the OLED lib. Did you try to print only one value without any prefixed text? Best would be to round the value before printing ;-)

@PeterPaulKiefer Yes, I tried to only print the letter "T" at the start of the loop (both air pressure and OLED are initialized) and the OLED still isn't working :(

Just for my understanding: You tried to print only the letter "T" and nothing else after that. When the pressure module is initialized the OLED does not display the "T" and when the Pressure Module is not initialized, the OLED shows the "T".

I've looked into the u8g2 lib that is used for the OLEAD. And I've found a possible issue with the constructor signature of this lib. But it could be a typo in the documentation. Later this day, I'll try to find the implementation and if it is an error I will report it with the resp. projects. It might not be you probleme here, as Olead can not work if this is really an error. But I may find an explanation while investigating the code.

I've also read that the Oled lib uses high speed I2C and that could be in conflict with the low speed Pressure I2C. Sadly, I forgott the reference. I'll have to look into the libs code. ;-)

@PeterPaulKiefer, regarding the I2C speed. I tested a similar OLED clone on the oscilloscope just now at 352kHZ, which would indicate it likely operates in fast I2C mode (up to 400kHz). The datasheet for the BMP280 indicates it is compatible with standard, fast or high speed I2C.

@fireblazer10, Juraj suggested (Jan 20) running an I2C Scanner sketch to see which devices it can see on your I2C bus. Did you get a chance to do that? An example is https://forum.arduino.cc/index.php?topic=197360. This will check addresses (and verify the information you found on the Seeed Studio website) and frequency compatability.

@RowanP Thank you for clearifying and for reminding me of what I what to do last evening. I completely forgott :-(. The BMP280 and Oled speed capabilities can be the same  but as the Pressure lib and the Oled lib both use the Wire lib when they initialize, there may be a side effect if both specify different speeds. It is just a guess. Perhaps the Wire lib gets confused.

@RowanP I apologize I honestly have forgotten about this but yes I did: 0x3C for the OLED and 0x77 for the pressure sensor

@PeterPaulKiefer Oh, that's a shame :(( I guess I would have to leave this project for a bit. I'll try other OLED libraries for a start and see if it changes anything

@fireblazer10, thanks for confirming the I2C scanner results. I put some general comments about I2C debugging on another question earlier today which may help. It may be difficult to make more progress without access to some additional test equipment.

I opend an issue on github. I think there is a problem with the Oled constructor. https://github.com/arduino-libraries/Arduino_SensorKit/issues/15 If i'm right, the clock of the 'I2C bus resets the OLED. If Pressure is active the I2C clock is active. -> reset the Oled. Tada. ;-)

About two weeks ago there was a change in the Arduino_SensorKit Library that introduced an error with the instanciation of the Oled object.
I found the error in the release (v1.0.6) of the library. The previous release (v1.0.5) could cause another issue, as it uses a software I2C. I doubt the hardwired sensores are connected with the correct pins. But I have no hardware, so I can not check this.
I propose a workaround to see, if the identified issue caused your observations.
#include "Arduino_SensorKit.h"

U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2;
// if the line above does not work
// comment it and uncomment the following line.
// U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2(U8X8_PIN_NONE);

void setup()
{
  Oled2.begin();
  Oled2.setFlipMode(true);
  Oled2.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

void loop()
{
  Oled2.clear();

  Oled2.setCursor(0, 10);
  Oled2.print("Temp: ");
  Oled2.print(Pressure.readTemperature());
  Oled2.print(" C");

  delay(1000);
}

Could you please try out and report your experience.
If it would work, I can support the fixing of the issue.

It works! OLED just keeps blinking but it shows the output now! The blinking could be fixed by changing Oled2.clear() to Oled2.refreshDisplay(). Thank you so much!

You're welcome. Meanwhile I got feedback from marqdevx. He is about to release a new version of the lib. I think as soon as it is available, this workaround is not necessary furthermore (<- don'T know if this is an english word. But it sounds good ;-) ). As soon as the new revision is available I'll edit my answer and add your "blinking" solution too.   Cheers!

FWIW, I had the same issue with the latest version at the time - 1.0.10, and this fixed it. I have no idea what this does but it fixed it.

@davetron5000 Thank you for this comment. I completely forgot about this topic. I just remember that I waited for the new release and it had last longer then I expected. And then the topic get's out of my view ;-). I simply forgott it. In the very Moment I have not the time to look after it. Perhaps if I find some time in November I check what happend with the fix. It's in my calender.


text:
I am making heated socks with adjustments by Nano and want to extend batterty life?
I want to set a temperature and have Nano turn on for 2 minutes then off for 2 minutes and repeat using the same temperature originally set and have the ability to change temperature settings and do the same.
The following sketch works along with displaying battery voltage using MIT Inventor 2 app via Bluetooth HC-05 to my Android phone (without the on/off sequence I am looking to do).
I hope to keep my feet warm but also extend the battery life.  Can you tell me what methods I should research to figure out how to do this? I have looked at millis(), blink without delay, and my own limited programming skills without success.  Thanks.
#define right 5
#define left 6

int leftval = 0;
int val=0;
int vg=0;

void setup() {
  Serial.begin(9600);
  pinMode(left, OUTPUT);
  pinMode(right, OUTPUT);
  pinMode(A0, INPUT);
}

void loop() {
  int vg = analogRead(A0);
  Serial.println(vg / 82.049, 1);
  delay(200);
  if (Serial.available() >= 2) {
    unsigned int a = Serial.read();
    unsigned int b = Serial.read();
    unsigned int val = (b * 256) + a;

    if (val >= 0 && val <= 255) {
      analogWrite(right,val);
      delay(200);
    }

    if (val >= 1000 && val <= 1255) {
      leftval = val - 1000;
      analogWrite(left, leftval);
      delay(200);
    }
  }
}

https://www.arduino.cc/en/Reference/ArduinoLowPower - however the Arduino's power consumption will pale into insignificance compared to the power consumption of your heating element.

@Majenko, why this comment? I don't see in question a request for lowering the consumption of the Nano. OP wants to turn on the heating element for 2 minutes then turn it off for 2 minutes

@Juraj Because the OP asked "have Nano turn on for 2 minutes then off for 2 minutes" - not turn the element on and off, but turn the Nano on and off. Maybe it's poor English?

With an electrical heating element powerful enough to warm your feet, the power to the heating element is hundreds or thousands of times greater than the power to your Arduino. Anything you do to reduce the power consumed by your Arduino will have no meaningful effect on your total power consumption. It's like trying to stop a drip in your faucet to save water while the main water pipe has water gushing out of a gaping hole.
Heating elements convert watts of power to calories of heat. The more watts you put in, the more heat you get.
Current • duty cycle • on-time = total power consumed AND total heat generated.
If you reduce the duty cycle to the heating element, you will reduce the power consumed, but you will also reduce the amount of heat generated.
Given that you already have the ability to vary the duty cycle to your heating element (via your analogWrite to right and left) the only meaningful way to reduce power consumption is to lower the heat setting. It looks like you already have that ability. Turn down the heat setting and have slightly colder feet, or use a higher capacity battery.
All that said, if you turn the heat setting down to 0, the heating element completely stops using power. At that point the Arudino will slowly drain your battery while your electric socks sit in your sock drawer. It would be worth putting your Arduino in ultra-low-power sleep mode (or even turning it off entirely) to avoid draining it while you're not using it.
Edit:
If you want to run the heating element on for 2 minutes, off for 2 minutes, that would give exactly the same power savings as running it at half the current power level, but constantly.
If you really want to implement the 2 minutes on, 2 minutes off approach, you will need to use millis() to keep track of the time when you last turned the elements on/off. I suggest refactoring your current code to remove delay and use millis as well.
Take a look at the "BlinkWithoutDelay" sketch (which I believe is included with the IDE, and is certainly available online) for an idea of how to handle timing things without using delay().

I don't see in question a request for lowering the consumption of the Nano. OP wants to turn on the heating element for 2 minutes then turn it off for 2 minutes

I edited my answer to address the issue of 2 minutes on, 2 minutes off vs. turning the power down, and provided a starting point for implementing it if that's what they really want to do. (As I pointed out, cycling the power on and off every 2 minutes will have exactly the same power savings as lowering the PWM duty cycle by half.)

Thank you.  The source battery for the heating element was my concern.  I had looked at millis() as an option but needed someone to confirm as a potential option.  I will study millis() and BlinkWithoutDelay.


text:
How to put Arduino Nano in low power sleep mode (<0.05mA)
I'm trying to put an Arduino Nano in low-power mode using this guide: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery.
The article suggests 3 things: use the Low-Power library from Rocketscream, cut the power to the power LED, and remove the voltage regulator.
So far I've only done the first two and reduced the clock speed to 8 MHz.
The important part of the source code that puts the Arduino in deep sleep looks like this:
void setup() {
  CLKPR = 0x80; // (1000 0000) enable change in clock frequency
  CLKPR = 0x01; // (0000 0001) use clock division factor 2 to reduce the frequency from 16 MHz to 8
}

void loop() {
  // Go to sleep until the next scheduled wake up
  int32_t waitSeconds = 60;
  while (waitSeconds > 0) {
    period_t waitFor = SelectWaitTime(waitSeconds);
    LowPower.powerDown(waitFor, ADC_OFF, BOD_OFF);
    waitSeconds -= PeriodToSeconds(waitFor);
  }
}

period_t SelectWaitTime(int32_t secondsToWait) {
  if (secondsToWait >= 8)
    return SLEEP_8S;
  else if (secondsToWait >= 4)
    return SLEEP_4S;
  else if (secondsToWait >= 2)
    return SLEEP_2S;
  else if (secondsToWait >= 1)
    return SLEEP_1S;
}

In essence, sleep for up to 8 seconds, remove the seconds from the counter, then sleep again.
So far I've only scratched off the trace to the power LED and haven't removed the voltage regulator. According to the article above, this should reduce the power consumption to around 0.05 mA but I get around 1.7 mA, which is over 30 times more!
Electrically, I only have a MOSFET as a power switch connected to one of the analog pins (I use it as a digital output) and another controller, connected to the I2C pins (the Arduino acts as Slave). The other controller is turned off through the MOSFET when I take the measurements. Physically removing the connections doesn't change the consumption, so I don't think any of that is related.
Is there something I did wrong? What can I do to achieve power consumption similar to the one in the article?

Turns out the voltage regulator was AMS1117 - not MIC5205-KB50/KB33/KBAA like the one in the article. Ripping it off gave me the 0.026 mA idle current which is even better than what I was hoping for.


text:
Searching for free OTA Server Host list name
I have seen this video:
Over The Air programming Tutorial
For programming the Arduino modules via internet  OTA system, so I have tried the adafruit account and don't find the AIO_KEY part on it, ( as you can see below):

So I like to know about other web server systems for testing this option on the Arduino module (for me is ESP8266 01!).
So please suggest some free internet website as alternative options  like suggested site via above video ( adafruit).
The codes for making the esp8266 ready to accept the OTA process is accessible here.
Note: Also the https://io.adafruit.com/ server have some Problem right now:
So if possible I like to know is any safe methods exist for the interrupt and server problem
situation like this (adafruit 503 error, seen below) during the Arduino  OTA programming?

Update:
I have found the link of adafruit OTA_Key :
https://io.adafruit.com/ss1/dashboards/<Your_acount_Name>

Thanks.


text:
DC Motor will not work. Transistor method nor L293D!
New to Arduinos and stuff.
I have tried the L293D and the transistor method but the motor just wouldnt work.
I have tested the motor and it definitely is fine.
Below is my layout for this attempt:
Bits used:

Arduino UNO
1N4007 Diode
PN2222
230 ohm resistor

My sketch is ::
int motorPin = 3;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(motorPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()) {
    int speed = Serial.parseInt();
    if (speed >= 0 && speed <= 255) {
      analogWrite(motorPin, speed);
    }
  }
}

HELP!!!

First of all don't power the motor using your Uno's 5V supply.  Motors are notoriously noisy and will almost always cause the Uno to be unstable and reset itself.

Check your line ending in the serial terminal. If you have anything other than "none" then you'll get your number followed immediately by 0.

You can sanity check your transistor setup by not controlling the base in software.  Just take your jumper out of pin 3 and manually connect it to 5V and GND.  If you motor doesn't turn then, it has nothing to do with your software.

use simplest possible code to run the motor ... there is absolutely no reason to have any Serial code in your sketch when testing the motor .... only two commands are needed, pinMode and analogWrite ... both can be in setup()

Actually you don't even need the pinMode - PWM is an alternative function and not affected by the direction register.

Thanks for all the help guys. I have tried this setup multiple times but it didn't work. So now I put it together again to try some of the suggestions and it just worked before I could implement any of the above suggestions. I will try now with the L293 and come back.


text:
Error 101 Server Did Not Report Size from OTA Upgrade framework via git hub
I have tried this video:
ESP8266 Self Update OTA from GitHub
Instruction and made this GitHub repo:
And changed the main code to this type, but I get this error:
HTTP_UPDATE_FAILD Error (-101): Server Did Not Report Size

when the    FirmwareUpdate(); code is running.
So I don't know why GitHub don't answer to the esp8266, as said here:

The error has nothing to do with your sketch. Also, the error code is
not a HTTP 101 error. The problem is that your server does not send
the response header 'Content-Length'

I have some dupt about the bin URL file address which have many dot on the end of it (https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay.ino.esp8285.bin) on it, could it be the reason for none answering and giving the 101 code form GitHub server!
Any suggestion would be good help to fix this bug.
Update 1:

I have changed the bin file name to this kind :
 BlinkWithoutDelay.ino.esp8285.bin  ---->      BlinkWithoutDelay_ino_esp8285.bin

But I have again the same GitHub 101 error.

Update 2:
Based on the timemage answer, I have changed the address of bin and TXT file by finding the download link of those files form the GitHub. And it has been working by changing the blob part of address to raw, so the bin address changed form https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin to https://github.com/soheilpaper/ota_github_blink/raw/main/BlinkWithoutDelay_ino_esp8285.bin And the https://github.com/soheilpaper/ota_github_blink/blob/main/version.txtto  https://raw.githubusercontent.com/soheilpaper/ota_github_blink/main/version.txt
And now that error has been fixed as you can see below:

Although I gave some dupt about upgrading the main code by getting this output via serial port:
Device already on latest firmware version

And I would check it after some resting!.
Thanks.

Your question seems to contain its own answer, so I'm confused.  Do you understand what the Content-Length header is?

please, no picture of text ... it is unreadable ... post the actual text

@timemage, I don't know how can I get this information via the main code!

@jsotola, there is not s information via serial port output, the main part of it is the 101 error type by this output : HTTP_UPDATE_FAILD Error (-101): Server Did Not Report Size

If Device already on latest firmware version is a problem, and it's not clear that it is, it is probably the subject of a new question.

The ESP8266httpUpdate library wants to know in advance how large the file is before it starts downloading it.  It wants to know this so it can tell, before trying to download (and program), whether or not there's enough space for it. If the size of the file isn't provided by the server it will report the error that you are seeing.
The size of the file is provided by the web server by means of the Content-Length HTTP response header read by HTTPClient.  This header is received in advance of the file content.
Your main code appears to contain a correct link to raw .bin file,
#define URL_fw_Bin "https://raw.githubusercontent.com/programmer131/otaFiles/master/firmware.bin", and reports the following headers:
cache-control: max-age=300
content-security-policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
content-type: application/octet-stream
etag: "b2ecfb5dc91587c089acdaace446b0d7b00863c9f42dffb36c7983c103d3a98a"
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
x-frame-options: deny
x-xss-protection: 1; mode=block
via: 1.1 varnish (Varnish/6.0), 1.1 varnish
x-github-request-id: 8728:2B67:9AFD3:AD0EC:6008FCFF
accept-ranges: bytes
date: Thu, 21 Jan 2021 04:03:32 GMT
x-served-by: cache-bos4651-BOS
x-cache: MISS, HIT
x-cache-hits: 0, 1
x-timer: S1611201812.154162,VS0,VE1
vary: Authorization,Accept-Encoding
access-control-allow-origin: *
x-fastly-request-id: bfc9702929b91be55d7aa040465a230436918e01
expires: Thu, 21 Jan 2021 04:08:32 GMT
source-age: 20
content-length: 270016

The content-length: 270016 at the bottom shows that this should work.  But your changed code that uses #define URL_fw_Bin "https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin is to the HTML page for downloading the file, which does not report Content-length, for me anyway, but then it's the wrong URL anyway.
Regarding the "101 error", it's -101 (negative) defined here, and like they said, it is not an HTTP status code,  it is just a value used by the ESP8266httpUpdate library.

Thanks, I have changed the address of bin and TXT file by finding the download link of those files form the GitHub. And it has been working by changing the blob part of address to raw, so the bin address changed form https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin to https://github.com/soheilpaper/ota_github_blink/raw/main/BlinkWithoutDelay_ino_esp8285.bin, also I have updated the question and add more details.