text:
HIGH and LOW reversed
i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed.
If the output should be
0

it displays
-

I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:
 #define HIGHX 0x0
 #define LOWX 0x1

but this is reversed and not a good solution...
The wiring is correct like this (just GND not connected):

But if i connect the GND, the hole display isn't showing something anymore.

Possibly related: http://arduino.stackexchange.com/questions/9925/a-led-should-be-lit-when-high-why-does-mine-only-burn-with-low

With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common cathode!)
It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:
#define DISPLAY_SEGMENT_ON HIGH
#define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a common cathode display, and the transistors are NPN types. If your displays are common anode then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be PNP types. Then you will indeed have inverted logic, and you should define:
#define DISPLAY_SEGMENT_ON LOW
#define DISPLAY_DIGIT_ON LOW

reversing a boolean can be done using the ! operator.
So doing something like print(!true); will print false (or 0, I'm not sure.)
And you make a wrapper or class to abstract this specific/odd behaviour.
Like:
"setLedPin(pinnr,state){digitalWrite(pinnr,!state)} //The pins are inverted, LOW is ON, HIGH is off, this piece inverts it."
You may even make a class for these segment displays and pass to your constructor if it's an inverted or "normal" one.
Or even make two classes that implement the same interface, but for such a small difference, that shouldn't be necessary.

If your display is a common anode type, the following will happen.
Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.
If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.
So the display is probably of the wrong type for your design.


text:
Student Project Inquiry(Building a Self Balancing robot)
I am currently building a self balancing robot using an L298N motors driver,and MPU6050 using an arduino microcontroller.
I managed to control my motors movements with no issues. After I extracted the data from my MPU6050 which was easy by using MPU6050 library I faced a problem: When linking the motors movement according to MPU6050 readings, the sensor freezes and stops showing its data on the serial monitor after giving couple of readings, the motors keep moving. I even have capacitors soldered into my motors to filter the noise. I am definitely sure my sensor works perfectly because it was tested before implemented into the motors drivers circuit and code.
If anyone can give me any hints why does the MPU sensor stop giving readings please.
Thanks.

Did you ever get this resolved? I'm struggling with the same problem right now. I've tried pullup resistors which didn't fix things.

The MPU6050 is an I2C device.  By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.
This is bad - it makes the I2C bus very susceptible to noise, and motors are very noisy devices.
You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.
Also keeping power sources as separate as possible is essential.  Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.

I am using a 12V battery to power my motors and the ground of the battery is linked to the ground of my motor driver then mounted onto the arduino. So you mean i must use 3.3K resistors and connect them to the SDA and SCL pins on the MPU6050??to prevent any oscillations affecting the sensor is that right ? Thanks

This answer addresses the additional questions in Salah's comment:

I am using a 12V battery to power my motors and the ground of the battery is linked to the ground of my motor driver then mounted onto the arduino. So you mean i must use 3.3K resistors and connect them to the SDA and SCL pins on the MPU6050??to prevent any oscillations affecting the sensor is that right ?

The MPU-6050 will work ok with Vdd = 3.3 V.  More specifically, page 14 of the 1788002.pdf datasheet for MPU-6000/MPU-6050 products shows

VDD = 2.375V-3.46V, VLOGIC (MPU-6050 only) = 1.8V±5% or VDD, TA = 25°C

The wiring diagram on page 39 shows SDA and SCL being pulled up to VLOGIC (which is either 1.8 V or VDD, say 3.3 V).
One suitable choice would be to operate an 8 MHz Mega and the 6050 at 3.3 V and pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors.
Another choice would be to operate a 16 MHz Mega at 5 V, operate the 6050 at 3.3 V, pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors, and use 3.3V/5V level translations on SDA and SCL into the Mega.
Built-in pullups for I/O pins on Mega2560 and similar devices are spec'd at 20 KΩ min, 50 KΩ max, so will provide less restoring current when a device releases a pin, than will a 3.3 KΩ resistor, and thus may be less noise-resistant or operate less speedily.
The important issues for your power wiring are these:
1, Isolate the motor drive and logic drives.  They can use the same ground point but motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050.  And use decoupling capacitors as necessary.
2, Power the MPU-6050 with 3.3 V or less; pull up SDA and SCL to that level via 3.3 KΩ resistors; use level translators if the Mega operates at a different voltage than the MPU-6050.
Edit: About Grounding – For a detailed discussion, see Staying Well Grounded, an analog.com article.  For overviews, see Star Grounding at lh-electric.net, or at wikipedia, Ground Noise, Ground Bounce, and Ground (electricity) Electronics.  By “motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050” I refer to the use of separate wires for conducting ground current.  Typically, this will matter only if your motor current is high or noisy.  The idea is to have a heavy wire from the ground post of the battery to the motors, and a separate wire from the ground post of the battery to the Arduino and the MPU-6050.  Voltage across a wire changes as current in the wire changes.  Using separate ground wires, the Arduino and the MPU-6050 are less affected by ground wire voltage changes caused by motor current.

Thanks for your clarification,Which i will definitely try on this week just a little concern about "hey can use the same ground point but motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050. And use decoupling capacitors as necessary.".Do you mean my ground from the l298N driver should not be connected to arduino ??.If this is right how will the motors driver be grounded then ?Because my 12V input is connected to the motor driver from the battery and ground is connected to arduino

@Salah, see edit

Hi,Thanks for all the support guys ,Unfortunately i am still getting the same results in which the sensor still freezes and the motors continue working normally.I have added pull up resistors of 3.3k on SDA and SCL pins of the MPU6050 and still same results .I wonder if anyone has any other suggestions or if anyone knows any perfect Gyroscope sensor that i can use without facing such difficulties again .Help and support will be very much appreciated guys thanks

source: Stack Exchange

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

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

sort: votes


text:
REST API on Industrial 101 (Yún family) lags, then crashes
I have tried to set up a very simple REST API on an Arduino Industrial 101 (which is, as far as I understand, equivalent to a Yún). The Arduino is hooked up to a temperature sensor, which value is returned over the REST interface. Everything works fine at first, but over the course of a day it starts taking longer and longer for the device to respond until it completely crashes and becomes unresponsive. (At that point it also doesn't respond to ping and ssh anymore.)
On the Arduino forum there are several threads reporting similar problems (e.g. this one) but they all seem to be at least a few years old and have been solved in the mean time. (The solution reported here, for instance, has already been incorporated in my Linino version.)
If I reset the ATMega the problem persists, but if I reboot the OS it is solved for a day, so I have reason to suspect something on the Linino side is not working properly. Any help would be much appreciated, although I realize this is quite an old board.
My sketch is basically a dumbed-down version of the Bridge example:
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  BridgeClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

void process(BridgeClient client) {
  // no matter what the command is, return value on A1 sampled 4096 times

  int pin = 1;
  float val = 0;
  for (int i = 0; i < 4096; i++){
    val += float(analogRead(pin))/4096.0;
  }
  client.println(val*5.0/1024.0, 5); //multiply by 5/1024 to get volts

}

I inspected the source code of the Bridge library. It is very simple.
There are no dynamic memory allocations. It uses String in client.connect(), but your sketch doesn't use it. You could print free memory in ATmega with MemoryFree library. But I am 99% percent sure it will show no memory leak.
There is no 'background' processing in the Bridge library as suggested by other answers. All commands and data are sent to the WRT on Atheros and wait for result or acknowledge. The WRT side of the Bridge library is coded in python.
The fact that the restart of the WRT is what helps to continue, confirms that the problem is on the python side of the Bridge.
Python on WRT is very far from Arduino knowledge base, so I doubt you will get a solution here.

It's a WiFi module so there is background processing to keep the TCP or just any connection up

@Zunzullaalagaty, the WiFi processing is done in the Atheros chip not in ATmega and input is checked only in library calls like available or read .

First of all you should try changing the delay(50);. Try using millis(); instead and see if the problem still persists.
int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

If that doesn't help, try adding the yield(); method after the delay(50); / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.
My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.

I'll try this soon, but just to make sure I understand your millis() suggestion: the conditional that's used by the if, shouldn't that be (nowMillis - startMillis) >= borderMillis?

@Julius for me it always worked without the brackets. But if that doesn't work for you, go ahead

I wasn't concerned so much about the brackets, it just seems to me that if you define nowMillis as millis() on every iteration it will almost always be larger than 50, and so the if will almost always evaluate to true.

@Julius I assume yield() didn't help?

I tried, but the Scheduler library is not available for my board.

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


text:
Connecting nRF24L01 to ATmega328PU with external 8 MHz crystal problem
I am trying to fix the problem of communicating between two nRF24L01+ together, one connected to an Arduino Uno and another connected to an ATmega328PU with an 8 MHz external crystal.
The bootloader on the ATmega328PU is “Arduino Pro or Pro Mini” 3.3 V, 8 MHz.
The problem is that the nRF24L01+ on the ATmega328PU is not responding (working). I am using the RF24 library as shown in the code below.
There are several things that I have already tried:

To make sure that both nRF24L01+ modules work, I connected one to an Arduino Uno and another to an Arduino Mega and they work perfectly. So, the problem is not with the nRF modules.
I changed the external crystal of the ATmega328PU to 16 MHz and changed the bootloader to Arduino Uno; didn’t work again.

The circuit diagram is shown below:

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

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

const byte address[6] = "00001";
const int btn = 4;
int buttonState = 0;
int programState = 0;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  pinMode(btn, INPUT);
}

void loop() {
  buttonState = digitalRead(btn);
    // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
    if ((buttonState == LOW) && (programState == 0)) {
      programState = 1;
    }

    else if ((buttonState == HIGH)&& (programState == 1)) {
      const char text[] ="Hello World"; // you can customize this text to your wish
      radio.write(&text, sizeof(text));
      programState = 0;
      Serial.println("BUTTON");

      delay(1000);
  }
}

Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
const int output = 2;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
  pinMode(output,OUTPUT);
  digitalWrite(output, LOW);
  delay(1000);
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
    if (strcmp(text,"Hello World")==0) {
      Serial.println("CORRECT");
      digitalWrite(output, HIGH);
      delay(2000);
      digitalWrite(output, LOW);
      delay(2000);
    }
  }
}

Crystal is an electronics component where you need to have certain knowledge about electronic design, you can't just plug in a crystal and hoping it will work. Different crystals have different load capacitances (this will involving reading the datasheet of the crystal) and need some calculation to get the right load capacitors in order for it to work properly.

I am not sure how did you find that I put crystal resonator (oscillator) in the circuit without knowing what I am doing! Each electronic component has datasheet that everyone read it before using them. I used crystal with 22pF capacitor as stated in its datasheet and as suggested in Atmega328PU datasheet.

Well, if you search for 8MHz crystal, you will noticed that different crystal has different load capacitance. You need to read the datasheet of your crystal, not the datasheet of the MCU, then you need to do some calculation based on load capacitance datasheet told you to come out the correct capacitors for the particular crystal. BTW, If I remember correctly ATmega328 datasheet give a range of 12-22pF, depend on the crystal you are using.

The bare ATmeaga328P Fritzing diagram has an error in that only one leg of the right  hand crystal load capacitor is connected to anything.

I am assuming that your barebone Atmega328PU can run simple sketches e.g. LED blink?

@Fahad Yes it can run LED blink

Here are a couple of things you can try. Because it sounds like the hardware setup is giving you issues. Because the same code worked on a mega as you mentioned.
I am assuming you will be using arduino uno bootloader and 16mhz crystal oscillator. Add a pull-up on the reset pin. Use a 5V supply for the mcu (better if you can use a regulator). Connect 5V to pin 7 and 20 and GND to pin 8 and 22 (your image doesnt show that). Use a filtering capacitor between pin 7 and 8. Make sure crystal is connected properly with caps (image shows one pin is not connected). .....

.....Module needs 3.3V. So don't connect 5V. The pin of the modules is 5V tolerant. With that, first check if you can run the blink example, by actually blinking an LED. Then try your code.

A Power Supply the Arduino is Not! Generally but not always they fail when connecting radios to them, this is intermittent and will drive you bonkers trying to find it.

Assuming a basic test of the MCU works, say the blink sketch works at normal speed (0.5 Hz), try this format of the constructor:
RF24 radio(7, 8, 4000000); // set SPI speed to 4MHz instead of default 10MHz
The default of 10MHz maybe too high for your MCU configuration.
From https://github.com/nRF24/RF24/blob/master/COMMON_ISSUES.md
Some more things to try:
EDIT
Most Nrf24L01 problems are related to an inadequate power supply. Some 3.3 volt power supplies, say those of a Nano where the 3.3 volts is derived from the USB/UART adaptor, don't work well here. You could try adding two capacitors across the power rails at the point on the breadboard where the power for the nrf24L01 is taken. Use a 100nF ceramic and a 10 to 100uF electrolytic. You barebones atmega328p should anyway have its own decoupling capacitor as close as possible to the chip's power pins. Use a 100nF ceramic.
The link above has other trouble shooting measures.

Tried didn't work.

@Jondepoy I've added some more suggestions in the answer.


text:
DS3231 not keeping time when Arduino is turned off
I am trying to make an LED clock using an DS3231 to keep track of time, but for some reason, it's not keeping time when the Arduino is turned off.
I tried to disconnect the clock from a power source for 5 minutes, and when I powered it back on, the clock picks up the time it was displaying before powering off. I thought the battery I was using at first ran out, and so I replaced it with a new one, but the issue persists. Then I read that it could be that I am using the non-rechargeable one, and to fix this, I removed some resistors and diodes to turn off the charging function, but that also didn't fix the issue. At this point, I'm not sure if this is more on hardware or software issue that the clock is not keeping count of time when Arduino is turned off. It could be that the module I bought was the cheap knockoff, which doesn't function like it should, so I ordered a better one.
I'll the provide the snippet of codes I used:
#include <RTClib.h>
#include <Wire.h>

RTC_3231 rtc;

int hoursNow;
int minutesNow;
int secondsNow;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  rtc.begin();
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
//  rtc.adjust(DateTime(2023, 6, 31, 14, 21, 0));
}

void loop() {
  DateTime now = rtc.now();
  hoursNow = now.hour();
  minutesNow = now.minute();
  secondsNow = now.second();
  Serial.print(hoursNow);
  Serial.print(":");
  Serial.print(minutesNow);
  Serial.print(":");
  Serial.print(secondsNow);
  delay(1000);
}

Maybe I'm missing something in the code that is causing it not to do what I want it to do, but I've looked online, and most were pretty similar to the code I have.

rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

You have this line in setup that sets the date and time to the date and time that the code was compiled.  That's fine to set it once, but that time never changes.  It's the time that it was when you compiled the code.  So every time it runs, you are setting the time back to this.  The RTC keeps the time running while the Arduino is off, but as soon as it's turned on your code sets it back to what it was before.
If you remove that line, then things will work the way you want.  You might need to load a sketch once with a line like this to set the time, run it once, then load a new sketch without that line.  Or include a routine in your code to allow a user to set the time.

How would that work? Should I use a conditional statement? I've tried commenting out that particular line just as you suggested, and sure enough, the rtc is keeping real time. However, without that line, it won't update the time to match my current time.

I said it in my answer.  Load a sketch that allows you to set the time.  Run it ONCE.  Now the time is set.  Then load a NEW sketch that doesn't set the time and the RTC will still have the right time that was set by the sketch before.

You might consider using the EEPROM to manage the execution of your time-set command based on a boolean flag. Initially, write a false (or 0) to a specific address in the EEPROM to signify that the command has yet to be executed. Your program can then check this flag at startup. If the flag is false, it triggers the time-set command and subsequently updates the flag to true (or 1) in the EEPROM. This ensures that the command only runs when necessary.
#include <EEPROM.h>

// Assume the flag is stored at address 0
const int flagAddress = 0;

void setup() {
  EEPROM.begin(512); // Adjust size as needed
  bool timeSetFlag;
  EEPROM.get(flagAddress, timeSetFlag); // Read the flag

  if (!timeSetFlag) {
    // Time-set command goes here
    timeSetFlag = true; // Update flag
    EEPROM.put(flagAddress, timeSetFlag);
    EEPROM.commit(); // Save changes to EEPROM
  }
}

void loop() {
  // Main code
}

You probably never use the DS3231 before, __DATE__ and __TIME__ is the date time information when a sketch is compiled, try any Arduino sketch to print it out and see yourself. Saving to EEPROM does not address the issue.

rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

I know this is an old question, however the answers so far doesn't correctly address the issue that the OP facing.
The __DATE__, __TIME__ is the time when the compiler compiled your code, if you compiled the code yesterday, and you never change the code and never compiled the code again, the two constants will contain the date and time of yesterday when the code was compiled. It is not a real time date time that you thought it was.
What you need to do is to following these steps.

Take out the back-up battery;
Only use __DATE__ and __TIME__ once when you first time powering up the module, with the following code:

if (! rtc.isrunning()) {
    Serial.println("Setup time based on compiled date and time");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

Plug in the module and immediately upload the new sketch, the date and time should be setup the sketch complied date time, if you do it quickly, the RTC will likely setup to the time 10-15s earlier (i.e. when code was compiled).
insert the battery while the module is powered by VCC.

Next time when you plug-in the module, the if block won't be executed to reset the time as long as the back-up battery is able to power the module.


text:
wake from powerDown to check sensor then put back to sleep
I am using an Arduino Pro Mini with various sensors.  I am powering it with 2 3.7v 3400mA batteries which I recharge with a solar panel.  I take a reading from the batteries and if the  reading is above a certain number I disconnect the solar panel from the batteries using a relay.  Then when the battery reading gets below a certain number I switch back on the solar panel using the same relay.  This all works fine.
To conserve energy I want to delay the loop to the Arduino's activities for say two hours.
Right now I call lowPower(); at the end of the loop{.
void lowPower(){ is
LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

Which I continually repeat for the two hours I want.
The problem is during this two hours the high or low limit of the battery charge could be reached but I wouldn't know it.
What I would like to do is repeat
LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

for 15 minutes and then check the batteries and turn on or off the solar charger as need.
Then repeat the whole thing until two hrs is reached.
At that point I would rerun the loop{ to check all sensors etc.
I have tried the following
   void loop(){
    //code to run other sensors etc.
    if (Delay ==4) {
  delay(180000);
//check the battery to begin with
sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
//put to sleep
lowPower();
//check battery again
delay(180000);//real
sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
// put to sleep
lowPower();
//repeat for total of 2 hours.
}

 void lowPower(){
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    //repeat until 15 minutes is reached
}

This doesn't seem to work.  The Arduino waits the correct time but from what I can tell the battery is never checked.
Or should I try
    void loop(){
    everything
    if (Delay ==4) {
  delay(180000);//real
  sensorBatValue = analogRead(batteryInPin);
  delay(500);
if(chargeSwitch ==1){
 if(sensorBatValue < batteryNoCharge) {
  }
 else if(sensorBatValue > batteryNoCharge) {
     digitalWrite(10,HIGH);
   delay(1000);
   digitalWrite(10,LOW);
   chargeSwitch = 2;
  }
   }
else if(chargeSwitch ==2){
    if(sensorBatValue > batteryCharge) {
    }
    else if(sensorBatValue < batteryCharge) {
      digitalWrite(13,HIGH);
    delay(1000);
   digitalWrite(13,LOW);
   chargeSwitch = 1;
    }
  }
    //include the checking of the battery inside the lowPower
    void lowPower(){
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    etc.
    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
    //check battery after 15 min.
    delay(500);
       sensorBatValue = analogRead(batteryInPin);
    delay(500);
    if(chargeSwitch ==1){
     if(sensorBatValue < batteryNoCharge) {
     }
     else if(sensorBatValue > batteryNoCharge) {
         digitalWrite(10,HIGH);
       delay(1000);
       digitalWrite(10,LOW);
       chargeSwitch = 2;
      }
       }
    else if(chargeSwitch ==2){
        if(sensorBatValue > batteryCharge) {
       }
        else if(sensorBatValue < batteryCharge) {
          digitalWrite(13,HIGH);
        delay(1000);
       digitalWrite(13,LOW);
       chargeSwitch = 1;
        }
      }
    //then repeat to two hours
    }

Do I need to do something to wake up the Arduino and Turn on the battery sensor pin and turn back on ADC?
Not sure how to do this Please HELP.

Please don't post pseudo code (how should we know what condition is?) and indent your code properly. I'm not going to solve that puzzle...

You have to note that if you go in "power down" mode, you will not be able to get the time as millis() will return the wrong time.
If you just want 15 minutes, you can just put it inside a for loop:
for(int j=0;j<112;j++) LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

So the next instruction will be executed approximately after 15 minutes (15 * 60 / 8 = 112).
I made a similar project with a Teensy. With it you have more functions for the time. Just remember that with the power down, you will not be able to have any time function without an external time module on the Arduino.
Battery measurement schematics is also important. If you insert 2 resistors like 1M and 4M you will not be able to measure it since the measurement is done internally over multiple measurements and the current is not enough to measure it more than 1 time every 10-20ms. You have to add a capacitor to read a good value.

Try to use an external timer. I have the same problem approximatly.

I don't want to use an external timer as that adds energy costs.  There should be a way to do this.

In your function lowPower(), instead of repeating the LowPower.powerDown(), loop over that call enough time to make up the total sleep-time you need. That's the general case. For your specific case, where you need 15-minute intervals and 2-hour intervals, lowPower() should loop 113 times (15:04, since 15 *60 doesn't divide evenly by 8). In your loop() function, loop over lowPower() 8 times (to make 2 hours), and each time it returns, check your battery. When the loop over lowPower() exits, it's time to do your "every 2 hours" jobs.
Because the 8s doesn't evenly divide 15 minutes, this timing isn't exact (but neither is the watchdog timer!), so you may want to tweak things a little, such as using a 4-second sleep, which does divide evenly.
Also, when I indented your code, I found void lowPower() nested inside the loop() function. C doesn't support that. If that was unintentional, check the pairing of your braces.


text:
Battery depleting on second prototype
I am working on a project which uses two 18650 3400ma batteries to power some sensors, an Arduino Mini Pro, an 433mhz RF transmitter and an ESP8266-01. Most of the time the Arduino is in sleep mode and I only wake it up to check sensors, send info to Wi-Fi, and if needed switch on RF transmitter.
On the original prototype I turn on the Arduino ever two hours. I then turn on a capacitive proximity sensor and I check the battery level once. I next turn on a potentiometer and temperature sensor for eight seconds while reading them then turn them off.
I then read the proximity sensor. Then I turn on the ESP8266-01 for eight seconds while I post all reading on line. Then off with the ESP.
Depending on the readings from the proximity sensor I turn on the RF transmitter for about one second and then turn off the proximity sensor and put the Arduino back to sleep.
I have made a second prototype in which the coding is the same except I check the battery 50 times in quick succession for a truer average reading. I check the potentiometer ten times for a better average reading and I only wake the Arduino up every six hours instead of two.
The schematic (I'm posting) is basically the same except I have added four small capacitors to smooth out the current. I will circle them in red. Wiring on the first prototype is with .5mm copper wire while on the second prototype the traces on the pcb are .25mm 1 oz copper and some of them have been redone with 28 gauge copper wire.
My problem is that the original prototype will last for seven days before needing to be recharged while the second prototype only makes it four days. Could the capacitors be making a difference, or the sampling of the battery and potentiometer, or is it the wiring size. Is there too much resistance?
If the wiring is the problem what is a good size to have my pcb traces be? Is 2.5mm at 1oz or 2oz enough?
I know there are things I can rewrite in my code to cut times when things are on and cut energy use but I want to know why such a difference in the two prototypes.
Does anyone have any suggestions or questions?

that is a somewhat convoluted and hard to read schematic diagram ... looks more like a wiring diagram ... there is no reason why the ground net should be intertwined throughout the diagram

Can you update your question and tell us exactly what value capacitors you are using. Your question would be better suited for https://electronics.stackexchange.com, however, the schematic would require improvement. Please read: Rules and guidelines for drawing good schematics
https://electronics.stackexchange.com/questions/28251/rules-and-guidelines-for-drawing-good-schematics. Have you tried running the original code (turn on the Arduino ever two hours) on the boards that you added 4 capacitors to?

Your diagram is hard to follow. Have you measured power consumption during the sleep period? Is it different from the first prototype?

I highly doubled it's anything to do with you do while it's awake. I'm pretty sure it has to do with the current consumption during sleep. Back of the envelope calculation gives me around 20mA of sleep current. Do you have a multimeter, so you can measure the current? Modify your code so it sleeps all the time, and start measuring. Start unplugging components (if you can safely do so) to see where the current draw is.

I'm finding that schematic almost impossible to follow. Power and GND placeholders exist for a reason. Use them.

And... are you really using a massive relay to control the power to the ESP-01?!

Among all the issues that rest of the comments highlighted, you don't need to read the battery voltage for 50 times to get a better reading, your voltage divider simply has too high input impedance to the ADC for getting an accurate measurement, read the datasheet of ATmega328p.

I updated the schematic.  Hope it helps  I am recharging the batteries and will try various suggestions when they are up.  I am using the HK19 because it was inexpensive.  Since it is only on for 8 seconds every two or six hours I doubt it makes a big difference.  If it were consuming the power it would be consuming more running every 2 hours instead of every 6 hours.  The multiple sampling was suggested and has made it much more consistent.  But I will read datasheet.  I can't see how connected sensors can be problem since I power them off before sleep mode.  But you never know, will thy all.

An update.  reprogrammed to run every two hrs. with no sensors plugged in.  Power consumption went up by 25%.  Rewrote some code for ESP8266 and other things- saved some power.  Plugged in sensors individually and found something strange.  When the non-contact liquid sensor is turned on and is on it functions properly but when the Arduino goes into sleep mode it continues to consume 110mA.  If the sensor does detect water and stays off and Arduino goes to sleep power consumption is at 20-30 mA.  Checked pins and everything is off.  Can't figure out what is consuming power.  Any ideas?  Thanks

So I constructed another prototype and now the power consumption is at 30-40 mA when sleep mode whether water detected or not. I know it should be at 20mA but it could be from the voltage booster and the small wire. The next PCB board will have 2.50mm power traces and 1.50mm for all others. We'll see if there is any improvement.


text:
How can I access ESP32-CAM from outside local network other than port forwarding?
I have a ESP32-CAM AIThinker which I have programmed using Arduino IDE to stream video.  I have another board ESP8266-12e that I am using on a MQTT system that turns on and off the ESP32 as well as sending it the Name and password of my local network to sign in.  When the ESP32-CAM is on and streaming I can access it on my local network and by port forwarding in my Router I can sign in and view it from anywhere.  I have built a Mac and Android app which will access and stream the ESP32 displaying it inside the app.
I would rather NOT port forward my router.  Is there a way to add some code to the ESP32 so that I could use Apple TV, or the Android equivalent, or HomeKit, to open the port associated with the ESP32 so it can be accessed outside my local network?  Port forward is not real secure and I would like to avoid it if possible.
I have added some code to try to POST the jpg-stream to my WIX website where I added a page with an image.  However even though the website got the POST and it was valid I received a response code 403 FORBIDDEN this is the full response.
10:25:03.026 -> 403
10:25:03.026 ->
10:25:03.026 -> <title>403 Forbidden</title>
10:25:03.026 ->
10:25:03.026 ->
403 Forbidden

10:25:03.026 ->
nginx
10:25:03.026 ->
10:25:03.026 ->

Here is the code currently running on the ESP32-CAM;
#include "src/OV2640.h"
#include <WiFi.h>
#include <WebServer.h>
#include <time.h>
#include "FS.h"                // SD Card ESP32
#include "SD_MMC.h"            // SD Card ESP32
#include <WiFiClient.h>
#include <EEPROM.h>
#include <string.h>
#include <stdio.h>
//ADDED FOR POST
#include <HTTPClient.h>

int know;
#define CAMERA_MODEL_AI_THINKER
#include "camera_pins.h"
//for reconnect
unsigned long previousMillis = 0;
unsigned long interval = 30000;
//stuff to bring in string
const byte numChars = 100;
char receivedChars[numChars];
char tempChars[numChars];        // temporary array for use when parsing
// variables to hold the parsed data
char messageFromPC[numChars] = {0};
float floatFromPC = 0;
char ssidString[numChars] = {0};
float floatFromPC2 = 0;
char pskString[numChars] = {0};
char IP[numChars] = {0};
char zone[numChars] = {0};
char myChar[numChars]= {0};
char myChar2[numChars]= {0};
char myChar3[numChars]= {0};
char myChar4[numChars]= {0};
boolean newData = false;
//end stuff ti bring in string
String f;
int addr = 0;
OV2640 cam;

WebServer server(XX);

const char HEADER[] = "HTTP/1.1 200 OK\r\n" \
                      "Access-Control-Allow-Origin: *\r\n" \
                      "Content-Type: multipart/x-mixed-replace; boundary=123456789000000000000987654321\r\n";
const char BOUNDARY[] = "\r\n--123456789000000000000987654321\r\n";
const char CTNTTYPE[] = "Content-Type: image/jpeg\r\nContent-Length: ";
const int hdrLen = strlen(HEADER);
const int bdrLen = strlen(BOUNDARY);
const int cntLen = strlen(CTNTTYPE);

void handle_jpg_stream(void)
{
  char buf[32];
  int s;

  WiFiClient client = server.client();

  client.write(HEADER, hdrLen);
  client.write(BOUNDARY, bdrLen);

  while (true)
  {
    if (!client.connected()) break;
    cam.run();
    s = cam.getSize();
    client.write(CTNTTYPE, cntLen);
    sprintf( buf, "%d\r\n\r\n", s );
    client.write(buf, strlen(buf));
    client.write((char *)cam.getfb(), s);
    client.write(BOUNDARY, bdrLen);
  }
}

const char JHEADER[] = "HTTP/1.1 200 OK\r\n" \
                       "Content-disposition: inline; filename=capture.jpg\r\n" \
                       "Content-type: image/jpeg\r\n\r\n";
const int jhdLen = strlen(JHEADER);

void handle_jpg(void)
{
  WiFiClient client = server.client();

  cam.run();
  if (!client.connected()) return;

  client.write(JHEADER, jhdLen);
  client.write((char *)cam.getfb(), cam.getSize());

}

void handleNotFound()
{
  String message = "Server is running!\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  server.send(200, "text / plain", message);
}

void setup()
{

  Serial.begin(57600);
  Serial.print("setup");

delay(10000);

//RESET EEPROM COMMENT OUT
if(Serial.available()){
delay(2000);

  recvWithStartEndMarkers();

    if (newData == true) {
        strcpy(tempChars, receivedChars);
            // this temporary copy is necessary to protect the original data
            //   because strtok() used in parseData() replaces the commas with \0
        parseData();
        showParsedData();
        newData = false;
    }
}
//TO HERE
    delay(10000);
    Serial.print("network");
    Serial.print(ssidString);
    Serial.print("pass");
    Serial.print(pskString);
    Serial.print("time zone");
    Serial.print(zone);

if(ssidString[0] != '\0'){
 EEPROM.begin(512);  //Initialize EEPROM

  // write appropriate byte of the EEPROM.
  // these values will remain there when the board is
  // turned off.

 EEPROM.write(addr, 'A');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'B');    //Write character B
  addr++;                      //Increment address
  EEPROM.write(addr, 'C');    //Write character C

  //Write string to eeprom

  //RESET EEPROM SWITCH THESE TWO
 String www =  ssidString +String(",") + String(pskString) + String(",")+String(zone)+String(",");
 //String www =  newString +String(",") + String(oldString) + String(",")+String(zoneString)+String(",");
  Serial.print (www);

for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
  {
    EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
  }

  EEPROM.commit();
  //Read string from eeprom           //Increment address
  //COMMENT OUT NEXT BRACKET RESET EEPROM
}
//RESET EEPROM COMMENT OUT NEXT SECTION
else if(ssidString[0] == '\0'){
   EEPROM.begin(512);
    Serial.println("WHAT"); //Goto next line, as ESP sends some garbage when you reset it
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x00
  addr++;                      //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x01
  addr++;                      //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x02
  addr++;   //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x03

  //Read string from eeprom
  String www;
  //Here we dont know how many bytes to read it is better practice to use some terminating character
  //Lets do it manually www.circuits4you.com  total length is 20 characters
  for(int i=0;i<100;i++)
  {
    www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
  }

 Serial.println("this");
  Serial.print(www);  //Print the text on serial monitor

  www.toCharArray(myChar,100);
    char * token = strtok(myChar,",");
    char * token2 = strtok(NULL,",");
    char * token3 = strtok(NULL,",");

Serial.println("one");
 Serial.print(token);
 Serial.println("two");
 Serial.print(token2);
 Serial.println("three");
 Serial.print(token3);

strcpy(myChar2,token);
strcpy(myChar3,token2);
strcpy(myChar4,token3);

//RESET EEPROM COMMENT OUT TO HERE
}

#define SSID1 ssidString
#define PWD1 pskString

  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;

  // Frame parameters
  //  config.frame_size = FRAMESIZE_UXGA;
  config.frame_size = FRAMESIZE_VGA;
  config.jpeg_quality = 12;
  config.fb_count = 2;

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

  cam.init(config);

  IPAddress ip;

  WiFi.mode(WIFI_STA);
  if(ssidString[0] != '\0'){
   // digitalWrite(33,LOW);
  WiFi.begin(ssidString, pskString);
  Serial.println("zone");
  Serial.print(zone);
 know = atoi(zone);
  }
  else if(ssidString[0] == '\0'){
     WiFi.begin(myChar2, myChar3);
     Serial.println("myChar4");
      know = atoi(myChar4);
     Serial.print(myChar4);
  }

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(F("."));
  }
  String rrr = String("/") + String(zone) + String("/") + String ("1");
  Serial.print("rrr");
  Serial.println(rrr);
  ip = WiFi.localIP();
  Serial.println(F("WiFi connected"));
  Serial.println("");
  Serial.println(ip);
  Serial.print("Stream Link: http://");
  Serial.print(ip);
  Serial.println(rrr);//userName
  server.on(String(rrr), HTTP_GET, handle_jpg_stream);
  server.on("/jpg", HTTP_GET, handle_jpg);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("loop");

delay(1000);

}

void loop()
{

 if (WiFi.status() == WL_DISCONNECTED){

  if(ssidString[0] != '\0'){

  WiFi.begin(ssidString, pskString);
  Serial.println("zone");
  Serial.print(zone);
 know = atoi(zone);
  }
  else if(ssidString[0] == '\0'){
     WiFi.begin(myChar2, myChar3);
     Serial.println("myChar4");
      know = atoi(myChar4);
     Serial.print(myChar4);
  }
   while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(F("."));
  }}
  unsigned long currentMillis = millis();

  if((WiFi.status()!= WL_CONNECTED) & (currentMillis-previousMillis >= interval)){
    Serial.print(millis());
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
 else if (WiFi.status() == WL_CONNECTED){

//THIS IS THE CODE I ADDED TRYING TO POST VIDEO
HTTPClient http;
  http.begin ("https://www.creatucate.com/video-1");
  http.addHeader("Content-Type","image/jpeg");

  int httpResponseCode = http.POST("POSTING from ESP32");

  if(httpResponseCode>0){
    String response = http.getString();
    Serial.println(httpResponseCode);
    Serial.println(response);
  }
  else{
    Serial.print("Error on sending POST: ");
    Serial.println(httpResponseCode);
  }

//END NEW CODE
server.handleClient();

}}
    //more new stuff for string
    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        }
    }

    //============
    //RESET EEPROM COMMENT OUT ALL THE REST
    void parseData() {      // split the data into its parts

        char * strtokIndx; // this is used by strtok() as an index

        strtokIndx = strtok(tempChars,",");      // get the first part - the string
        strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

        strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
        strcpy(ssidString,strtokIndx);

        strtokIndx = strtok(NULL, ",");
        strcpy(pskString,strtokIndx);
        strtokIndx = strtok(NULL, ",");
        strcpy(zone,strtokIndx);

    }

    //============

    void showParsedData() {
        Serial.print("Message ");
        Serial.println(messageFromPC);
        Serial.print("water level ");
        Serial.println(floatFromPC);
        Serial.println(ssidString);
        Serial.print("battery level ");
        Serial.println(floatFromPC2);
        Serial.println(pskString);
        Serial.print("time zone is ");
       Serial.println(zone);

    }

If this is not the correct place for this question please advise me.  I am not even sure this can be done but I hope so.

you can push the frame data to a web-based WebSocket server, which you can connect to your app w/o port configs. You could also do that with a web-based http server for that matter; POST the image to the server, GET it from the app.

I have changed my original post to include code to POST to a http server and the response from the server.  The request contained valid data and was understood by the server, but the server is refusing action.  I am trying to post to WIX.  Could you give me some more guidance?


text:
Using Arduino UNO for uploading a sketch to the Espresso Lite v2
I am trying to use my Arduino UNO as a programming interface to load sketches on the Espresso Lite v2.
I followed the instructions to setup the Wifi network (long press gpio13 and the AP thing), but now I want to run code on it.
I uploaded this sketch to the UNO, in order to allow for serial communication(i chose method 3):

void setup(){
  pinMode(0,INPUT);
  pinMode(1,INPUT);
}
void loop(){
}

Afterwards I configured the Arduino IDE with the necessary libraries and device manager plugins for the Espresso, so I selected "Espresso Lite 2.0" as the target board and for programmer "Arduino as ISP".
This is what my tools menu looks like:

I connected the 3.3V, GND, TX (to TX) and RX (to RX) and RESET (to RST) headers from the Arduino UNO to the Espresso Lite holes. If I open the Serial Monitor I can see serial output so I think the connections are correct.
I tried to upload an empty sketch and i got these errors (verbose upload):

Sketch uses 246096 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 27588 bytes (33%) of dynamic memory, leaving 54332 bytes for local variables. Maximum is 81920 bytes.
C:\Users\Administrator\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.13/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x0 -cz 0x400000 -ca 0x00000 -cf C:\Users\ADMINI~1\AppData\Local\Temp\arduino_build_89/sketch_oct08a.ino.bin
esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    setting erase size to 0x00400000
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
An error occurred while uploading the sketch
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 45 instead of C0
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 74 instead of C0
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 0D instead of C0
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    serialport_receive_C0: 45 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed

This is the serial output after i tried to upload:

What am I doing wrong?

@gre_gor this is different: I am trying to troubleshoot the "sketch upload" function on a specific board

You can't use "Arduino as ISP" to program an ESP8266.

@gre_gor What should I select in this case? Is the fact that I can see serial output irrelevant?

Don't connect reset pins together.  Selecting "Arduino as ISP" is irrelevant in many ways.
Put the esp8266 into flashing mode by resetting it with io 0 LOW at reboot (hold button GPIO0 and click the RESET button). And then Upload from IDE. The esptool can't reset the board to flashing mode because you don't have RTS and DTS line from Uno.
Picture from manufacturers page:

This solved my issue!


text:
How to make a button work a second time in my code?
I am making a security system, and the alarm starts when the button gets pressed. If i turn the alarm off by the serial communication, and want to turn it on again using the button, it will only let the alarm go on for about 0.5 seconds. Does someone see the mistake i'm making, and can help me? Thanks in advance!
const int ledrood = 11;
const int ledgroen = 12;
const int buttonPin = 2;
int buttonState = LOW;

int statePin = LOW;
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
bool alarm = false;
int speakerPin = 8;
String Message = "";
String NMessage = "";
String Command = "";
int index = 0;
bool Bericht = true;

void PlaySong()
{
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
}
void alarmaan()
{
 alarm = true;

  digitalWrite(ledrood, HIGH);
  digitalWrite(ledgroen, LOW);
  digitalWrite(trigPin, LOW);

 }

void AlarmUit() {
  Serial.println("alarm uit");
  alarm = false;
  digitalWrite(ledgroen, HIGH);
  digitalWrite(ledrood, LOW);
  digitalWrite(trigPin, LOW);

 }
void setup() {
  pinMode(ledrood, OUTPUT);
  pinMode(ledgroen, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);
 }
String Doorsturen() //Methode om te communiceren via de serial monitor
{
 if (Serial.available() > 0)
  {
   char readChar = (char) Serial.read();
   NMessage = NMessage + readChar;
  }
  if (NMessage.startsWith("#") && NMessage.endsWith("%"))
  {
   index = NMessage.indexOf("%");
   NMessage = NMessage.substring(1, index);
   Serial.println(NMessage);
   Command = NMessage;
   NMessage = "";
   Bericht = true;
  }
  else if (NMessage.endsWith("%"))
 {
   NMessage = "";
 }
 return Command;
}
void loop() {
 Message = Doorsturen();
 int buttonState = digitalRead(buttonPin);
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = duration * 0.034 / 2;
 Serial.print("Distance: ");
 Serial.println(distance);

 if (alarm == false) {
   digitalWrite(ledgroen, HIGH);
 }

 if (Message == "alarm_off")
 {
   AlarmUit();
   Message = "";
 }
  if (Message == "1234")
  {
   AlarmUit();
   Message = "";
  }
  if (Message == "aan") {
   alarmaan();
   Message = "";
   }

  if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("fout");
   }
  }

  if (distance < 10 && alarm == true) {
   PlaySong();
  }

 if (alarm == true) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("Test");
   }

 }
}

Please create a minimal, complete, verifiable example of the problem. Strip out all the extraneous stuff, tune playing and so on, and include only the code required to demonstrate the problem. You'll probably fix it yourself in the process, and if not, someone will have an easier time helping, and hence you're more likely to get useful help.

Could you provide the serial output you are getting? How can you see that the alarm is only on for half a second?

@Gerben Serial output is 'Distance: ...' + 'alarm uit', this keeps looping. I know the alarm is on for short because i see 'alarm on' (test in this case) only once and the red led (meaning the alarm is on) only flashes once, then goes back to green led (alarm off)

The problem is that Message = ""; doesn't actually do anything, because the next time doorsturen is called, it will just load the previous command from the command variable. I'd suggest having the doorsturen function only return the command once, and not on consecutive calls.
String Doorsturen() //Methode om te communiceren via de serial monitor
{
  Command = "";
  if (Serial.available() > 0)
  {
    char readChar = (char) Serial.read();
    NMessage = NMessage + readChar;

    if (NMessage.startsWith("#") && NMessage.endsWith("%"))
    {
      index = NMessage.indexOf("%");
      NMessage = NMessage.substring(1, index);
      Serial.println(NMessage);
      Command = NMessage;
      NMessage = "";
      Bericht = true;
    }
    else if (NMessage.endsWith("%"))
    {
      NMessage = "";
    }
  }
  return Command;
}

see comment in the code
if (alarm == false) {
  if (buttonState == HIGH) {
    //here you set alarm to true
  }
}

...

if (alarm == true) { //now this if statement is true
  if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

  }

to fix do this
if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    delay(50);// this is to negate switch bounce, on release, from interfering
    buttonState = false;// add this line
    alarmaan();
    Serial.println("fout");
   }
  }

This does not seem to work, the alarm 'on' only still works for about half a second, then it switches off again...

I think I found the problem. See my edited answer.

It works! Thank you very much for the help, i really appreciate it. Have a nice day :)

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


text:
Can I use a ThunderBorg is a dual motor controller on an Arduino UNO R3
I am new to Arduino and Electronics and am thinking of making a 6 wheel drive all terrain platform similar to the MonsterBorg pi, but I want to use an Arduino instead of a Raspberry pi  to control the motors. The motors I intend to use need to be powerfull.
Any advice on what would be shield or motor controllers I should use would be a great help.

First select the motors and the batteries. Find the stall current of the motors. Then find a motor driver (or motor controller) that can handle the voltage and the stall current. The motor driver can be more expensive than the motors. Pololu has many motor drivers. A common mistake is that someone buys big motors and a tiny motor driver, for example motors with 60A stall current and a motor driver of 0.6A.

Hello Jot, Many thanks for this it has been very useful information.

Hello,
You have many possibility for drive one or more motor.

Transistor(1 motor)
L293D(2 motor backward and forward or 4 motor just forward)
L298D (like L293D but he support more Amp and Vol
L293D Adafruit shield(4 motor)
...

Here is an example for L293D:
enable PWM(0-255), inputs digital(0-1).
Motor1 : Input1, Input2, Enable1,2
Motor2 : Input3, Input4, Enable3,4
void motor1RotationDirection(int input1arg, int input2arg){
    digitaleWrite(input1, input1arg);//  LOW  |  HIGH
    digitaleWrite(input2, input2arg);//  HIGH |  LOW
                                     //Forward|Backward
}

void motor1speedRotation(int speed){
    analogWrite(enableMotor1, speed);
}    //for motor2 is the same.

I have already use l293D for project.

Many thanks for the prompt reply and the resource list. I think these will be of a great help.


text:
Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno
It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?
On the setup i just finished, I used two linear regulators: 5V -> 3.3V to power the MCP602 op-amps and MCP3201 ADC, and another one 5v -> 2.5V for the Vref.
Everyone recommends to connect the Vref from MCP3201 to Arduino's 5V but this does not apply in my case.

The green connector is connected to GND and ADC's Dout where the measured voltage fluctuates from 0.180V when i touch the sensor and his shield, to 0.6V when i'm not touching those parts.
I have no ideea if this is a normal behaviour but everything looks fine to me.
Voltage measured at the output of A4 ( MCP3201 +IN ) is 0.85V and the current Iref is 1mA(through the yellow jumper) as they recommend.
Sorry if these details are a bit off-topic but i think they are relevant to the ADC role in this setup.

It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.
If you look at the functional block diagram from the datasheet:

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD

Now it makes sense. So Dout, CLK, CS and GND should be the only pins connected to Arduino for SPI communication. CS->pin9, Dout->pin12, CLK->pin13 and GND->GND.
Is this correct?

That is correct.

Thank you so much for clarifying this aspect. I came from web development so Arduino, C++ and electronics are new and beautiful territories for me.


text:
Why Are My High and Low Values Not Updating Correctly During Successive Loops
I am attempting to capture the high and low temperature and humidity values, then clearing the LCD and displaying them on 2 successive screen updates. All is working correctly except that the variables for high and low are updating on every loop to the current sensor pin read after the "if" statements are run. Why is this occurring?
Also note that I declare the floats for the highs and lows to the unlikely value of 10000 in order to change them all to the initial pin read on the 1st loop as I didn't find a method to determine null on the initial loop.  I would appreciate any suggestions for a better method!  TIA
    #include <dht.h>
    #include <LiquidCrystal.h>

    //Low and High Temp and Humidity Variables
    float lTemp=10000;
    float hTemp=10000;
    float lHumid=10000;
    float hHumid=10000;

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    dht DHT;

    #define DHT11_PIN 7

    void setup(){
      lcd.begin(16, 2);
      Serial.begin(9600);
    }

    void loop(){
       lcd.clear();

      int chk = DHT.read11(DHT11_PIN);

      float CurrTemp = DHT.temperature * 1.8 + 32;  //Converts celsius read from DHT read to farenheit

    //Sets High and Low Temperature Readings

       if (lTemp = 10000) {
         lTemp = CurrTemp;
       }
      if (CurrTemp < lTemp) {
         lTemp = CurrTemp;
      }

      if (hTemp = 10000) {
        hTemp= CurrTemp;
      }
       if (CurrTemp > hTemp) {
        hTemp = CurrTemp;
      }

    //Sets High and Low Humidity Readings

      if (lHumid = 10000) {
        lHumid = DHT.humidity;
       }
      if (DHT.humidity < lHumid) {
        lHumid = DHT.humidity;
      }

      if (hHumid = 10000) {
        hHumid = DHT.humidity;
      }
      if (DHT.humidity > hHumid) {
        hHumid = DHT.humidity;
      }

      //Prints Current Temp and Humidity to LCD and Serial Monitor
      lcd.setCursor(0,0);
      lcd.print("Temp: ");
      lcd.print(CurrTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print(CurrTemp,1);

      Serial.println(" F");

      lcd.setCursor(0,1);

      lcd.print("Humidity: ");
      lcd.print(DHT.humidity,0);
      lcd.print("%");

      Serial.print("Humidity: ");
      Serial.print(DHT.humidity,0);
      Serial.println("%");
      Serial.println("");

      delay(10000);

      //Prints Low and High Temp to LCD and Serial Monitor
      lcd.clear();

      lcd.setCursor(0,0);
      lcd.print("L Temp: ");
      lcd.print(lTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print("Low Temp: ");
      Serial.print(lTemp,1);
      //Serial.print((char,223);
      Serial.println(" F");

      lcd.setCursor(0,1);

      lcd.print("H Temp: ");
      lcd.print(hTemp,1);
      lcd.print((char)223);
      lcd.print("F");

      Serial.print("High Temp: ");
      Serial.print(hTemp,1);
      Serial.println(" F");
      Serial.println("");

      delay(3000);

     //Prints Low and High Humidity to LCD and Serial Monitor
      lcd.clear();

      lcd.setCursor(0,0);
      lcd.print("Low Humid: ");
      lcd.print(lHumid,0);
      lcd.print("%");

      Serial.print("Low Humid: ");
      Serial.print(lHumid,0);
      Serial.println("%");

      lcd.setCursor(0,1);

      lcd.print("High Humid: ");
      lcd.print(hHumid,0);
      lcd.print("%");

      Serial.print("High Humid: ");
      Serial.print(hHumid,0);
      Serial.println("%");
      Serial.println("");

      delay(3000);

    }

you have a small logic error in your code ...  unnecessary code actually ... in if (lTemp == 10000) { set lTemp, hTemp, lHumid and hHumid  ... there is no need for if (hTemp == 10000) { or if (lHumid == 10000) { or if (hHumid == 10000) {

When programming in C, the "=" assigns a value and the "==" tests a value.  So in this line of code:
if (lTemp = 10000)

... you are actually assigning variable lTemp the value of 10000.  Consider changing the line of code to this:
if (lTemp == 10000)

... this will test if the variable lTemp is equal to 10000.

Turning up the compiler warning level File/Preferences will show a useful message pointing to this in the code.

Thanks much!    I appreciate your time and knowledge.

@Mav where you found their answers useful, you can upvote them.

Although you already have two perfectly valid answers, I will share a
trick that completely sidesteps the problem. Instead of choosing a
particular number (here, 10,000) as a “magic” value that has a special
meaning, you can instead initialize the highs and lows in a way that
ensures they will be updated on the very first iteration:

make lTemp higher than any temperature you may ever read
make hTemp lower than any temperature you may ever read

For example:
float lTemp = +INFINITY;
float hTemp = -INFINITY;

and the same of course for the humidities. This way the first iteration
does not need special handling anymore, as it becomes a regular
iteration:
if (CurrTemp < lTemp) lTemp = CurrTemp;
if (CurrTemp > hTemp) hTemp = CurrTemp;

Note that the choice of ±∞ for the min and max of an empty set of
readings is not just a dirty hack. It is actually consistent with the
mathematical notion of infimum and supremum of the empty
set.

You have this or similar a number of times:

  if (lTemp = 10000) {
     lTemp = CurrTemp;
   }

This is incorrect.  The == operator is used for comparison.
Try:

  if (lTemp == 10000) {
     lTemp = CurrTemp;
   }

The way you have it, the lTemp variable is assigned 10000 every time the statement is executed.  It's not doing the comparison as you intend.

Turning up the compiler warning level File/Preferences will show a useful message pointing to this in the code.

Thank you!  I knew that but couldn't see it.  Works great now.

@Mav If this was the answer to your question, please accept it as an answer.  Thanks.


text:
Unable to retrieve heart rate reading and send to JY-MCU Bluetooth
Hello Arduino Community,
I am encountering an issue trying to retrieve a heart rate reading from an op-amp and instrumentation amplifier and sending it via Bluetooth.  I used this website as a basis of my design:  http://www.instructables.com/id/Electrocardiograph-Heart-Rate-Monitor/?ALLSTEPS.  I would appreciate it if you could take a look at that.  Here are a couple of pictures of my design.

Here is the code that I used:
    const int  signal = 7;    // Pin connected to the filtered signal from the circuit
    unsigned long time;
    unsigned long frequency;

    // Internal variables
    int period = 2000;
    int starttime = 2000;
    int input = 0;
    int lastinput = 0;
    unsigned long death = 0;

         void setup() {
           pinMode(signal, INPUT);
           Serial.begin(9600);
         }

     void loop() {
       delay(1000);

       time = millis();
       input = digitalRead(signal);

       if ((input != lastinput)&&(input == HIGH)) {
       // If the pin state has just changed from low to high (edge detector)
       period = time - starttime; // Compute the time between the previous beat and the one that has just been detected
       starttime = time; // Define the new time reference for the next period computing
       death = time;
      }
      lastinput = input; // Save the current pin state for comparison at the next loop iteration

      if (period < 0) {
      frequency = 0;
      }
      else {
      frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
      }

      if ((time - death) > 2000) { // Detect if there is no beat after more than 2 seconds
      Serial.println("dead");
      }

      else {
      char freq[3];

      if (frequency/100 == 0) {
       freq[0] = 32; // Print a space to the first character if the frequency is below 100 bpm
      }
      else {
       freq[0] = frequency/100+48; // Sort the hundreds character and convert it in ASCII
      }
       freq[1] = (frequency/10)%10+48; // Sort the thents character and convert it in ASCII
       freq[2] = frequency%10+48; // Sort the units character and convert it in ASCII

      Serial.print(freq);
      Serial.print("alive! ");
      }

      }`

But all I'm getting as output is 'dead'.  I am really starting to lose it here since I am a complete amateur with Arduino and circuitry.  For reference, I copied the design from this image from the website (this is just an enlarged version): http://www.instructables.com/file/FVBC6TYHOW0HQ7H/?size=ORIGINAL.  I would appreciate it if anyone could provide some extra guidance.

This question (at least the wiring) may be better suited for an EE.SE post, it involves circuitry.

As far as I see, you amplified the electr. signal comming from your heart and read the coresponding voltage (hopefully cliped at 5V ;-) ) from pin seven of your arduino. But in your loop you wait for a second then check the pin 7 if it has been changed. This checking lasts a few microseconds so the probabillity that "the heart beats" at that moment is low. It would be better to use interrupts for this purpose to react on every heartbeat. Or at least: avoid any delay where possible. Another finding:  Use if (period <= 0) in your program to avoid divide by zero in the else case.

assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works.  Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.
const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

unsigned long myBeatFreq;
unsigned long myBeat;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
    pinMode(signal, INPUT);
    pinMode(2, OUTPUT);
    Serial.begin(9600);

    previousBeatTime = millis();
    myBeat = previousBeatTime;
}

void loop() {
    if ( millis()-myBeat > myBeatFreq )
    {
      digitalWrite(2, HIGH);
      myBeat=millis();
    }
    else
    {
      digitalWrite(2, LOW);
    }

    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
}

It compiles OK!

Hey, sorry, late post.  I'll see if it works for me and get back to you! Thanks!

Hey, I tried it, but it I still received "dead" as my output.  Is there something wrong with my circuitry?

I can't see your images at the moment (blocked from work), but if it says "dead" after two seconds that means signal is never going high. To be sure, connect a wire to pin 7. Start the Arduino and then connect the wire to 5V and then disconnect it repeatedly to simulate a proper heartbeat signal. If it works, you'll know the code is working and something else is wrong with your circuit or the heartbeat detector.

@imjosh Hey I just did that with a battery and found out it still says 'dead'.  I'm pretty sure it's the circuitry, but I don't know how to fix it.

I revised the answer with a circuit I have tested and slightly modified the code.  This should work for you.  To diagnose the rest of the circuit, you should draw a schematic of your circuit and post it to a new question, perhaps on the EE stack exchange.  Pictures of a breadboard are not sufficient and it will help you understand what you've actually done to have to draw it out on paper.


text:
LoRa to MQTT sensor data can't be read
I'm trying to transfer data from a temperature sensor that is located outside my WiFi area. I have chosen LoRa technology between an ESP32 equipped with an SX1278 and a TTGO Lilygo LoRa.
So far everything works fine, but as soon as I try to publish the data via Mosquitto MQTT in order to have access to the home assistant, things are get worse. I use MQTT Explorer to view the exchanges with Mosquitto. I also monitor the data on the serial port.
Everything works correctly as long as I don't publish the temperature data. But from the moment I publish it after changing it to string to switch to MQTT, I have some problems:

The serial port displays wrong values of the string  and scrolls continuously.
The data sent to MQTT are well displayed, coherent with the serial port, but remain incoherent and the number of publications increase quickly.
From a certain moment, things do not move anymore.

So I have at least two problems, and even though I looked at many examples, I have trouble understanding everything.
You will find attached the code loaded into the Lilygo receiver hoping that it will help solve my problem(s):
#include <SPI.h>
#include <LoRa.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <Streaming.h>
#include <Ticker.h>

#define OLED_SDA 21 // Attention: Les broches SDA et SCL de l'affichage OLED sont inversées sur le dessin de LilyGO et sur GitHub.
#define OLED_SCL 22
#define OLED_RST 12 // Note: Le TTGO Lora32 v2 n'utilise pas le signal reset, mais la librairie Adafruit_SSD1306, oui.
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

const int csPin = 18; // LoRa radio chip select-TTGO
const int resetPin = 23; // LoRa radio reset-TTGO
const int irqPin = 26; // change for your board; must be a hardware interrupt pin-TTGO
const int sckPin = 5; //-TTGO
const int misosPin = 19; //-TTGO
const int mosiPin = 27; //-TTGO
const char* ssid = "xxxxxx"; // Nom du wifi
const char* password = "xxxxxx"; // Mot de passe wifi

const char* mqtt_server = "xxx.xxx.x.xx"; // Adresse IP du brovker MQTT
const char* mqtt_username = "xxxxx"; // User MQTT
const char* mqtt_password = "xxxxxx"; // Password MQTT
const char* mqtt_topic = "ESP32/DS18B20/temp_piscine"; // Nom du topic MQTT envoyé par home assistant

char incoming ;
char msg[4];

WiFiClient espClient;
PubSubClient client(espClient);

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);

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

  // setup WiFi
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  //initialize OLED
  Wire.begin(OLED_SDA, OLED_SCL);
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
  }
  display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(1);
  display.setCursor(0,0);
  display.print("LORA RECEIVER ");
  display.display();

  Serial.println("LoRa Receiver");

  // override the default CS, reset, and IRQ pins (optional)
    SPI.begin(sckPin, misosPin, mosiPin, csPin);
    LoRa.setPins(csPin, resetPin, irqPin); // set CS, reset, IRQ pin

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

//Fonction connexion au wifi appelé dans le setup
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  display.setCursor(0,0);

  WiFi.begin(ssid, password);

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

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

//Fonction connexion au wifi appelé dans le setup
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
}

//Fonction connexion au serveur Mqtt  dans le loop
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void loop() {
  client.loop();
  // try to parse packet
  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    // received a packet
    Serial.print("Received packet ");
    // read and print packet
    display.clearDisplay();
    display.setCursor(0,0);
    while (LoRa.available()) {
      incoming = ((char)LoRa.read());
      //Serial.print((char) LoRa.read());
      Serial.print(incoming);
      display.print(incoming);
    }
    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
    //display.setCursor(0,0);
    display.print("' with RSSI ");
    display.println(LoRa.packetRssi());
    display.display();
  }
  if (!client.connected()) {
    reconnect();
  }
  dtostrf(incoming, 6, 2, msg);
  Serial.print (msg);
  client.publish(mqtt_topic,msg,false);
  //client.publish(mqtt_topic,dtostrf(LoRa.packetRssi(),6,2,msg),false);
}

Hi, I don't see anything obviously wrong - what are the reported RAM usage values when the program is built ? It could certainly by that you are experiencing some kind of stack overflow, or memory corruption.

Hello and thank you for your support. I finally found the problem, which was that using incoming needs to be stored in a buffer to be used as it was sent char by char. I also found the possibility to use LoRa.readString(), which allows a full string storage. I used after the function LoRaData.indexOf..., which allows to select specific parts of text with specific marks such as #, *, /, ...
Here is an example of the code used for those who could be interested.
void loop() {
  client.loop();
// try to parse packet
  int packetSize = LoRa.parsePacket();
  if (packetSize)
{
    // received a packet
    Serial.println("Received packet ");
    // read and print packet
    display.clearDisplay();
    display.setCursor(0,0);
    while (LoRa.available()) //>0 retiré
    {
      String LoRaData = LoRa.readString();
      Serial.print(LoRaData);
    // Get Text, temperature and end text : *Temp.piscine #21.56*C*
      int pos1 = LoRaData.indexOf('#');
      int pos2 = LoRaData.indexOf('*');
      Text = LoRaData.substring(0, pos1);
      temperature = LoRaData.substring(pos1 +1, pos2);
      End = LoRaData.substring(pos2+1, LoRaData.length());
    }
    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
     display.print("temperature Piscine = ");
    display.print(temperature);
    display.print("°C");
    display.print("' with RSSI ");
    display.println(LoRa.packetRssi());
    display.display();
      }
}

I still need to work on it, but it seems to work fine.

In your dtostrf(incoming, 6, 2, msg);, you want to store a float that has a minimum width of 6, with 2-digit precision, you will need an array of at leat 9 bytes(plus NULL terminator) for a value like '12345.78', you only allow 4 bytes for your msg[4]; which is definitely insufficient.
Even if your temperature is 32.45, it will still need an array of 6 for msg.


text:
Can an Arduino Uno be used to measure the frequency of a square wave of up to 600 kHz?
I am doing a project with a color sensor, where the output of the color sensor is a PWM square wave.
To measure its frequency using an Arduino Uno I am using the pulseIn() function, but I can't get the correct result.
Can an Arduino Uno measure a frequency of up to 600 kHz using the pulseIn() function?

I can't get the correct result ... what does that mean? ... what result do you get?

Do you want to measure the frequency or duty cycle?

The documentation for pulseIn states that it can be used for intervals of 10 microseconds to 3 minutes.
600 kHz frequency will have an interval of 1.6 microseconds and thus is not suitable for this application. (1 / 600000 = 0.000001666).
I have code on my web page about timers for a sketch that can measure up to 8 MHz with only 0.5% error.
This code is reproduced below:
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Whether Arduino UNO can measure the frequency upto 600 KHz if we use the pulseIn() function?

No. Not using pulseIn. However see the code above for a way of measuring such a frequency.


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

#define SD_CS 10

const int SPI_CS = 7;

ArduCAM myCAM( OV2640, SPI_CS );

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

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

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

  // initialize SPI:
  SPI.begin();

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

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

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

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

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

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

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

  // Flush the FIFO
  myCAM.flush_fifo();

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

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

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

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

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

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

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

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

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

const byte address[6] = "00001";

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

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

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

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

const byte address[6] = "00001";

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

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

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

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

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

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

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

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

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

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


text:
My brand new LCD screen doesn't display anything, even though there is no code errors?
I have a LCD screen, and I wanted to use it with a Simon Says game that I am making. I tried the tutorial on the Arduino website, but it doesn't work. Then I tried another tutorial on Adafruit. On this one, the LCD screen seemed brighter which is good, but it also doesn't work.
What it is supposed to look like:

My code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  lcd.print("Test!");
  delay(500);
  lcd.clear();
  delay(500);
}

I have verified that the wiring is correct on the official version and the Adafruit version, and my screen is brand new from the kit, so what is wrong?
Edit 1:
Let me define "doesn't work." I can turn the potentiometer, but nothing changes. I can't even see white rectangles or even a single pixel on the display. It is blank. Absolutely nothing to see other than the blacklight, which does work.
Edit 2:
Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!

Define "doesn't work". Can you adjust the contrast to see dark blocks? Can you see anything else beside the blocks?

I can't even see any dark blocks. Nothing works except for the blacklight. If I were to turn the potentiometer, nothing happens.

Turns out that the diagram was wrong. Needed to move the potentiometer 1 pin to the right, now it works!