text:
How Should I Send Data to My Laptop from Multiple Arduinos?
I'm working a project which involves reading multiple RFID tags, from multiple directions, at the same time. Because of the multiple directions, I need to use multiple antennae. Because of the multiple tags, I need to use a simultaneous RFID reader.
Unfortunately, the wiring of the simultaneous RFID reader doesn't support multiple antennae, so each antenna will need its own simultaneous RFID reader. It seems likely - although I'm waiting for confirmation on this - that each RFID reader will have to have its own Arduino as well. What's the least horrible way of sending the data those antenna-reader-Arduino combinations are gathering to a laptop?
If this makes a difference, the laptop I'm going to be sending the data to will be running Ubuntu, and I'd like to collect the data using Python's pyserial package. Once I've got the data in a Python program, we're home and dry.

Maybe SPI to get the data from the RFID  Arduinos to the main Arduino. From there simply Serial

Plug the Arduinos into a USB hub then plug the hub into your laptop. Open and read from multiple serial ports at once in your code.

An Arduino Mega might provide hardware serial channels for the RFID tag readers.

There are multiple solutions but the simplest one is probably to use Software serial, I2C, or SPI. The idea is basically the same for any of the protocols. You select one Arduino which is gonna be the master and be connected to the laptop. Than using any of those interfaces you connect the Arduino boards in to a chain. Than you can ask the slave Arduino boards if they have new data one by one. If they do they send it and the master forwards it to the laptop. In this way all the slave boards will wait until they are asked for data and thus avoid collisions of data streams.

If you have not purchased the Arduinos yet, you could consider using the ESP8266 ("Arduino-like" with embedded wifi module, and not much more expensive, depending on the project size). Then you use your laptop as a server, and each ESP8266 sends the data via wifi to the laptop.
Arduino as a client (via wifi): https://www.arduino.cc/en/Reference/WiFiClient

Here is an example of a project where I have done that although I used arduino with ethernet shield, the principle is the same. Also I used arduino as a REST server (instead of as a client). This meant that the server (PC) polls the Arduinos for data. But  this can be reversed using arduino as the client. https://www.instructables.com/id/Household-Environmental-Monitor-IoT-Solution/


text:
Designing RGB leds
I am interested in creating a string of ~80 RGB LEDs run on an Arduino Uno. Each LED is to have its own on/off timing and color and the distance from one LED to the next about 4-5 feet.
Since I want to program each LED separately can I do that with strings like the Adafruit Pixels (https://www.adafruit.com/product/322) or do I have to set it up with separate RGB LEDs and daisy chain them?
Thanks for your help with this.

Because of the distances, I'm tempted to suggest going with DotsStars instead of NeoPixels. Those have a separate clock line, so you could run them slower, if there's too much interference.

Since you'd have to change the wires anyway, https://www.adafruit.com/product/4356 might be better than the ones you linked.

Good recommendation Gerben. I will definitely consider that and would probably be cheaper then the ones I was looking at given the fact that I need 80 ish.

do I have to set it up with separate RGB LEDs and daisy chain them?

That's exactly, what the string of Neopixels, that you linked, is: Separate WS2801 RGB LED chips, which are daisy chained together. Since the distance of the LEDs on the string is not 4-5 feet, you cannot use the string directly.
You can either cut the string and extent the cables, as you need to. Or you can buy single LEDs and use completely your own cables. That's up to you; technically it is completely the same.
But since 80 LEDs, each 4 feet apart, will give you about 100m/330feet, you get a problem with the resistance of the wire. First about power supply:
You whole strip would need up to 4.8A of power, with every pixel at full white. You need to transport that current from your source, down to the very last LED. Make sure, that the used wire has very low resistance and is rated for such a current. If the resistance is to high, you will loose voltage over every meter of the cable and the last LEDs might be off color or not working.
I think the signal lines will be fine despite the distance, since every LED outputs them again to the next LED, so the signal should be kind of refined on every LED (though I don't know, how the WS2801 chips work internally).

Re “I think [...] the signal should be kind of refined on every LED”: this has indeed been observed.

It wasn't clear to me that that is what the neopixels do. That is super! Can you point me to code that illustrates how to manage each pixel separately? The only examples I have seen  create overall patterns. I want one pattern that loops per pixel and separate from the group. Thanks also for the power and signal comments they are good to bear in mind.

@ChinaBlue The code for iterating over each pixel depends on the library used. I've had success using FastLED with a Neopixel WS2811. Here's a code example setting each LED in a loop.

source: Stack Exchange

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

sort: votes


text:
How to send sms message on specific area using Longitude and Latitude
Good day everyone! what code should i used for sending sms message depends on the area. the things that i used in my protoype i have MPU6050 accelometer, SIM800C GSM MODULE, NEO6MV2 GPS MODULE. So the flow is if the Accelometer triggred the GSM module will get the GPS location only if the area is on the target location 1 so it will only send to the recepient 1. But if its triggred in another location, Targetlocation2 it will only send on receipient 2.
My question is how to used the longitude and latitude data to get the exact data of what my gps module gets? so that i can use that data to send sms message on specific place or area thank a lot
also i used TINYGPS.H LIBRARY thank you!

You get location information from GPS, and you have some target locations stored. You check, which of the targets is closest and send an SMS to the corresponding phone. And what exactly is your problem in detail?  If you ask "How to do it?" rather show what you tried and why you are not satisfied with the result. And split the task into a couple of smaller ones :)

why are you asking again? ... https://arduino.stackexchange.com/questions/72626/how-to-send-sms-message-depends-on-the-gps-locatiom

Thank you DataFiddler i'm just asking for a format code use to set longitude and latitude, Is it float distance_between (float Lat1, float Lon1, float Lat2, float Lon2)? and how to set this for if statement? to send the sms if my location area is on the target Lat1 Lon1 thank you

sorry jsotola im just despirate sorry for my bad  english

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


text:
How to use tinygps.h library to measure distance? using NEO6mv2
any reference site for the format code for tinygps.h to measure distance?
or any codes for tinygps.h for measuring distance i'm just a beginner in learning arduino thank you

Do you know Pythagoras's theorem?

You don't use the tinygps.h library to measure distance. You use the tinygps.h library to get coordinates. Over short distances those coordinates (longitude and latitude) can be equated to x,y coordinates on a plane (over greater distance - hundreds or thousands of miles - it gets a whole lot more complex).
Two sets of x,y coordinates form a line. A line is one side of a right-angled triangle (the hypotenuse).
Pythagoras (remember him from math class? That rubbish you thought you'd never need? Well, now you do...) says that the square of the hypotenuse is equal to the sum of the squares of the other two sides.
You know the other two sides - they're just the difference between the two x coordinates and the two y coordinates.
We're not going to write the code for you, and Google is probably better at finding websites with example code on than we are.

thanks man appreciate it :D
by the way can i use this format code?
float X = ((long2 - long1) * 24901 * cos(lat1)) / 360.0
float Y = ((lat2 - lat1) * 24860) / 360.0
float X2 = X * X;
float Y2 = Y * Y;
float Distance = sqrt(X2 + Y2);
also how to define to my arduino that i set Lon1 Lat1 is equal to my desired gps coordinates should i used long or const or float sorry for many question


text:
Which board to use for wireless communication of small packages?
I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).
While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.
The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.
What would be the best board for a project like this / are there other boards that are well-suited for a project like this?
Thanks!

i would consider ESP-NOW. It's under-appreciated imho for what it can do, but it's taken my smart home to a new level with cheap battery-powered "infinite standby"  sensors and actuators.

WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.
On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.
Also, there are ZigBee module. They developed for home automation specially.


text:
Stepper motor is only moving one step at a time with an IR sensor
I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

Arduino Mega (ATMega 2560)
(2) NEMA 17 stepper motor/ A4988
Digital IR Sensor Module

#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}

I think the run function must be called repeatedly until you reach the position and not just once

As chrisl said, you need to call run repeatedly.
I tried to rewrite the code you've given, though I'm not entirely sure what it is you try to achieve.
void loop()
{
  stepper.run();  // Actually makes stepper move
  stepper2.run();

  int curr_state = digitalRead(pin_ir_in);
  if (curr_state != prev_state)
  {
    if (curr_state == 0) // Motion sensor activated
    {
      stepper.moveTo(100);
      stepper.setMaxSpeed(200);
      stepper.setAcceleration(100);
      stepper2.moveTo(100);
      stepper2.setMaxSpeed(200);
      stepper2.setAcceleration(100);
    }
    prev_state = curr_state;
  }
}


text:
Using Arduino Sensors with STM32 based NUCLEO boards
Right now I'm programming an Arduino Uno Rev3, I'm using a Sensor Shield v5 (image at the bottom) to be able to have several Ultrasonic sensors and Servos. Right now I'm thinking about getting a Nucleo board, due to the better CPU, more memory and more flash. Although on the page, Arduino compatibility is listed, I don't quite understand what it means in my case. I understand that it has the same pins as the Arduino, but can I be sure that my Sensor Shield (v5) will work?
I found too little resources about this, one concern was that Arduino and Nucleo board have separate needs (3V or 5V), but the Sensor Shield can get power separately. (Lower right corner.)
Also, there is a Bluetooth shield for the Nucleo, I will buy it if I buy the Nucleo board, how can I know that it will work with the Sensor Shield? Or how can I know how many shields can I connect to a Nucleo or an Arduino?

The "sensor shield" is nothing more than a replacement for wires. You really don't need it. It's just lazy.

buy Arduino Mega if you need more flash and SRAM. what for do you need so much faster CPU? with Mega you will not have problems with 5 V to 3.3 V logic levels.

the support for STM32F4 in the STM32 Arduino core is very new.

Wow! Thanks for the fast reply.
So with Sensor Shield, I wouldn't have problems with 3.3/5V as I mentioned, because it can use a separate power supply.
I wasn't aware of theat Sensor Shield is lazy, I got it with my Arduino and it helped me a lot, also I think I would need a breadboard for 7 sensor without it, so it stays.
I just don't understand how many shields I can get to Arduino/STM32 because I don't quite understand how I can read values from them if I connect (for example) a Bluetooth Shield and several other shield.


text:
status whether the switch is connected to arduino or not?
I made a small circuit in which a push-button is connected to Arduino via a pulldown resistor. So, whenever it is pressed it connects to 5V otherwise pulled down to the ground. this is working fine but I wanted to know is there any way to detect whether the push-button is connected to the circuit or not? In case if push-button disconnects from the circuit, how to detect it?

resistor across the switch ... use analog input

no ... it would produce a voltage level that is dependent on the state of the switch

another way would be to remove the pulldown resistor and connect the switch between two data pins

A push-button that is not being pushed is electrically equivalent to no push-button at all. Your Arduino will never be able to tell the difference.

Create a dpdt switch that uses two resistors to give different values for the two positions and use an analog pin.  Still you have the possibility that the floating input just accidentally reads the same as one of those values so it isn’t very reliable.

@Delta_G you could add a pull-up/pull-down on the Arduino pin, so it's never really floating.

No, not the switch I described.  If you put a pull-up or pull down you wouldn’t be able to tell the difference between not-pressed and disconnected.  The switch I’m describing would have two different analog readings for made or not made.  It would never read a simple high or low.  If you put a pull-up or pull down on the switch I described it wouldn’t work.  What I described requires the pin to float if disconnected so you can tell it’s been unplugged.

The simplest way, as @jsotola has said, is to put a resistor across the terminals of the SPST push-button and read the voltage using an ADC input of the MCU.
However, the resistor needs to be bonded to the push-button (or inside the push-button housing) to ensure that when, for example, a vandal rips the push-button out of your switchboard, the resistor is certain to go with it so that the MCU can tell the difference between HIGH, LOW, and MISSING as @EdgarBonet pointed out. You also need to consider the continuous current draw of the extra resistor for low power/battery devices. You could increase the resistor values, but that tends towards weak pullup/pulldown. If you increase the value of only the extra resistor, it shifts the output voltage closer to the rail voltage reducing the margin for error.

Figure 1 – SPST Push-Button AWOL Detector.
Perhaps a better, but more expensive way, is to use a SPDT push-button. This push-button requires no modification, but is more expensive than a SPDT push-button and requires an extra wire and resistor. This circuit draws less continuous current and has stronger pullup/pulldown.

Figure 2 – SPDT Push-Button AWOL Detector.


text:
Arduino with ESP8266 via serial pass through
I bought an Arduino Mega 2650 alongside a couple of ESP8266 chips hoping to make a wireless project take off.
Using the basic serial passthrough code
void setup() {
    Serial.begin(9600);
    Serial1.begin(115200);
    Serial.write("Starting");
}

void loop() {
    if (Serial.available()) {      // If anything comes in Serial (USB),
       Serial1.write(Serial.read());   // read it and send it out Serial1 (pins 0 & 1)
    }

    if (Serial1.available()) {     // If anything comes in Serial1 (pins 0 & 1)
       Serial.write(Serial1.read());   // read it and send it out Serial (USB)
    }
}

updated to use a 115200 baud rate which it seems my version of the 8266 is programmed to use, I encounter this problem when trying to issue it commands:
Starting
AT

ERROR

Looking around I found that this could be caused by the chip not getting enough power. So I hooked it up to a small power breakout board
 with a small 12 power supply I used to have connected to something else. After doing that all it does is spit out question marks even when I dont send anything. Weird part is the TX pin on the arduino thats going crazy? As if I am sending it to myself without a prompt from the ESP board. This only happens when I'm connected to that breakout supply.

Other oddity:
If I have all my wires except for VCC/CH_PD connected everything is fine, but the second I connect them to that power supply everything goes crazy and my TX pin starts flashing up a storm (can it be a voltage issue that also transfers to my Arduino board as well?)

set Both NL & CR line ending in one of the Serial Monitor comboboxes

Many questions are open here: Are you sure the baud rate of the ESP8266 is 115200? Show us the code or firmware running on it please? Where are the voltage divider resistors to protect the ESP8266 receiving 5V from the Arduino Mega's UART TX line? What does is show when you read the ESP8266 serial to 74880, which is the baud rate of the first-stage bootloader?

You are also making the mistake of reading from serial at 115200 baud and sending it to the other at a much lower 9600 baud. When the ESP8266 will send a stream of data and you write it byte-wise to the 9600 serial, it takes too much time for writing it, and you will loose incoming data. You must set the serial you're outputting to at least as high or higher than its input.

@MaximilianGerhardt From power supply to VCC and from Arduino TX to ESP RX I have a 1/2kohm voltage divider to turn 5v -> ~3.3v. I've tried every baud rate now, and the only one that gave me anything other than question marks was 115200. I havent touched the code or firmware, I cant even establish a serial connection to start looking into that.

@Juraj Yeah the blue light isn't even active on the ESP module anymore so its like is not getting a signal

it replays with ERROR, so it is alive. do you have the line ending characters set?

@Juraj It will now print ok in response to the AT command but any other command from this list returns an error https://nurdspace.nl/ESP8266#AT_Commands

Was using the wrong commands, please write an answer and I will mark it as correct :)

But you didnt get marked as the answer for that one either, it would be good to have one marked as solved (and without -2 votes)

@Juraj - The OP did not use the @ symbol before your username, so you may not have seen their comment. They said "Was using the wrong commands, please write an answer and I will mark it as correct :)".

@VE7JRO, OP meant line endings not commands so I linked it to duplicate


text:
Controlling VFD with ModBus RTU via RS485 and Arduino
I am attempting to control a Folinn VFD (Manual: Manual) with an Arduino Uno via a MAX485 module such as this.

Pins for MAX485:

DI > D8
DE & RE > D10
RO > D11

VFD settings:

F00.01 set to 2
F00.06 set to 9
F13.00 set to 1
F13.01 set to 5
F13.02 set to 3

At this stage I am attempting a very simple code just to turn the VFD on:
/*

   ModBus RTU control VFD

   Address               : 01H  (is the address of the VFD)
   Function              : 06H  (write function code)
   Starting data address : 20H
                         : 00H  (2000H  is the address of control command)
   Data(2Byte)           : 00H
                         : 01H  (0001H is forward command)
   CRC CHK Low           : 43H
   CRC CHK High          : CAH

*/

#include <SoftwareSerial.h>

#define SSerialRX        11  //Serial Receive pin
#define SSerialTX        8  //Serial Transmit pin
#define SSerialTxControl 10   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

// From manual vfd Forward command = 01H 06H 2000H 0001H 43CAH

byte request1[] = {0x01, 0x06, 0x20, 0x00, 0x00, 0x01, 0x43, 0xCA};

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  // digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);

}
void loop()
{
    digitalWrite(SSerialTxControl, RS485Transmit);
    RS485Serial.write(request1, sizeof(request1));

}

With the MAX485 connected to the correct ports (S+ and S-) on the VFD, this current setup receives no response is someone able to spot where I am going wrong? I have taken the values for CRC CHK Low & High from a different example, is this the issue?
Have also tried setting F00.01 to an unlisted '3' setting that I have seen pop up in other discussions but this made no difference. Any advice would be much appreciated, let me know if I can supply further details.
(I chose this method based on this example

User on other site (https://forum.arduino.cc/index.php?topic=663365.0) Might have default run conditons on VFD set differently or by hardware.
Check the VFD is listening to the ModBus Comms.  OK.
Check VFD is 'Ready to Run'. Hardwire e-stop or 'Active' inputs.
F00.22 Check Binding source
F00.05 Check Set min Hz
F01.01 Check Set min Hz
Give drive MIN Hz So when received RUN signal has default speed to goto.
Are you doing a Hard Reset on the UNO every time you want to send the Modbus string? Code runs once, does not actively transmit.

Hi Spannerz, thanks for the suggestion
I have set:

F00.01 Command source selection - 2:RS 485 communication control
F00.06 Frequency A command selection - 9:RS 485 Communication

Is there another setting I need to look at to be sure it is listening to ModBus?

OK.   F00.06 is the frequency setpoint.   Sure you can send it a number of the speed you want to run at, but are you?  Almost suggest setting to 1:Keypad value, retentive on power failure.        RUN signal is different to SPEED setpoint.

I'll be back tomorrow.   Cheers.

That makes a lot of sense. Will try setting the frequency via keypad and just sending the run command.
Will give it a crack in the morning and let you know how it goes.

Hi Spannerz, thanks for the additional information.
I have been hard resetting the UNO so I think the problem lies in one of the settings you have mentioned.
Flat out this morning but will try adjusting these settings later today and report back

Hi Spannerz, have still not been getting the VFD to operate via the Arduino even with F00.06 set to keypad. What settings should I be inputting for F00.22? I think this may be the issue.

I'd try = 1.   Making sure keypad value is the running frequency the drive is referencing.

Couldn't get it going through Modbus unfortunately.
But managed to get Start/Stop & Frequency control using the digital inputs with the Arduino controlling relays. Bit more of a clumsy work around but will work for the needs of this project.
Thanks so much for your advice.


text:
How to multitask with interrupts on Arduino?
I am trying to build a cashless RFID based water dispensing unit. I am using Arduino mega 2560, PN532, relay, flow sensor. Here is the flow of the program in I2C mode; I have two functions, one to scan the card and the other for the flow sensor. As soon as the RFID card is placed on the NFC module, data stored in the card (i.e, date of expiry and balance amount) is obtained and is checked for validity. If the card is valid, then the relay is turned on. A flow sensor measures the quantity of water dispensed. As soon as the limit of 1000 ml is reached, the relay is turned off. The whole process happens serially, when the card scanning is complete, it waits for the entire 1000 ml of water to be dispensed. What I want to achieve is after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin. If the first relay is busy, second relay has to be assigned to it. Can I achieve this using Arduino Mega? How do I manipulate the atmega to perform all these tasks at once?

BlinkWithoutDelay from the Arduino IDE samples is your friend.

Here's a really thorough write-up I did on how to do bare metal (like Arduino usually is) cooperative multi-tasking: https://stackoverflow.com/a/50032992/4561887

You do not necessarily need a build a "multitask with interrupts on Arduino".  Instead consider using a state machine.  First define the problem by drawing a state diagram:

Consider all state you wish to be in.  Including your example "...after one card is scanned, 1st relay with the flow sensor has to be turned on and simultaneously the scanning of the second card has to begin...".  Once you have defined all states and the rules that need to be tested for before jumping to a new state you can start programming your state machine.
There are plenty of tutorials including this one on the web specifically for people who want to implement a state machine on an Arduino.  But, briefly, you will want to create a loop that will execute with out stopping over and over again as fast as possible.  This loop will (1) know what the current state is and (2) will repeatedly test to find out if the program can change to any of the possible next states. When you change states is when, if you need to, you perform tasks such at turning the water on or off.
If you forsake the state machine and only use interrupts, testing the code tends to be very difficult.  As controlling exactly when an interrupt occurs relative to other interrupts and the state of the processor becomes problematic and nearly impossible to reliably repeat.  This is why the state machine is suggested. Interrupts can still detect external events. But by using a state machine the program is in control of what happens next. Instead of leaving it up to luck.

I tried implementing the state machine for my program. It helped me get to the solution. Thanks a lot. Cheers!

You are welcome.  Please choose the best answer to your question so that others with a similar problem can find your question and an appropriate solution.  Comment if nether solution is the best answer - telling us how to edit the answer to make the overall question & answer better.

As you mentioned, I designed a state diagram. Hence, it was clear to me in which state each component had to be at a particular time. I ensured that the program did not have to wait for anything to continue. I got the solution by simply manipulating the interrupts used by the flow sensors to make them function almost at the same time. However, I did not entirely implement the state machine program on my arduino. Designing the state diagram helped me get to the solution.

Glad the answer helped.  Now I have a question for you:  Since it sounds like you implemented your solution using only interrupts, how easy was it to test?  And are you sure you tested every situation?  Are you willing to ride a rocket ship or drive a car running your code?  I'm trapping you.  The answer?  It is very hard to test all situations when interrupts are involved.  That is why I suggested the state machine.  You can still detect situations using interrupts.  But using a state machine means you are in control of what happens when.  Instead of leaving it up to luck.

Thanks @st2000. You do have a valid point. I will try to implement it using state machines to have control over the program.

There is no real multitask on Arduinos. The Arduino can only do one thing at a time.
But, you can do things sequentially, one after another, so fast, that a human will think, that it happens simultaneously. This involves a non-blocking coding style, which needs no interrupts

Every delay in your code (at least the long onces) need to be removed. if you want to do timed things, you should use the coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
Also no function should wait for something to happen. Think of a function, that waits for a command from the serial interface. Blocking code would wait indefinitely, until a command was received, preventing any other code from execute. Instead the function could exit fast, when there is currently no command to process, leaving time for the other code to execute.

The whole principle relies on the loop() function executing very fast, so that your code can still be reactive. This works for most of the situations. Only sometimes you need to react that fast, that you need interrupts. Your usecase doesn't seem to belong to the interrupt needed faction.

Thank you for helping me out! I removed all the delays in my program and got the code working just right.

@Riya Please mark one answer that fits you most. This will help others seeking for help on similar problems.


text:
Question about Buttons and INPUT_PULLUP
I am ok as a developer but have very little experience if it comes to electronics/hardware. I am always too cautious and have the fear that I could wreck something with the wrong wiring. This question may sound silly to you, but I couldn't find the answer anywhere. It's probably very easy to answer.
I'd like to integrate a Push Button into my Arduino Uno Setup. The only other connections are 3 wires leading to an WS2811b Strip, standard setup. From what I have found out online, I should basically connect Digital Pin 2 (or any other) to one side/connector of the Button and GND to the other side, no Resistor, and then set the Pin Mode to INPUT_PULLUP:
pinMode(BUTTON_PIN, INPUT_PULLUP);

This makes sense. But all tutorials I'v seen use these small black Push Buttons looking like the Reset Switch. I needed something bigger, so I bought these:
https://de.aliexpress.com/item/4001095221773.html
Now the question: Should I connect these Buttons to my Arduino in the same way? Or could it be that there is some difference from one type of Push Button to the other that I have not thought about (that could probably ruin things)?
Thanks a lot!

Hello fellow programmer. I suggest you to google word Tinkercad. :) You are welcome.

Aha. Thanks a lot :-)

Yes, just connect them in the same way.
It doesn't matter what type of button you use. You could even use a wire and let it touch ground when you want a "press". That also would work correctly. The only requirement is, that the part has to make a direct connection between the digital input pin and ground when pressed and it has to release that connection when no longer pressed.

I'm sorry to hear you had that experience with that other group. Sometimes people forget that they are there to help people who ask questions, not tell them how stupid the question is.

I am very cautious when it comes to electricity, so I need to ask a lot of things and make sure nothing bad will happen. But a lot of users in technical user groups seem to view beginners as cannon fodder and use them to show off and boast their ego. The question will not be answered, of course.

You can connect them with no external pull up resistors. If those switch wires are more than a few inches long or you are in an electrical noisy environment I would suggest an external pull up as well as the wires will act as an antenna. The internal pull ups are week so electrical noise can easily overpower them. The buttons you selected will probably oxidize over time and fail as the oxide is an insulator. To prevent that use pull up resistors that will force at least 1mA through the contacts (old school). We use to be sure we had some current through the switch when it was not a dry contact switch (those were expensive). Rule of thumb was at least 1mA more was good. This also helped reduce noise in the switch lines. Long term this is much more effective then sealing the switch.

Thanks for this information. What can be done to prevend oxidizing? Will hot glue on the back be a good idea once the soldering is done?

https://en.wikipedia.org/wiki/Wetting_current


text:
Difficulty getting Arduino data via puTTY
I am working on a project with a simple particulate matter sensor hooked up to an Arduino Uno. I'm using puTTY to log the sensor's output. My Arduino program converts the data to a numerical format, then prints it to the serial monitor every 30 to 31 seconds. I want to use puTTY to log this data to a file over a period of weeks. My problem now is that when I run it using puTTY, it stops after about 30-90 mins and "Fatal error: error reading from serial device" pops up. The wires connecting my sensor to the Arduino, and the USB cable connecting the Arduino to my computer all appear fine. Here is the code on the Arduino:
int pin = 8;
unsigned long duration;
unsigned long starttime;
unsigned long sampletime_ms = 30000;
unsigned long lowpulseoccupancy = 0;
float ratio = 0;
float concentration = 0;

void setup() {
  Serial.begin(9600);
  pinMode(8,INPUT);
  starttime = millis();
  Serial.print("Data is collected roughly every ");
  Serial.print(sampletime_ms/1000);
  Serial.println(" seconds.");
}

void loop() {
  duration = pulseIn(pin, LOW);
  lowpulseoccupancy = lowpulseoccupancy+duration;
  if ((millis()-starttime) >= sampletime_ms)
  {
    ratio = lowpulseoccupancy/(sampletime_ms);
    concentration = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62;
    Serial.print("Concentration = ");
    Serial.print(concentration);
    Serial.print(" pcs/0.01cf at ");
    Serial.print(millis()/1000);
    Serial.println(" seconds.");
    lowpulseoccupancy = 0;
    starttime = millis();
  }
}

I'm using the shinyei PPD42 particulate matter sensor.
Can anyone tell me what's going on, and if there's any sort of workaround I can use? I don't necessarily need to use puTTY, I just need to log the serial output from my Arduino.
Thanks!

Genuine Uno or a Chinese clone with a CH340G USB chip?

It's a genuine Uno board.

Does this happen if you use Arduino Serial Monitor only?


text:
How to connect two LED strips (APA102/SK9822) to Arduino UNO?
So what I am trying to do is to connect two SK9822 LED strips to Arduino UNO.
I am a bit confused about how to properly set this up so I can individualy control any led. So obviously 5V should go to 5V and GND to GND, but what about the CLOCK and the DATA pin.
According to the tutorials and stuff I found here, CLOCK pin needs to be connected to pin 13 and DATA to pin 10, but they only use one strip... so what I am trying to ask is can LED strips share pins? Can they be connected to the same CLOCK pin and different DATA pins or how can i set this up to use the minimum amount of pins?
I was planning on using FastLED library, where it looks like you can specify which pin is DATA and which is CLOCK,
FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN>(leds, NUM_LEDS);

Is this because different boards have different CLK and MOSI pins or can i use any pin and set it as CLOCK or DATA? This is probably obvious but I am new to this and this is my first project.

Did you give it a try? This FastLED Wiki page gives you some suggestions for Arduino connectivity. Tip: An Arduino Uno uses the 328P MCU. But the wiki page implies that any(?) pins can be used by FastLED. If h/w SPI support is available on the pins it will use it automatically (implying that if h/w support is not available, it will drive them via s/w).

I don't know about SK9822 LED strips, however the other type of led strips can be used with every pin; this is to support multiple LED strips.
Because every LED strip has its own CLK input (wire), it would be inconvenient to share them... I'm not sure if it is possible practically, because the timing is critical and if you have just one 'master' CLK signal than the data signals for all LED strips should be sent in time. Also writing the library would be more difficult, since there is a relation between a (shared) CLK signal and other data lines.

For minimum pins, daisychain them together, with the clock and data outputs on the tail end of the first strip connecting to the clock and data inputs on the second strip.
https://www.pololu.com/product/3089 says:

Multiple LED strips can be chained together by connecting input
connectors to output connectors. When strips are chained this way,
they can be controlled and powered as one continuous strip.


text:
How to compile Arduino Framework with GNU
I'm wondering if it's possible to use GNU (g++) to compile a arduino Sketch.
I wanna be able to unit test my code with catch2.
g++ -std=c++11 <filename> works well with catch2, but I obviously does not recognize Arduino's framework (Strings, Serial etc).
What I think is, maybe if I use Arduino's compiler [ which is compatible with -std=c++11 I would be able to do run the catch2 with the Arduino framework.
Does anyone knows where to find Arduino's compiler? or how to make GNU accept Arduino's framework?

Never heard of "catch2". But the  "arduino" compiler is g++. avr-g++ to be precise. If you're using Linux you can install it as a system package if you like.

But if you're asking if you can compile Arduino code to run natively on a PC, no, not without using a core and board written specifically for the PC. You might look at Wiring-Pi as a starting point for that.

https://forum.arduino.cc/index.php?topic=662682.msg4637993#msg4637993

Some keywords that may help: "arduino-builder", "Sudar Arduino Makefile", "simavr".


text:
MQTT PubSubClient connection problem with ESP32
I am experiencing some problems with string in Arduino application with ESP32.
I don't understand why this code works:
mqtt.setServer ("m20.cloudmqtt.com", port);  //is OK
and this does not work does not connect
String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strSBM.c_str (), port);  //no OK
I use library PubSubClient 2.7
Any of you can help me
Many thanks

When you set the server from a C string it doesn't copy the string - it just retains a pointer to it:
PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
    this->domain = domain;
    this->port = port;
    return *this;
}

If the string it's pointing to goes out of scope (it's a local variable and the function finishes) the data for the string will be invalidated and lost.
It is really intended to work with string literals and global constant variables that never change.
If this is the one and only time that you ever set the server you could get away with using strdup() to duplicate the string data on the heap, but without direct access to the domain member variable of the PubSubClient class you have no way to free() the memory again should you ever wish to change the server.
String strSBM = "m20.cloudmqtt.com";
mqtt.setServer (strdup(strSBM.c_str()), port);

To make it so you can free the value you need to keep track of it separately:
static char *temp = NULL;
if (temp != NULL) {
    free(temp);
    temp = NULL;
}
temp = strdup(strSBM.c_str());
mqtt.setServer(temp, port);

same problem for the port number
what function should i use for the port?
Thanks for your help

No, not the same problem for the port number - that's just a number and gets copied. The problem only exists for the server name because that is a pointer.

Ok now everything seems to work with client.setServer (strdup (strSBM.c_str ()), (int) strPSBM.toInt ());

As long as you only ever do that once it's fine - if you do it more than once you have created a memory leak and you will crash after a while. Why exactly do you want the server name in a String though?

Ohh, then this is not good for me, because in my project I save the name of the server and number port to an external EEPROM and I have the possibility to change the configuration parameters. So having static parameters is not good. Do you have any suggestions?

Create a global char array to store the data in. Read it from the EEPROM into that char array, then pass that to the setServer as is.  Any time you change the contents of that char array the PubSubClient library will instantly see the new data - all that is left is then to connect again.

Nice idea but my project is too complicated for this change.
What do you think of this lease
char * temp;
free(temp);
temp = strdup(strSBM.c_str ());
client.setServer (temp, 15534);
so that each time I change the parameters of the empty server with free() ??? an idea help help help

Sure, that could work - as long as temp is global or static so it remains all the time. static char *temp = NULL; if (temp != NULL) { free(temp); temp = NULL; } temp = strdup(strSBM.c_str()); - It's important to check that temp actually has something allocated to it before trying to free it...


text:
Arduino PWM 1kHz and 10-bit resolution
As the title says, I need 1khz frequency signal with 10-bit resolution. But I am not good with uControllers and complicated programming.
I need a simple code for this task.
I tried using this Interactive PWM from arduinoslovakia.eu but I dont know what the frequency is at 10-bit resolution and how to set frequency in this code.

Are you talking about a square wave? In what way would it have 10-bit resolution? Either it is 1 kHz or not, yes? Are you talking about an error factor? Like, 1 kHz +/- 5% ?

@NickGammon The "10-bit resolution" will refer to the resolution of the duty cycle parameter. i.e., a duty cycle between 0 and 1023 instead of the normal 0 to 255.

Perhaps but the rather brief question does not mention duty cycles.

@NickGammon No, but it does mention PWM, and PWM has a duty cycle (which is what makes it PWM).

I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.
Assuming you are using a Uno this code will do it:
// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

void setup()
 {
  pinMode (outputPin, OUTPUT);

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()
  {
  }

You can change the 1000 in the calculation for timer1_OCR1A_Setting, within reason, to get other frequencies.
See my page about timers for more background information.

On a 16Mhz Arduino you'd get around 14 bits of resolution, using this code. It is however impossible to get exactly 14-bit (or 10-bit) of resolution without changing the frequency (to around 0.9765kHz).

To explain that comment, OCR1A would be set to 16000 using the above code, and that is log(16000)/log(2) bits, namely 13.97 bits roughly. Therefore your duty cycle (OCR1B) could be in the range 0 to 15999 giving at least 10 bits of resolution.

Thanks for the answer.


text:
Why do most arduino function return a -1 instead of a 0
Many arduino functions return -1 if something 'fails'. Serial.read for example returns -1 or the infamous ÿ when this function is called while the serial buffer is empty.
As embedded C progammer, I am personally a fan of letting functions return data in the form of modifying pointers which points to passed on addresses and return states with the actual return functionality of a function. I am used to return a 0 if a function is 'not done' or 'failed'.
I see no logic in why many arduino functions return an int type which contains -1 instead of just a 0.
Would it not be better to let functions return a boolean type or an unsigned char type in which false or '0' would indicate a 'failed' process and true or '1' would indicate a 'succesful' process?
Also: if I type:
if(Serial.read()) {/* body */ }
and Serial.read() returns -1 because the buffer is empty. Will the If's body be executed or not?

how would you return a byte with value 0 from read() if 0 would indicate error?

@Juraj I realized that Serial.read() was perhaps a very poor example as this function returns  both return values as a state (-1). Perhaps that Serial.begin() would be a better example

I cannot assert anything for sure, as I was not involved in the design
of the Arduino APIs. However, just like Elliot Alderson, I suspect this
was inspired by the traditional C APIs. The manual page for getchar(),
which is a very old function from the standard C library, states:

fgetc(),  getc() and getchar() return the character read
  as an unsigned char cast to an int or EOF on end of file or
  error.

Given that EOF is usually defined as -1, this is consistent with the
behavior of Serial.read().
Being beginner-friendly is also a major goal of the API. Pointers are
known to be a huge difficulty for beginners.
There may also be some efficiency considerations involved. Arduino
started on the AVR platform. This is a RISC architecture, with a large
number of generic CPU registers (namely 32). The compiler usually
manages to allocate most local variables to registers. The calling
convention ensures that in most cases function parameters and return
values also go through CPU registers. This means we can avoid many RAM
accesses, which are inherently much slower than register access. Using a
return-by-pointer convention defeats these optimizations.
Lastly, it is a good thing that simple things are easy to write. For
example, an interpreter for single-character commands can be very easily
written as:
switch (Serial.read()) {
case 'a':
    do_command_a();
    break;
case 'b':
    do_command_b();
    break;
// etc...
}

with no need to explicitly test for the serial buffer not being empty.
Obviously, a more complex command language will need a full-blown
interpreter, but the focus of Arduino has always been on simple
programs being easy to write.

Arduino API is port of Processing. Processing is Java API to communicate with a MCU running Firmata. Arduino enabled sketches with the same API to run directly on the MCU.
So for example stream functions from Java stream classes were ported to Arduino API. This includes the read() function, to read one byte. Of course Java and Java basic libraries have inspiration in C++.
For other read and write functions, if the return value is count of bytes written or read then 0 is a valid return value and -1 indicates error.
Processing, Wiring and Arduino were created by interactive arts teachers and students, not by embedded systems developers. So you can't wonder about not ideal data types used. Later some things were improved by software developers.

as embedded C developer you should know that:

0 is a valid value to read, so it can't be a value indicating error
'if' executes if the evaluated value is not 0

How does this answer the question? You didn't say anything about return values.

sorry, you are not familiar with the Java read function.. I added a link to JavaDoc of Java read() function. and I addressed the thought error of OP about the error return value of read() in a comment

In an Arduino forum I think you should assume that readers are not familiar with Java. Also, could you include the important information directly in your answer, just in case the link breaks some day?

So to get to the heart of the matter, can you explain why (if in fact it is true) Java functions return -1 instead of 1 (or True) for an error condition? I mean even those functions that are not returning a byte value, but only a pass/fail indication.

@ElliotAlderson, that is explained in your answer :-). I have "inspired in C++", which is inspired in C...

if the return value is count of bytes written or read then 0 is a valid return value

I was unsure if if(something) would also be true, if something was signed AND negative. I hardly use signed value types at all.

Also, as 'embedded C developer' I do know that Serial.read() does not have to be interperted as a charachter. For all you know I use Serial.read() to read an array of numbers which also could contain 255

-1 is returned when "0" would be a perfectly valid response.
To take your example of Serial.read(): 0 is a valid byte or ASCII character.  -1 isn't.  If you returned 0 for "failure" then there would be no way of differentiating between that and the valid byte value 0.

Are you sure that the Serial.read() can not return binary values rather than just ASCII? I can't find that in the documentation.

What is ASCII? It is just shapes that humans have decided to associate with numbers. Everything is numbers. The numbers 0-255 - and we have decided that certain ones of those numbers will represent letters in our minds. Serial.read() returns the byte that is next in the receive buffer. That byte is 0-255, and if we want 65 to mean "A" then we can. But if there's no byte to return from the receive buffer then something "not a byte" must be returned to mean "there's nuffink there, bruv!", and -1 is not a byte.

Ah, so the missing bit of information is that we are assuming that an int is defined to be bigger than 8 bits, and the Serial.read() returns an int rather than a char. A char value of 0xFF could be a valid return value, but an int of 0xFFFF is not.

That's not an assumption. It's a cold hard fact. An int will always be bigger than a byte.

Agreed, given an ANSI compiler. I shouldn't have said "assuming" I should have said "recognizing".

I suspect that this a legacy from Unix command programming, which was first done in C. For commands that only needed to return status and not data, a return value of zero meant success and any other return value indicated some kind of failure. Individual programmers could designate specific non-zero values for specific error types, if desired.
Remember that the return value comes back to the calling function in a register. And these days the term "Arduino" encompasses a broad range of architectures, including 32-bit ARM Cortex-M. Specifying that the return value is a char offers no advantage in this case.
The boolean datatype is a fairly recent addition to the C language, so it's not surprising that you don't see it used much in existing, portable libraries.
Returning an address from a simple function that just needs to indicate success or failure seems like overkill.
If you really want control over the datatypes, include stdint.h and use the types defined therein. If you want an unsigned 8-bit value use uint8_t and not unsigned char. If you want to allow the compiler to choose the best datatype that is at least 8 bits, use uint_fast8_tf.


text:
Arduino Uno not working after Short-circuit
While wiring up my new Arduino Uno R3, I accidentally shorted the 5V pin and the GND pin (for less than a sec). It was powered by a 12V 500mAh power supply through the Arduino DC power jack. . The ON, Rx, X1 and L LED's are glowing continuously, and also, pressing the reset button doesn't have any effect on the LED's and arduino doesn't restarts. How can I get my arduino working again?

Because short only lasted for a sec, maybe just maybe one of the component in the supply part of Arduino burned out. or the 500mA damaged the the main IC(ATMEGA328). so before anything change the regulator (AS1117) that is next to the power jack, and then turn on the Arduino. if it didn't work try changing the main IC.

The regualator of that 5V Blew up or the diode you need to read the schemtics of the Arduino Uno and check the circuits.
https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf

Chances are the cheap Chinese clone board you have has an inferior 5V regulator with no thermal protection.
These are notorious for breaking with a short circuit (over-current = over-temperature = meltdown).  And when they break they "fail short", which means that they end up working like a simple piece of wire - the voltage you put in is the voltage you get out.
That means that 12V has now been sent into the rest of the Arduino, and has destroyed everything - the main MCU, the USB interface chip, etc.
In short: your board is dead.

You can tell it's a fake Uno because the USB chip is not an Atmega32U4.


text:
Wiring power new power button to UPS power module for raspberry pi
I have a UPS Power Module Expansion Board for Raspberry Pi 3B/3B+(Plus) and removed the power button because it is in the way and would like to attach this read button instead. But it is not working, they board does not turn on?
Am i wiring the incorrectly?

you want to replace an on/off switch with momentary button? and where is the Arduino?

This looks like a momentary push-button; use a latching button (push-on/push-off) instead.

Thanks! Will try it out :)


text:
Arduino Firebase connection refused error
I am making a project for school where I have to send data from a sensor to a webpage. After doing some research I decided to use a Real-Time Firebase database. Security is not really important and I want to focus on other aspects of the project, so this seemed like an easy and quick option. I am using a d1 mini (esp8266) and a DHT11 humidity and temp sensor. For libraries I am using DHT, FirebaseArduino and ESP8266WiFi. The code is:
#include <ESP8266WiFi.h>                                                    // esp8266 library
#include <FirebaseArduino.h>                                                // firebase library
#include <DHT.h>                                                            // dht11 temperature and humidity sensor library

#define FIREBASE_HOST "xx"                   // the project name address from firebase id
#define FIREBASE_AUTH "xx"            // the secret key generated from firebase

#define WIFI_SSID "xx"                                             // input your home or public wifi name
#define WIFI_PASSWORD "xx"                                        //password of wifi ssid

#define DHTPIN D5                                                           // what digital pin we're connected to
#define DHTTYPE DHT11                                                       // select dht type as DHT 11 or DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  delay(1000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);                                     //try to connect with wifi
  Serial.print("Connecting to ");
  Serial.print(WIFI_SSID);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("Connected to ");
  Serial.println(WIFI_SSID);
  Serial.print("IP Address is : ");
  Serial.println(WiFi.localIP());                                            //print local IP address
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);                              // connect to firebase
  dht.begin();                                                               //Start reading dht sensor
}

void loop() {
  float h = dht.readHumidity();                                              // Reading temperature or humidity takes about 250 milliseconds!
  float t = dht.readTemperature();                                           // Read temperature as Celsius (the default)

  if (isnan(h) || isnan(t)) {                                                // Check if any reads failed and exit early (to try again).
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print("Humidity: ");  Serial.print(h);
  String fireHumid = String(h) + String("%");                                         //convert integer humidity to string humidity
  Serial.print("%  Temperature: ");  Serial.print(t);  Serial.println("°C ");
  String fireTemp = String(t) + String("°C");                                                     //convert integer temperature to string temperature
  delay(4000);

  Firebase.pushString("Humidity/", fireHumid);                                       //setup path and send readings
  Firebase.pushString("Temperature/", fireTemp);                                //setup path and send readings

}

replaced some 'sensitive' information with "xx". When running this code, it connects to my wifi connection and shows data from the DHT11 in the serial monitor. However NOTHING changes in Firebase. After enabling the feature to display extensive feedback/errors in the serial monitor, I noticed it's displaying this:
[HTTP-Client][begin] host: https://testtesttest-bd679.firebaseio.com/ port: 443 url: /Temperature/.json?auth=xxxx httpsFingerprint: 03 D6 42 23 03 D1 0C 06 73 F7 E2 BD 29 47 13 C3 22 71 37 1B
[HTTP-Client][sendRequest] type: 'POST' redirCount: 0
[HTTP-Client] failed connect to https://xxx-xxx.firebaseio.com/:443
[HTTP-Client][returnError] error(-1): connection refused
[HTTP-Client][returnError] error(-4): not connected
[HTTP-Client][end] tcp is closed
Humidity: 43.00%  Temperature: 22.50°C

I have tried the following things:

Using a different version of the FirebaseArduino library (5.13.x (still using this one))
Manually updating the fingerprint of the FirebaseArduino library (see current fingerprint in 2nd code section above)
Using different versions of the Arduino IDE, using 1.8.12 now

And some other minor changes like creating a new Firebase Database or using something different from pushString to add data to the database.
None of this helped and I am running out of time for my project, hope someone here knows what's wrong and can help me out! :)

You added a / to the end of the Humidity and Temperature collections.
e.g
    Firebase.pushString("Humidity/", fireHumid);
    Firebase.pushString("Temperature/", fireTemp);
The firebase API translates it to an address
https://testtesttest-bd679.firebaseio.com/Temperature/.json?auth=xxxx`

as we can see in the output.
I'm pretty sure the correct address is ...Temperature.json... and not ...Temperature/.json....
Please try to remove the slashes from the end of the collection names in the pushString statements..
Firebase.pushString("Humidity", fireHumid);
Firebase.pushString("Temperature", fireTemp);

If this does not help, it is possibly a problem with the auth string or the Host name. e.g trailing or leading space characters or something like that.

Thank you for your answer. It is able to connect to Firebase now. However i am getting this error now, maybe you know how to resolve this one aswell :) [HTTP-Client][handleHeaderResponse] RX: 'HTTP/1.1 400 Bad Request' This error occurs after it connects and it starts trying to push information into the database.

I deleted my former comment because my explanation was not correct. I do not know Firebase very well. The message says that page (respective the api method ) you try to access did not exist, Perhaps it works if you use other access methods. Perhaps push is not supported (for what reason ever): try setString insteadof pushString for example. If that works, I can not explain why, but you have a start point for further investigations. It would be helpful to know that, the Firebase. ... methods are translated to REST api calls and send as HTTP Requests to the firebase server.


text:
Temp Sensor not working on ESP32
I am using SHT21 temp sensor with ESP32 using I2C. The sensor only reports temp of -273 and 0 for RH. The sensor is not faulty as I have tried this on an Arduino UNO with the same sketch and it works fine. I am using the default data and clk pins on ESP 32. Also I tried it on a different ESP32 board as well as powering the sensor from the ESP32 and externally but still get incorrect readings. I suspect it is more of a software issue than a hardware one. Could you please help me find the cause?
Here is my sketch:
#include <Wire.h>
#include <Sodaq_SHT2x.h>

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

void loop()
{
  Serial.print("Humidity(%RH): ");
  Serial.print(SHT2x.GetHumidity());
  Serial.print("     Temperature(C): ");
  Serial.println(SHT2x.GetTemperature());
  Serial.print("     Dewpoint(C): ");
  Serial.println(SHT2x.GetDewPoint());

  delay(1000);
}

The two things that are different between your working- and non-working trials are the hardware (board and connections to the sensor) and the library code. Your own code and the sensor are already proven. So what is different between the Uno connections and ESP connections to your sensor? Between the Uno-specific and the ESP-specific code sections in the library (if any)?

In my code there is no UNO or ESP specific code. I use the exact same sketch on both microcontrollers. May be when it compiles there are certain things which change but I don't know about that. Other differences that I can think of are the I2C pins which are of course different for UNO and ESP32. I wonder if the library I am using can detect the correct data and clock pins on different mcu's.  But I am able to find the sensor when using the I2C address scanner. It just gives the wrong readings.

Maybe there is some MCU-specific code in the Sodaq_SHT2x library, such that maybe one section might compile for an Uno while another might compile for an ESP. That and connectivity, voltages, etc. seem to be the only differences. I agree that your own code should run on either MCU.

This is my first experience with ESP32 and so far using sensors on I2C bus is giving me a lot of issues. Good sensors (tested on arduino UNO) just stop working on ESP32. What am I missing here? Do I need to modify libraries and my code to make it ESP specific?

"so far using sensors on I2C bus is giving me a lot of issues" sounds like a clue, doesn't it? Especially if other sensors have given you the same problem. If that's the case, your issues sound very likely related to differences in hardware compatibility such as voltages, supply capability, connections, choice of ESP pins - something that is different about the ESP that applies consistently across the various sensors, and less likely to be software related. Has any sensor worked with ESP32 and I2C?

Exactly how is your sensor wired to the ESP32? What pins are connected to what pins? How is it powered? What happens when you run an I2C scanner on the ESP32?

@JRobert I doubt it's due to issues like voltage, supply capabilities etc. Both ESP32 and sensors am I having problem with are 3.3V and I have tried both powering the sensors using ESP32 and through external power supply. Another sensor that wasn't working initially on ESP32 was a BME280. But after sometime it started working. Same code, same circuit. Another sensor that worked right out of the box was an AHT10. So the I2C behaviour is pretty inconsistent.

@romkey It's a very basic setup. I am using 3.3V breakout board with 4 pins(Vin, GND, SCL, SDA). I am using the default I2C pins (D22 for SCL and D21 for SDA). Both the MCU and the breakout board are powered using external 3.3V supply.  The I2C scanner detects the sensor with it's address so ESP32 has no problem seeing the sensor

@Zaffresky that sounds solid - you wouldn't believe the number of people who wire stuff up and don't hook up GND or something like that... :) the only other issue there I can think of is if the wires are really long; that can cause issues with I2C. I'd try a different library that's known to work with the ESP32 - Adafruit and Sparkfun are both very good about this but unfortunately they don't seem to have an SHT21 library. FWIW, I've used BME280s with the ESP32 extensively with no problems.

There's a small chance that adding pull-up resistors to SCL and SDA might help - the ESP32's internal pull-ups are quite weak. A 47K resistor between SCL and 3.3V and SDA and 3.3V might make a difference.

@romkey you were right about the library. I have tried another library for SHT21 that was tested with ESP32 and it works like a charm :)  I was assuming that my tried & tested arduino libraries would work also for ESP32 but its not that simple. Anyways at least I know now where the issue lies

@Zaffresky in my experience many of them do but unfortunately not 100%. glad that resolved it!

The two main issues I encounter with sensors/I2C and different board types are that the needed pullups are different for 5V and 3.3V parts/systems, and if the library is written for AVR (i.e. Uno) it may not work properly on a ESP8266, etc, due to variances in the architecture, etc. So it's always good to try a few libraries, especially if you were able to detect the i2c device using the scanner sketch ;)

@PeterFeerick yeah I have learn't that now. I only had experience with AVR MCUs so far. I have learnt about the library issues now but you make a good point regarding the pull ups. Will keep that in mind as well


text:
Problem with a class? SHT21 library
I am using ESP32 and SHT21 temp+humidity sensor but while compiling the code I get the following error:
variable "SHT21" is not a type name

I see an SHT21 class defined in the SHT21.cpp file in the library folder. I don't know much about classes so could you please tell what is wrong with the SHT21 class in this case?
Here is the link to the library:
https://github.com/markbeee/SHT21
Sketch:
#include <Arduino.h>

#include <Wire.h>
#include "SHT21.h"

SHT21 SHT21;

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

void loop()
{
  Serial.print("Humidity(%RH): ");
  Serial.print(SHT21.getHumidity());
  Serial.print("     Temperature(C): ");
  Serial.println(SHT21.getTemperature());

  delay(1000);
}

Don't name your instance the same as the class. It confuses the compiler as it never knows what you're talking about.

Ah Ok! I see it. Thanks for the tip. It compiles without error now.


text:
Initiating 2nd I2C bus on ESP32 with CCS811 sensor
I want to connect two CCS811 sensors with ESP32 dev board. Since the sensors have fixed address, I am unable to use them simultaneously. I have read that on ESP32 multiple I2C buses can be created. While trying to follow that route I tried to modify the library but I am stuck. I can't simply pass different pins for SDA and SCL when calling ccs.begin() function. It only takes one argument and that is the sensor address (code chunk from library below):
bool Adafruit_CCS811::begin(uint8_t addr) {
  _i2caddr = addr;

  _i2c_init();

  SWReset();
  delay(100);

  // check that the HW id is correct
  if (this->read8(CCS811_HW_ID) != CCS811_HW_ID_CODE)
    return false;

  // try to start the app
  this->write(CCS811_BOOTLOADER_APP_START, NULL, 0);
  delay(100);

and the actual wire.begin() function is called in the _i2c_init() function which is defined in the lib as:
void Adafruit_CCS811::_i2c_init() {
  Wire.begin();
#ifdef ESP8266
  Wire.setClockStretchLimit(500);
#endif
}

With my very basic knowledge of classes and object, I am unable to modify the library to make it work with 2 I2C buses. Could you please help me with this?
Link to Adafruit CCS811 library:(https://github.com/adafruit/Adafruit_CCS811/blob/master/Adafruit_CCS811.cpp)
My Code so far:
#include <Arduino.h>
#include <Wire.h>
#include "Adafruit_CCS811.h"

Adafruit_CCS811 ccs1;
Adafruit_CCS811 ccs2;

TwoWire sen1 = TwoWire(0);
TwoWire sen2 = TwoWire(1);

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

  Serial.println(F("CCS811 test"));

  if (!ccs1.begin(25, 26, 100000))
  {
    Serial.println("CCS 1 Failed.");
    //while (1);
  } else {
    Serial.println("CCS 1 OK!");
  }

  // Wait for the sensor to be ready
  //while (!ccs.available());
}

void loop()
{
  if (ccs1.available())
  {
    if (!ccs1.readData())
    {
      Serial.println(" This is CSS");
      Serial.print("CO2: ");
      Serial.print(ccs1.geteCO2());
      Serial.print("ppm, TVOC: ");
      Serial.println(ccs1.getTVOC());
    }
    else
    {
      Serial.println("ERROR!");
      //while (1);
    }
  }
  delay(500);
}

CSS811 chip can have either address 0x5A or 0x5B depend on the logic level of ADDR pin. Read the datasheet.

Yes the chip can but the module I am using can't. There is no ADDR pin.

which module do you use then? the module will include either a pull up or a pull down resistor. Instead of using an extra I2C bus for the second sensor you could buy one which has the address pin broken out (for a clean solution) or desolder the onboard pullup/-down and control it with a gpio or hardwire it to Vcc/Gnd with a solder bridge.

I use this module https://www.banggood.com/CJMCU-811V1-CCS811-NTC-CO2-eCO2-TVOC-Air-Mass-Sensor-p-1250571.html?cur_warehouse=CN&rmmds=search. I know I could buy another sensor but I also want to learn to use the second I2C bus on ESP32. That's why I trying to implement it this way


text:
How to control 30 stepper motors using Arduino?
To prototype my project, I'm going to use an Arduino. I need to control 30 step motors.
4 of these step motors should always be ready to work, no matter other motors are working or not. But the other 26 motors never work in the same time (only one or none of these 26 step motors work at the same time).
So I'm looking for a fast and cheap way to prototype my machine and I need your advice.
I think a CNC Shield or 4 EasyDriver can do the job for controlling those 4 step motors (those motors which need to be ready to work at any moment of time).
But for the other 26 step motors (which can be controlled one by one) is there a way to avoid using 26 EasyDrivers or stacking several other shields? Is there a way to control those 26 step motors using a single driver?
Thanks.

@jsotola, Thanks for reply. There is no need to stay in holding position. When one of those 26 step motors are rotated for n steps, we can safely turn the motor off until the next time we need it. So we can use the driver for another motor.

this question is not really about the Arduino, but about stepping motor drivers and should be moved to https://electronics.stackexchange.com/questions

https://forum.arduino.cc/index.php?topic=123547.0, https://reprap.org/forum/read.php?2,196989, https://electronics.stackexchange.com/questions/266213/multiplexing-h-bridge-stepper-control, etc. Personally... meh. You can get a cheap stepper controller for like $1-1.5 w/o even trying, and it'll be easier to multiplex the control signals rather than the driver output.

Have a microcontroller + driver per motor and network them all together to a master controller.


text:
How to eliminate drift with the magnetometer in the MPU9250
I have a sketch running that uses a complementary filter for my X and Y values.

However, the Z value has no complementary filter (as you can tell by the slight drift when stationary) because I was told that a magnetometer is required to eliminate this drift.
Thus I purchased the MPU9250.
How would a magnetometer be able to eliminate drift it only measures magnetic fields?
How would I be able to help reduce the drift?

I tried to answer this in your other question.

@chrisl yeah I saw thank you. Thought I should create a new post because the problems differ slightly so for anyone in the future needing help, the posts are sorted better


text:
Mega2560 has 2 Crystal Oscillator?
Who knows this Mega2560 with two Crystal Oscillators: 12 000 MHz and 16 000 MHz? What is the use of them?

there is an ATmega16u2 as USB converter. it has the 12 MHz oscilator

Don't the 16U2s also use 16 MHz, while the CH340 use 12 MHz?  The 2560 itself more typically use a  smaller 3-pin16 MHz resonator.

Please expand on your question.

There are two devices on an Arduino board than need a clock source:

The ATMega328 / ATMega2560 main MCU (16MHz)
The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal.  Cheap Chinese clones use a CH340G which takes a 12MHz crystal.
Note that normally it's one crystal and one ceramic resonator.  USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.


text:
Why is observed clock rate < 3MHz on Arduino Uno?
I wrote a simple loop to test the processor speed on my Arduino Uno. The numbers I'm getting are much worse than the 16MHz advertised, by a factor of ~5. Trying to figure out what I'm missing.
long counter = 0;
int sum = 0;
uint32_t t = 0;

void setup() {
  Serial.begin(9600);
  t = micros();
}

void loop() {
  sum += counter;

  if (counter == 10000) {
    float usecsPerIteration = (micros() - t) / (counter * 1.0);
    Serial.print(usecsPerIteration);
    Serial.println(" microseconds per iteration");

    // Print result to avoid loop getting optimized away
    Serial.println(sum);
  }

  ++counter;
}

The output is:
3.77 microseconds per iteration

Here's how I'm estimating clock rate from this. The body of the loop involves two additions and an equality check. Even if we assume that these simple operations take 10 clock cycles, the implied clock rate is still just (1 iter / 3.77 us) * (1e6 us / sec) * (10 cycles / iter) = 2.65 MHz.
What am I missing?

You forgot that the printing itself also contributes to the equation. This is VERY EXPENSIVE. You should reset your time after every printing.

I only print once after 10,000 iters and it is after I compute time elapsed.

As Michael says there is a lot more going on than you think.
Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).
Secondly you vastly under estimate the number of instructions that are being called.  For a start the loop is being called from a for(;;) loop in main():
    for (;;) {
        loop();
4   572:    0e 94 73 00     call    0xe6    ; 0xe6 <loop>
        if (serialEventRun) serialEventRun();
2   576:    20 97           sbiw    r28, 0x00   ; 0
2   578:    e1 f3           breq    .-8         ; 0x572 <main+0x10>
-   57a:    0e 94 1d 01     call    0x23a   ; 0x23a <_Z14serialEventRunv>
2   57e:    f9 cf           rjmp    .-14        ; 0x572 <main+0x10>
10 total

Then for the call to loop() the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning.  This is the code for loop when disassembled:
000000e6 <loop>:
    // Save the registers to the stack
2   e6:     cf 92           push    r12
2   e8:     df 92           push    r13
2   ea:     ef 92           push    r14
2   ec:     ff 92           push    r15
8 total

    // Add to the sum
2   ee:     40 91 44 01     lds r20, 0x0144 ; 0x800144 <counter>
2   f2:     50 91 45 01     lds r21, 0x0145 ; 0x800145 <counter+0x1>
2   f6:     60 91 46 01     lds r22, 0x0146 ; 0x800146 <counter+0x2>
2   fa:     70 91 47 01     lds r23, 0x0147 ; 0x800147 <counter+0x3>
2   fe:     80 91 42 01     lds r24, 0x0142 ; 0x800142 <sum>
2   102:    90 91 43 01     lds r25, 0x0143 ; 0x800143 <sum+0x1>
1   106:    84 0f           add r24, r20
1   108:    95 1f           adc r25, r21
2   10a:    90 93 43 01     sts 0x0143, r25 ; 0x800143 <sum+0x1>
2   10e:    80 93 42 01     sts 0x0142, r24 ; 0x800142 <sum>
18 total

    // Check the value to see if it's time to print
1   112:    40 31           cpi r20, 0x10   ; 16
1   114:    57 42           sbci    r21, 0x27   ; 39
1   116:    61 05           cpc r22, r1
1   118:    71 05           cpc r23, r1
2   11a:    d1 f5           brne    .+116       ; 0x190 <loop+0xaa>
6 total

    // From here on is the "IF" section - skipped by the BRNE above
-   11c:    0e 94 f5 04     call    0x9ea   ; 0x9ea <micros>
-   120:    c0 90 3e 01     lds r12, 0x013E ; 0x80013e <__data_end>
-   124:    d0 90 3f 01     lds r13, 0x013F ; 0x80013f <__data_end+0x1>
-   128:    e0 90 40 01     lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
-   12c:    f0 90 41 01     lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
-   130:    6c 19           sub r22, r12
-   132:    7d 09           sbc r23, r13
-   134:    8e 09           sbc r24, r14
-   136:    9f 09           sbc r25, r15
-   138:    0e 94 68 06     call    0xcd0   ; 0xcd0 <__floatunsisf>
-   13c:    6b 01           movw    r12, r22
-   13e:    7c 01           movw    r14, r24
-   140:    60 91 44 01     lds r22, 0x0144 ; 0x800144 <counter>
-   144:    70 91 45 01     lds r23, 0x0145 ; 0x800145 <counter+0x1>
-   148:    80 91 46 01     lds r24, 0x0146 ; 0x800146 <counter+0x2>
-   14c:    90 91 47 01     lds r25, 0x0147 ; 0x800147 <counter+0x3>
-   150:    0e 94 6a 06     call    0xcd4   ; 0xcd4 <__floatsisf>
-   154:    9b 01           movw    r18, r22
-   156:    ac 01           movw    r20, r24
-   158:    c7 01           movw    r24, r14
-   15a:    b6 01           movw    r22, r12
-   15c:    0e 94 c7 05     call    0xb8e   ; 0xb8e <__divsf3>
-   160:    ab 01           movw    r20, r22
-   162:    bc 01           movw    r22, r24
-   164:    22 e0           ldi r18, 0x02   ; 2
-   166:    30 e0           ldi r19, 0x00   ; 0
-   168:    88 e4           ldi r24, 0x48   ; 72
-   16a:    91 e0           ldi r25, 0x01   ; 1
-   16c:    0e 94 a9 04     call    0x952   ; 0x952 <_ZN5Print5printEdi>
-   170:    60 e0           ldi r22, 0x00   ; 0
-   172:    71 e0           ldi r23, 0x01   ; 1
-   174:    88 e4           ldi r24, 0x48   ; 72
-   176:    91 e0           ldi r25, 0x01   ; 1
-   178:    0e 94 0b 03     call    0x616   ; 0x616 <_ZN5Print7printlnEPKc>
-   17c:    60 91 42 01     lds r22, 0x0142 ; 0x800142 <sum>
-   180:    70 91 43 01     lds r23, 0x0143 ; 0x800143 <sum+0x1>
-   184:    4a e0           ldi r20, 0x0A   ; 10
-   186:    50 e0           ldi r21, 0x00   ; 0
-   188:    88 e4           ldi r24, 0x48   ; 72
-   18a:    91 e0           ldi r25, 0x01   ; 1
-   18c:    0e 94 b0 03     call    0x760   ; 0x760 <_ZN5Print7printlnEii>

 // All this is just counter++
2   190:    80 91 44 01     lds r24, 0x0144 ; 0x800144 <counter>
2   194:    90 91 45 01     lds r25, 0x0145 ; 0x800145 <counter+0x1>
2   198:    a0 91 46 01     lds r26, 0x0146 ; 0x800146 <counter+0x2>
2   19c:    b0 91 47 01     lds r27, 0x0147 ; 0x800147 <counter+0x3>
2   1a0:    01 96           adiw    r24, 0x01   ; 1
1   1a2:    a1 1d           adc r26, r1
1   1a4:    b1 1d           adc r27, r1
2   1a6:    80 93 44 01     sts 0x0144, r24 ; 0x800144 <counter>
2   1aa:    90 93 45 01     sts 0x0145, r25 ; 0x800145 <counter+0x1>
2   1ae:    a0 93 46 01     sts 0x0146, r26 ; 0x800146 <counter+0x2>
2   1b2:    b0 93 47 01     sts 0x0147, r27 ; 0x800147 <counter+0x3>
20 total

 // Get the registers back and return
2   1b6:    ff 90           pop r15
2   1b8:    ef 90           pop r14
2   1ba:    df 90           pop r13
2   1bc:    cf 90           pop r12
4   1be:    08 95           ret
12 total

That's more than 10 instructions.  I make it 74 clocks to run one full iteration. (counter++ alone is 20 clock cycles - double your estimation for the total...)
You have to remember two important things:

AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).

I am counting 72 clock cycles per iteration in your disassembly (20 for counter++). It looks like you compiled without -flto.

@EdgarBonet Quite possibly, yes. I use UECIDE which may not use the same compilation flags as Arduino if they decide to change things like that randomly - also probably not the same version of the compiler (I have lots of versions to choose from).

@EdgarBonet ADIW is two clocks not one I see, even though it only needs one read from the flash. I was counting flash reads as clocks. So yes, there's even more than at first it appears.

Indeed, the Arduino folks changed the compilation flags, adding LTO in 1.6.10.

@EdgarBonet I should add that to the arduino core in UECIDE then really. It's time to build a new version anyway I guess.  Any way - I have listed (and summed) the actual clock cycle values in the answer now.

@EdgarBonet Oh... and for a "RISC" system, the AVR sure has a lot of instructions...

The loop function is called within the framework of the Arduino IDE.
Beyond the code you write, also an interrupt check is done, which also cost time, and explains the difference.
The following function CAN be called after every loop call.
See Majenko's answer about the details.
/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

See SerialEvent for more info.
However, as Kwasmich's comment says, you can easily circumvent this by performing your test inside a while  loop.

Does the interrupt loop check really take ~50 cycles?

Repeat your experiment by moving the loop code into a while(1) {} loop inside of setup(). That way you can eliminate the contribution of the arduino framework.

I'm trying to find the code.

SerialEvent is an optional function the user may implement in their sketch if they want. If they don't implement it then nothing gets called. It does, however, do a quick check to see if the function has been defined or not though, which takes a couple of clock cycles.

@Majenko ... thanks, I will update my answer, and upvote yours.


text:
Need to know what USB cable to get for Arduino Nano-33-BLE-Sense
I have recently purchased an Arduino Nano-33-BLE-Sense with Headers and wrongly assumed that it would come with a USB cable with it. I was searching the online store for the cable but the only cable on the store that I see is for Type A to Type B which in its description does not mention my board.
Does anyone have any experience with this board and know which cable I need? Thanks in advance!

why don't you google USB connector types and compare pictures?

it is the most common USB cable. I am sure you have more then one at home. – Juraj Sep 26 at 9:02

Looks like this board

Is connected to the PC with connector commonly named simply "Micro USB". Wikipedia calls it "USB 2.0 Micro-B"
It's the same cable that all mobile phones used (before USB-C standard arrived). Check your phone charger.


text:
How do I extract code from an arduino?
I updated and uploaded some code on another computer that got wiped and didn't send the new code to my current computer, the updated code is still on the board but I don't have access to it. How do I get it back?

You have a couple of answers, but here's a piece of advice for going forward... protect yourself against code loss by learning how to use a VCS (Version Control System). This will allow you to keep all changes to your software on both your local computer as well as a remote system which stores it. Nowadays, I use git, but there are several. Github is a free online git storage facility. So you do some code, "commit" your changes, and then "push" them up to Github. You can then pull your code down to any computer with git on it thereafter.

You likely can't recover the source code, but if you had some important logic that you don't want to rewrite from scratch, it's very likely you can dump out the assembly and reconstruct that into C pretty easily (although manually).

Isn't the code in one of your backups, or your version control system?

The short answer: You don't.
With enough know-how, you could probably extract the executable binary from the Arduino, but the source code is not installed on the device. You would need to run a decompiler on the binary. (Or read the machine code directly.) The output of a decompiler is usually pretty ugly however, and will look quite different from the original source-code. It won't have meaningful variable names, class names, or function names, and the code structure will likely be a little different than the original source code.
EDIT:
As mckenzm pointed out in his answer, you could download the binary image from your Arduino, and then copy it onto another Arduino, but all that would let you do is to make an exact copy of the program. You wouldn't be able to modify it at all.

You never can get the actual code back ... by reading the flash you might be able to get the executable/runtime code, but this doesn't look at all similar as your code, although it's functionally the same.
For example, all function names, all variable names will be just numbers (or non recognizable names), and all C statements are converted in machine language instructions, probably so many, you will need much knowledge to find out which instructions belong to which (original) C statements.

I'm rather new to Arduino so can you explain how I can do this

See this link: https://stackoverflow.com/questions/42770319/how-to-read-arduino-flash-memory

Do I upload "avrdude -p m328p -P usb -c usbtiny -U flash:r:flash.bin:r" in a new sketch?

You have to start it from the command line

how do I get there

go to the windows icon (left bottom, type 'cmd'  go with cd to the correct path

Do you know how to do it on a mac? Sry

Sorry, I don't know much about macs, I do not have one myself. Maybe ask on stackoverflow? (how to startup a console)

On a Mac, open the application `terminal. Then the command should be the same. (Mac terminal windows use BASH, and the Windows command line has vague similarity to Unix)

You read the contents of flash and save it to a file. It can then be re-flashed if your need is not to edit, but duplicate.

This reads all flash, including the bootloader, and also PROGMEM data.

Use avr-objdump (or similar) to disassemble the instructions.

Again, PROGMEM data is going to be interpreted as opcodes, and may not be valid opcodes.
You may want to dump the fuses as well, for redirected vectors and such.

Use pattern analysis to recognise source patterns as compiled. Then iteratively compile and compare fragments.

This is harder than is looks, whilst most Arduino code is very simple, the libraries can be be wild and woolly. At least the hex file is human readable, but little endian.
It might be easier to "walk through" the assembly and perform a translation of the perceived behaviour. OK for 10 instructions, but harder for 16K of them.
You will also need the Atmel/Microchip *def.inc files for the MPU component enumerations so that you know your DDRB from you DDRC a good disasembler should know.
You can do this well enough for Blink, and recognise stack pointer initialization.
It is much easier without a bootloader, as booting should jump to main and main can start at 0 other than after the vectors.
Of course lock bits will ruin your day, and it may just be better for character to code it again.

Note that: 1. The Arduino IDE does not mess with the fuses nor lock bits. 2. Full-program optimization, which the IDE sets on by default, will make it near to impossible to find Arduino library functions by pattern-matching. Avr-libc is pre-compiled (with no LTO sections AFAICT), so it can be pattern-matched. 3. The boot loader will not be a problem: application code always starts at address 0, which is a jmp to __init. A few instructions through __init you find call main followed by jmp _exit. Thus, at least main is easy to find. Anything beyond will likely be a mess.

Good points. The IDE does set fuses for "burn bootloader".  Especially for contributed cores and in particular for clock selection and bootloader operation. You always have the ICSP option.


text:
Reset I2C connection with arduino as slave
I am currently using I2C serial communications with arduino as slave and raspberry pi as the master. I am sending sensor data from arduino to raspberry pi. I need to reset the I2C connection once the sensor readings cross a threshold. I tried setting the TWCR =0 but it throws a Error 121 Remote I/O error on the raspberry pi when I do that. I also read that one way is to set TWCR =0, but for this I need to execute the Wire.begin(), Wire.onRequest(), and Wire.onReceive() again. Can you please tell me how to run these again since they are put in setup function. Does it mean I need to restart the Arduino program again? Or can I put these in void loop()? Thanks for the help.

Why do you need to reset the I2C connection? And you can use all the functions of the library wherever you want

Hi Chrisl, I want to reset the connection because I don't want Arduino to send any more values to the master once the sensor readings cross a threshold value. Is there a better way to implement it?

You have a misconception about how I2C works. Unlike Serial (UART) I2C is a strictly master-slave interface. The slave cannot do anything without the master, since only the master controls the clock. Thus you don't need to reset the I2C interface to stop the transmission from the slave to the master.
When the master requests data from the slave the following happens: First the master sends the address of the targeted slave, including the direction bit set for "reading from slave". The slave with this address reacts with an acknowledgement (ACK) and start to transmit one byte. This byte get's acknowledged by the master. When the master decides, that it has received enough data, it does not acknowledge (NACK), which let's the slave stop it's transmission. Then the master sends a STOP condition to stop the I2C transmission.
I don't know, how you implemented the I2C communication on the Pi. Normally, when you initiate a read transaction from the master, you provide a number of bytes, that you want to request from the slave. The I2C module/library will then request data from the slave, until is has received all the requested bytes.
Thus you don't need to reset the I2C connection on the Arduino. The master totally controls the communication. When you end the transmission on the master, the slave cannot send further data.
Setting TWCR to zero in the middle of transaction will disrupt the I2C communication protocol. Thus you get an error on the Pi, that states an error in the I2C communication protocol. Just use the correct implementation of the I2C protocol to end the transmission correctly.


text:
Arduino I2C Multiplexing uisng TCA9548A
I am using 5 sensors out of which two have the same I2C address and are connected via TCA9548 multiplexer. The remaining 3 sensors are connected to the main arduino I2C bus. In example sketches online I see the following function to choose the specific port/channel on the multiplexer:
#define MPLXADR 0x70 // Address of TCA9548A I2C Multiplexer
void multiplexer (uint8_t ch) {
  if (ch > 7) return;
  Wire.beginTransmission(MPLXADR);
  Wire.write(1 << ch);
  Wire.endTransmission();
}

I understand that this function should be called before executing instructions for the sensors with shared address but how would it still send the data to the right sensor when the last line "Wire.endTransmission();" just closes connection?
Since in my circuit there are sensors which are connected directly to the arduino I2C bus, I wonder if the code related to those sensors comes after the code for sensors with shared address, wouldn't those instructions also be sent to the ensors with shared I2C address? To me it makes more sense if the instructions for the shared address sensors are enclosed inside the above mentioned function as follows:
channel select -> execute instruction -> end transmission
But the usage I see in the tutorials baffles me. Could somebody please clarify these points? Thanks
Here is the complete sketch I am using:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <AHT10.h>
#include <HDC2080.h>

Adafruit_BME280 bme1; // on Arduino I2C bus
Adafruit_BME280 bme2; // on multiplexer I2C bus
Adafruit_BME280 bme3; // on mulitplexer I2C bus
AHT10 AHT(AHT10_ADDRESS_0X38); // on Arduino I2C bus
HDC2080 HDC2080(0x41);// on Arduino I2C bus

#define MPLXADR 0x70 // Address of TCA9548A I2C Multiplexer
void multiplexer (uint8_t ch) {
  if (ch > 7) return;
  Wire.beginTransmission(MPLXADR);
  Wire.write(1 << ch);
  Wire.endTransmission();
}

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

  while (AHT.begin() != true)
  {
    Serial.println(F("AHT10 not connected or fail to load calibration coefficient"));
    delay(5000);
  }
  Serial.println(F("AHT10 OK"));

  HDC2080.begin();

  // Begin with a device reset
  HDC2080.reset();

  // Set up the comfort zone
  HDC2080.setHighTemp(28);         // High temperature of 28C
  HDC2080.setLowTemp(22);          // Low temperature of 22C
  HDC2080.setHighHumidity(55);     // High humidity of 55%
  HDC2080.setLowHumidity(40);      // Low humidity of 40%

  // Configure Measurements
  HDC2080.setMeasurementMode(TEMP_AND_HUMID);  // Set measurements to temperature and humidity
  HDC2080.setRate(ONE_HZ);                     // Set measurement frequency to 1 Hz
  HDC2080.setTempRes(FOURTEEN_BIT);
  HDC2080.setHumidRes(FOURTEEN_BIT);

  //begin measuring
  HDC2080.triggerMeasurement();
  Serial.println();

  Serial.println(F("BME280 test"));

  //BME280 sensor 1
  multiplexer(0);
  if (! bme1.begin(0x77, &Wire)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  // weather monitoring
  Serial.println("-- Weather Station Scenario --");
  Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,");
  Serial.println("filter off");
  bme1.setSampling(Adafruit_BME280::MODE_FORCED,
                   Adafruit_BME280::SAMPLING_X1, // temperature
                   Adafruit_BME280::SAMPLING_X1, // pressure
                   Adafruit_BME280::SAMPLING_X1, // humidity
                   Adafruit_BME280::FILTER_OFF   );

  //BME280 sensor 2
  multiplexer(1);
  if (! bme2.begin(0x77, &Wire)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  // weather monitoring
  Serial.println("-- Weather Station Scenario --");
  Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,");
  Serial.println("filter off");
  bme2.setSampling(Adafruit_BME280::MODE_FORCED,
                   Adafruit_BME280::SAMPLING_X1, // temperature
                   Adafruit_BME280::SAMPLING_X1, // pressure
                   Adafruit_BME280::SAMPLING_X1, // humidity
                   Adafruit_BME280::FILTER_OFF   );

  //BME280 sensor 3
  if (! bme3.begin(0x76, &Wire)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  // weather monitoring
  Serial.println("-- Weather Station Scenario --");
  Serial.println("forced mode, 1x temperature / 1x humidity / 1x pressure oversampling,");
  Serial.println("filter off");
  bme3.setSampling(Adafruit_BME280::MODE_FORCED,
                   Adafruit_BME280::SAMPLING_X1, // temperature
                   Adafruit_BME280::SAMPLING_X1, // pressure
                   Adafruit_BME280::SAMPLING_X1, // humidity
                   Adafruit_BME280::FILTER_OFF   );

  // suggested rate is 1/60Hz (1m)
 }

void loop() {
  bme3.takeForcedMeasurement(); // has no effect in normal mode
  printValuesBME3();
  delay(5000);

  printValuesAHT();
  delay(5000);

  printValuesHDC2080();
  delay(5000);

  multiplexer(0);
  bme1.takeForcedMeasurement(); // has no effect in normal mode
  printValuesBME1();
  delay(5000);

  multiplexer(1);
  bme2.takeForcedMeasurement(); // has no effect in normal mode
  printValuesBME2();
  delay(10000);
}

void printValuesBME1() {

  Serial.println();
  Serial.print("BME1 Readings");

  Serial.print("Temperature = ");
  Serial.print(bme1.readTemperature());
  Serial.println(" *C");

  Serial.print("Humidity = ");
  Serial.print(bme1.readHumidity());
  Serial.println(" %");

  Serial.println();
}

void printValuesBME2() {

  Serial.println();
  Serial.print("BME2 Readings");

  Serial.print("Temperature = ");
  Serial.print(bme2.readTemperature());
  Serial.println(" *C");

  Serial.print("Humidity = ");
  Serial.print(bme2.readHumidity());
  Serial.println(" %");

  Serial.println();
}

void printValuesBME3() {

  Serial.println();
  Serial.print("BME3 Readings");

  Serial.print("Temperature = ");
  Serial.print(bme3.readTemperature());
  Serial.println(" *C");

  Serial.print("Humidity = ");
  Serial.print(bme3.readHumidity());
  Serial.println(" %");

  Serial.println();
}

void printValuesHDC2080() {
  Serial.println("HDC2080 Values");
  Serial.print("Temperature (C): "); Serial.print(HDC2080.readTemp());
  Serial.print("\t\tHumidity (%): "); Serial.println(HDC2080.readHumidity());
}

void printValuesAHT() {

  Serial.println(F("AHT10: read 12-bytes, show 255 if communication error is occurred"));
  Serial.print(F("Temperature: ")); Serial.print(AHT.readTemperature()); Serial.println(F(" +-0.3C")); //by default "AHT10_FORCE_READ_DATA"
  Serial.print(F("Humidity...: ")); Serial.print(AHT.readHumidity());    Serial.println(F(" +-2%"));   //by default "AHT10_FORCE_READ_DATA"
}

The TCA9548 is a switch.
You begin a transaction to it, change the channel that it allows through, and then end that specific transaction.
From that point on one and only one of the other two sensors are attached to your bus - the other doesn't exist.  When you communicate on the address of that sensor it passes through the TCA9548 as if it doesn't exist.
You can think of the TCA9548 as a controller that sits next to the switch:

simulate this circuit – Schematic created using CircuitLab
Send channel 0 and it flips the switch one way. Send channel 1 and it flips the switch the other way. Once the switch is flipped it stays flipped until you tell it otherwise.
From your sketches perspective the two HDC2080s on the MUX are only one HDC2080. You just flip the switch to the right position to access the specific physical device you want at the time.