text:
Return json from AsyncWebserver
I am using ESPAsyncWebServer ArduinoJson (6.19.4)
 server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
    {
      AsyncJsonResponse  *response = request->beginResponseStream("application/json");
      DynamicJsonDocument doc(1024);
      doc["deviceType"] = deviceType;
      for (uint8_t i = 0; i < NUM_RELAYS; i++)
      {
        doc[String(i)] = !configJSON["devices"][i]["ledState"];
      }
      serializeJson(doc, *response);
      request->send(response);
    });

the above code works fine but seems the response doesnt ends, any subsequent calls also doesnt work on the same URL.
Any help please.

check developer tools in your web browser to see what is wrong


text:
Arduino UNO won't move servo
I have a simple MG996 servo motor and I am trying to make it move with my Arduino Uno. I tried different ways of wiring but nothing seems to work as fully expected.
For the wiring I followed this video: https://www.youtube.com/watch?v=b_xvu6wWafA and at 9:02 min the guy is showing how the wiring is done. As you can see in my photo, I have done the same thing (as you can see in the "my wiring" picture), with an external battery pack and everything but my code still does not work. No errors or anything, compiles and uploads perfectly. The code I was trying to execute is:
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(8);
}

void loop() {
  myservo.write(0);
  delay(1000);
  myservo.write(90);
  delay(1000);
}

This code is essentially trying to move the servo from 0 to 90 degrees back and forth. The pin is the correct one (#8). The arduino is receiving the right code (because I tried it with exemplary ones).
Important note: One thing I tried, however, was to not even have an external battery pack. Just connect the wires like so but instead of the 2 GNDs, only 1 GND and 1 +5V pin. That way I was able to move the servo only forward but never backwards! And every time I wanted to move it I had to write a higher degree value.
So the question is, is my wiring bad? I must be missing something.
Photos:

It looks like you have it wired to Vin? That's a voltage in pin. You probably want 5V.. It's pretty hard to tell anything from the pic, though; diagrams are easier to understand.

You can cross check your circuit diagram and code with this tutorial. This one uses MG996: https://www.theengineeringprojects.com/2017/05/servo-motor-control-using-arduino.html

You have not connected the supply pin properly.
here is the connection diagram for the standard basic Arduino example
I also verified this on the video you have linked. Connect the 5V and you should be good to go.
https://wokwi.com/arduino/projects/306894988845777472

source: Stack Exchange

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

sort: votes


text:
Start LED blink at certain millis() value
I was looking at the blink without delay sketch and I was trying to modify it so the LED would start blinking after 1000 ms. I changed the previousMillis variable to 1000, but the program didn't change. In fact, it doesn't seem to change for any value of previousMillis. I thought that this would change the if statement:
if (currentMillis - previousMillis >= interval)
because 2000ms would have to pass for currentMillis - previousMillis to be equal to 1000ms (interval). What am I missing?

If you initialize previousMillis to 1000 then, initially, currentMillis - previousMillis is −1000. But you are dealing with unsigned numbers, which cannot be negative, so the subtraction wraps around and you get 2^32−1000 = 4294966296.

Thanks, I removed the unsigned from both variables and it works now. However, is there any downside to this? And any better solutions?

“is there any downside to [removing unsigned]?” Yes. millis() will eventually overflow. Unsigned overflow is well behaved, whereas signed overflow is undefined behavior in C and C++. “any better solutions?” You can set an initial interval and change it later.

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


text:
Can I just use one Arduino in a receiver/transmitter circuit?
I am trying to build a system to control lights remotely, but I am a student and am operating on a tight budget. Is there any way I can have just one Arduino along with a receiver and transmitter (I am using the 433Mhz RF Wireless Transmitter Module and Receiver Kit 5V DC 433MHZ) to do a simple on/off command for lights? I don't want to unnecessarily spend money on another Arduino (especially since I am not going to be transmitting complicated data). If this were possible, what are the other things I would need and what would the code look like?

try Arduino simulators if you are building only for a demo

do you actually need an arduino at all?

It depends on your hardware. You are not transmitting complicated data, but you need to transmit some data. Just wiring a switch to a standard RF transmitter is not enough. Though there are RF modules, which support exactly this (by having corresponding electronic components on the board). If you haven't already bought the modules, you could buy these.
If you already have bought the RF modules, you can buy a standard 433MHz key fob. They are normally rather cheap. Then you can record the key fobs signal with your receiver and write code to check for this signal in the received data.
If you plan to keep on building with Arduino, you might wanna buy directly a bunch of Arduinos (also for future projects). You can get Arduino clones directly from china for very cheap (a Nano clone for example costs normally between 1 and 2$ each in packs of maybe 10).

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


text:
Assign static IP and set host name
Im trying to assign a static IP to my ESP32 and also set the host name.
I am able to get one or the other to work, but not get them to work together.
Tried moving around WiFi.hostname & WiFi.config in the code, tried WiFi.begin and then setting hostname & IP
#include <WiFi.h>
void setup() {

IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(208, 67, 222, 222);
IPAddress secondaryDNS(208, 67, 220, 220);

WiFi.mode(WIFI_STA);
WiFi.hostname("ESP");
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.begin("xxxx", "yyyy");

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

question in a question:
The WiFi.config that that gives me a static IP is in the format local_IP, gateway, subnet, primaryDNS, secondaryDNS but the documentation for WiFi.config 2 (and also looking at the library WiFi.h code) is ip, dns, gateway, subnet.
and according to the documentation this should also work, but doesn't WiFi.config (ip)

How are you determining that the "hostname" is working or not? The concept of a "hostname" only exists in the realm of DHCP (which you aren't using), DNS (which isn't controlled by the ESP32 and you're not using anyway) or mDNS (which again you're not using).

There is no such thing as a hostname associated with a specific device.

When you request an IP from your router using DHCP the ESP32 has the option (which it uses) to tell the router what it'd like to be called. The router may, if it chooses, decide to inject that name into DNS lookups done through the router to resolve that allocated IP address.
You can manually "advertise" a name through the mDNS protocol which requires the inclusion and use of another library and some more configuration in your sketch, along with mDNS support in the devices and applications doing the name lookup (it is getting more universally implemented but is by no means certain to be available).

Since you're not using either DHCP to obtain your IP, nor using mDNS to advertise your name, there is no mechanism that exists to magically make your device have a "name" on your network.
The simplest method to "get around" the issue is to just use DHCP and let your router do all the work. If you really want a static IP address then configure your router to provide a static IP address to your device.

Well that certainly would explain my issue. But what doesn't addup is that other devices on my network (printers, NAS, etc) have static IPs and they show custom host names

Thats because these devices use DHCP to tell the router their name. Just as Majenko described. For the static IPs: you may have set the devices to static IPs in the router setting. In that case they still get their IP from the routers DHCP, just the same every time. Or they don't use DHCP and you have set the IP on the device while hopefully making sure, that no other device can have the same IP

More likely they are advertising their names with mDNS. myPrinter.local for example.

None of the devices I am talking about are using DHCP. They all have static IPs and custom hostnames in the device itself. The printers have mDNS, the NAS doesnt but I am still seeing it's custom name. Im going to try to add mDNS to the ESP32 tomorrow and see if that helps

The NAS is probably using SMB which includes network name resolution of its own.

I think you nailed it. The NAS does use SMB.


text:
How to light up middle points in a display with 4 digits?
How to light up the two points that is in the middle? It only lights up when the digB is set to LOW, and it lights up all 3 points that is in the middle.

Example code:
const int displayPins[] = {2,3,4,5,6,7,8,9,10,11,12,13};
const int digA = 7;
const int digB = 4;
const int digC = 3;
const int digD = 8;
const int decimalPoint = 10;

void setup() {
    for (int i = 0; i < (sizeof(displayPins)/sizeof(displayPins[0])); i++) {
        pinMode(displayPins[i], OUTPUT);
    }

    digitalWrite(digA, 1);
    digitalWrite(digB, 0);
    digitalWrite(decimalPoint, 1);
    digitalWrite(digC, 1);
    digitalWrite(digD, 1);
}

void loop() {
}

I want to display a clock in this format: 00:00. But did not found a way to light up the two points that is in the middle.

refer to the datasheet

@jsotola Did not found the right one, all that i found is the display with 4 digits and decimals without the two points in the middle. I also searched for the model of the item "sh5463AS-34", but did not found anything.

there are several schematics on the web ... the part number to search is in the picture you posted ... your question is not arduino specific ... voting to close

Try all the contacts that do not light up other segments. You will find the right ones eventually, if they can be separately controlled at all.

Possibly this link about exactly the same question can help. This seems to suggest that what you want might not be possible if you have the same display.

The schematic on this site shows,  that the three dots are all connected together, thus can only light up together. Seems to be the model, that you have. In that case you cannot do anything about that, other than buying a different 7segment display.

@chrisl the schematic diagram of the display may be incorrect ... the colon leds could actually be reversed

@jsotola What do you mean by "reversed"? The schematic shows the LEDs of the middle dots connected together on both sides. Or do you mean middle dots in one direction and the decimal dot in the other? We cannot really determine if the schematic is correct. That can only be done by testing the real component, but the schematic is consistent with the experiments of the OP so far

@chrisl i somehow missed the part about the three leds lighting ... have not had my morning coffee yet ... my thought was that reversing the polarity would light the colon leds ... looks like the display requires black tape for selecting the display mode

It is not possible to separate the colon dots from the decimal point dot - they are all wired together in parallel internally:

As has been mentioned in the comments you need to use the "black tape" method of selecting the LEDs. That's not a joke, that's really what's done. Cover the LED that you don't want visible with black tape (or black paint, etc).


text:
ESP8266: error: 'getLocalTime' was not declared in this scope
I am getting

error: 'getLocalTime' was not declared in this scope

when I am compiling this code for ESP8266, however works for ESP32:
#include "time.h"

void gettime()
{
  static int16_t delaycount = 0 ;                         // To reduce number of NTP requests
  static int16_t retrycount = 100 ;

  if ( timeinfo.tm_year )                                 // Legal time found?
  {
    sprintf ( timetxt, "%02d:%02d:%02d",                  // Yes, format to a string
              timeinfo.tm_hour,
              timeinfo.tm_min,
              timeinfo.tm_sec ) ;
  }
  if ( --delaycount <= 0 )                                // Sync every few hours
  {
    delaycount = 7200 ;                                   // Reset counter
    if ( timeinfo.tm_year )                               // Legal time found?
    {
      dbgprint ( "Sync TOD, old value is %s", timetxt ) ;
    }
    dbgprint ( "Sync TOD" ) ;
    if ( !getLocalTime ( &timeinfo ) )                    // Read from NTP server
    {
      dbgprint ( "Failed to obtain time!" ) ;             // Error
      timeinfo.tm_year = 0 ;                              // Set current time to illegal
      if ( retrycount )                                   // Give up syncing?
      {
        retrycount-- ;                                    // No try again
        delaycount = 5 ;                                  // Retry after 5 seconds
      }
    }
    else
    {
      sprintf ( timetxt, "%02d:%02d:%02d",                // Format new time to a string
                timeinfo.tm_hour,
                timeinfo.tm_min,
                timeinfo.tm_sec ) ;
      dbgprint ( "Sync TOD, new value is %s", timetxt ) ;
    }
  }
}

What shall I replace getLocalTime with?

It looks like the esp8266 Arduino core don't have a similar function.
The getLocalTime in esp32 arduino core is a simple function implemented in esp32-hal-time.c.
bool getLocalTime(struct tm * info, uint32_t ms)
{
    uint32_t start = millis();
    time_t now;
    while((millis()-start) <= ms) {
        time(&now);
        localtime_r(&now, info);
        if(info->tm_year > (2016 - 1900)){
            return true;
        }
        delay(10);
    }
    return false;
}

The function compiles on esp8266 arduino as it is so you can copy it to your sketch.

there are two parameters you need to pass. Whereas in my example is only one

@BJackson, the declaration in header file has a default value for the second parameter bool getLocalTime(struct tm * info, uint32_t ms = 5000); (you can't set default value on function definition). you can call the function with 5000 as second parameter or remove the parameter and use the fixed value in the function.

It works, thanks. But is there a ESP8266 way? I was looking at https://github.com/scanlime/esp8266-Arduino/blob/master/cores/esp8266/time.c and there is nothing similar

@BJackson, it is a only convenience function only to wait with timeout until the very first response from NTP server is received and RTC is set


text:
My PN532 doesn't detect RFID card when connected with ESP32 in I2C mode while it works perectly with Arduino Uno
I have a Elechouse PN532 module (bought here - https://robu.in/product/pn532-nfc-rfid-read-write-module-v3-kit/). When I try to use to it with I2C and connect it to my ESP32 (DOIT ESP32 DEV KIT V1, 30 pin version), the PN532 gets detected but it doesn't detect when a card or token shown to it. When I try the exact same code with Arduino Uno with I2C, it works flawlessly. Below are the connections for both boards, the code, the output and actual connection picture (since some said wire position matters for PN532).
Connections

ESP32

ESP32
PN532

GPIO 22
SCL

GPIO 21
SDA

3.3V
VCC

GND
GND

Arduino Uno

Uno
PN532

A5
SCL

A4
SDA

3.3V
VCC

GND
GND

The code
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);

void setup(void) {
  Serial.begin(115200);
  //Wire.begin(21, 22);        //used this line only when connected with ESP32
  Serial.println("Hello!");

  pn532i2c.wakeup();    //delays 500ms
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // Set the max number of retry attempts to read from a card
  // This prevents us from waiting forever for a card, which is
  // the default behaviour of the PN532.
  nfc.setPassiveActivationRetries(0xFF);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop(void) {
  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    Serial.println("Found a card!");
    Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i=0; i < uidLength; i++)
    {
      Serial.print(" 0x");Serial.print(uid[i], HEX);
    }
    Serial.println("");
    // Wait 1 second before continuing
    delay(1000);
  }
  else
  {
    // PN532 probably timed out waiting for a card
    Serial.println("Timed out waiting for a card");
  }
}

Output

For Arduino Uno

For ESP32

Connection Placements

For Arduino Uno

For ESP32

Also, the configuration of ESP32 in Arduino IDE

The PN532 requires I2C clock stretching. It doesn't work well over I2C with the ESP8266 or ESP32 (Adafruit has it working with the ESP32 under certain conditions - using an interrupt and being the only device on the I2C bus - you might try their driver). Your best solution is to connect it via SPI and not I2C.

Are there pullups on the board? I don't know if the arduino enables its pullups in I2C master mode, bit I don't see any on those images. Try to enable them and use the I2CScanner sketch for debugging.

@romkey While using my PN532 with Adafruit library I need to connect 6 pins right? (VCC, GND, SDA, SCL, IRQ, RST)

@SimSon I will try with external pullups and one more thing, since the firmware on PN532 is getting detected, doesn't that mean I2C is working perfectly between PN532 & ESP32, and not require external pullups? I am beginner in I2C so forgive if anything is illogical.

To use PN532, UART or SPI seems to be a good choice. Also, the little red board needs a strong power supply, and the power supply capacity from the ESP32 DEV KIT will be insufficient; I recommend adding a capacitor of about 47uF on the PN532.

Jumper settings for SPI -
For I2C is 1 up and 2 down.


text:
First I2C project - Unable to get any servo movement with PCA9685
I'm working on a project where I need to run multiple servos. For now though, I'm trying to get a single MG90S servo running with a PCA9685 servo driver but I'm unable to get any movement from the servo.
What I have setup is as follows;

Servo power is 5v 2A in the form of a standalone power supply.
Arduino UNO GND to shield GND
Arduino 5v to shield VCC
Arduino A4 to shield SDA
Arduino A5 to shield SCL (Ive also tried SDA and SCL on the uno)

The code I'm running is just the standard adafruit library example (see below) with the only change being the I2C address is set to 0x41 as I have soldiered across the first pair of pads (I have verified the new address with an I2C scanner program).
Ive tried multiple servos, two PCA9685s and two different arduinos. The servos work without the PCA9685 and I can see println info when viewing the Serial Monitor. Any ideas?

/***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 8 servos, one after the other on the
  first 8 pins of the PCA9685

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These drivers use I2C to communicate, 2 pins are required to
  interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);
// you can also call it with a different address and I2C interface
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41, Wire);

// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN  400 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

// our servo # counter
uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("8 channel Servo test!");

  pwm.begin();

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  delay(10);
}

// you can use this function if you'd like to set the pulse length in seconds
// e.g. setServoPulse(0, 0.001) is a ~1 millisecond pulse width. its not precise!
void setServoPulse(uint8_t n, double pulse) {
  double pulselength;

  pulselength = 1000000;   // 1,000,000 us per second
  pulselength /= 60;   // 60 Hz
  Serial.print(pulselength); Serial.println(" us per period");
  pulselength /= 4096;  // 12 bits of resolution
  Serial.print(pulselength); Serial.println(" us per bit");
  pulse *= 1000000;  // convert to us
  pulse /= pulselength;
  Serial.println(pulse);
  pwm.setPWM(n, 0, pulse);
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }

  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }

  delay(500);

  servonum ++;
  if (servonum > 7) servonum = 0;
}

I haven’t seen anything obviously wrong. Does the PCS9685 show up using the I2CScanner sketch? https://www.arduino.cc/reference/en/libraries/i2cscanner/

Can you post the serial monitor output?

If you do not have access to an oscilloscope to check the actual PWM output to make sure it is in the target range for the specific servo, then it might be useful to try some broader values of SERVOMIN and SERVOMAX.

While you’ve got just the one servo connected it may pay to comment out the third last line “servonum ++;” so that the loop just concentrates on exercising/swinging port 0 where you have it connected.

@RowanP
Yes the board shows with an I2C scanner. Address is 0x41 as I mentioned
12:57:17.341 -> --- Scan started --- 12:57:17.341 -> I2C device found at address 0x41  ! 12:57:17.387 -> --- Scan finished ---
No oscilloscope, but I've tried MIN 0, MAX 3500. This also doesnt work.
I have now removed the ++counter but still nothing.
13:00:18.091 -> 8 channel Servo test! 13:00:18.138 -> 0 13:00:23.585 -> 0

Do you have a multimeter? I wonder how many volts are showing V+ to GND on the PCA9685, and how many amps are being drawn from the external power supply when the sketch is running compared to when it’s idle.

Could you add a close up picture of the PCA9685 with connections? Is the polarity of the external supply the right way around?

Thanks for the reply Rowan.
Current draw from the power supply with a blank arduino sketch and the pwm example sketch are 0A which is clearly the issue. I've had a look back at the website I bought these PCA9685 boards from and there is a comment from another buyer with the exact same issue in the last week. They had no voltage to the servo connectors. I've checked and mine is the same. I get a pwm signal and I can see that changing as the script runs, but no 5v. I'm going to return the boards and buy from somewhere else. Many thanks.


text:
DS18B20 sending variable via Enthernet shield
I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.
I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:
sensors.requestTemperatures();
Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

I am sending data via ethernet shield, and important part is:
 client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...
Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

I think that the question is how to convert float to string in Arduino? ... why the misleading title? ... why all the stuff about 1-wire and temperature?  .... ask what you mean to ask, do not give a long unrelated story

Uhm, maybe because "I think" part? I am not so good with Arduino programming, and I don't see how including as much RELEVANT information as possible is a bad thing?

Having re-read the question just before posting this answer, I find it odd that the DHT temp and humidity (also floats) work for you - how odd

Use dtostrf
char tStr[9] = { 0 }; // buffer to store the string - length 9, because at most you need 8 chars "-23.5678" , plus null terminator
dtostrf(sensors.getTempCByIndex(0), 7, 3, tStr)

Note: dtostrf returns char pointer to tStr
The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values
Resolution     Arguments to dtostrf
 9             5, 1                  -nn.n
10             6, 2                  -nn.nn
11             7, 3                  -nn.nnn
12             8, 4                  -nn.nnnn

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in
For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use 5,1 for the format

This is an awesome explanation of dtostrf. I experimented a little with samples that I found online, but could not figure it out.
Anyway, I tried the code that you posted, and I get the error when I try to combine results with the rest of the string:
client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + tStr + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret= HTTP/1.1");
Error:
invalid operands of types 'const char [42]' and 'char [9]' to binary 'operator+'

the issue is the + operator on char * .. try + String(tStr) + ...

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


text:
Converting (char*)variable to int
I have the following code:
      uint8_t buf[1];
      uint8_t buflen = 1;
      if (driver.recv(buf, &buflen)) // Non-blocking
         {
            int i;
            // Message with a good checksum received, dump it.
            Serial.print("Message: ");
            Serial.println((char*)buf);//this prints out okay
            highPins[(char*)buf] = 1;
         }

The problem is in highPins[(char*)buf]. highPins is array, and in (char*)buf I get index number. When I display it with Serial.println, it shows the number, but here it does not. I am guessing its because (char*)buf is not a number. I have tried to convert it to int with few functions I have found online, but it was unsuccessful. Any help is appreciated :)

String(buf).toInt() is how i do it, but there might be better ways...

highPins[buf[0] - '0'] = 1; should do the trick :)

Note that Serial.println(const char[]) expects a NUL-terminated buffer. It will read your memory starting at &buf and continue until it finds a NUL byte.

I would suggest improving your code slightly as follows:
  uint8_t buf;
  uint8_t buflen = 1;
  if (driver.recv(&buf, &buflen)) // Non-blocking
     {
        int i;
        // Message with a good checksum received, dump it.
        Serial.print("Message: ");
        Serial.println(buf);//this prints out okay
        highPins[buf] = 1;
     }

The important point is that you do not need to declare buf as an array of just one element, but just declare the element itself (as uint8_t) and pass its address (&buf) to driver.recv(...).
As @Majenko suggested, you should alos check buf before using it as an index to highPins array, in order to avoid using an index bigger than teh array size.

The thing is, when I use your code, I get a strange result. I send string 33 with driver.send("33",  sizeof("33"));       , and with your code I get "53" over the serial. Any idea on what might be causing it?

You have to know what gets transferred between both devices: is that string or numbers? Your question made me think this was numbers (in binary representation, not as ASCII strings). You probably need to provide more details in your question.

The function you want is atoi.
int pinno = atoi((char *)buf);

I would suggest checking that the result is in the right range before using it.


text:
Door sensors on every cabinet in the kitchen
At this point, I have yet to actually touch an Arduino.  I'm toying with the RPi3 along with Home Assistant, but I'm always thinking of ways to do useless things that are fun.
Let's say I had a kitchen with 32 cabinet doors and drawers and I wanted to make sure that each one had a switch that would detect a simple on/off state.  That would translate to a map whereby a visual indicator would show that something's "ajar."

Is this the best approach to achieve this goal?
How many Arduino boards would this require, and/or are there other methods or concepts to achieve the same ultimate goal?

Thanks!

Not to douse your enthusiasm, but start simpler.  There is plenty to learn w/o getting the car out of the garage just yet.  As for your specific cabinet door open / close conundrum - I would solve it completely in software using a more powerful computer like a RaspberryPi3.  And using OpenCV and a camera.

I agree with starting simpler.  For what you are describing you would need an external multiplexer circuit to reduce the 32 switch inputs to a manageable amount like 5 bits for the address then 1 bit for the input - 6 input pins on a single Arduino.  BUT THEN you would need a way to do a "hold-up" or "hold-down" on each external input so the sensor can rely on the voltages it encounters.  ---Have you considered simply setting up an Arduino and the IDE then making the "Blink" program work?  That is how most of us began.  Once you have done that then you can see how the unit works.

Touch less sensors (IR, magnetic hall), detecting drawer state.
1pc Arduino with I/O expanders to increase I/O ports.

Since you are just starting out, start simple and build from there. Build a system that can handle one cabinet door. By doing that, you will learn a lot of the basics, without the risk of having to troubleshoot a large complex system.
The most common sensor to detect open or closed door is called a reed switch. They are low cost and simple to use.
The number of Arduinos required is mainly dependent on how much wiring you want to do. I would probably choose one battery-powered Arduino with wireless communication for each door, to avoid having wires between cabinets at all.

Most reed switches are made of glass. That link to the Sparkfun reed switch is probably a glass reed switch inside plastic. When a drawer is slammed hard or the drawer is not in shape anymore, then the reed switch could break. Would a sealed microswitch with a lever last longer ?

I was thinking that the reed switch could be embedded on the back side of the cabinet door such that it might even be flush with the surface and wouldn't be visible at all, and would probably remain in tact.


text:
3 digit 7 segment display
I have 3 digit 7 segment display with 10 pins
I found this image pinout but it not working for me I need to know the pin out of this display

How do you think you have wired it? Also, do you have the datasheet for your actual device?

What is not working? How is it connected to the arduino?

make a test tool consisting of a 1.2V battery and a 2.2k ohm resistor in series with the battery .... apply one side to pin 10 and the other side to pin 7 .... if nothing lights, reverse the wires .... if nothing lights still, try other pins ..... if no lights, lower the resistor value to 1k ohm and try again

I am also get a weired 3 digit display MK5631G3 .. find its pinout and I get this ...... check this link for circuit of the display : http://ibb.co/mvvmE8
for model of the display : http://ibb.co/hdvsnT
for pinout of the Display : http://ibb.co/b5NcMo Thank you

you are supposed to multiplex this display. Put a current limiting resistor between pins 10, 8 and 6 and the arduino and all the rest can be connected directly.
First pull pin 10 low and use pins 7,9,2,3,4,1 and 5 to set the segments of the first digit.
Then put 10 high and 8 low and again use pins 7,9,2,3,4,1 and 5 to set the segments of the second digit.
repeat with pin 6 pulled low.
You can test the display with a battery and resistor. Connect them in series and put positive on the lower left pin and negative on the upper left pin. That should light up the top left vertical segment on the left most digit. You may need to turn the display around.

I believe that the problem is that the asker has found some random datasheet on the Internet that doesn't match their device, not that they don't know how to drive it (although they may also not know how to drive it).


text:
My sketch is not working as intended
I am a beginner with Arduino. I am doing something to cool down my room temperature using an exhaust fan and cooler through relays. I am trying to reduce the temperature initially using an exhaust fan and wait for 10 minutes to see if the temperature reduced to a set range. If not, the exhaust fan is turned off and the rest of the cooling is done by the cooler.
At the beginning of the program all goes well: it turns on the exhaust fan and waits 10 minutes and if it's not dropping, it transfers the job to the cooler. But after one cycle, when the temperature increases, the cooler is turned on directly, without the exhaust fan urning on, or waiting for 10 minutes and things. I tried a lot but I can't understand what is happening. Please suggest something to solve the problem.
#include <dht.h>

dht DHT;

#define DHT1_PIN 7 // dht11 connected to pin 7

int exhaustpin = 4; // set pin for exhaust fan relay
int coolerpin = 5; // set pin for cooler relay
boolean exhaust;
void setup(){
   Serial.begin(9600);
    pinMode(exhaustpin, OUTPUT);
  pinMode(coolerpin, OUTPUT);
  digitalWrite(exhaustpin,HIGH );
  digitalWrite(coolerpin,HIGH );
  exhaust= LOW;

}
void loop()
{

    DHT.read11(DHT1_PIN);
  Serial.print(" MY Room Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("MY Room Humidity = ");
  Serial.println(DHT.humidity);
 delay(500);
  int  roomtemp =DHT.temperature;
  static unsigned long interval;
  long interval;
  if (exhaust== LOW){
  if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH )){
    digitalWrite(exhaustpin,LOW ); // if temperature increses above 30 the exhaust starts to work
     interval = millis();
  }
  }
   if (digitalRead(exhaustpin)==LOW){
     exhaust= !exhaust;
 if ((millis()-interval) >= 600000){
    digitalWrite(coolerpin,LOW );
    digitalWrite(exhaustpin,HIGH );   // after the starting of exhaust fan it wait for 10 minutes ,then it turn
                                      // on the cooler and turns off the exhaust fan
       }
   }
  if (roomtemp<28){
    digitalWrite(coolerpin,HIGH );
     digitalWrite(exhaustpin,HIGH );
     exhaust= !exhaust;
   // i am trying here to start cooling the room with my exhaust fan
   // then wait 10 minutes ,if it is still not less than 28 degrees turn on the cooler to do the cooling
   // and turn off the exhaust fan
   }
  }

FYI you may want to fix indentation, it will help a lot with making the flow of the program clear. I edited your post with that.

I doubt this code works at all. The DHT object is not initialized...

The DTH11 working part is fine.All other functions are going as planed but except the Time schedule

What should happen when the temperature drops after the cooler run to 28 and then again grows over 30? Try the fan again? Please show all the sketch after correction.

yes my intention is as you said

  if (digitalRead(exhaustpin) == LOW) {
    static unsigned long interval = millis();
    if ((millis() - interval) >= 600000) {
      digitalWrite(coolerpin, LOW);
      digitalWrite(exhaustpin, HIGH);
      // after the starting of exhaust fan it wait for 10 minutes, then it turns on
      // the cooler and turns off the exhaust fan
    }
  }

interval is only ever set once. So 10 minutes after it is first set it will remain over 10 minutes.
The simplest fix is to set interval to millis() when you set exhaustpin to low:
if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH)) {
  digitalWrite(exhaustpin,LOW );
  // if temperature increses above 30 the exhaust starts to work
  interval = millis();
}

i tried your help but now the cooler pin is not turning on after the 10 minute on the first time

interval has to be a global. You can't create it every time you enter the if clause...

can you be more specific i can't get my head behind it.

Put unsigned long interval = 0; on the line before loop() and then when you want to assign it, leave out the unsigned long and just say interval = millis()

still the problem is not solved , the interval is not working now


text:
Play .Wav sound only once on switch change
I have a project where if you change the value of the spdt switch the colour of the LEDs change. As well as this a .wav file plays. The problem is I only want the .wav to play once. At the moment it constantly plays over and over as it's within the loop. I've tried using a mute or disabling the pin after the play through but I am unable to re-enable so I scrapped it. I deally I want to keep the SPDT switch due to asthetics instead of a push switch. This is my code:
#include <TMRpcm.h>
#include <SD.h>
#define SD_ChipSelectPin 10
#include <SPI.h>

TMRpcm tmrpcm;

void setup()
{
// put your setup code here, to run once:

tmrpcm.speakerPin=9;
Serial.begin(9600);
if(!SD.begin(SD_ChipSelectPin))
{
  Serial.println("SD fail");
  return;
}
     tmrpcm.setVolume(6);
     tmrpcm.play("1.wav");
     while (tmrpcm.isPlaying()) {
     delay(1);
}
     tmrpcm.setVolume(6);
     tmrpcm.play("3.wav");
//set the switch input, pin 8, as an
pinMode(8, INPUT);

//set both the LED pins, pin 5 and 6 as OUTPUTs
pinMode (5, OUTPUT);
pinMode (6, OUTPUT);
 delay(1000);
}

void loop()
{
 int switchValue = digitalRead(8);
 if (switchValue == 1)
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
  tmrpcm.setVolume(6);
  tmrpcm.play("4.wav");
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);

}
else
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
   digitalWrite(6,HIGH);
   digitalWrite(5,LOW);
   tmrpcm.setVolume(6);
   tmrpcm.play("5.wav");

}
}

how can I make the wav play once but when the switch changes?

Make a variable to hold the "last state" of the switch. Compare that last state to the current state as obtained by switchValue = digitalRead(8).
Only call the play function if the old value and the current value are different.

Hi I added this:  if (switchValue != lastButtonState)
{
tmrpcm.setVolume(6);
tmrpcm.play("4.wav");
                      while (tmrpcm.isPlaying()) {
                  delay(1);}
              }

              lastButtonState = switchValue;

I added it on both sides of my If Statement and It worked :-)


text:
Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound
My Dad and I are just learning how to use my new UNO.
We have learned how to make leds flash at the touch of a button. We have also learned how to make a passive buzzer sound at the touch of a button and change tone to sound like a police car.
We have just learned that we cant run more than one loop so we have combined the buzzer code and the LED code twice (for blue and red LEDs) and it works... but the delay on the LEDs is ruining the buzzer sound. Is there anything we can do?
The code is below.
Thank you!
Code:
int buzzerPin = 9;    // the number of the buzzer pin
int BlueLEDpin = 5;   // the number of the blue LED pin
int RedLEDpin = 7;    // the number of the Red LED pin
float sinVal;         // Define a variable to save sine value for buzzer
int toneVal;          // Define a variable to save sound frequency for buzzer

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT); // Set Blue LED pin to output mode
  pinMode(RedLEDpin, OUTPUT); // Set Red LED pin to output mode
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

void RedLED() {
  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

+1 for nicely formatted code ... would give you another, if i could, for keeping comments and code separate ... code that is joy to look at

Wow, thanks. We are feeling very proud right now.

We made it better with Nathan's pointer.
We learned how to make a class but the LEDs flashed together so we learned how to make another class (with Public and Void Update in the class - caught us out at first that bit). One class starts with state HIGH and the other with state LOW so the LEDs alternate. When we press all three buttons we get the two tone buzzer, and the alternating LEDs.
Using this method we can add as many new LEDs as we like.
Here is the code we wrote:
/*
  Jacob & Dad’s Police Car light and sounds
*/

int buzzerPin = 9;
float sinVal;
int toneVal;

class FlashingLED_A
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_A(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = LOW;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

class FlashingLED_B
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_B(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = HIGH;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

FlashingLED_A led1(5, 100, 400);
FlashingLED_B led2(7, 100, 400);

void setup() {
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  Buzzer();
    led1.Update();
    led2.Update();
}

void Buzzer() {
  for (int x = 0; x < 360; x++) {
    sinVal = sin(x * (PI / 180));
    toneVal = 2000 + sinVal * 500;
    tone(buzzerPin, toneVal);
    delay(1);
  }
 }

Is the only difference between FlashingLED_A and FlashingLED_B the fact that A starts LOW and B starts HIGH?  If so then I would add an extra parameter to the class constructor and just use one of the classes.

Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.

Thanks very much Harper; that was very helpful. We followed your advice and have just solved it!!! Thanks!

That was quick work! Glad you got it going.

We have done it. Thanks for the help Harper Shelby.
We combined the Blink Without Delay example with our original code:
int buzzerPin = 9;    // the number of the buzzer pin
const int BlueLEDpin = 5;
const int RedLEDpin = 7;
float sinVal;         // Define a variable to save sine value
int toneVal;          // Define a variable to save sound frequency
int BlueLEDState = LOW;
int RedLEDState = HIGH;
unsigned long previousMillisBlue= 0;
unsigned long previousMillisRed= 0;
const long interval = 200;

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT);
  pinMode(RedLEDpin, OUTPUT);
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  unsigned long currentMillisBlue = millis();

  if (currentMillisBlue - previousMillisBlue >= interval) {
    previousMillisBlue = currentMillisBlue;
    if (BlueLEDState == LOW) {
      BlueLEDState = HIGH;
    } else {
      BlueLEDState = LOW;
    }

    digitalWrite(BlueLEDpin, BlueLEDState);
  }

}

void RedLED() {
  unsigned long currentMillisRed = millis();

  if (currentMillisRed - previousMillisRed >= interval) {
    previousMillisRed = currentMillisRed;
    if (RedLEDState == LOW) {
      RedLEDState = HIGH;
    } else {
      RedLEDState = LOW;
    }

    digitalWrite(RedLEDpin, RedLEDState);
  }

}

Firstly, congratulations! you've taken your first step into the very rewarding world of micro-controllers. I teach robotics at a local university, so it's always nice to see when the light-bulb goes on and people start understanding.
As mentioned above, the blink without delay code is a good start. Good code should also be expandable in case later you want to add another light or 10, and this is where coding every line can get very large. There are many other methods for doing this sort of task, however you might want to have a look at this series of tutorials. Multitasking with the Arduino.
The benefit to the state machine approach used in that example is it becomes very easy later on to change your code; if you want to have more lights flashing in sequence (like the knight-rider lights) or more sirens, it becomes easier to include. In your second code, the void redLED() and void blueLED() codes contain mostly the same lines; you could make an object called 'LED' and then just make as many instances of this as you need, all working at different speeds and different pins (the example on the website should provide this much. The buzzer can probably reuse the servo sweep part of the code). You could also for example, program 4 different types of siren as a switch:case, and after the elapsed time, switch between them.
Another more advanced method would be to include a real-time operating system. An RTOS makes it very easy to have multiple independent tasks running. Each light could be on its own task and the siren on a third, and the system would keep each working, effectively simultaneously. This approach then has advantages if you want to change the timing of one light; it gets changed in one place without fear of needing to change the whole code. Information on FreeRTOS on the arduino can be found here. There is an example at the bottom of the page which includes both Blink and analog read examples.
These are fairly advanced topics, but I think you and your dad will get there. Once again, congratulations.

Thank you very much Nathan! We will look in to this next, and the website link you gave us looks great.

This is probably a bit advanced but...
You could use a base class and pointers to the derived LED and Buzzer classes to reduce you loop function to a loop.  You won't gain much at this level, but as you add more objects, such as the flashing headlights and mirror lights, maybe even a rear facing message board you will make life easier for your self.
/*
Jacob & Dad’s Police Car light and sounds
*/

class BaseOutputObject
{
protected:
    int Pin;
public:
    BaseOutputObject(const int& pin)
        : Pin(pin)
    {
        pinMode(Pin, OUTPUT);
    }
    virtual void Update()
    {
    }
};

class FlashingLED : public BaseOutputObject
{
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
public:
    FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
        : BaseOutputObject(pin)                     // Call base class constructor
        , OnTime(on)                            // Use initialisers rather than assignments
        , OffTime(off)
        , ledState(startLow ? LOW : HIGH)
        , previousMillis(0)
    {
    }

    void Update()
    {
        // check to see if it's time to change the state of the LED
        const unsigned long currentMillis = millis();           // Make it const because it won't change within this call of the function.

        if (currentMillis - previousMillis >= OnTime)
        {
            ledState = (ledState == LOW ? HIGH : LOW);  // Toggle the state.
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(Pin, ledState);  // Update the actual LED
        }
    }
};

class Buzzer : public BaseOutputObject
{
    float SinValue;
    int ToneValue;
public:
    Buzzer(const int& pin)
        : BaseOutputObject(pin)
        , SinValue(0.0f)        // Always initialise variables, in case you change the code later.
        , ToneValue(0)
    {
    }

    void Update()
    {
        for (int x = 0; x < 360; x++)
        {
            SinValue = sin(x * (PI / 180));
            ToneValue = 2000 + SinValue * 500;
            tone(Pin, ToneValue);
            delay(1);
        }
    }

};

// The objects could be declared dynamically, but thats not a great idea on embedded systems.
FlashingLED ledOne(5, 100, 400);
FlashingLED ledTwo(7, 100, 400);
Buzzer buzzer(9);
enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
// Have to have pointers to the objects to allow you to cast them down to the base objects.
BaseOutputObject* objects[MaxObjects] = {  &ledOne, &ledTwo, &buzzer};

void setup()
{
}

void loop()
{
    for (int index = 0; index < MaxObjects; ++index)
    {
        objects[index]->Update();
    }
}


text:
Problem Using pins A4 and A5 for input and output I2C
Hardare used:
Arduino nano ( old Bootloader )
Oled Monochrome Display ( 4 pins, 128 x 32 )
MPU 6050
Both display and MPU use A4 and A5 as I2C communication protocol, They interfere, as the MPU is used 2-way and the Display 1-way.

How can I change those 2 pins( does not matter witch Display/Sensor )
Can this method ( the one you propose ) be used for more cases like this? ( ex 3 sensors )

There is what I tried so far:
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;

#define OUTPUT_READABLE_YAWPITCHROLL
#define OUTPUT_READABLE_REALACCEL

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
volatile bool mpuInterrupt = false;
void dmpDataReady() {
  mpuInterrupt = true;
}

void setup() {
  volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
   for(;;); // Don't proceed, loop forever
  }

  // Clear the buffer
  display.clearDisplay();

  delay(150);

  #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    delay(50);

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

  if (devStatus == 0) {
        // Calibration Time: generate offsets and calibrate our MPU6050
        mpu.CalibrateAccel(6);
        mpu.CalibrateGyro(6);
        mpu.PrintActiveOffsets();
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

  Serial.begin(9600);
}

void loop() {
  if (!dmpReady) return;
    // read a packet from FIFO
    if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) { // Get the Latest packet

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            /*
            data.gyro_data[0] = ypr[0] * 180/M_PI;
            data.gyro_data[1] = ypr[1] * 180/M_PI;
            data.gyro_data[2] = ypr[2] * 180/M_PI;
            */
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            /*
            data.acc_data[0] = aaReal.x;
            data.acc_data[1] = aaReal.y;
            data.acc_data[2] = aaReal.z;
            */
        #endif
    }

    display.print(String(ypr[0] * 180/M_PI));
    display.print('/');
    display.print(String(ypr[1] * 180/M_PI));
    display.print('/');
    display.print(String(ypr[2] * 180/M_PI));
    display.print("\n\n");
    display.print(String(aaReal.x));
    display.print('/');
    display.print(String(aaReal.y));
    display.print('/');
    display.print(String(aaReal.z));

    //display.print(String(data.id));
    display.display();

    delay(500);
}

Now I know this looks like a bunch of code thrown together with the hope to work, But it is composed from 2 other of my codes separately for MPU and Display, those work fine.

They interfere, as the MPU is used 2-way and the Display 1-way. -- No, that's nonsense. I2C is bidirectional half duplex regardless. Even if you only think you use one direction you're actually always using both. You have described everything except the actual problem  You say they "interfere" but don't actually tell us how you think they interfere with each other or what the symptoms actually are.

Several devices can share an I2C bus, unless they have the same address (which is unlikely with a display and an MPU).

There are many aspects of your code that don't make any sense. Such things as the whole of the interrupt system (which appears to do nothing at all).

#include "I2Cdev.h" #include "MPU6050_6Axis_MotionApps20.h" take care of communication with the MPU, and through previous tests the interrupt pin stabilises the z-axis. I used this as a reference. Then what I mean by interference is that normally the display would show 0.00/0.00/0.00 on two lines, ( as there is no data). But with the MPU added it just shows some random pixels on.

So after repeated tests I found several problems, software and hardware.

The cables I used on the breadboard where facing each other. The metal parts where touching ( from a defect of the cables ). Turned them 90*.

The Oled display was NOT Initialized properly. When using display.write() or display.print() you must first put the cursor at (0;0) by display.setCursor(0,0). Furthermore for more compatibility in Setup(){} you have to add display.setTextSize(1) and display.setTextColor(WHITE).

Power control. I found the best, either adding a capacitor on the VCC and GND lines when using them to power 2 Sensors at the same time, or ad a 5 mls delay in the first function. delay(5)


text:
Adafruit MPU-6050 and adafruit I2C Multiplexer

I have 3 adafruit MPUs hooked up to adafruit I2c Multiplexer. All of which is hooked up to a Arduino uno.
Attached is also my code.
/* Assign a unique ID to this sensor at the same time */

/*Adafruit_HMC5883_Unified mpu1 = Adafruit_HMC5883_Unified(1);
Adafruit_HMC5883_Unified mpu2 = Adafruit_HMC5883_Unified(2);*/

#define TCAADDR 0x70

#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu1 = Adafruit_MPU6050();
Adafruit_MPU6050 mpu2 = Adafruit_MPU6050();
Adafruit_MPU6050 mpu3 = Adafruit_MPU6050();

void displaySensorDetails(Adafruit_MPU6050 *mpu)
{
sensor_t sensor;
mpu->getGyroSensor();
Serial.println("------------------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" uT");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" uT");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" uT");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}

void setUpMPU(Adafruit_MPU6050 *mpu)
{
  mpu->setAccelerometerRange(MPU6050_RANGE_8_G);
  Serial.print("Accelerometer range set to: ");
  switch (mpu->getAccelerometerRange()) {
  case MPU6050_RANGE_2_G:
    Serial.println("+-2G");
    break;
  case MPU6050_RANGE_4_G:
    Serial.println("+-4G");
    break;
  case MPU6050_RANGE_8_G:
    Serial.println("+-8G");
    break;
  case MPU6050_RANGE_16_G:
    Serial.println("+-16G");
    break;
  }
  mpu->setGyroRange(MPU6050_RANGE_500_DEG);
  Serial.print("Gyro range set to: ");
  switch (mpu->getGyroRange()) {
  case MPU6050_RANGE_250_DEG:
    Serial.println("+- 250 deg/s");
    break;
  case MPU6050_RANGE_500_DEG:
    Serial.println("+- 500 deg/s");
    break;
  case MPU6050_RANGE_1000_DEG:
    Serial.println("+- 1000 deg/s");
    break;
  case MPU6050_RANGE_2000_DEG:
    Serial.println("+- 2000 deg/s");
    break;
  }

  mpu->setFilterBandwidth(MPU6050_BAND_21_HZ);
  Serial.print("Filter bandwidth set to: ");
  switch (mpu->getFilterBandwidth()) {
  case MPU6050_BAND_260_HZ:
    Serial.println("260 Hz");
    break;
  case MPU6050_BAND_184_HZ:
    Serial.println("184 Hz");
    break;
  case MPU6050_BAND_94_HZ:
    Serial.println("94 Hz");
    break;
  case MPU6050_BAND_44_HZ:
    Serial.println("44 Hz");
    break;
  case MPU6050_BAND_21_HZ:
    Serial.println("21 Hz");
    break;
  case MPU6050_BAND_10_HZ:
    Serial.println("10 Hz");
    break;
  case MPU6050_BAND_5_HZ:
    Serial.println("5 Hz");
    break;
}
}

void tcaselect(uint8_t i) {
if (i > 7) return;
Wire.beginTransmission(TCAADDR);
Wire.write(1 << i);
Wire.endTransmission();
}

void setup(void)
{
while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens
Serial.begin(115200);
Serial.println("HMC5883 Magnetometer Test"); Serial.println("");
Serial.println("HMC5883 Magnetometer Test"); Serial.println("");

/* Initialise the 1st sensor */
tcaselect(0);
mpu1.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu1.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu1.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Initialise the 2 sensor */
tcaselect(1);
mpu2.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu2.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu2.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Initialise the 3rd sensor */
tcaselect(2);
mpu3.setAccelerometerRange(MPU6050_RANGE_8_G);
Serial.print("Accelerometer range set to: ");
switch(mpu1.getAccelerometerRange()) {
case MPU6050_RANGE_2_G:
  Serial.println("+-2G");
  break;
case MPU6050_RANGE_4_G:
  Serial.println("+-4G");
  break;
case MPU6050_RANGE_8_G:
  Serial.println("+-8G");
  break;
case MPU6050_RANGE_16_G:
 Serial.println("+-16G");
  break;
}
mpu3.setGyroRange(MPU6050_RANGE_500_DEG);
Serial.print("Gyro range set to: ");
switch (mpu1.getGyroRange()) {
case MPU6050_RANGE_250_DEG:
  Serial.println("+- 250 deg/s");
  break;
case MPU6050_RANGE_500_DEG:
  Serial.println("+- 500 deg/s");
  break;
case MPU6050_RANGE_1000_DEG:
  Serial.println("+- 1000 deg/s");
  break;
case MPU6050_RANGE_2000_DEG:
  Serial.println("+- 2000 deg/s");
  break;
}
mpu3.setFilterBandwidth(MPU6050_BAND_21_HZ);
Serial.print("Filter bandwidth set to: ");
switch (mpu1.getFilterBandwidth()) {
case MPU6050_BAND_260_HZ:
  Serial.println("260 Hz");
  break;
case MPU6050_BAND_184_HZ:
  Serial.println("184 Hz");
  break;
case MPU6050_BAND_94_HZ:
  Serial.println("94 Hz");
  break;
case MPU6050_BAND_44_HZ:
  Serial.println("44 Hz");
  break;
case MPU6050_BAND_21_HZ:
  Serial.println("21 Hz");
  break;
case MPU6050_BAND_10_HZ:
  Serial.println("10 Hz");
  break;
case MPU6050_BAND_5_HZ:
  Serial.println("5 Hz");
  break;
}

/* Display some basic information on this sensor */
tcaselect(0);
displaySensorDetails(&mpu1);
tcaselect(1);
displaySensorDetails(&mpu2);
tcaselect(2);
displaySensorDetails(&mpu2);
}

void loop(void)
{
/* Get a new sensor event */
sensors_event_t a, g, temp;
tcaselect(0);
mpu1.getEvent(&a, &g, &temp);
/* Display the results (magnetic vector values are in micro-Tesla (uT)) */
Serial.print("Sensor #1 - ");
//Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print(" ");
//Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print(" ");
//Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print(" ");Serial.println("uT");
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");

tcaselect(2);
mpu2.getEvent(&a, &g, &temp);
/* Display the results (magnetic vector values are in micro-Tesla (uT)) */
Serial.print("Sensor #2 - ");
Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print(" ");
Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print(" ");
Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print(" ");Serial.println("uT");
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");
delay(500);
}

In this configuration All of my mpu sensors are sending back unreasonable numbers for acceleration and temperature. Am I initializing my mpus correctly in my code?

It seems like you would need to call .begin() on your Adafruit_MPU6050 instances, like the examples do.
So, following the pattern, in setup() you would need to:
 tcaselect(0);
 if (!mpu1.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 1"));
    while (1) {
      delay(10);
    }
 }

 tcaselect(1);
 if (!mpu2.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 2"));
    while (1) {
      delay(10);
    }
 }

 tcaselect(2);
 if (!mpu3.begin()) {
    Serial.println(F("Failed to find MPU6050 chip 3"));
    while (1) {
      delay(10);
    }
 }

I see you're removing some repetition with functions.  I'm guessing you just haven't gotten to doing that with the repeated switch statements for printing frequencies and such. You may want to put your mcu1/mcu2/mcu3 into an array instead for similar reasons.
An array of Adafruit_MPU6050:
Adafruit_MPU6050 mpus[3];

The code for calling begin() could look something like:
size_t index = 0;
for (auto &an_mpu: mpus) {
  tcaselect(index);
  if (!an_mpu.begin()) {
    Serial.print(F("Failed to find MPU6050 chip, mpu["));
    Serial.print(index);
    Serial.println(']');
    Serial.println(F("Halting..."));
    while (1) {
      delay(10);
    }
  }

  ++index;
}

Thanks for the nice and helpful answer :), usually people are pretty condescending

You don't need the I2C multiplexors at all - I currently have seven MPU6050 modules being managed by one Teensy 3.5 chip.  Four MPU6050's are on one of the T3.5's I2C busses, and the remaining three are on another.  I could run them all from just one I2C bus, but I split them just for wiring convenience.  The 'trick' is to replace the I2C address of each MPU6050 in turn in the setup() routine, as shown by the code associated with the blog post referenced below
See this post and related ones on my blog site 'Paynter's Palace'.
I've been using this technique for quite a while now, so let me know if you have any additional questions.
22 Sept 21 edit:
Here's the function that handles address initialization for the four MPU6050's on the Wire2 I2C bus:
bool InitWire2Sensors()
{
  delay(1000);
  Serial.printf("Initializing VL53L0X Sensor Array Elements on Wire2\n");
  bool retval = true;

  //Put all sensors in reset mode by pulling XSHUT low
  digitalWrite(LF_XSHUT_PIN, LOW);
  digitalWrite(LC_XSHUT_PIN, LOW);
  digitalWrite(LR_XSHUT_PIN, LOW);
  digitalWrite(Rear_XSHUT_PIN, LOW);

  //left-front
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LF_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LF.init())
  {
    Serial.println("Failed to detect and initialize LF sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LF successfully initialized at %x\n", lidar_LF.getAddress());
    lidar_LF.setMeasurementTimingBudget(20000);
    lidar_LF.startContinuous();

    lidar_LF.setAddress(DEFAULT_VL53L0X_ADDR + 4);
    Serial.printf("lidar_LF. address is now 0x%x\n", lidar_LF.getAddress());
  }

  //now bring lidar_LC only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LC_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LC.init())
  {
    Serial.println("Failed to detect and initialize LC sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LC successfully initialized at %x\n", lidar_LC.getAddress());
    lidar_LC.setMeasurementTimingBudget(20000);
    lidar_LC.startContinuous();

    lidar_LC.setAddress(DEFAULT_VL53L0X_ADDR + 5);
    Serial.printf("lidar_LC. address is now 0x%x\n", lidar_LC.getAddress());
  }

  //now bring lidar_LR only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LR_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LR.init())
  {
    Serial.println("Failed to detect and initialize LR sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LR successfully initialized at %x\n", lidar_LR.getAddress());
    lidar_LR.setMeasurementTimingBudget(20000);
    lidar_LR.startContinuous();

    lidar_LR.setAddress(DEFAULT_VL53L0X_ADDR + 6);
    Serial.printf("lidar_LR. address is now 0x%x\n", lidar_LR.getAddress());
  }

  //now bring lidar_Rear only out of reset and set it's address
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(Rear_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_Rear.init())
  {
    Serial.println("Failed to detect and initialize Rear sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_Rear successfully initialized at %x\n", lidar_Rear.getAddress());
    lidar_Rear.setMeasurementTimingBudget(20000);
    lidar_Rear.startContinuous();

    lidar_Rear.setAddress(DEFAULT_VL53L0X_ADDR + 7);
    Serial.printf("lidar_Rear. address is now 0x%x\n", lidar_Rear.getAddress());
  }
  //input w/o pullups sets line to high impedance so XSHUT pullup to 3.3V takes over
  pinMode(LR_XSHUT_PIN, INPUT);
  delay(10);

  if (!lidar_LR.init())
  {
    Serial.println("Failed to detect and initialize LR sensor!");
    retval = false;
  }
  else
  {
    Serial.printf("lidar_LR successfully initialized at %x\n", lidar_LR.getAddress());
    lidar_LR.setMeasurementTimingBudget(20000);
    lidar_LR.startContinuous();

    lidar_LR.setAddress(DEFAULT_VL53L0X_ADDR + 2);
    Serial.printf("lidar_LR. address is now 0x%x\n", lidar_LR.getAddress());
  }

  return retval;
}

Frank

Good point:  Here's the 'essential' code snippet:

Wow I was really confused about the Teensy 3.5 chip name, I thought you just meant a small chip. Thanks for the helpful answer :)


text:
What external battery do I need?
For a school project I need to connect an Arduino with an accelerometer gyroscope sensor and 2 mini servo motors. Of course I need a battery for this. However, I don’t know what battery I need for this. I have no clue where to start. Does anyone know which battery I can use? Or how I can find this out? I added links of the sensor, Arduino and servo motors that I have below.
Thanks in advance! :)
Sensor:
https://www.tinytronics.nl/shop/nl/sensoren/acceleratie-rotatie/mpu-6500-accelerometer-gyroscope-6dof-module-3.3v-5v
Arduino uno:
https://www.tinytronics.nl/shop/nl/development-boards/microcontroller-boards/arduino-compatible/uno-r3-met-usb-kabel
Mini servo motor:
https://www.tinytronics.nl/shop/nl/mechanica-en-actuatoren/motoren/servomotoren/ts90d-mini-servo-1.6kg-continuous

Before you can select a battery, you have to find out how much current your setup uses. You could do this by connecting everything up to a power supply, running the code you intend to run on batteries and measuring the (average) current from the power supply with a multimeter. You also have to figure out how long you need your battery to last as this will determine the minimum capacity you need. You need to take into account voltage conversion (for example for converting the output of a 3.7V LiPo to the 5V needed by the Arduino).

If you don't want to build your own battery system, you could probably just use a common 5V power bank (i.e. the type used for charging your phone on the road) with sufficient capacity.

Unless you want to make the battery part of your learning experience I second StarCats suggestion of the USB power bank. It is the easiest way to add a battery. I often use them in my projects. Though this can also depend on the exact power bank. Often the bigger ones automatically turn off, when not enough current is drawn. Havent seen that with cheap little power banks (which might be enough for you)

@chrisl There is kind a remedy for these auto turn-off power banks, designed by Mr Carlson

Hi Thank you for answering! Sadly I do not have a multimeter of anything like that. I am really not familiar with things like this to be honest… So what battery should I use now then? …

given the constraints of usb power bank, and an unknown amp hour need and no ability to figure it out, go with the highest amp hour usb power bank you can use and hope it's enough.

If you can't figure the requirements out you are only left with trail and error. I would think any USB power bank can provide enough current for your project. Then choose a power bank with an amp hour rating of your liking (that sets the run time with the fully charged power bank


text:
How to change brightness of LED light?
I'm trying to change the brightness of an LED light with RGB. I can change the brightness of simple colors like red, green, and blue. But I'm not sure how to change brightness of colors like purple, turquoise, and yellow green.

When it comes to adjusting the brightness of red, green, and blue. I have tried changing the values inside colorRGB().
With colorRGB():
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup(){
    pinMode(redPin, OUTPUT);
    delay(500);
    pinMode(greenPin, OUTPUT);
    delay(500);
    pinMode(bluePin, OUTPUT);
    delay(500);
}
void loop(){
    colorRGB(255, 0, 0); //Brightness level 255
    colorRGB(150, 0, 0); //Brightness level 150
    colorRGB(50, 0, 0); //Brightness level 50
}
void colorRGB(int red, int green, int blue){
    analogWrite(redPin, red);
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
}

I have also tried using analogWrite(), however it needs the pin as one of its arguments so I'm not quite sure how to connect that with the already set up colors inside void loop(){}.

To change the brightness of any RGB color you need to multiply each color component by the brightness ratio. Lets look at some examples:

Red is 255,0,0 in RGB. Full brightness is represented by 1, half brightness by 0.5, quarter brightness by 0.25 and so on. So we get the following values (we are doing integer calculations, so cutting away any decimal digits):

half brightness: 255*0.5,0*0.5,0*0.5 --> 127,0,0
quarter brightness: 255*0.25,0*0.25,0*0.25 --> 63,0,0

Yellow is the combination of red and green, so 255,255,0. Doing the same math as above we get:

half brightness: 255*0.5,255*0.5,0*0.5 --> 127,127,0
quarter brightness: 255*0.25,255*0.25,0*0.25 --> 63,63,0

Cyan is the combination of red green and half blue, so 255,255,127. Doing the same math as above we get:

half brightness: 255*0.5,255*0.5,127*0.5 --> 127,127,63
quarter brightness: 255*0.25,255*0.25,127*0.25 --> 63,63,31

So you can change your function to include a brightness parameter:
void colorRGB(int red, int green, int blue, int brightness_percent){
    analogWrite(redPin, red*brightness_percent/100);
    analogWrite(greenPin, green*brightness_percent/100);
    analogWrite(bluePin, blue*brightness_percent/100);
}

Here I used not the value range from 0 to 1 but instead in percent from 0 to 100. This is because floating point operations on Arduinos are rather time intensive (because the Arduino has no hardware for that and needs to do all that in software) so its better to multiply by the percent value and then divide by 100. So we have only integer calculations which is way faster. The outcome is the same.
Note: As the the color components get in the lower values you might see color errors due to the quantification. Though normally RGB LEDs aren't really color accurate either so probably you won't notice.

Thank you so much. I was actually thinking about manually converting it with percentages or fractions in relation to the brightness, but I thought I would be wrong. Thank you very much once again.

I just created a simple simulation for the nice answer written.
Here is the code:
int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup() {
  pinMode(redPin, OUTPUT);
  delay(500);
  pinMode(greenPin, OUTPUT);
  delay(500);
  pinMode(bluePin, OUTPUT);
  delay(500);
}
void loop() {
  colorRGB(255, 0, 0, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 0, 0, 25); //Brightness level 25%
  delay(3000);

  colorRGB(255, 255, 0, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 255, 0, 25); //Brightness level 25%
  delay(3000);

  colorRGB(255, 255, 127, 100); //Brightness level 100%
  delay(3000);
  colorRGB(255, 255, 127, 25); //Brightness level 25%
  delay(3000);
}
void colorRGB(int red, int green, int blue, int brightness_percent) {
  analogWrite(redPin, red * brightness_percent / 100);
  analogWrite(greenPin, green * brightness_percent / 100);
  analogWrite(bluePin, blue * brightness_percent / 100);

}

i hope this is helpful. I am from the Wokwi team and I will welcome all your questions.
You can have a look at the Wokwi Arduino simulation link here:
https://wokwi.com/arduino/projects/313797447551812161


text:
Common/standard library and/or protocol for Arduino to be I2C slave for driving NeoPixel
I would like to control a string of WS2812/NeoPixels from a SBC like a BeagleBone or C.H.I.P. I realize someone has gone through the trouble to come up with a way to drive the WS2812 string from a BeagleBone directly with the PMU, but I would like to have an Arduino like a Pro Mini do the signal generation, while the SBC would direct the Arduino what to display.
I found the node-pixel setup with I2C backpack on the arduino, but it requires on the SBC side NodeJS, Johnny-Five and other libraries that I would have no other use for. It seems overkill.
Is there some commonly used protocol over I2C for controlling NeoPixels (with the arduino being the I2C slave), or will I be better off developing my own simple protocol?
On the SBC side, I would likely be coding either in C/C++ or Python.

You could use APA102 led strips, they use an "spi-like" protocol (see datasheet) which is much less time-restrictive. Using the right parts is IMHO a better solution than adding more parts to get something working.

Plus, NeoPixel's timing constraints are so bad that you can't even generate the pixels on the go. You need to put the whole strip in memory, before writing it. The APA102 led strips can be "streamed", pixel by pixel. So you can "calculate-send, calculate-send, calculate-send" to theoretically drive limitless strips witouth using limitless memory ;)

@Paul wrote: “NeoPixel's timing constraints are so bad that you can't even generate the pixels on the go”. No, they aren't so bad. See: NeoPixels Revealed: How to (not need to) generate precisely timed signals.

If it helps simplify your project, I wrote a small library that outputs to NeoPixels using the SPI hardware. The code to send one byte is simply this on the Atmega328P:
void sendByte (byte b)
  {
    // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
    //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
    for (byte bit = 0; bit < 8; bit++)
      {
      if (b & 0x80) // is high-order bit set?
        SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
      else
        SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
      b <<= 1; // shift next bit into high-order position
    } // end of for each bit
} // end of sendByte

One pixel is 3 bytes (green / red / blue):
void sendPixel (const byte r, const byte g, const byte b)
  {
  sendByte (g);        // NeoPixel wants colors in green-then-red-then-blue order
  sendByte (r);
  sendByte (b);
  } // end of sendPixel

The timing issue arises because the pixels "latch" if around 9µs elapses with no data. Thus you either precompute the data to be sent, or decide what to send very quickly.

Under the circumstances, using I2C, you would need to precompute the data, these is no way you could receive I2C on the fly and send it out to the Neopixels with them latching.

Is there some commonly used protocol over I2C for controlling NeoPixels ?

Not that I am aware of. I suggest you either send the pixel data (which would be a lot, and have to be broken into smallish packets), or send a "pattern number" and have the receiver generate the data.
Be aware that the standard I2C library has a 32-byte buffer so you can't send hundreds of bytes in a single I2C transaction.

Fortunately, this particular project is only using 3 to 5 LEDs and I can have the Arduino hold pre-computed patterns to be selected by the host controller. [I am using FastLED for the actual NeoPixel signalling.]

You should break your project up into smaller parts.

Consider using other led strips, that can be driven directly. Consider using ready-made parts or opensource code (google).
Make an Arduino drive a NeoPixel Ledstrip. (Check adafruit libraries/NeoPixel guide)(Sanity/wiring check)
Communicate with Arduino and Beaglebone over I2C. Try sending "Hi" and respond "Ok".
Think of a protocol, how to indicate start/stop of a message.
Send the "color bytes" using said protocol.
Unpack the color bytes and put them in a pixel array (See NeoPixel library).
Run "ledstrip.show();”

Please atleast try to do these steps. If one fails, you can create a question with details on what you have tried or what isn't working.
Maybe "nodepixel" already has the Arduino code for you. You then only need to know what bytes to send over I2C, which you can do with any programming language that supports I2C access on your platform.

Appreciate the response, but I have success on steps 1, 2, 3 and 7. Steps 4, 5, and 6 constitute the heart of my question -- is there a popular/standard/common protocol, or is it simply better that I "think of a protocol" myself.


text:
Is there a need to put a delay in the main loop
Im a complete beginner. Generally speaking, is there any need at all to have a delay in the main loop()? Im not used to writing infinite loops
Is it correct to say that the delay() command is simply helpful for tutorials (i.e turn light on, wait, turn light off. wow!) but normally speaking a delay would not be helpful, and instead we are just rapidly infinitely polling our connected devices. Is that correct?
(I get that in some specialized cases it might be helpful to put a delay in the loop. Im not asking about the specialized cases.)

Like anything, it depends--I'm not sure there's a "normally speaking" given the wide range of Arduino applications. "delay" is perfectly suitable when there are no other time-sensitive processes (interrupts, background tasks, etc.) happening during the delay.

@DaveNewton  If you want to post an answer please do so. Comments under questions are for clarifying the question, which this comment does not do. If you make a proper answer you may well get credit for it, and people can comment on the accuracy or otherwise of your answer.

There is no absolute need for any Arduino program to use delay()
The blink without delay sketch that is included in the standard sketch examples is the canonical illustration of this.
In most cases you don't need to poll your sensors thousands of times a second. It is good discipline to only poll sensors as often as makes sense for the specific application. Sometimes this might be once every five minutes. For example an ambient temperature sensor. In those cases there is nothing to be gained be polling a thousand times a second. To do so wastes resources and is a poor habit that could be troublesome for battery powered applications.
For example, the use of millis() for timing allows you to effectively poll several peripherals each at different intervals, perhaps averaging some readings to reduce noise, perhaps also updating a display at other intervals that suit human perception.
For long running battery powered applications it is likely that you will benefit from finding out about putting the microcontroller to sleep using sleep() or deepSleep() and using interrupts to wake it. A real time clock (RTC) or the watchdog timer interrupt can perhaps be used to schedule your sensor readings and other actions, perhaps in conjunction with millis().
For very simple programs that don't need precise timings. delay() can be the simplest and clearest way to manage timings.

+1 Good answer. I would add that sometimes one needs to rate limit specific actions, which rely on hardware or other code, to avoid problems (like buffer overruns, filling up the Serial buffer, which then blocks execution),...). Using delay() is one easy way to do it, though by far not the best.

In many cases, rate-limiting the polling is only useful if you sleep. On a mains-powered application, polling thousands of times a second is fine, and is easier.

No, there is no need to use delay() at all. Unlike the sleep() or deepSleep() commands, delay does not save power or do anything else that's special.
The standard implementation of delay is just doing a busy-wait until the time has elapsed, something like:
void delay(int ms)
{
    int end = millis() + ms;
    while (millis() < end) {}; // do nothing
}

So for the CPU itself, this just wastes CPU cycles, it doesn't save any power.


text:
Combining the code of MAX30100 and DS-18B20
sorry to ask this but I am very very new to Arduino.
My project aims to collect the skin temperature by 18B20 and the heart rate & SPO2 level by MAX30100.
I have tested the codes for the respective sensors and they work fine, but when i am trying to merge these two codes together, only 18B20 works and 30100 isn't delivering any information (Heart rate:0.00bpm / SpO2:0%). Is there a way to combine these two codes? Thank you very much!
Code of 18B20
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire device
OneWire oneWire(ONE_WIRE_BUS);

// Pass oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);

void setup(void)
{
  sensors.begin();  // Start up the library
  Serial.begin(9600);
}

void loop(void)
{
  // Send the command to get temperatures
  sensors.requestTemperatures();

  //print the temperature in Celsius
  Serial.print("Temperature: ");
  Serial.print(sensors.getTempCByIndex(0));
  Serial.print((char)176);//shows degrees character
  Serial.print("C  |  ");

  delay(500);
}

Code of 30100
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#define REPORTING_PERIOD_MS     1000

PulseOximeter pox;
uint32_t tsLastReport = 0;

void onBeatDetected()
{
    Serial.println("Beat!");
}

void setup()
{
    Serial.begin(115200);
    Serial.print("Initializing pulse oximeter..");

    // Initialize the PulseOximeter instance
    // Failures are generally due to an improper I2C wiring, missing power supply
    // or wrong target chip
    if (!pox.begin()) {
        Serial.println("FAILED");
        for(;;);
    } else {
        Serial.println("SUCCESS");
    }
     pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);

    // Register a callback for the beat detection
    pox.setOnBeatDetectedCallback(onBeatDetected);
}

void loop()
{
    // Make sure to call update as fast as possible
    pox.update();
    if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
        Serial.print("Heart rate:");
        Serial.print(pox.getHeartRate());
        Serial.print("bpm / SpO2:");
        Serial.print(pox.getSpO2());
        Serial.println("%");

        tsLastReport = millis();
    }
}


text:
U-Blox Neo M8N GNSS-GPS interface with ESP32-TTGO-T-CALL
I have tried contacting the manufacturers as well as many Google searches.
I have tried many different libraries to get this GNSS-GPS working.
Libraries I've Tried:

Arduino_GPS

Arduino_Parser_Ublox_Neo_M8N

esp32-ublox

MicroNMEA

NEO-M8N

NeoGPS

UBLOX-NEO-M8N

The library I am trying now:

Parser_Ublox_Neo_M8N
with:
ESPSoftwareSerial

(I have a non-AVR board so NeoSWSerial and SoftwareSerial didn't work for me.)
Link to files on GitHub:
https://github.com/toskyRocker/Arduino_Parser_Ublox_Neo_M8N
My questions for someone who has done this before with a U-Blox M8N:

Must I use U-Center software to configure the gps before it will output data?
Does my code look to be functional? I can compile but then when attaching GPS I get the output (as my psuedo error message) that lets me know the serial connection between my TTGO T-Call V1.3 and U-Blox-M8N is not valid.
Here is a link to the board I have and the GNSS-GPS:

Board:
https://www.ebay.com/i/284030711638?chn=ps&norover=1&mkevt=1&mkrid=711-213727-13078-0&mkcid=2&itemid=284030711638&targetid=4580840328168117&device=c&mktype=&googleloc=&poi=&campaignid=403206339&mkgroupid=1235851284533722&rlsatarget=pla-4580840328168117&abcId=9300372&merchantid=51291&msclkid=52c16af1ba571d52ddfe35755ba68854
GPS:
https://www.bidorbuy.co.za/item/319275677/GYGPSV5_NEO_M8N_NEO_M8N_001_GPS_Chip_Module_for_APM2_6_Flight_Control.html
(The "<#include SoftwareSerial.h>" in the code below is what was added when I used the Arduino IDE's drop down libraries menu when I selected espsoftwareserial to include.)
Here is the (.ino) code:
#include <SoftwareSerial.h>

#include "Ublox.h"
#define SERIAL_BAUD 115200
#define GPS_BAUD 9600
#define N_INTS 4
//gpsSerial(3,1);
Ublox M8_Gps;
// Altitude - Latitude - Longitude - N Satellites
int gpsArray[N_INTS] = {0, 0, 0, 0};
SoftwareSerial gpsSerial;

/////////////////////////////////////////////////////////////

void setup() {
Serial.begin(SERIAL_BAUD);
gpsSerial.begin(GPS_BAUD,SWSERIAL_8N1,3,1);
//gpsSerial.begin(GPS_BAUD);
pinMode(0,OUTPUT);
}
///////////////////////////////////////////////////////////
void loop() {
digitalWrite(0,LOW);
if(!gpsSerial.available()){
    Serial.print("Problem with GPS ");
}
while(gpsSerial.available()){
    char c = gpsSerial.read();
     if (M8_Gps.encode(c)) {
      gpsArray[0] = M8_Gps.altitude;
      gpsArray[1] = M8_Gps.latitude;
      gpsArray[2] = M8_Gps.longitude;
      gpsArray[3] = M8_Gps.sats_in_use;
    }
 }
 for(byte i = 0; i < N_INTS; i++) {
 Serial.print(gpsArray[i], 10);Serial.print(" ");
 }
 Serial.println("");
 }

By default the GPS module has a baud rate of 115200; 2) ESP32 has more than 1 hardware serial, use Serial2 allows you to operate at 115200 and connect to GPS module.

Thank you very much for your help.  Is serial2 the pins labeld Rx Tx or would that be a different UART pin combo?

ESP32 Serail2 is at Pin16 (Rx) and Pin 17 (Tx), see HardwareSerial source code for ESP32.

Must I use U-Center software to configure the gps before it will
output data?

No, but it is HIGHLY recommended.  It's the only (easy) way to change the baudrate, and the only (easy) way to change what messages are output over serial.

Does my code look to be functional?

I can't answer 100%, as I have not used that library before, but the problem I did run into with the NEO-M8N and multiple libraries I tried (MicroNMEA, TinyGPS, TinyGPS++, ...) was that as a multi-constellation GNSS receiver that can receive more satellite constellations than just GPS, it by default outputs $GNGGA.  These libraries I had tried using only decoded the old standard $GPGGA, and ignored the more universal ones.
Here is how you can use U-Center to verify this is the problem, and if so how to configure your module to output GPGGA messages that these libraries will parse:

Connect to your NEO-M8N using U-center.  (Usb is pprefered, but serial will work fine too)
Confirm that this is the problem by clicking View -> Messages View.
You should see either GPGGA or GNGGA messages being received.

If you are currently getting GNGGA, here is how to switch them to GPGGA:

View -> configuration View
Click on "NMEA (NMEA Protocol) config entry
Click "Poll" at the bottom to pull the current settings from your device.
Change the "Main Talker ID" to "1 - GP (GPS)"
Change the "GSV Talker ID" to "1 - Use main talker ID"
Click "Send" at the bottom to upload your changes.
Click on the "CFG (Configuration)" config entry
Choose "Save current configuration" and then "Send" at the bottom.

Now just use the method above to verify what NMEA packets you are receiving!
Now that you're in U-Center, I'd recommend also checking out the GNSS config, to enable the use of more satellites (GPS, Glonass, Galileo) and set the SBAS config depending on your location.  (In the US, setting to WAAS may help it lock on quicker as it won't bother searching for other SBAS sources)  You can also change the baud rates for different ports under "PORTS", increase or decrease the frequency of sending location updates under "RATE" and enable or disable individual NMEA messages for each port under "MSG"