text:
Problemm with the MPU6050 library
I have a curiosity. What is the difference between adding a header file directly on the arduino IDE and the header file inside another h-file.
For example:
#include "MPU6050_6Axis_MotionApps20.h"
void setup()
{
}
void loop()
{

}

This last didn't give me any problem, but when I create a h-file and add inside that h-file that library, it gave me an error:
ARDUINO:
#include "Prueba.h"
void setup()
{
}
void loop()
{

}

Prueba.h
//#ifndef Prueba_H
//#define Prueba_H
//#define LIBRARY_VERSION   1.0.0

#include "MPU6050_6Axis_MotionApps20.h"
class Prueba
{
  public:
  Prueba();
};
//#endif

Part of the error code is:
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: implicit this pointer type mismatch
 uint8_t MPU6050::getIntStatus() {
         ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.h:438:7: note: type 'struct MPU6050' itself violates the C++ One Definition Rule
 class MPU6050 {
       ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src/MPU6050.h:438:7: note: the incompatible type is defined here
 class MPU6050 {
       ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: 'getIntStatus' was previously declared here
 uint8_t MPU6050::getIntStatus() {
         ^
C:\Users\linco\Documents\Arduino\libraries\MPU6050-0.2.1\src\MPU6050.cpp:1679:9: note: code may be misoptimized unless -fno-strict-aliasing is used
collect2.exe: error: ld returned 1 exit status
exit status 1

Can someone explain me this?
Thanks in advance.

why is ths commented out? ... //#ifndef Prueba_H

I have tried both. Commented and not.

Well I don't know exactly why this work, but base on this question this. To solve this I should add 'inline' keyword in every method definition on the MPU6050_6Axis_MotionApps20.h
Like this:
inline uint8_t MPU6050::dmpInitialize() {
    // reset device
    DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
    reset();
    delay(30); // wait after reset

    // disable sleep mode
    setSleepEnabled(false);

    // get MPU hardware revision
    setMemoryBank(0x10, true, true);
    setMemoryStartAddress(0x06);
    Serial.println(F("Checking hardware revision..."));
    Serial.print(F("Revision @ user[16][6] = "));
    Serial.println(readMemoryByte(), HEX);
    Serial.println(F("Resetting memory bank selection to 0..."));
    setMemoryBank(0, false, false);

    // check OTP bank valid
    DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
    DEBUG_PRINT(F("OTP bank is "));
    DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

    // setup weird slave stuff (?)
    DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
    setSlaveAddress(0, 0x7F);
    DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
    setI2CMasterModeEnabled(false);
    DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
    setSlaveAddress(0, 0x68);
    DEBUG_PRINTLN(F("Resetting I2C Master control..."));
    resetI2CMaster();
    delay(20);
    DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
    setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

    DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
    setIntEnabled(1<<MPU6050_INTERRUPT_FIFO_OFLOW_BIT|1<<MPU6050_INTERRUPT_DMP_INT_BIT);

    DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
    setRate(4); // 1khz / (1 + 4) = 200 Hz

    DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
    setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

    DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
    setDLPFMode(MPU6050_DLPF_BW_42);

    DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
    setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

    // load DMP code into memory banks
    DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
    DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
    DEBUG_PRINTLN(F(" bytes)"));
    if (!writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) return 1; // Failed
    DEBUG_PRINTLN(F("Success! DMP code written and verified."));

    // Set the FIFO Rate Divisor int the DMP Firmware Memory
    unsigned char dmpUpdate[] = {0x00, MPU6050_DMP_FIFO_RATE_DIVISOR};
    writeMemoryBlock(dmpUpdate, 0x02, 0x02, 0x16); // Lets write the dmpUpdate data to the Firmware image, we have 2 bytes to write in bank 0x02 with the Offset 0x16

    //write start address MSB into register
    setDMPConfig1(0x03);
    //write start address LSB into register
    setDMPConfig2(0x00);

    DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
    setOTPBankValid(false);

    DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
    setMotionDetectionThreshold(2);

    DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
    setZeroMotionDetectionThreshold(156);

    DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
    setMotionDetectionDuration(80);

    DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
    setZeroMotionDetectionDuration(0);
    DEBUG_PRINTLN(F("Enabling FIFO..."));
    setFIFOEnabled(true);

    DEBUG_PRINTLN(F("Resetting DMP..."));
    resetDMP();

    DEBUG_PRINTLN(F("DMP is good to go! Finally."));

    DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
    setDMPEnabled(false);

    DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
    dmpPacketSize = 42;

    DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
    resetFIFO();
    getIntStatus();

    return 0; // success
}
inline bool MPU6050::dmpPacketAvailable() {
    return getFIFOCount() >= dmpGetFIFOPacketSize();
}
inline uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[28] << 24) | ((uint32_t)packet[29] << 16) | ((uint32_t)packet[30] << 8) | packet[31]);
    data[1] = (((uint32_t)packet[32] << 24) | ((uint32_t)packet[33] << 16) | ((uint32_t)packet[34] << 8) | packet[35]);
    data[2] = (((uint32_t)packet[36] << 24) | ((uint32_t)packet[37] << 16) | ((uint32_t)packet[38] << 8) | packet[39]);
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[28] << 8) | packet[29];
    data[1] = (packet[32] << 8) | packet[33];
    data[2] = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[28] << 8) | packet[29];
    v -> y = (packet[32] << 8) | packet[33];
    v -> z = (packet[36] << 8) | packet[37];
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[0] << 24) | ((uint32_t)packet[1] << 16) | ((uint32_t)packet[2] << 8) | packet[3]);
    data[1] = (((uint32_t)packet[4] << 24) | ((uint32_t)packet[5] << 16) | ((uint32_t)packet[6] << 8) | packet[7]);
    data[2] = (((uint32_t)packet[8] << 24) | ((uint32_t)packet[9] << 16) | ((uint32_t)packet[10] << 8) | packet[11]);
    data[3] = (((uint32_t)packet[12] << 24) | ((uint32_t)packet[13] << 16) | ((uint32_t)packet[14] << 8) | packet[15]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = ((packet[0] << 8) | packet[1]);
    data[1] = ((packet[4] << 8) | packet[5]);
    data[2] = ((packet[8] << 8) | packet[9]);
    data[3] = ((packet[12] << 8) | packet[13]);
    return 0;
}
inline uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    if (status == 0) {
        q -> w = (float)qI[0] / 16384.0f;
        q -> x = (float)qI[1] / 16384.0f;
        q -> y = (float)qI[2] / 16384.0f;
        q -> z = (float)qI[3] / 16384.0f;
        return 0;
    }
    return status; // int16 return value, indicates error if this line is reached
}
inline uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (((uint32_t)packet[16] << 24) | ((uint32_t)packet[17] << 16) | ((uint32_t)packet[18] << 8) | packet[19]);
    data[1] = (((uint32_t)packet[20] << 24) | ((uint32_t)packet[21] << 16) | ((uint32_t)packet[22] << 8) | packet[23]);
    data[2] = (((uint32_t)packet[24] << 24) | ((uint32_t)packet[25] << 16) | ((uint32_t)packet[26] << 8) | packet[27]);
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    data[0] = (packet[16] << 8) | packet[17];
    data[1] = (packet[20] << 8) | packet[21];
    data[2] = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
    // TODO: accommodate different arrangements of sent data (ONLY default supported now)
    if (packet == 0) packet = dmpPacketBuffer;
    v -> x = (packet[16] << 8) | packet[17];
    v -> y = (packet[20] << 8) | packet[21];
    v -> z = (packet[24] << 8) | packet[25];
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
    // get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
    v -> x = vRaw -> x - gravity -> x*8192;
    v -> y = vRaw -> y - gravity -> y*8192;
    v -> z = vRaw -> z - gravity -> z*8192;
    return 0;
}
inline uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
    // rotate measured 3D acceleration vector into original state
    // frame of reference based on orientation quaternion
    memcpy(v, vReal, sizeof(VectorInt16));
    v -> rotate(q);
    return 0;
}
inline uint8_t MPU6050::dmpGetGravity(int16_t *data, const uint8_t* packet) {
    /* +1g corresponds to +8192, sensitivity is 2g. */
    int16_t qI[4];
    uint8_t status = dmpGetQuaternion(qI, packet);
    data[0] = ((int32_t)qI[1] * qI[3] - (int32_t)qI[0] * qI[2]) / 16384;
    data[1] = ((int32_t)qI[0] * qI[1] + (int32_t)qI[2] * qI[3]) / 16384;
    data[2] = ((int32_t)qI[0] * qI[0] - (int32_t)qI[1] * qI[1]
           - (int32_t)qI[2] * qI[2] + (int32_t)qI[3] * qI[3]) / (2 * 16384);
    return status;
}
inline uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
    v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
    v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
    v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
    return 0;
}
inline uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);   // psi
    data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y);                              // theta
    data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1);   // phi
    return 0;
}

#ifdef USE_OLD_DMPGETYAWPITCHROLL
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
    return 0;
}
#else
inline uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
    // yaw: (about Z axis)
    data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
    // pitch: (nose up/down, about Y axis)
    data[1] = atan2(gravity -> x , sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
    // roll: (tilt left/right, about X axis)
    data[2] = atan2(gravity -> y , gravity -> z);
    if (gravity -> z < 0) {
        if(data[1] > 0) {
            data[1] = PI - data[1];
        } else {
            data[1] = -PI - data[1];
        }
    }
    return 0;
}
#endif

inline uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
    return 0;
}

inline uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
    uint8_t status;
    uint8_t buf[dmpPacketSize];
    for (uint8_t i = 0; i < numPackets; i++) {
        // read packet from FIFO
        getFIFOBytes(buf, dmpPacketSize);

        // process packet
        if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;

        // increment external process count variable, if supplied
        if (processed != 0) (*processed)++;
    }
    return 0;
}

inline uint16_t MPU6050::dmpGetFIFOPacketSize() {
    return dmpPacketSize;
}
#endif

I don't know why the guys that made this library didn't add this. Maybe I'm missing something.


text:
Multiple definition class in arduino
Help me out here. I don't know what I'm missing.
I have this code in my arduino IDE
#include "Foo2.h"
void setup() {
  // put your setup code here, to run once:

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

And I have five files: Foo.h, Foo.cpp, Foo2.h, Foo3.cpp and Foo.h
Foo.h
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    bool Fooa();
    bool Foob();
};
#endif

Foo.cpp
#include "Foo.h"

Foo::Foo()
{

}

bool Foo::Foob()
{
    return true;
}

Foo2.h
#ifndef Foo2_H
#define Foo2_H
#define LIBRARY_VERSION 1.0.0
#include "Foo.h"

bool Foo::Fooa()
{
    return true;
}
#endif

Foo3.h
#ifndef Foo3_H
#define Foo3_H
#include "Foo2.h"

class Foo3
{
    public:
        Foo3();
        Foo _foo;
};
#endif

Foo3.cpp
#include "Foo3.h"

Foo3::Foo3()
{
}

And it is give me an error:
libraries\Foo\Foo3.cpp.o (symbol from plugin): In function `Foo::Fooa()':
(.text+0x0): multiple definition of `Foo::Fooa()'
sketch\kk2.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

what i'm doing wrong
regards,

Please show us "Foo3.cpp" that is mentioned in the error.

If you want Fooa() to be defined in a header that can be included in more than one .cpp file, you would need to declare it as an inline function like so:
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    inline bool Fooa();
    bool Foob();
};
#endif

Alternately, you can provide the function definition directly inside class definition; this also makes the function inline despite not requiring the inline keyword.
Or if you want to keep Fooa as a non-inline function, you'd need to move the definition out of the header and into a .cpp file as you did with Foob().
Making a function inline has a second effect beyond implying that you want a function's code to be generated at the call site; it informs the compiler (or more accurately the linker) to expect to see multiple definitions (that are required to be identical) of the code for the function.  Without that advanced noticed, you will get the multiple definition of error when a function definition is inserted into multiple .cpp file by way of an #include.
As a side note: #include is an automated form of copy-and-paste.  It logically plants the contents of another file (and all of its reachable #include uses transitively) into place where the #include directive appeared.  It does not behave the same way that many similar looking directives in other languages do.  E.g. #include does not behave like the import keyword does in say Java or python for example.

It didn't work adding the 'inline' keyword. I have edit part of my question, because I have other files too.

I'm trying to solve this [https://arduino.stackexchange.com/questions/79641/problemm-with-the-mpu6050-library]. And I think that I have to figure out this problem first.

No, you were right it works. I have to put the 'inline' keyword in the Foo.h and Foo2.cpp

source: Stack Exchange

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

sort: votes


text:
Arduino Yun Disk Expander low memory but it looks like my memory is fine
I can't quite understand this when I run arduino yun disk expander sketch with a sd card plugged in I get the the following message. You do not have enough flash memory need 1mb. I ssh into my arduino and I get this
Filesystem                Size      Used Available Use% Mounted on
rootfs                    6.9M    632.0K      6.3M   9% /
/dev/root                 7.5M      7.5M         0 100% /rom
tmpfs                     29.8M    148.0K     29.7M   0% /tmp
tmpfs                     512.0K       0    512.0K   0% /dev
/dev/mtdblock3            6.9M    632.0K      6.3M   9% /overlay
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /
/dev/sda1                29.7G      2.4M     29.7G   0% /mnt/sda1

The only thing that is full is the /dev/root but the reading I have done through the posts here and online say that's fine. Why may this be I am quite confused???

I don't have a YUN or a lot of experience with OpenWRT, so I'm not sure I'm going to be of much help but, I'm guessing the error you're seeing is from this line of the sketch.
Excerpting that here:
Process awk;

awk.runShellCommand(F("df / | awk '/overlay/ {print $4}'"));
int output = awk.parseInt();
if (output < 1000) {
  Serial.println(F("\nYou don't have enough disk space to install the utility software. You need to free at least 1MB of Flash memory.\nRetry!"));
  halt();
}

So, it appears they are executing df / | awk '/overlay/ {print $4}' on the YUN.
They're using awk to extract the fourth column ($4) of the line containing overlay (/overlay/), which by the way is awfully hackish.
Given that they expect the result of awk.parseInt() to compare less than 1000 to mean you have less than 1 Mbyte available, it's fairly clear they expected this column to be reported in kilobytes.  And yet in your own df listing
overlayfs:/overlay        6.9M    632.0K      6.3M   9% /

the fourth column is 6.3M and the rest are choosing different units, what is sometimes called "human" output.  So, we know what they care about is the overlay mount point.  And that at the time someone tested this code it either they didn't try an SDCard of any size or the output of df was different back then, which is why parsing something like df isn't a good idea.
And that's about as far as I can take you with any real confidence.  I don't know how overlay is set up on a YUN.
I guess, if you wanted to "fix" the code with a minimal change, it would be to add -k to the df command-line to force kilobyte based output, assuming -k works on whatever df comes with YUN.  If you wanted to go a step further, I suppose you could use -P to get POSIX output from df, again assuming that's supported, and change the expected units in the sketch accordingly.  But if this is just for you, and you know overlay has more than 1 MB free, you could just as easily change the function so it cannot fail:
void haltIfInternalFlashIsFull() {
}

All that said, I wouldn't be surprised if you run into another problem just like this in another part of the sketch.

yeah I got an error err. installing e2fsprogs dosfstools fdisk rsync kmod-fs-ext4 I've hacked away at this yun for a while. Such a headache. Dont know what to do at this point. Thanks anyways

Given that it will probably be a long drawn out process, I'd steer your toward something interactive like a chat network for forum.  About the only other thing I'll add here is that since most of the sketch seems to be executing shell command-lines on the YUN, you may get better help from people more knowledgeable in OpenWRT than in Arduino.

Ok I will look in those forums. Thanks Im gonna select your answer because it solved the initital problem I had. Thanks

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


text:
can anyone help me debug this code my delay microseconds is not working and my servo write for 180 as well
this is not my code this is what i found on makersguide i tried to use the same but it doesn't work
#include <Servo.h>

// Define Trig and Echo pin:
#define trigPin 10
#define echoPin 9
// Define variables:
long duration;
int distance;
void setup() {
// Define inputs and outputs:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, pulseIn() returns the duration (length of the pulse) in
microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor (Ctrl+Shift+M):
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm");
delay(50);
}

// Include the servo library:
#include <Servo.h>
// Create a new servo object:
Servo myservo;
// Define the servo pin:
#define servoPin 9
// Create a variable to store the servo position:
int angle = 0;
voidsetup() {
// Attach the Servo variable to a pin:
myservo.attach(servoPin);
}
  void loop(){
  myservo.write(90);
  delay(1000);
  myservo.write(180);
  delay(1000);
  myservo.write(0);
  delay(1000);
  // Sweep from 0 to 180 degrees:
  for (angle = 0; angle <= 180; angle += 1) {
  myservo.write(angle);
  delay(0);
  }
  for (angle = 180; angle <= 0; angle -= 1) {
    myservo.write(angle);
    delay(0);

  }
  delay(1000);
 }

"Doesn't work" doesn't tell us much. What happens? Anything? Maybe it's a wiring issue, which we can't tell by reading your question. Maybe it doesn't compile? You seem to have two loop functions, and a voidsetup whatever that is.

it says that my void loop is previously defined

and it also says that ISO C++ forbids declaration of void setup with no type [-fpermissive]  in function of void loop( )

It actually said "warning: ISO C++ forbids declaration of 'voidsetup' with no type [-fpermissive]". Notice that you omitted the space between "void" and "setup". That's why we ask you to copy and paste the error message, not just paraphrase them.

For combining sketches, look at this question. There are also links to similar questions.

Your code has two "loop" functions in it. You cannot have two functions of the same name (and with the same argument list, in your case with no arguments) in the one compilation unit (piece of code).
It looks very much like you have combined two pieces of code you found into one and then tried to compile that. You can't do that. Choose one or the other. In the second "half" you incorrectly have "voidsetup" which should be "void setup".
Next time you post a question, and if the question is about an error message, please copy and paste the error message. We aren't mind readers. You can see what is on your screen, we can't.
See: How do I ask a good question about the Arduino?


text:
Error compiling for board NodeMCU 1.0 (ESP-12E Module)
I am trying to connect MFRC522 using nodeMCU and send a simple code to scan the tags but the IDE brings the following error:
Multiple libraries were found for "MFRC522.h"
 Used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/rfid-master
 Not used: /home/georgewayne/snap/arduino/current/Arduino/libraries/MFRC522-spi-i2c-uart-async
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

What do I do to rectify this error?

This mate over here seems to fix his bug by just reviewing his code: https://forum.arduino.cc/index.php?topic=660724.0
But, apparently there is a bug in the ArduinoIDE. Try to use Platform.IO(platformio.org/), it has a "better" debugger, (it's a little bit hard to install tho), this may help you.

More complete output may help.  If you haven't already, turn on verbose for compiling in File/Preferences.   In and of itself, the Multiple libraries were found thing is not an error.  It's just warning you that it found multiple and telling you which one it chose.  If it chose the wrong one, then that might result in an actual compiler error that isn't shown.


text:
Serial communication between nodemcu and Arduino Uno
For the last days, I am trying to establish serial communication between nodemcu and Arduino Uno but I failed to do this. Currently, I am working on a Home Automation project. I receive data from nodemcu and send it to Arduino Uno, but some dummy data also receive with original data. Please help.
Nodemcu code:
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

#define Automated   D0
#define Led         D1
#define Fan         D2

#define WLAN_SSID       "JioFi2_1EAFF8"
#define WLAN_PASS       "Ode9c@,1S%31ja$1xANkeL"

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "_inishu"
#define AIO_KEY        "aio_HZUG00TupkcsC2dvraQM7HLHrCd4"

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

Adafruit_MQTT_Subscribe speed = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Fan");
Adafruit_MQTT_Subscribe inten = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Led");
Adafruit_MQTT_Subscribe autom = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Automate");

void MQTT_connect();
void datatransfer(int);

int on_off;
int sliderval1;
int sliderval2;
void setup(){
    Serial.begin(9600);
    pinMode(Automated, OUTPUT);
    pinMode(Led, OUTPUT);
    pinMode(Fan, OUTPUT);

    WiFi.begin(WLAN_SSID, WLAN_PASS);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }

    mqtt.subscribe(&autom);
    mqtt.subscribe(&speed);
    mqtt.subscribe(&inten);
}

void loop (){
    MQTT_connect();

    Adafruit_MQTT_Subscribe *subscription;
    while ((subscription = mqtt.readSubscription(5000))){
        if (subscription == &autom){
            on_off = atoi((char *)autom.lastread);
            if (on_off == 1)   digitalWrite(Automated,HIGH);
            if (on_off == 0)   digitalWrite(Automated,LOW);
        }

        if (subscription == &speed){
            sliderval1 = atoi((char *)speed.lastread);
            analogWrite(Fan, sliderval1);
        }

        if (subscription == &inten){
            sliderval2 = atoi((char *)inten.lastread);
            analogWrite(Led, sliderval2);
        }
    }
    datatransfer(on_off);
    datatransfer(sliderval1);
    datatransfer(sliderval2);
}

void MQTT_connect() {
    if (mqtt.connected()) {
         return;
    }

    while (mqtt.connect() != 0) {
        mqtt.disconnect();
        delay(2000);
    }
}

void datatransfer(int value){
    Serial.println(value);
    delay(500);
}

Arduino Uno code:
int x = A0, y = A1, z = 1;
int fan = 11, led = 10;
float temp, lux;
int autom = 1;
int inten = 0;
int speed = 0;
int fanspeed, light;

int datareceive(){
    int receiver = 0;
    while(Serial.available()==0 );
    String s = Serial.readStringUntil('\r');
    receiver = s.toInt();
    Serial.println(receiver);
    delay(1000);
    return receiver;
}

void setup(){
    Serial.begin(9600);
    pinMode(fan,OUTPUT);
    pinMode(led,OUTPUT);
    pinMode(x,INPUT);
    pinMode(y,INPUT);
    pinMode(z,INPUT);
}

void loop(){
    autom = datareceive();
    speed = datareceive();
    inten = datareceive();
    if(autom == 1){
        fanspeed = 255 - speed;
        light = 255 - inten;
        analogWrite(fan,fanspeed);
        analogWrite(led,light);
    }
    else {
        temp = analogRead(x);
        if (temp >= 52 && temp <= 104){
            int fanspeed = -4.90384615*temp + 510;
            analogWrite(fan, fanspeed);
        }
        else if(temp > 104)  digitalWrite(fan,LOW);
        else digitalWrite(fan,HIGH);
        lux = analogRead(y);
        if (lux >= 430 && lux <= 594){
            int light = 1.342657*lux-577.342657;
            analogWrite(led,light);
        }
        else if (lux < 430) digitalWrite(led, LOW);
        else digitalWrite(led,HIGH);
    }
}

You didn't describe, what actually happens, just that it doesn't work. Please add this description to your question. At the first glance I see, that you send up to every halve second, while you receive only once a second, since you delay for 1s. Why are you even delaying there? That doesn't fit any purpose

I agree with @chrisl, don't use delay, bad practice, search for "Arduino millis delay" that's a better way. And why do you transfer a value without a tag, when I have done similar tasks I have used a transfer format like ", ", example "speed, 200".

And to trouble shoot, create a simple KISS program so you learn how to do transfer over serial first before you do a more complex program.

Delete you AIO details from sketch.

give us example of data and what is extra. I for one have noticed that you use println, so after each message you are getting a newline symbol. (extra data at the end).
Although NODEMCU sends some data to serial every time it starts.
Also dont forget the difference between number and symbols of numbers. print sends numbers as their symbols, while "write" sends numbers as numbers

Arduino UNO is 5v logic and esp8266 is 3.3v logic.  You need a level shifter for them to be able to have bidirectional serial link. Alternatively you can just use a voltage divider between Arduino Tx and ESP Rx pin to protect the rx pin of the esp.

It would be a preferencial but arduino is more then capable of handling the ESP8266 input and while not ideal, esp is designed to STRESS handle up-to 5.1 volt. Full shifter is an overkill. So if you extend your message to show a simple ressistive divider to protect nodemcu, dropping message voltage from arduino tx towards nodemcu RX, your note (rather then answer) might become useful


text:
Capture GRAYSCALE image with ESP32 Cam
For one of my projects, I would like to transfer a camera image with the best possible resolution and as many FPS as possible with the ESP32Cam.
For this I successfully used the code from
https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/
A grayscale image would be enough for further processing, if it allows a higher speed.
Problem is, if I set the format to PIXFORMAT_GRAYSCALE, the ESP only outputs "Camera capture failed".
Are there any other settings to do?

I just tried this with my ESP32Cam with no problems.  I would check that you are supplying enough power; I've definitely seen the 'Camera capture failed' when I had power issues.  Also, I would try a more recent tutorial on the ESP32Cam; the latest Expressif ESP32 Arduino libraries have AI Thinker ESP32Cam as a device choice.  I would try the CameraWebServer example in the ESP32 library and see if you still have the problem.

I guess that 1 year later you shouldn't work on this anymore, but for every one that need the grayscale too, here my solution.
For reference I've found here that we can set  : s->set_special_effect(s, 2);
Where 2 is grayscale effect.
0 - No Effect
1 - Negative
2 - Grayscale
3 - Red Tint
4 - Green Tint
5 - Blue Tint
6 - Sepia
  // Camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  s->set_special_effect(s, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)


text:
Why Arduino Pro IDE is not open source?
I just found the alpha version of Arduino Pro IDE and I was wondering why this project is not open source as the classic IDE.
I didn't found anything about that online.

https://github.com/arduino/arduino-pro-ide/blob/master/README.md#user-feedback-and-issue-report

It appears that they intend to open-source the project but that the developers may not have reached the point where they believe that would be useful.  If you are wanting to contribute to the project you might send them a request.


text:
How to separate a specific frequency signal from a summation of a few signals?
I want to calculate THD. SO how do I isolate the fundamental frequency from a signal with harmonics?
I have a signal V which is a sum of V1, V2 and V3. V1=A1sin(w1t+phi1), V2=A2sin(w2t+phi2) and V3=A3sin(w3t+phi3). I want to find out the magnitude/amplitude of a known frequency w1 in the signal. How do I proceed? Should I use the FFT library? If yes then how?

Though this is not really Arduino specific: Yes, I think you need to do an FFT on the signal. When googling something like "Arduino FFT" you get for example this library. It also has examples. You can use it, or program the FFT yourself. That would be a pure C/C++ programming question.

What are the values of the frequencies ω₁/2π...? To what precision are they known? Are they constant? How long does the signal last? Is it steady enough to allow you to measure V₁, V₂ and V₃ sequentially, rather than simultaneously? To what precision do you need the THD measurement?

@chrisl: He may not need an FFT. The FFT computes the amplitude of many frequencies. If the OP only needs three frequencies, the FFT is most likely overkill.

What exactly are you trying to do?  If you want to measure THD from an external signal, an Arduino is probably not the best choice.  It only has 10-bit ADCs and they are DC-coupled. You can build a simple circuit (https://www.daqarta.com/dw_rrll.htm) to shift an AC-coupled input to DC for the Arduino, but you will still have only 10-bit resolution.  I haven't looked deep enough into the library that chrisl mentions to see how big an FFT it can perform in the limited RAM of an Arduino, but I suspect the spectral resolution would be so poor as to be unhelpful for real-world THD measurements.
The way you describe the signal makes me think that this is an academic exercise, not a real-world problem.  If so, you don't need an Arduino or any other hardware, just run the FFT on your main computer.   If you do need to make real-world measurements, an ordinary sound card on your computer is a better way to go.  See https://www.daqarta.com/dw_0d0t.htm for an example.  The sound card approach has the added advantage that it can generate a low-distortion test signal to drive the device whose distortion you are trying to measure.  That allows a "trick" (called "Spectral Line Lock" in the example) to get even better resolution, by making the test signal synchronous with the sample rate so you don't need window functions.
If you really want to measure THD with an Arduino, consider an approach used in what used to be called a "wave analyzer".  The block diagram is shown here:
https://www.daqarta.com/dw_0h0p.htm.  This is essentially a one-spectral-line analyzer, which actually can be more selective than an FFT.  You basically multiply the input signal by the sine and cosine of the reference frequency (the fundamental) and then rectify and filter the results, and combine RMS-wise.  That gives you the fundamental value (or any individual harmonic you tune the reference to), so to get THD you divide by the RMS of the overall input signal.

The approach of the wave analyzer you describe is called “homodyne detection”. It can be used for real-time analysis of a signal on an Uno, if the sampling frequency and accuracy requirements are not too stringent.


text:
trying to do a security motion sensor using the peizer and hc-sr04 but i am not able to find the errors the error code is all the way down
#define trigPin 10
#define echoPin 9
#define buzzer 12
long duration;
int distance;

void setup() {
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);
pinMode(buzzer,OUTPUT);
}

 void loop() {
 digitalWrite(trigPin,LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin,LOW);
 duration=pulseIn(echoPin,HIGH);
 distance=duration*0.034/2;
 Serial.print("DISTANCE=");
 Serial.println(distance);
 if (distance<=15){
 tone(buzzer,450);
 delay (500);
 noTone(buzzer);
 }
 else{
 noTone(buzzer);
 }
 }

this is the error code
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

sketch_nov27a:9:15: error: stray '\342' in program

 void setup() {

               ^

sketch_nov27a:9:16: error: stray '\200' in program

 void setup() {

                ^

sketch_nov27a:9:17: error: stray '\213' in program

 void setup() {

                 ^

sketch_nov27a:9:18: error: stray '\342' in program

 void setup() {

                  ^

sketch_nov27a:9:19: error: stray '\200' in program

 void setup() {

                   ^

sketch_nov27a:9:20: error: stray '\213' in program

 void setup() {

                    ^

sketch_nov27a:14:2: error: stray '\342' in program

 }

  ^

sketch_nov27a:14:3: error: stray '\200' in program

 }

   ^

sketch_nov27a:14:4: error: stray '\213' in program

 }

    ^

sketch_nov27a:14:5: error: stray '\342' in program

 }

     ^

sketch_nov27a:14:6: error: stray '\200' in program

 }

      ^

sketch_nov27a:14:7: error: stray '\213' in program

 }

       ^

sketch_nov27a:18:14: error: stray '\342' in program

 void loop() {

              ^

sketch_nov27a:18:15: error: stray '\200' in program

 void loop() {

               ^

sketch_nov27a:18:16: error: stray '\213' in program

 void loop() {

                ^

sketch_nov27a:18:17: error: stray '\342' in program

 void loop() {

                 ^

sketch_nov27a:18:18: error: stray '\200' in program

 void loop() {

                  ^

sketch_nov27a:18:19: error: stray '\213' in program

 void loop() {

                   ^

sketch_nov27a:28:19: error: stray '\342' in program

 if (distance<=15){

                   ^

sketch_nov27a:28:20: error: stray '\200' in program

 if (distance<=15){

                    ^

sketch_nov27a:28:21: error: stray '\213' in program

 if (distance<=15){

                     ^

sketch_nov27a:28:22: error: stray '\342' in program

 if (distance<=15){

                      ^

sketch_nov27a:28:23: error: stray '\200' in program

 if (distance<=15){

                       ^

sketch_nov27a:28:24: error: stray '\213' in program

 if (distance<=15){

                        ^

sketch_nov27a:32:2: error: stray '\342' in program

 }

  ^

sketch_nov27a:32:3: error: stray '\200' in program

 }

   ^

sketch_nov27a:32:4: error: stray '\213' in program

 }

    ^

sketch_nov27a:32:5: error: stray '\342' in program

 }

     ^

sketch_nov27a:32:6: error: stray '\200' in program

 }

      ^

sketch_nov27a:32:7: error: stray '\213' in program

 }

       ^

sketch_nov27a:33:6: error: stray '\342' in program

 else{

      ^

sketch_nov27a:33:7: error: stray '\200' in program

 else{

       ^

sketch_nov27a:33:8: error: stray '\213' in program

 else{

        ^

sketch_nov27a:33:9: error: stray '\342' in program

 else{

         ^

sketch_nov27a:33:10: error: stray '\200' in program

 else{

          ^

sketch_nov27a:33:11: error: stray '\213' in program

 else{

           ^

sketch_nov27a:36:1: error: stray '\342' in program

 }

 ^

sketch_nov27a:36:2: error: stray '\200' in program

 }

  ^

sketch_nov27a:36:3: error: stray '\213' in program

 }

   ^

sketch_nov27a:36:4: error: stray '\342' in program

 }

    ^

sketch_nov27a:36:5: error: stray '\200' in program

 }

     ^

sketch_nov27a:36:6: error: stray '\213' in program

 }

      ^

sketch_nov27a:36:8: error: stray '\342' in program

 }

        ^

sketch_nov27a:36:9: error: stray '\200' in program

 }

         ^

sketch_nov27a:36:10: error: stray '\213' in program

 }

          ^

sketch_nov27a:36:11: error: stray '\342' in program

 }

           ^

sketch_nov27a:36:12: error: stray '\200' in program

 }

            ^

sketch_nov27a:36:13: error: stray '\213' in program

 }

             ^

exit status 1

stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Nice error there. I copied your code into my Arduino IDE and also got many errors with "stray X in program".
Then I looked at the file in the text editor vim and made all non-printable characters visible (that are characters, that cannot be seen, like control characters). Here is the result (as image, so that you can see the unprintable characters)

As you see, you have some extra characters marked as <200b>. Google gives me the description for it as

zero width space

so a space character, that has zero width and is thus not visible.
The compiler doesn't know, how to interpret these characters. I removed them and the compilation succeeded. Here again your code as text without the unprintable characters (and autoformatted to make it easier to read):
#define trigPin 10
#define echoPin 9
#define buzzer 12
long duration;
int distance;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  Serial.print("DISTANCE=");
  Serial.println(distance);
  if (distance <= 15) {
    tone(buzzer, 450);
    delay (500);
    noTone(buzzer);
  }
  else {
    noTone(buzzer);
  }
}

How these unprintable characters got into your code can only be guessed. Maybe you have copied parts of it from some website, which had these extra characters in it. Maybe you inserted them with some kind of text editor by accident.

For reference: The used FAQ section of vim with the commands to display non-printable characters here:

11.5. How do I highlight all the non-printable characters in a file?
You can use the following commands and search pattern to highlight all the
non-printable characters in a file:
:set hlsearch
/(\p|$)@!.
For more information, read
:help /\p
:help /bar
:help /$
:help /(
:help /@!
:help 'hlsearch'


text:
Recognition of the signal duration from the sensor
Good afternoon!
I create a human movement alarm.
I am signaling atmega328. I receive a signal from the sensor and if there is a signal, then using the "tone" I generate a sound.

I am using a motion sensor. I want that if one movement was noticed for a short time, then turn on a short melody, and if the movement continues longer than a certain time, then play a long melody.
I wrote the code to play a short melody. How can you track that the input from the sensor is at a high logical level for a long time and play a long melody in this case?
unsigned long timing; // Variable to store the starting point
int T = 15; // Signal playback time!
int S0 = PIND0; // With Doppler Probe

int S1 = PIND1; // Food
int S2 = PIND2; // Audio

void setup ()
{

  // Port control via registers:
  DDRD = B00000110; // Set the output pin (the first and second pins of register D as output pins, the rest (0.3-7) are set as input pins)
  // 76543210
  pinMode (PIND0, INPUT);
  pinMode (PIND1, OUTPUT); // Power for the audio amplifier
  pinMode (PIND2, OUTPUT); // Audio
}
void loop ()
{
  if (digitalRead (PIND0))
  {
    sendSignal ();
  }

  if (digitalRead (PIND0) == 0)
  {
    digitalWrite (PIND1, LOW); // Food
    digitalWrite (PIND2, LOW); // Sound
  }
}

void sendSignal ()
{
  digitalWrite (PIND1, HIGH); // Food
  for (int n = 0; n <4; n ++)
  {
    for (int i = 4800; i <5800; i ++)
    {
      tone (PIND2, i, 10); // tone (port, frequency in Hz, duration in ms) 600 - 6 sec.
    }
  }
}

And yes, if my code can be optimized, tell me how!

What is the threshold duration between a “short” and a “long” signal? How long are the short and the long melodies? Is the short melody a prefix of the long one? What should the program do if it reads a long signal while playing the short melody?

I don't see where you are even attempting to detect the long condition in your code.
First of all you need determine what constitutes a long vs. a short detection.  My recommendation is to write your code to do the following:

Initial detection.
Wait for your "short" interval.  If the detection is gone, then you know it was a "short" one and you can play your short music.
If the detection is still there, wait for the remainder of the time for your "long" detection.
If the detection is gone you know it was a "short" one since it didn't make it to the "long" state.  So play your "short" song.
Play your "long" music since the detection lasted for the duration of the long interval.

I'll leave the actual coding of that to you.  I'll also add that doing it this way, that is using the built-in delay() function is probably not the best approach overall.  The issue is that delay() blocks your loop() function and prevents you from doing anything else while it's delaying.
A better approach is to implement this as a state-machine coupled with an timer-driven interrupt.  That will give you much better control over your detections and also allow you do handle other inputs or set other outputs while you are waiting for detections to occur.
There are many resources online that discuss how to configure and handle AVR timers and their interrupts and there are also many resources discussing state machines and programming them in C.

You don't need both a “short” and a “long” interval: only a single “threshold” duration to tell them apart. If the signal stops before the threshold duration, short melody, otherwise long melody. 2. Nothing here is time-critical to the point where you would need a timer-driven interrupt. Timing with millis() is easier and perfectly appropriate in this case.

all the same, I do not understand, if the melody is playing and there are delays, then the microcontroller at this time does not look at what comes from the sensor. In fact, after being triggered, the sensor still remains in a high state for another 2 seconds, so I count 2 responses (4 seconds) - to play a short melody.
more than two - long. How to implement it? study interrupts? Two functions of short and long melody to write?

I am trying to make interrupts, but I cannot set pin PD0(PCINT16) for interrupt

@Антон It doesn't really help to say "I cannot set pin...".  It's also not directly related to this question.  Please ask another question, post your code, show how you are connecting the pin.  Then someone can help you.


text:
How to program Arduino manually via STK500?
I am trying to program an Arduino Nano (with an ATmega328P) from an ESP32 that is attached to its UART and the reset pin. I have to do this via the ESP, because the Arduino is supposed to run on its own, detached from a PC (where I could use an existing programmer for it). But its program should be changable, hence, it is attached to the ESP, which is accessible from a web server via Wifi, so that the Arduino can be reprogrammed on request. I almost got the whole setup figured out: The server is running, files can be sent to the ESP, and the ESP can talk with the Arduino Bootloader. The only problem is that I cannot get the Arduino to execute new programs.
The whole procedure goes like this: The server communicates with the ESP, sends the HEX file of the Arduino sketch (which is successfully verified by a checksum, so this part is working properly). Then, the ESP pulls the reset pin of the Arduino and waits for a while before it attempts to talk to its bootloader. Then, it basically does the same sequence of STK500 commands as avrdude.
I really just copied the commands from the avrdude log after executing
avrdude -c arduino -vvvvv -p m328p -b 57600 -P /dev/ttyUSB0 -U flash:w:sketch.hex:i

and skipping query commands like which firmware version it uses etc. So, basically: enter programming mode, erase chip, re-enter programming mode, write the hex file to flash, starting from address 0, moving in steps of 128 bytes (using 1's to pad the last message to the full size of 128 bytes). Then afterwards reading back the file from the Arduino and veryfing that all bytes match (which they do!) and leaving the programming mode (which is the very last thing that happens in the avrdude log). Afterwards, I trigger the reset. I am using exactly the same type of file which I gave to avrdude, and all the responses of the Arduino bootloader exactly match the values from the avrdude log.
But whereas the Arduino just starts executing the sketch after this procedure when using avrdude, in my own implementation it just blinks its LED in a regular interval (when the test sketch should make it blink short, long, short, long etc.). I don't get what's going wrong here. I thought that the blinking might represent an error code, but I couldn't find any documentation about that. I feel like I've searched the whole Internet (including arduino stackexchange), and I even looked at the avrdude source code to check if there's something else done after the last STK500 command, that is not listed in its log. I feel (hope) that I'm very close to having it work and this whole thing just needs like a one-line fix, but I don't know what else to try anymore and would greatly appreciate a second opinion from someone more experienced.

In your stated programming sequence, I don't see where you are resetting the AVR chip.

You should reset the chip after programming.

Sorry, I forgot to mention that. I tried to reset it via the ESP, as well as manually via button. But it doesn't seem to make a difference.

@programonkey In that case I think the only remaining possibility is that you are not properly programming the AVR code using your ESP32.  At this point you are giving us a high-level description of what you are doing, and that sounds correct, but you are asking for detailed evaluation of your problem but not providing that level of detail.  I think your next step to get help here is to post your schematic and your code.

Are you using some kind of level shifter? Rememeber the Arduino is 5v and the ESP32 is 3v3, I dont think this should be the problem tho, but can be :-)

No, I'm not using a level shifter, but thanks for the hint. :)

Bridging an existing programmer via network is an interesting idea, but my application requires a certain level of decentrality, which would be destroyed by this solution.

Okay, by comparing the data packets my implementation sends with those from the avrdude log for the same sketch, I finally found the cause of trouble. I was sending the hex file byte-by-byte exactly as it is read from storage. But of course, the metadata needs to be skipped (i.e. the addresses at the beginning of each line, the magic bytes at the end of each line, and the newline). I added this simple fix, and now it works fine.
EDIT: Here is the preprocessing code from my Python3 script:
import codecs

program = b''
for line in open('sketch.hex', 'rb'):
    program += codecs.decode(line[9:-4], 'hex')

so a question without code, an answer without code. nobody could answer your question if the problem was in the code you didn't show. how should this be useful as Q&A? add the code or delete the question please

The reason why I didn't post code with my question is that I thought that the error was on the conceptual level, and so I saw no point in posting kilobytes of code before clarifying whether the underlying procedure is actually correct. I did add the code that fixed my implementation to my answer now, though. I do think that this question might be of relevance for someone facing a similar undertaking, if only to compare and verify his approach.

now I understand what you do. it would be simpler to work with a binary of the sketch, not with hex file. https://github.com/jandrassy/ArduinoOTA/blob/2a591d028c5384849cdaf4ee7398b97b528bc054/extras/avr/platform.local.txt#L4

Yeah, that would've been better. But since initially, I didn't know how to go about, I just followed some online examples and tried to mimic the resulting behavior of avrdude as closely as possible. I am smarter now.


text:
I tried to make a obstacle avoiding car (OAB), but my code seems to have a lot of errors
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 200
#define MAX_SPEED 190
#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

myservo.attach(10);
myservo.write(115);
delay(2000);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
distance = readPing();
delay(100);
}

void loop() {
int distanceR = 0;
int distanceL = 0;
delay(40);

if(distance<=15)
{
moveStop();
delay(100);
moveBackward();
delay(300);
moveStop();
delay(200);
distanceR = lookRight();
delay(200);
distanceL = lookLeft();
delay(200);

if(distanceR>=distanceL)
{
turnRight();
moveStop();
}else
{
turnLeft();
moveStop();
}
}else
{
moveForward();
}
distance = readPing();
}

int lookRight()
{
myservo.write(50);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
}

int lookLeft()
{
myservo.write(170);
delay(500);
int distance = readPing();
delay(100);
myservo.write(115);
return distance;
delay(100);
}

int readPing() {
delay(70);
int cm = sonar.ping_cm();
if(cm==0)
{
cm = 250;
}
return cm;
}

void moveStop() {
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}

void moveForward() {

if(!goesForward)
{
goesForward=true;
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
motor1.setSpeed(speedSet);
motor2.setSpeed(speedSet);
motor3.setSpeed(speedSet);
motor4.setSpeed(speedSet);
delay(5);
}
}
}

void moveBackward() {
goesForward=false;
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2)
{
motor1.setSpeed(speedSet);
motor2.setSpeed(speedSet);
motor3.setSpeed(speedSet);
motor4.setSpeed(speedSet);
delay(5);
}
}

void turnRight() {
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
delay(500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}

void turnLeft() {
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
delay(500);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}

These are the error messages:

    Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"

sketch_nov27b:44:15: error: stray '\342' in program

 void setup() {

               ^

sketch_nov27b:44:16: error: stray '\200' in program

 void setup() {

                ^

sketch_nov27b:44:17: error: stray '\213' in program

 void setup() {

                 ^

sketch_nov27b:44:18: error: stray '\342' in program

 void setup() {

                  ^

sketch_nov27b:44:19: error: stray '\200' in program

 void setup() {

                   ^

sketch_nov27b:44:20: error: stray '\213' in program

 void setup() {

[ trimmed ]
                       ^

sketch_nov27b:199:24: error: stray '\342' in program

 void turnLeft() {

                        ^

sketch_nov27b:199:25: error: stray '\200' in program

 void turnLeft() {

                         ^

sketch_nov27b:199:26: error: stray '\213' in program

 void turnLeft() {

                          ^

sketch_nov27b:199:27: error: stray '\342' in program

 void turnLeft() {

                           ^

sketch_nov27b:199:28: error: stray '\200' in program

 void turnLeft() {

                            ^

sketch_nov27b:199:29: error: stray '\213' in program

 void turnLeft() {

                             ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

stray '\342' in program

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You already asked about this sort of problem a few minutes ago. It's the same issue. Make sure you use a text editor for code or an IDE, nothing like Word. And be careful when you copy/paste from web pages.

could u pls recommend one

i am actually new to this so i have no idea of these text editors

Why do you ask essentially the same question again? You should really first look into, why you have those unprintable characters in the code? Have you just copied it somewhere? Then check that source.

For removing the unprintable characters, you can use Notepad++. Look for example (here)[https://www.shahabjafri.com/2020/03/01/how-to-find-non-ascii-unprintable-characters-using-notepad-plus-plus/] for a tutorial on how to find the unprintable characters (just found by googling). When you have removed them, you can again work in the Arduino IDE

Duplicate: trying to do a security motion sensor using the peizer and hc-sr04 but i am not able to find the errors the error code is all the way down

You copied and pasted the code from a website that presents the code using typography, not code blocks.
You have lots of typographical special characters in your code from pasting it.
Instead of copying and pasting code you should read and understand code then write your own.


text:
cannot open source file "WProgram.h" in VSCode
So I started typing out this question, but in the process of taking screenshots and looking up sources for the question I figured out the answer :P
That said, this problem has been a snag for me for a while and I've asked multiple people about it with no solution. Because it seemed kind of daunting for me and I haven't seen many well explained reasons I figured I'd finish out the post here to help anyone that is running into this or will run into it in the future.

The snag
I'm using vscode for my editor and I've had this snag for a while but it's finally driving me nuts enough to ask for help.
When in include certain libraries I get error squiggles under the include.

In this case the squiggle is popping up because of the error:

cannot open source file "WProgram.h" (dependency of "Adafruit_MPR121.h")C/C++(1696)

At first I though the snag was because my include path needed my arduino libraries directory so I added that for the project, but I still get the snag.

I did a computer wide search for the WProgram.h file but was not able to find it.

The thing is, all of my sketches still compile and upload fine so for the most part I'm just able to ignore it ... but the squiggle!!!!!!.
Any ideas of how I can resolve this?

I landed here in the same position as you, and after researching the comments mentioning -DARDUINO=10813 and some more googling I found: https://github.com/microsoft/vscode-arduino/issues/1148
This led me to adding one more line to defines in my c_cpp_properties.json
and this also removed the squiggly!
{
    "configurations": [
        {

            ...

            "defines": [
                "USBCON",
                "ARDUINO=10813"
            ],

            ...

        }
    ],

}```

Just because this doesn't answer why this works: Arduino versions <1.0 used WProgram.h, but Arduino >=1.0 use Arduino.h. As @Chris Schmitz explained, many libs use a check to determine which to load for backwards compatibility. Because the VSCode extension should be up to date, we can use the (current) latest version of 1.8.13, or 10813 as it's defined in the code. Adding this to VSCode lets packages checking versions see we're running modern versions.

The answer
Like I said in the question, I found the answer after doing some searching while typing up the question itself and I want to explain it for future squiggle-haters :)
WProgram.h vs Arduino.h
I did a bunch of searching to try to track down what's going on and I eventually found this helpful (and depending on the veracity of the source, kind of sad) bit of history:

There is history of the arduino project not everyone was aware of or supposed to know. I only this much: this all started with some graduate student(s) that created the wiring platform and IDE, called wiring board and wiring "programming language". This project is still active with active users like the arduino project. Then the arduino folks decide to create the arduino project based on wiring project so they took the wiring IDE (which took from the original Processing IDE), including all the libraries etc. and created the first Arduino board (slightly different than wiring board, cheaper!) called it arduino. Arduino project has not very positively acknowledged the wiring project as the source of their project and wiring folks didn't take it very well.
Now, that WProgram.h, is a definition file created by and for the wiring project and board. That's why it has a W on it. It has been in Arduino IDE since its beginning and was replaced by Arduino.h only recently when Arduino 1.0 was released. Now all Arduino 1.0+ IDE will use Arduino.h and not WProgram.h so if you have that plus some other old stuff, you will have to make changes to work with Arduino 1.0+ IDE.

The temp fix
With that in mind I dove into the source file for the Adafruit_MPR121.h library and found where it includes the WProgram.h header file and commented it out.

It's also worth pointing out that the pre-compiler conditional here supports the renaming of the file in newer versions of Arduino.

I labeled this section of the answer as "The temp fix" because it involves modifying a 3rd party dependency which is normally not a great idea. Yeah it fixes it now, but as soon as I need to update this library that edit is going to get blown away and I'd need to manually do it again. In this case the update is pretty minimal so maybe that's no big deal, but if the fix was more involved, like a heavy edit, that would be a real big pain in the butt and could cause other unforeseen consequences (and I played half-life as a kid so I know that's not good).
The better fix
Normally I would say the better fix for this would be to clone the source repository, make the fix there, and do a pull request so the dependency itself gets updated at the source (if someone approves and merges the PR).
But this is a bit different, the conditional in there is actually fine as it adds backwards compatibility. It's there so that the library can support both pre-1.0 and post-1.0 arduino IDE versions. If we did a PR to cut out the WProgram.h reference we'd add in breaking code for anyone on the older versions.
So, the better solution is to appease my local compiler.
We know that the Arduino.h header for all intents and purposes is the same as the WProgram.h, so a almost-full-proof solution would be to fake out the WProgram.h file on my computer to appease the compiler.

An important part to note here is that to make sure I faked it out correctly I went to the arduino repository, scrolled back through the tags, found the last tag before they switched to 1.0+, and found the WProgram.h file. Once there I grabbed the same pre-compiler check and definition for the WProgram header so I could be sure I did the correct define for the WProgram name.

This feels like a bit of overkill because it protects me from other headers being included with the same string defined, but if that happened it would be because I have the WProgram file anyway, but I figured if I was going to fake it out I'd do it right.
This could backfire if I include a library that only includes WProgram.h and not the Arduino.h in that arduino version check conditional, but this would 100% be the case for a correction and pull request for that library.
Summary
So now I know that the Arduino.h file is the reason I'm able to compile everything correctly even with the red squiggle, I have a faked out WProgram.h so that my compiler can find something when looking for the file and, most importantly, I no longer need to look at those red squiggles under the includes :)

Next step, figure out the same thing for Sam.h :P

The simplest fix: create WProgram.h and place in it #include <Arduino.h>.

Ah, that's a good point, though I feel like I'd run into the same modifying-code-that-could-be-overwritten issue if I put it in Arduino.h and then an update to the arduino IDE modifies that file.

platformio doesn't define Arduino version? you can add -DARDUINO=150 somewhere in projects properties?

If you want to be compatible with the Arduino ecosystem, the proper fix would be to use the same preprocessor macros as the Arduino IDE itself. For instance, Arduino 1.8.13 compiles every file with the command-line option -DARDUINO=10813.

Oh interesting, I didn't know about preprocessor macros! I did some searches through the arduino docs just now but can't find where it's talked about. Could someone point me to the right spot in the docs? If I figure out how to add that in on the vscode side I'll update my answer.

https://arduino.github.io/arduino-cli/platform-specification/#global-predefined-properties

Ah awesome, thanks for the point :clap:

If you used the free version of IntelliJ Idea you could have just right-clicked on the warning (red squiggle) and told the IDE that it's ok. IntelliJ would remember that and not bother you about it again. (IntelliJ supports most common programming languages, including C and C++, python, and javascript, as well as Java).

I recently figured out, it's way too simple.
Just tap F1 and look for this then select the configuration for "Arduino".

(Pardon my Grammer)

Simple and effective!

My VS code has no configuration for Arduino. It only has win32. How do I get the configuration for Arduino?


text:
Nodemcu OTA - no response issue
I was trying to use nodemcu for a project. No issues when uploading the OTA sample code. Added led blink to test. But when trying to upload the second sketch via OTA getting an error

no response from device.

Tried ping to the Nodemcu IP and no issue there. Have the OTA codes in both sketch.
When trying to upload the 2nd second, the led blink will stop for 2,3 seconds and resumes the normal blinking, gets an error in ide after.
How to check if there is any firewall issue?
IDE settings

Attaching code below
const char* ssid = STASSID;
const char* password = STAPSK;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_FS
      type = "filesystem";
    }

    // NOTE: if updating FS this would be the place to unmount FS using FS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  ArduinoOTA.handle();

  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  delay(100);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(100);

  Serial.println("Looping");
}

Are you calling ArduinoOTA.handle() fast enough in your sketch? Please show your code.

Hi, added the code I am using.

I suspect it's those delay() calls that are making it time out. You need to learn to write non-blocking code. Examine BlinkWithoutDelay.ino.

Tried the BlinkWithoutDelay code, still getting the same error.

You mean you compiled and manually uploaded the code over USB and then found it still wouldn't upload over OTA after that?

Yes, No issues when uploading the updated code via COM3 port, but can't upload via the network port.

Have you manually reset the board since uploading over USB?

Yes, manually reset the board after the first upload.

Let us continue this discussion in chat.


text:
MegaCore ATmega2560 PB7 activation randomly at boot
I uploaded in my custom board (ATmega2560 with an external oscillator 16MHz) the MegaCore bootloader using the AVR pinout. I found that when I switch on the board the pin PB7 is activated 2 short times. This happens even with a blank Arduino sketch.
I found out that the problem was the reset pin connection. When the reset pin (for uploading a new sketch) is connected to the board I got the previous behaviour.
How can the reset pin affect only the pin PB7?
PS I found this issue even in the Arduino Mega standard bootloader.

PB7 is pin 13. That's the traditional LED pin.
The bootloader blinks that LED to indicate it's active.
If you want other behaviour then you will have to compile your own version of the bootloader that doesn't blink the LED.

Many thanks, I thought it was that.


text:
Why am I only getting -1 values in the Serial Monitor, when interfacing with the MPU 6050?
I am trying to smoke test my Seeeduino XIAO (Arduino-compatible) board with an IMU sensor, the MPU 6050. I mainly care about the accelerometer and gyroscope values.
But when I run my Arduino code on the XIAO, I am only getting -1 values in the Serial Monitor. When I first smoke tested the MPU 6050, I actually saw regular X,Y,Z values (e.g. 123, -456, etc), but it disappeared after a few readings. Both the microcontroller and IMU chips are able to power on, since they both display the LED light. The XIAO seems to display a blue LED light when it is transmitting/receiving data, but I am not entirely sure that is what is going on.
The MPU 6050 communicates via I2C, so I have connected Vcc to 3.3V on the XIAO since I read somewhere that the MPU 6050 runs on 3.3V, Gnd to Gnd, SCL to Pin 5 on the XIAO, SDA to Pin 4, and the INT pin to Pin 2 (not sure if I need the INT pin or not, but I read that it helped clear the buffer I think). Then I have the XIAO connected to my laptop's 5V USB port. Also not sure if I need to connect to 3.3V or 5V from the MPU to the XIAO.
Any idea why I am getting -1 values? I also occasionally get 0 values, but mostly -1s.
Here is a snippet of the output I am getting on the Serial Monitor:
12:06:32.476 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.578 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.681 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.057 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.159 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.465 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.566 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.738 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.841 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.014 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.390 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.492 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.596 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.699 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.903 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.378 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.480 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.584 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:37.064 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:37.710 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.122 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.257 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.393 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.529 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.664 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1

Here is the code I found on some tutorial website:
https://www.electronicshub.org/getting-started-arduino-mpu6050/
#include<Wire.h>
const int MPU6050_addr=0x68;
int16_t AccX,AccY,AccZ,Temp,GyroX,GyroY,GyroZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU6050_addr,14,true);
  AccX=Wire.read()<<8|Wire.read();
  AccY=Wire.read()<<8|Wire.read();
  AccZ=Wire.read()<<8|Wire.read();
  Temp=Wire.read()<<8|Wire.read();
  GyroX=Wire.read()<<8|Wire.read();
  GyroY=Wire.read()<<8|Wire.read();
  GyroZ=Wire.read()<<8|Wire.read();
  Serial.print("AccX = "); Serial.print(AccX);
  Serial.print(" || AccY = "); Serial.print(AccY);
  Serial.print(" || AccZ = "); Serial.print(AccZ);
  Serial.print(" || Temp = "); Serial.print(Temp/340.00+36.53);
  Serial.print(" || GyroX = "); Serial.print(GyroX);
  Serial.print(" || GyroY = "); Serial.print(GyroY);
  Serial.print(" || GyroZ = "); Serial.println(GyroZ);
  delay(100);
}

Attached is my current electronics setup. Yes, I know I should have used a breadboard, but I did not have one on me at the time. The connection was not stable, so maybe that messed with the readings.

-1 is usually all 1's and 0 is all zeros.  So it looks like you are not getting any data.  The code appears to be set up for an I2C device at address 0x68.  The 6050 can be set to appear at that address or at address 0x69.  What is pin 9 of the 6050 chip connected to?

Oh ok. I ran i2c device scanning code that I found online and it said the address at 0x68 was available, along with the rest of that address space. The 6050 only has 8 pins.

I am not sure what "running i2c device scanning code" means.  It sounds like the scan did not find anything at 0x68 and as such indicated that address was available. BTW, the 6050 chip has 24 pins.  The board the 6050 chip is soldered onto has 8 pins. For more help, you need to let us know where you got that board from.  As we need the board's schematic to do a good job at figuring this out.

Yes, the scan indicated that the address at 0x68 was available. Oh ok. Diymore 6DOF MPU-6050 GY-521. That's the name of the board.

A quick look around and I can not find the schematic.  If you know where to find one please let us know.  I did find this project which is what you are doing only they are using a real Arduino Uno board.  I am now wondering if the XIAO is as compatible as needed for this project.

The schematic and board look like this:
https://www.theengineeringprojects.com/wp-content/uploads/2019/02/mpu6050.jpg

Thanks @rmutalik but a schematic looks more like the image in the answer "There may be a couple of issues to consider:".  As the instructables.com project I linked to in that answer is connected just like your project is (and assuming that project is working) I would suggest you try to follow that project's instructions while using an Arduino Uno.  Again, this wouldn't be the 1st time a new Arduino board does not behave just like the original Arduino Uno.

Ok thanks, I will try that and then reply back to this post with my findings.

There may be a couple of issues to consider:

In the 6050 specification we see that the 6050 can be configured to show up at address 0x68 or 0x69.  In the photo there appears to be no connection to a pin (AD0?) which may control the 6050 address.  The code appears to expect the 6050 at address 0x68. (Note: The board the 6050 comes on may already deal with this issue by including a pull up or pull down resistor.)

An I2C bus normally needs pull up resistors on the data and clock lines as all drivers are normally of type open collector.  Here is part of a figure from the 6850's specification document:

(Note: The board the 6050 comes on may already deal with this issue by including 2 pull up resistor.)

Look for a working project which is the same or nearly the same as yours.  Here is a project that uses the same 6050 board connected to an Arduino Uno.

Consider if the libraries and other supporting software are truly abstracting your XIAO hardware (in this case an SAMD21CortexM0+ processor) (the real Arduino Uno uses a ATmega328P processor).  It would not be the first time trying to emulate an Arduino using different and more powerful processors has affected otherwise working sketches with unexpected behaviors.

Finally, there appears to be many schematics many with and a few without a 5 volt to 3.3 volt LDO regulators. It may be even with a Low Drop Out regulator that supplying the board with 3.3 volts will not result in 3.3 volts at the 6050 chip.  This may lead to problems.  But supplying a board with no regulator with 5 volts may damage the 6050 chip. Here is one of the schematics found:

(Note: In this schematic, the data and clock lines are pulled high on the board.  And pin 9 (AD0) of the 6050 chip is pulled low.)


text:
Arduino with HC-05 Bluetooth Module | No data will be transmitted
I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.
My Arduino code:
#include <SoftwareSerial.h>

int state = 0;

void setup() {
  //Serial.begin(38400);
  Serial.begin(9600);

  pinMode(13, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    state = Serial.read();

    if (state == '1') {
      Serial.println("Turned on LED");

      digitalWrite(13, HIGH);
    }

    if (state == '0') {
      Serial.println("Turned off LED");

      digitalWrite(13, LOW);
    }
  }
}

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".
I also tried different apps from the PlayStore but all of them didn't work.
Does someone has an idea how I could fix this? Thank you for your answers.
EDIT: A drawing how my Arduino is connected to my HC-05 https://i.stack.imgur.com/N2YsJ.jpg

It may be helpful to show how the RX and TX signals are connected between the bluetooth module and Arduino.

@timemage A drawing: https://imgur.com/a/FtUz5So

I appreciate the effort, but what I was most interested in what what signals you connected to what on the HC-05, and this doesn't show the HC-05's pins labeled.  So, rather than have a back and forth, I'll tell you what my wild guess is, and if I turns out to be correct I'd like you to post it an answer to you own question.  The TX signal coming from either the Arduino or HC-05 should be connected to the RX of the other as I understand it, because both are labeled from the perspective of their respective chips.

The TX signal coming from either the Arduino or HC-05 should be
connected to the RX of the other as I understand it, because both are
labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).
Thank you for your help. :)


text:
NP532 doesn't detect NTAG213 tag
I'm using a PN532 module to read/write NTAG213 tags. They both should be working at 13.56 MHZ, and Adafruit should support these tags in their library.
The Arduino Uno board and the module are connected as follows
PN532 Module  |  Arduino Uno
--------------+-------------
VCC           |  5V
GND           |  GND
SCK           |  D2
MI            |  D5
MO/SDA/TX     |  D3
NSS           |  D4

SPI is enabled on the PN532 module:
SET 0 -> L
SET 1 -> H

Using the ntag2xx_read example provided by the library, I can pick up MIFARE tags, with an error thrown in the Serial Monitor.
This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!

So far, so good. But when I try to place one of my NTAG213 tags, nothing happens. I thought maybe I'd need to change the page read to match NTAG213 specs (instead of default NTAG203) but unsurprisingly id didn't change anything.
I'm not sure where to go from there. I don't know whether there's some hardware incompatibility or if I'm missing something in the setup or the code. Any help would be greatly appreciated.
The NTAG213 tags can be read with a smartphone.

The code I'm using is exactly the same as the one linked from the library above (besides page read), I'm pasting it here for future reference
/**************************************************************************/
/*!
    @file     readntag203.pde
    @author   KTOWN (Adafruit Industries)
    @license  BSD (see license.txt)

    This example will wait for any NTAG203 or NTAG213 card or tag,
    and will attempt to read from it.

    This is an example sketch for the Adafruit PN532 NFC/RFID breakout boards
    This library works with the Adafruit NFC breakout
      ----> https://www.adafruit.com/products/364

    Check out the links above for our tutorials and wiring diagrams
    These chips use SPI or I2C to communicate.

    Adafruit invests time and resources providing this open source code,
    please support Adafruit and open-source hardware by purchasing
    products from Adafruit!
*/
/**************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>

// If using the breakout with SPI, define the pins for SPI communication.
#define PN532_SCK  (2)
#define PN532_MOSI (3)
#define PN532_SS   (4)
#define PN532_MISO (5)

// If using the breakout or shield with I2C, define just the pins connected
// to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
#define PN532_IRQ   (2)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

// Uncomment just _one_ line below depending on how your breakout or shield
// is connected to the Arduino:

// Use this line for a breakout with a software SPI connection (recommended):
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

// Use this line for a breakout with a hardware SPI connection.  Note that
// the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
// hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
// SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
//Adafruit_PN532 nfc(PN532_SS);

// Or use this line for a breakout or shield with an I2C connection:
//Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);
  while (!Serial) delay(10); // for Leonardo/Micro/Zero

  Serial.println("Hello!");

  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);

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

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

void loop(void) {
  uint8_t 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 NTAG203 card.  When one is found 'uid' will be populated with
  // the UID, and uidLength will indicate the size of the UUID (normally 7)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println("Found an ISO14443A card");
    Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("  UID Value: ");
    nfc.PrintHex(uid, uidLength);
    Serial.println("");

    if (uidLength == 7)
    {
      uint8_t data[32];

      // We probably have an NTAG2xx card (though it could be Ultralight as well)
      Serial.println("Seems to be an NTAG2xx tag (7 byte UID)");

      // NTAG2x3 cards have 39*4 bytes of user pages (156 user bytes),
      // starting at page 4 ... larger cards just add pages to the end of
      // this range:

      // See: http://www.nxp.com/documents/short_data_sheet/NTAG203_SDS.pdf

      // TAG Type       PAGES   USER START    USER STOP
      // --------       -----   ----------    ---------
      // NTAG 203       42      4             39
      // NTAG 213       45      4             39
      // NTAG 215       135     4             129
      // NTAG 216       231     4             225

      for (uint8_t i = 0; i < 45; i++)
      {
        success = nfc.ntag2xx_ReadPage(i, data);

        // Display the current page number
        Serial.print("PAGE ");
        if (i < 10)
        {
          Serial.print("0");
          Serial.print(i);
        }
        else
        {
          Serial.print(i);
        }
        Serial.print(": ");

        // Display the results, depending on 'success'
        if (success)
        {
          // Dump the page data
          nfc.PrintHexChar(data, 4);
        }
        else
        {
          Serial.println("Unable to read the requested page!");
        }
      }
    }
    else
    {
      Serial.println("This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!");
    }

    // Wait a bit before trying again
    Serial.println("\n\nSend a character to scan another tag!");
    Serial.flush();
    while (!Serial.available());
    while (Serial.available()) {
    Serial.read();
    }
    Serial.flush();
  }
}

And nothing happens in the monitor after the setup
22:28:56.855 -> Hello!
22:28:56.888 -> Found chip PN532
22:28:56.888 -> Firmware ver. 1.6
22:28:56.922 -> Waiting for an ISO14443A Card ...

If I uncomment #define PN532DEBUG in Adafruit_PN532.cpp, I get some extra logs but still none when I pass my NTAG213 tag. Adding a timeout doesn't help the tag to be detected either.
// Passing the NTAG213 here
15:51:00.519 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,
15:51:01.582 -> TIMEOUT!
15:51:01.582 -> No card(s) read
15:51:01.582 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,
15:51:02.614 -> TIMEOUT!
15:51:02.614 -> No card(s) read
15:51:02.614 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,

// Passing another tag here
15:51:03.212 -> Reading:  0x0 0x0 0xFF 0xC 0xF4 0xD5 0x4B 0x1 0x1 0x0 0x4 0x8 0x4 0x47 0xF5 0xC 0xD8 0xAE 0x0 0xAA
15:51:03.212 -> Found an ISO14443A card
15:51:03.212 ->   UID Length: 4 bytes
15:51:03.249 ->   UID Value: 0x47 0xF5 0x0C 0xD8
15:51:03.249 ->
15:51:03.249 -> This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!
15:51:03.249 ->
15:51:03.249 ->
15:51:03.249 -> Send a character to scan another tag!

I have no special knowledge the related NFC topics, but I have been looking over everything you've referenced and I noticed nfc.SAMConfig() returns a bool value to indicate success on true (I think).  For lack of anything more intelligent to suggest for now, I thought maybe you might see that this is call is indicating success.

A fair mount of useful debugging information may come from uncommenting PN532DEBUG and MIFAREDEBUG (https://github.com/adafruit/Adafruit-PN532/blob/1.2.1/Adafruit_PN532.cpp#L67) in Adafruit_PN532.cpp.  Might help to include that information with the question.

Thanks for commenting @timemage. nfc.SAMConfig() returns 1 so this seems ok I think. I've tried adding the debug macros in the .ino file but it didn't print any additional info. I haven't tried to recompile the library yet, as I have never done it before.

It is usually enough to edit the source in place and just compile again.  In the past, I believe the IDE has incorrectly cached object files.  You can restart the IDE to get it to use a new temporarily build directory to prevent that from happening.  You may need to change the macro for the Serial port the library is using to print diagnostics.

@timemage I did t didn't get any more luck :/ It still doesn't print anything when i try to pass the tag on the reader. I do see extra logs when I pass another tag but it's still not detecting the NTAG213

What happens if you use the version of the readPassiveTargetID() that accepts a timeout?  Does it in fact timeout or does it lock up inside the function?

@timemage It loops until it detects something. With a NTAG213 it keeps going as if nothing happened, and then stops when detecting another tag. I've updated the question with the logs from PN532DEBUG and readPassiveTargetID() with a timeout

I'll keep looking at it.  I get the sense though that someone who knows this library and part will be able to say something useful based on the information you have in the question now.

Well, I'm curious about this stuff.  So, you should know I've ordered some things to test with here.  Some NTAG213 and a reader using the PN532, though not your exact board.  Perhaps within the week I'll be able to test locally.

Have you checked your tag with other readers? Many smartphones should be able to read (and write to) such tags, if that helps.

@timemage I truly appreciate your involvment in this :) I've also contacted the sellers just in case

@jcaron You're right, I absolutely meant to test the tags with a phone but I forgot. Mine doesn't support NFC but I live with a person who owns such a phone. I'll try that and let you know.

I have tags, but my board for testing won't come until Tuesday at the earliest.  I'm not sure how much longer I'm going to be on arduino.stackexchange.com.  I can be found on freenode if you want to talk there.

Received my board a day early it seems.  Wired it as described.  Using the code given unaltered on an UNO.  When I try an NTAG213, it recognizes it, prints the 7 byte UID, and proceeds to dump 4-byte pages numbered 0 to 44 inclusive.

@timemage Looking back on the PN532 link I initially provided, I think it might be a reader issue. It states that it supports ISO14443 but I couldn't find NTAG213 mentioned anywhere. I expected it to work because PN532 usually do but apparently this one doesn't. I contacted the vendor but they haven't been of much help knowing what their product supports or not. I've also tried reading the tags with a smartphone, and didn't have any problem doing so.

What you're saying seems to hinge on the idea that, since we're running the same code, that the PN532 can be configured to work (or not) with NTAG213 and that this configuration must exist in some non-volatile way, as part of the circuit construction or built-in eeprom etc.  I can't seem to substantiate that idea.

@timemage I'm not 100% sure I understood your last comment. I'll try my best to reformulate what I understood. I thought - seemingly wrongly - that any PN532 module would be able to work with NTAG213 because a quick google search indicates that these two can be compatible. However PN532 does not seem to be follow a specific norm or specification. Therefore simply being a PN532 module is not enough to ensure compatibility with NTAG213.

I'm not sure what more I can do while staying inside the stack-exchange format.  If you want, you can locate me on freenode.  If we come to a conclusion, you can write up your experience an answer to your own question.