title: SD seems too slow for SMTP

text:
# Question
Title: SD seems too slow for SMTP
I have asked this question on the arduino forum as well.

I have used SMTP before using client.print (and client.println) but I am now trying to move as much text as I can from RAM to SD (and so I need the \<SD.h\> library). It does not work and I am thinking it may be because the SMTP server "dies of boredom" as it waits for my Arduino to read from the SD card and write it to the client (server?). In the code below, I have included what I am trying (it will be uncommented if you copy+paste the code) and what already works (which will be commented when you copy+paste the code, but you can uncomment and comment the other section relatively easily). The text file I have on the SD in the code (commented). If anyone can think of a workaround, that would be great.

```
#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>

//-v--- Ethernet -----------
byte MyMac[] = {0xFE, 0xED, 0xBE, 0xEF, 0xFE, 0xED}; // <- The physical address of the machine's network card. Should be unique (no two network cards have the same MAC address)
byte MyIp[] = {1, 1, 1, 1}; // <- This is the not the real IP address, but for the real address I have verified that the static IP works for sending mail
byte Dns[] = {1, 1, 1, 1}; // <- Not the real DNS but I got it once through Serial.println(Ethernet.dnsServerIP()); and I know that it works
byte Gateway[] = {1, 1, 1, 1}; //<- Not real
byte Subnet[] = {1, 1, 1, 1}; //<- Not Real

EthernetClient client ;
//-^--- Ethernet -----------

//-v-- Smtp --------
char ServerChar[] = "blahblah";
//-^-- Smtp --------

//-v--- SD ------
File theFile; String line;
//-^--- SD ------

void setup() {
  Ethernet.begin(MyMac, MyIp, Dns, Gateway, Subnet);
  SD.begin(4);
  bool test = TrySend();
}

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

}

bool TrySend(){

  //*-v---- What I am trying ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    theFile = SD.open("Smtp.txt");   //Smtp.txt is listed toward the bottom of the code

    if(theFile){
      while(theFile.available()){
        client.write( theFile.read() );
      }
      theFile.close();
    }
  }

  else{ SuccessOrNot = false; }
  return SuccessOrNot;
  //-^---- What I am trying --- */

  /*-v-- The following works if used in place of [What I am trying] ---
  bool SuccessOrNot;

  if(client.connect(ServerChar, 25)){
    SuccessOrNot = true;
    client.println("EHLO ktlan");
    client.println("AUTH LOGIN");
    //-v- Most SMTP servers require verification in the form of base64-encoded username and base64-encoded password. However, since your IP must be whitelisted by the SMTP server, you don't need authentication
    //client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
    //client.println("ThisIsInBase64"); // Encoded version of the password
    //-^-
    client.println("MAIL FROM:<sender@blah.blah>");
    client.println("RCPT TO:<receiver@blah.blah>");
    client.println("DATA");
    client.println("to:receiver@blah.blah");
    client.println("from:sender@blah.blah");
    client.print("SUBJECT: TRIGGER");
    client.println();
    client.println("The temperature Monitor Triggered.");
    client.println(".");
    client.println("QUIT");
  }
  else{ SuccessOrNot = false; }

  //-^-- The following works if used in place of [What I am trying] ---*/
}

/*-v--- Smtp.txt -------
EHLO ktlan
AUTH LOGIN
MAIL FROM:<sender@blah.blah>
RCPT TO:<receiver@blah.blah>
DATA
to:receiver@blah.blah
from:sender@blah.blah
SUBJECT: TRIGGER

The temperature Monitor Triggered.
.
QUIT

//-^--- Smtp.txt -------*/

// NO NEED for authentication. For many Smtp servers you need:
//client.println("ThisIsInBase64"); // Encoded version of 'sender@blah.blah'
//client.println("ThisIsInBase64"); // Encoded version of the password
// My IP must be whitelisted by the SMTP server, and since it is, I don't need authentication

```

# Answer
Try a simpler approach (with some code refactoring)

```
bool TrySend(){

  if(client.connect(ServerChar, 25)){
    theFile = SD.open("Smtp.txt");

    if(theFile){
      while(theFile.available()){
        client.print(theFile.readStringUntil('\n'));
        client.print('\n');
      }
      theFile.close();
      return true;
    }
  }
  return false;
}

```

> As a side note, you might want to consider some better code structure (e.g. local variables). But I assume this is just a sample/test. Also, the code above assumes the file uses `\r\n` at the end of each line. If it only has `\n`, then you can simply use: `client.println(theFile.readStringUntil('\n'));` (notice the `print*ln*`). `println` sends both `\r\n`.
> 1 votes

---
Tags: communication, ethernet, sd, web-service
---


title: How to get the sizeof array of structs

text:
# Question
Title: How to get the sizeof array of structs
I'm trying to make a use of a relay module, I want a clear way to configure and control my relay module I've defined the struct and filled it with some info about id, pin number, title, and relay state I can't loop with for in the array of controls, because I can't get the sizeof the array right

```
typedef struct{
  int id;
  int pin;
  String title;
  bool state;
}  SwitchControl;

SwitchControl controls[2] = {
  {1, 22, "Switch 01", 1},
  {2, 23, "Switch 02", 0},
};

for(int i=0; i<sizeof(controls) - 1; i++){
}

```

thanks

# Answer
> 3 votes
To make it generic, you simply divide the `sizeof` the array by the `sizeof` the type:

```
for(int i=0; i<sizeof(controls)/sizeof(SwitchControl); i++){
}

```

Then you can later change the items if the array, or the structure and the code will be the same.

# Answer
> 2 votes
A more generic way (usable in future cases) is:

```
// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

```

Now you can use ARRAY\_SIZE (the\_array) in your code like this:

```
for(int i=0; i<ARRAY_SIZE (controls); i++){
}

```

The above works in C as well as C++.

---

The more C++ way of doing it is to use a template like this:

```
// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

```

Now ArraySize(the\_array) returns the number of elements in the array:

```
for(int i=0; i< ArraySize (controls); i++){
}

```

The "Arduino language" is C++ with some initial pre-processing. For all intents and purposes any tutorial on C++ will help you with Arduino programming (except that the Standard Template Library (STL) is not included by default).

---

I don't know why you were subtracting 1 in your posted code. Did you not want to iterate through the whole array?

# Answer
> 0 votes
sizeof(controls) returns the size, in bytes, of the entire object which is not what you want. You want the number of elements.

I'll point out that since you're statically allocating this as:

> SwitchControl controls\[2\]

The size you are looking for is always going to be 2. So just use 2 in your for loop like:

> for(int i=0; i\<2; i++)

---
Tags: c++, array, struct
---


title: SIM800l is not Avalible

text:
# Question
Title: SIM800l is not Avalible
I am using : -arduino uno r3 -SIM800L

connection:

Arduino SIM800L 5v --\> vcc gnd --\> gnd pin10 --\> TX pin11 --\> RX

the led on the module blinks once each 3~5 seconds but when i use the function sim.available() i got 0; thus as i guess there is a problem .

the code :

```
#include <SoftwareSerial.h>
SoftwareSerial sim(10, 11);
int _timeout;
String _buffer;
String number = "000000000000"; //-> change with your number
void setup() {
  delay(7000); //delay for 7 seconds to make sure the modules get the signal
  Serial.begin(9600);
  _buffer.reserve(50);
  Serial.println("Sistem Started...");
  sim.begin(9600);
  delay(1000);
  Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
}
void loop() {
  Serial.print(Serial.available());
  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        RecieveMessage();
        break;
      case 'c':
        callNumber();
        break;
    }
  if (sim.available() > 0)
    Serial.write(sim.read());
}

```

i looked the internet they say the voltage should be 3.7~4.2 itriedgivving 3.55 and it didn't work

# Answer
> 1 votes
Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.

For short test you can connect module directly to LiPo 3,7V.

You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

> The power IC and the bypass capacitor should be placed to the module as close as possible.

*SimCom, SIM800\_Hardware Design\_V1.09, available 27.11.2020*

---
Tags: arduino-uno
---


title: DHT11 not working with LED in arduino

text:
# Question
Title: DHT11 not working with LED in arduino
the point of my code is to turn on a LED when the humidity level reaches a certain amount. However it reads the amount of humidity but the LED is not turning on. Why isn't it working??

```
#include <SimpleDHT.h>

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11;

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

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");

  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  if (humidity > 70 ) {
     digitalWrite(9, HIGH);
  }
  else if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

```

# Answer
Your code does not work because in fact error statement reads the value of temperature and humidity sensor.

You set the `humidity` and `temperature` variables to 0. If statement compares this variables to 70, before actually reading sensor data.

I haven't tested but this should work.

```
#include <SimpleDHT.h>

int pinDHT11 = 2;
SimpleDHT11 dht11;

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

void loop()
{
    // start working...
    Serial.println("=================================");
    Serial.println("Sample DHT11...");

    // read without samples.
    byte temperature = 0;
    byte humidity = 0;

    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL))
        != SimpleDHTErrSuccess)
    {
        Serial.print("Read DHT11 failed, err=");
        Serial.println(err);
        delay(1000);
        return;
    }

    Serial.print("Sample OK: ");
    Serial.print((int)temperature);
    Serial.print(" *C, ");
    Serial.print((int)humidity);
    Serial.println(" H");

    if (humidity > 70 )
    {
        Serial.println("Humidity is above 70%");
        digitalWrite(9, HIGH);
    }
    else
    {
        Serial.println("Humidity is below 70%");
    }
    // DHT11 sampling rate is 1HZ.
    delay(1500);
}

```
> 1 votes

---
Tags: arduino-uno, c++, led
---


title: Arduino Nano randomly resetting

text:
# Question
Title: Arduino Nano randomly resetting
I am currently struggling with an intermittent problem with an Arduino project.

**Background**

I am using a LabVIEW program to control a few pieces of hardware. One of them is a NEMA 17 stepper motor that drives a rack and pinion actuator. I am using a genuine Arduino Nano with an (official) EasyDriver motor driver to drive the NEMA 17. The Arduino listens for the state of a DI pin, and if it is pulled high it moves out the rack until a U-shaped sensor sends a high input signal at the outermost position, it then listens for that DI pin to be pulled low and retracts the rack until a proximity sensor sends a high input signal.

**The Problem**

I noticed that my actuator was either becoming unresponsive to the input signals from the LabVIEW DAQ, or that it was getting stuck mid actuation (motor has plenty of torque for this application). After changing up the code to print updates to the serial port, I realized that after a few cycles the Arduino resets and re-enters the Setup() function.

I changed out the Nano and it made no difference. I am using a timeout feature for the first time and I was wondering if the memory usage of this feature could be causing problems - however I commented out this part of the code and the Arduino still reset. The code is below - would really love to hear any thoughts on whether this is likely to be a hardware or software issue. I am powering the Arduino with a 7V line from a Power Supply into the Vin port. The prox sensor operates at 24V but I divide the output signal's voltage so that the input voltage is ~4.8V (I have measured this). I am using the same U-shaped sensor with a few other Arduinos and I am not seeing this issue. I have powered Arduinos with the same 7V line in the past and have also never seen them reset like this.

Let me know what you think, thank you!

```
 const int uSensor = 12;
const int proxSensor = 10;

const int labViewHomePin = 9;
const int labViewInputPin = 8;

const int labViewOutFeedback = 7;
const int labViewInFeedback = 6;

const int StepperStepPin = 2;
const int StepperDirectionPin = 3;
const int ENPin = 13;

enum {IdleState, ForwardState, BackwardState} State;            // this switch case is used to call the correct function that turns the motor in the desired direction

boolean rampDone = false;
boolean pusherIn = false;
boolean pusherOut = false;
boolean homingDone = false;

boolean updateGiven = false;

int motorSpeed = 300;
int rampStartSpeed = 500;
int rampStepCountNo = 800;

boolean boolInitialMove = true;
unsigned long timeInitialMove = 6000;
unsigned long startTime;
unsigned long endTime;

void setup() {
  Serial.begin(9600);
  pinMode(uSensor, INPUT);
  pinMode(proxSensor, INPUT);
  pinMode(labViewHomePin, INPUT);                                  // initialising input pins
  pinMode(labViewInputPin, INPUT);                                  // initialising input pins

  pinMode(StepperDirectionPin, OUTPUT);                             //Direction
  pinMode(StepperStepPin, OUTPUT);                                  // Step
  pinMode(ENPin, OUTPUT);                                           // Enable

  Serial.println();
  Serial.println("Setup phase called");
  Serial.println();

  pinMode(labViewInFeedback, OUTPUT);
  pinMode(labViewOutFeedback, OUTPUT);

  State = IdleState;
  digitalWrite(ENPin,HIGH);                                         // Disable the drive by default

  homingDone = false;
}

void loop() {
  if ((digitalRead(labViewHomePin) == HIGH) && (homingDone == false)) {
    Serial.println("Homing Pin High Detected");
    homingRoutine();
    homingDone = true;
    Serial.print("Homing Done = ");
    Serial.println(homingDone);
    State = IdleState;

    if(digitalRead(proxSensor) == HIGH) {
      digitalWrite(labViewInFeedback,HIGH);
      digitalWrite(labViewOutFeedback,LOW);
    }
    else if(digitalRead(uSensor) == HIGH)  {
      digitalWrite(labViewInFeedback,LOW);
      digitalWrite(labViewOutFeedback,HIGH);
    }
    else {
      digitalWrite(labViewInFeedback,LOW);
      digitalWrite(labViewOutFeedback,LOW);
    }

  }

  switch (State) {
    case IdleState:
    boolInitialMove = true;
    digitalWrite(ENPin,HIGH);

      if(updateGiven == false) {
        Serial.println("I am in IdleState");
        Serial.print("Pusher Out Boolean = ");
        Serial.println(pusherOut);
        Serial.print("Pusher In Boolean = ");
        Serial.println(pusherIn);
        Serial.print("Prox Sensor status: ");
        Serial.println(digitalRead(proxSensor));
        Serial.print("U-Sensor status: ");
        Serial.println(digitalRead(uSensor));
        updateGiven = true;
      }

      if ((digitalRead(labViewInputPin) == HIGH) && (pusherOut == false) && (homingDone == true)) {
        digitalWrite(ENPin,LOW);                                    // Enable drive
        State = ForwardState;
        Serial.println("LabVIEW High detected. Case switched to ForwardState");
        Serial.println("");
        updateGiven = false;
      }
      else if ((digitalRead(labViewInputPin) == LOW) && (pusherIn == false) && (homingDone == true)) {
        digitalWrite(ENPin,LOW);                                    // Enable drive
        State = BackwardState;
        Serial.println("LabVIEW Low detected. Case switched to BackwardState");
        Serial.println("");
        updateGiven = false;
      }
      else {
        //do nothing
      }

      if(digitalRead(uSensor) == HIGH) {
        pusherOut = true;
        pusherIn = false;
      }
      else if(digitalRead(proxSensor) == HIGH) {
        pusherOut = false;
        pusherIn = true;
      }
      else {
        //do nothing
      }

      break;

    case ForwardState:

    if(updateGiven == false) {
        Serial.println("I am in ForwardState");
        Serial.print("LabVIEW Actuate Pin = ");
        Serial.println(digitalRead(labViewHomePin));
        updateGiven = true;
      }

    if(boolInitialMove == true) {
        digitalWrite(StepperDirectionPin, LOW);
        rampUpCosineWave(rampStartSpeed, rampStepCountNo, motorSpeed);
        startTime = millis();
        endTime = startTime;
        boolInitialMove = false;
      }

      endTime = millis();
      rotateForward(motorSpeed);                                            // this calls the function ForwardState which starts pushing out the pusher

      if (digitalRead(uSensor) == HIGH) {
        digitalWrite(labViewInFeedback,LOW);
        digitalWrite(labViewOutFeedback,HIGH);
        Serial.println("U-Sensor High detected. Case switched to Idlestate");
        Serial.println("");
        updateGiven = false;

        pusherOut = true;
        pusherIn = false;
        State = IdleState;
      }
      else if((endTime-startTime) > timeInitialMove) {
        digitalWrite(ENPin,HIGH);
        digitalWrite(StepperStepPin, LOW);
        digitalWrite(StepperDirectionPin, LOW);
        digitalWrite(labViewOutFeedback,HIGH);
        digitalWrite(labViewInFeedback,HIGH);

        Serial.println("");
        Serial.println("**TIMEOUT DETECTED**");
        Serial.println("");

        State = IdleState;
      }
      break;

    case BackwardState:

    if(updateGiven == false) {
        Serial.println("I am in BackwardState");
        Serial.print("LabVIEW Actuate Pin = ");
        Serial.println(digitalRead(labViewHomePin));
        updateGiven = true;
      }

    if(boolInitialMove == true) {
        digitalWrite(StepperDirectionPin, HIGH);
        rampUpCosineWave(rampStartSpeed, rampStepCountNo, motorSpeed);
        startTime = millis();
        endTime = startTime;
        boolInitialMove = false;
      }

      endTime = millis();
      rotateBackward(motorSpeed);

      if (digitalRead(proxSensor) == HIGH) {
        digitalWrite(labViewInFeedback,HIGH);
        digitalWrite(labViewOutFeedback,LOW);                                // Disable drive
        Serial.println("Prox Sensor High detected. Case switched to Idlestate");
        Serial.println("");
        updateGiven = false;

        pusherOut = false;
        pusherIn = true;
        State = IdleState;
      }
      else if((endTime-startTime) > timeInitialMove) {
        digitalWrite(ENPin,HIGH);
        digitalWrite(StepperStepPin, LOW);
        digitalWrite(StepperDirectionPin, LOW);
        digitalWrite(labViewOutFeedback,HIGH);
        digitalWrite(labViewInFeedback,HIGH);

        Serial.println("");
        Serial.println("**TIMEOUT DETECTED**");
        Serial.println("");

        State = IdleState;
      }
      break;

  } // end switch
}

void rotateForward(int mtrSpeed) {
  digitalWrite(StepperDirectionPin, LOW);
  digitalWrite(StepperStepPin, HIGH);
  delayMicroseconds(mtrSpeed);
  digitalWrite(StepperStepPin, LOW);
}

void rotateBackward(int mtrSpeed) {
  digitalWrite(StepperDirectionPin, HIGH);
  digitalWrite(StepperStepPin, LOW);
  delayMicroseconds(mtrSpeed);
  digitalWrite(StepperStepPin, HIGH);
}

void homingRoutine() {
  digitalWrite(ENPin,LOW);
  Serial.println("Homing Routine called");
  bool firstCycle = false;
  bool secondCycle = false;
  bool thirdCycle = false;
  bool fourthCycle = false;

  while(digitalRead(uSensor) != HIGH) {
    rotateForward(rampStartSpeed);
  }
  delay(500);
  Serial.println("First home movement completed");
  while(digitalRead(proxSensor) != HIGH) {
    rotateBackward(rampStartSpeed);
  }
  delay(500);
  Serial.println("Second home movement completed");
  while(digitalRead(uSensor) != HIGH) {
    rotateForward(rampStartSpeed);
  }
  delay(500);
  Serial.println("Third home movement completed");
  while(digitalRead(proxSensor) != HIGH) {
    rotateBackward(rampStartSpeed);
  }

  delay(500);

  homingDone = true;
  pusherIn = true;
  pusherOut = false;

}

  int rampUpCosineWave(int startSpeed, int rampUpSteps, int maximumSpeed) {
  int countedSteps = 0;
  float amp = ((startSpeed-maximumSpeed)/2);
  for(int currentSpeed = startSpeed; currentSpeed > maximumSpeed; currentSpeed = (int)((amp + maximumSpeed)+(amp*(cos((PI/rampUpSteps)*countedSteps))))) {
    digitalWrite(StepperStepPin, LOW);
    delayMicroseconds(currentSpeed);
    digitalWrite(StepperStepPin, HIGH);
    countedSteps++;
  }

  return countedSteps;
}

```

# Answer
> 3 votes
Thank you all for your contributions. I managed to find the issue and solve the intermittent reset. I was expecting to find a hardware problem as the root cause, but just in case it was software related I wanted to check as well. It turned out to be hardware

Gil is certainly questioning the correct piece of hardware. It was indeed the wiring of the Prox sensor. I had connected both the data and power common rails to facilitate the prox sensor but on inspection, I decided to keep these separate and voltage divide the prox sensor away from the rails and instead bring a direct 4.8V line into the Arduino. Whatever noise the stepper motor was creating was unable to impact the data lines of the Arduino, and I haven't seen the issue return since.

Really appreciate the help everyone. I didn't scope the power lines to the Arduino, as the issue continued regardless of me powering the arduino through only the COM port of a PC, a combo of both the COM port and 7V to the Vin line (presume the Arduino draws from the 7V line but I am unsure) and just the 7V line. Appears to have been noise disrupting the data common rail of the Arduino.

# Answer
> 1 votes
I expect you have a lot going on with your design. Dividing down is never a good voltage (power) supply regardless of what you measure unless you are using a good scope to measure and it is well bypassed. Consider a Buck regulator from one of the China suppliers they are just a few bucks and will stabilize your circuit. If the prox sensor draws just a few mills consider powering it with the Arduino 5 volts. Motors like other inductive devices generate lots of transinents that are both conducted and radiated, something like that may be getting into your system possibly via the prox sensor. This should get you started.

---
Tags: arduino-uno, programming, arduino-nano, hardware, reset
---


# Question
Title: Current Sensor ACS712 not changing its value even when connected bulb is lit
My task is to find the amount of current a light bulb uses, with that motive I used ACS712 current sensor of 30A connected all the connections properly as shown in the circuit diagram below

I tried all different codes available to calculate current...

**Arduino Code :**

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

void loop(){
  int rVal = 0;
  int sampleDuration = 100;       // 100ms
  int sampleCount = 0;
  unsigned long rSquaredSum = 0;
  int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

  uint32_t startTime = millis();  // take samples for 100ms
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(A0) - rZero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
  double ampsRMS = voltRMS * 10.0;
  Serial.println(ampsRMS);
  Serial.println(analogRead(A0));
}

```

**Output**

The output remains the same, even when the bulb is still lighting up.

Thank You in advance :)

# Answer
> 1 votes
In a comment about `rZero = 511;`, you wrote:

> For illustrative purposes only - should be measured to calibrate sensor.

This may well be the cause of your problem. If, instead of 511, the “zero” of your measurement is around 445, then you end up measuring a non-existing DC current of about 3.23 A. When you turn on the light bulb, you add roughly 435 mA (100 W / 230 V) of AC current. The total RMS current you see is then:

√(3.232 \+ 0.4352) ≈ 3.26 A

Barely visible at the resolution at which you are printing the result. And this is assuming you are using a 100 W bulb, as shown in the diagram. These bulbs are getting hard to come by. If you are using anything less powerful, you may not see any change in the displayed value.

As a quick and dirty fix, you may replace `511` by `445`. A better solution would be to compute the quadratic average of the AC part of the signal alone. In other words, compute:

√(average(current2) − average(current)2)

---
Tags: arduino-uno, sensors, current
---


title: switching power sources

text:
# Question
Title: switching power sources
I have a small project I am working on that accepts power from either a 5v DC power source or a USB power source.

Now, I know that both of the power sources are effectively 5v. I have measured the power on both with my meter and can see that the USB supply is at 5.4 and the DC supply is at 5.01v.

I would like to be able to build something that switches over to the USB supply when the cable is connected. However, I have never done this before. I have taken a look around on Google already and have read some things about P Channel MosFETs and PowerPath controllers - but I am a little confused as to whether the two incoming voltages I have are suitable for this?

Would someone be able to give me a little advice on this at all?

Cheers,

Rafa

# Answer
> 1 votes
Consider copying the Arduino Uno reference design. This is part of that schematic showing the MOSFET used to turn on / off the USB power when the barrel jack power source is active:

---
Tags: power
---


# Question
Title: Adafruit Neopixel Individual Addressable LEDs issue - Any and every code make LEDs go "crazy"
Hi everyone I have an issue with getting these LEDs to cooperate.

I'm using a 470ohm resistor on the data port and a capacitor for the power. I complied and uploaded the "strandtest"(I changed the variables NUM\_LED & LED\_PIN) and this occurs \[10s Video: https://drive.google.com/file/d/1xabkHW1xgFo9kh3YnGwIsaS5tSfFCsrb/view?usp=sharing\] This happens to all code in a loop. If I send no signals (aka put an empty pin and run) then the lights that were last on stay lit. If I try to clear the LED nothing happens. If I try to set a specific LED to a specific color/brightness nothing happens.

I'm at my wit's end; help a brother out!

LEDs Used:https://www.amazon.com/gp/product/B00ZHB9M6A/ref=ppx\_yo\_dt\_b\_asin\_title\_o02\_s01?ie=UTF8&th=1 AC to DC 5V 5A: https://www.amazon.com/ALITOVE-Converter-5-5x2-1mm-100V-240V-Security/dp/B078RT3ZPS/ref=pd\_bxgy\_img\_2/143-9706163-2199558?\_encoding=UTF8&pd\_rd\_i=B078RT3ZPS&pd\_rd\_r=4133e781-45a6-4112-a571-c311f45e0720&pd\_rd\_w=t0bs4&pd\_rd\_wg=TIEcS&pf\_rd\_p=f325d01c-4658-4593-be83-3e12ca663f0e&pf\_rd\_r=PPCEVPJVY8N6XFTY1AD4&psc=1&refRID=PPCEVPJVY8N6XFTY1AD4

```
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 150

// For led chips like WS2812, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define DATA_PIN 3
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
    // Uncomment/edit one of the following lines for your leds arrangement.
    // ## Clockless types ##
    //FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);  // GRB ordering is assumed
    // FastLED.addLeds<SM16703, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1829, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1812, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS1904, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<UCS2903, DATA_PIN, RGB>(leds, NUM_LEDS);
     //FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<WS2852, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical

    // FastLED.addLeds<GS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SK6812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<APA106, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<PL9823, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SK6822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2813, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2811_400, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GE8822, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<LPD1886, DATA_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<LPD1886_8BIT, DATA_PIN, RGB>(leds, NUM_LEDS);
    // ## Clocked (SPI) types ##
    // FastLED.addLeds<LPD6803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical
    // FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<WS2803, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
    // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
    // FastLED.addLeds<SK9822, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);  // BGR ordering is typical
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

```

# Answer
Don't use the Neopixel library. for LEDs that have WS2812B the FastLED is the best option. I also had issues with the LEDs flashing on and off randomly but using this library and then changing the driver to W2812B made it work. Your power supply is plenty strong.
> 2 votes

---
Tags: led, neopixel, led-strip
---


# Question
Title: Plotting data from Arduino and using the serial monitor in parallel
I'm very new to the Arduino world so bare with me. I would like to plot live data that I receive from my arduino. I use the Serial Monitor to read user input, show text, etc.

The only way I found to plot data from the arduino is by printing the data out in the serial monitor I would rather prefer the data not to be shown in the serial monitor at all (just from a visual standpoint) but I guess there is no way around it.

Anyways, I would like to read and plot the data only when the user makes a specific input into the Serial Monitor.

Let's say the user types in: "start" now the arduino prints out the values that needs to be plotted.

But every plotting tutorial on plotting with the arduino that I could find always prints out the data right from the start. I want to start the plotting with the specific user input.

I hope I could explain my question well enough. Thank you in advance for your help.

Luca

# Answer
> 1 votes
You can also use the Serial Plotter in the Arduino IDE. If you use `Serial.println(<some number>)` and then open the Serial Plotter(Tools-Serial Plotter), you will see a live graph. Based on your baud rate, the update speed will change. It is very powerful.

# Answer
> 0 votes
Is using the Serial Monitor a requirement, or are you just looking for a good way to get and plot the data? If the latter, you may be interested in the open-source DaqPort sketch. https://www.daqarta.com/dw\_rraa.htm This was created to use the Arduino as a peripheral for data acquisition, as opposed to the more typical case of the Arduino being the central device. With DaqPort you can program in any language you like on the host computer, and use it to plot data from the Arduino. The Daqarta software package that includes DaqPort has several examples that use Daqarta's macro language to implement a multi-channel chart recorder, high-speed multi-function oscilloscope, timers, signal generator, etc. You can use these for free, forever, even after Daqarta's 30-day trial ends. Since Daqarta already has plotting, you may find it simpler to use than rolling your own, perhaps by modifying one of the examples.

---
Tags: input
---


# Question
Title: Timer STM32 #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting
I have installed the library of **TimerInterrupt\_Generic** for ArduinoSTM32 module via Arduino IDE, so i have tried to test the example of library as you can see below:

and i have gotten this error:

```

TimerInterruptLEDDemo:45:4: error: #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
   #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
    ^
In file included from /home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/examples/STM32/TimerInterruptLEDDemo/TimerInterruptLEDDemo.ino:64:0:
/home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/src/TimerInterrupt_Generic.h:86:4: error: #error Unsupported Board! Please check your Tools->Board setting.
   #error Unsupported Board! Please check your Tools->Board setting.
    ^
exit status 1
#error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.

```

Also, This question is asked here:

https://github.com/khoih-prog/TimerInterrupt\_Generic/issues/2

# Answer
The **Roger Clark's STM32 core** you're using is not currently supported. I don't know in the future if I can add that core into the supported list.

You have to use this **Arduino\_Core\_STM32**.

Convert to new core by following the intructions in **Getting Started**
> 4 votes

---
Tags: timers, stm32
---


title: Multiple definition class in arduino

text:
# Question
Title: 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,

# Answer
> 0 votes
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.

---
Tags: arduino-uno, c++
---


# Question
Title: 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???

# Answer
> 2 votes
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.

---
Tags: arduino-yun
---


# Question
Title: 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);
 }

```

# Answer
> 0 votes
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?

---
Tags: arduino-uno
---


# Question
Title: ERROR: Timed out waiting for Arduino 101 - anything I can do?
I just received an Arduino 101 so I did the following in a wave of excitement...

1. Connected the USB cable between it and my Macbook Pro
2. Started the Arduino IDE version `1.6.7`
3. Wrote a little bit of code
4. Selected `Tools | Boards | Boards Manager...` and installed the `Intel Curie Boards` as per Getting Started
5. Selected `Tools | Board: "Arduino 101"`
6. Selected `Tools | port: "/dev/cu.usbmodemFA141 (Arduino 101)"`
7. Selected `Sketch | Upload`

I was expecting something amazing, but I got the error:

```
Starting upload script
Payload: /var/folders/jr/5rmqcrqj58103d4p1f6_3sjr0000gn/T/build7c6ce067b9e8a57f9917c651ec494989.tmp/orientation.ino.bin
Waiting for device...
ERROR: Timed out waiting for Arduino 101.

```

Is there anything I can do to debug this or did I miss a step perhaps?

(I tried the good ol' turn it off and on again, including shutting the IDE down).

# Answer
Press the reset button next to the USB port. (either one, the master reset is between the DC jack and USB ).

This will cause the Arduino 101 to reboot and enter DFU mode for 5 seconds if it is connected on USB. The download will proceed when the Curie enters DFU.

The IDE uses a baud-rate signal over USB. It is a virtual serial port, so baud rate doesn't matter. But when the host side (Arduino IDE) switches the baud rate to 1200, the board will reboot and enter DFU mode for download. If it gets stuck for some reason and misses the message to reboot, you can just hit the reset button and accomplish the same thing.
> 5 votes

# Answer
If the path to your source file contains a space, it might be causing this error. For more information, and a workaround, see this topic in the Arduino forum.
> 1 votes

# Answer
I was having the same problem: unable to upload a program to a brand new 101. Now it works.

I can successfully load both BLE LED example programs and also the ReadTime program read via Serial Monitor. (BTW, using the iOS MCP app, you need to send either 00 or 01 to turn the LED on/off.)

I am running a modern 64 bit laptop with USB 3.0 ports. All ports work fine with either of two USB cables that I have. So I don't believe the problem is related to USB cables or USB 2.0/3.0.

How did I fix it? Well, I tried several things and I'm not sure which one fixed it, so perhaps someone can try these methodically and confirm the best fix.

1. Uninstall the Arduino IDE and manually deleted the Arduino15 folder in user..\AppsData.
2. Restart laptop.
3. Download and install IDE 1.6.8. (Earlier failed attempt was with current 1.6.9.)
4. Restart laptop.
5. Open IDE. In Boards Manager, searched Intel, selected Curie boards, and install v1.0.4. (Earlier failed attempt was with current 1.0.5.)
6. Restart laptop.
7. Open IDE. Plug in 101 for the first time. Device showed up normally in Device Manager.
8. Select proper port (COM5 for me) and proper board (101). Select example file LED under CurieBle. Click verify. Looks good. Click upload. SUCCESS! Can now see the 101 in nRF MCP, can turn LED on/off. BLE functions now work with 5V USB charger. (but not 9V battery, guess that's not an option) When connected to laptop USB 3.0 port, the 101 now stays in COM5 the entire time, no longer cycling on/off when I try to upload. No need to press either reset button during upload.

So the fix is either one of the software downgrades, or careful installation procedure.

Previously, I tried the dfu-utils updates but that didn't fix this problem.
> 1 votes

# Answer
I am running Ubuntu 18.04 and I had a similar problem but solved it in the end.

What worked for me was:

1. Update Arduino Curie driver in Boards manager to the latest version which is v 2.02 at the time of this post
2. Run the following command in terminal in order to grant execution rights:

```
 chmod +x ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

```
3. Run the executable

```
 sudo ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

```
4. Restart Arduino and try to reupload

### Edit for Debian testing

At the time of this edit, all the previous steps work for the Bookworm distribution, with the latest Arduino IDE version (1.8.19) and the latest Arduino Curie driver version (2.0.5). Just remind to adapt the previous path according to the driver version.
> 1 votes

# Answer
I posted a fix here:

https://forum.arduino.cc/index.php?action=profile;area=showposts;u=1472279

I was really looking forward that this will be the fix for all Arduino 101 Error
> 1 votes

# Answer
I was really persistent to look for ways on how to fix the Arduino/Genuino 101 Timeout Error, I searched different forums and read a lot of suggestions on how to fix the error, but still all failed, I know some of the 101 users already bricked their 101 or other just left it behind. We are all aware that the Arduino 101 is already discontinued and even support is already stopped, Hence this little but powerful microcontroller is still out there and probably used by the some. Anyhow, to be straight to the point I finally I discovered the fix for the error. Notice that when you insert your 101 to the USB plug it will read and install the device, checking it in the device manager will show the Arduino/Genuino 101 in "Other Devices" and a new COMPort (COMX) is added, then you install the Arduino IDE (regardless of the version), then install the Arduino 101 Board thru "Board Manager", the manager will install the Arduino 101 but it will not notify you that the driver for Arduino 101 is not installed due to error. So in short we are assuming that the driver for Arduino 101 is successfully installed. This is where the error lies. The software driver "dpinst-amd64" is not digitally signed and Windows is blocking to install unsigned drivers. So what's the fix? The fix here is still to install the "dpinst-amd64" since it is the driver needed to recognize your 101, the trick here is you need to install it in other way, not in your regular PC operation. You need to access the "disable signature enforcement" under the startup options (not safe mode). This startup mode will enable you to install unsigned drivers (I trust this Intel Curie driver since it was downloaded with the board). After installation restart your PC to its regular startup and plug-in again your Arduino/Genuino 101, this time the PC will now recognize the microcontroller and you can now upload sketches without the time out error.

For a step by step procedure:

1. Access Update and Security\>Recovery\>Advanced Startup
2. Your computer will eventually restart and will bring you to the Advanced Startup, access Troubleshoot\>Startup Settings. Your PC will restart again and options for the startup will display, choose number 7 "disable signature enforcement"
3. Your PC will start. Locate "dpinst-amd64.exe" in C:\>Users\>YOUR USERNAME\>AppData\>Local\>Arduino15\>packages\>Intel\>hardware\>arc32\>2.0.4(latest version)\>drivers\>dpinst-amd64
4. During installation a message will prompt if you want to install the unsigned driver, just click install.
5. After installation restart your PC and your Arduino/Genuino 101 is good to go.
6. To confirm that your Arduino/Genuino 101 is installed go to Device Manager and you will see that the Arduino/Genuino 101 is not anymore in the Other Devices.

I hope this will help. :D I will try to make a video about this fix. :D Thanks!

Regards,

Raf
> 1 votes

# Answer
It's already documented in the arduino.cc, but I will just add here as reference:

> Linux only: some distributions need to be configured to perform the upload. After installing the core, execute
>
> ```
> sudo ~/.arduino15/packages/Intel/tools/arduino101load/1.6.4+1.18/scripts/create_dfu_udev_rule
>
> ```
>
> inside a shell to gain upload permissions.

Reference: Upload Procedure
> 0 votes

---
Tags: arduino-ide, uploading, mac-os
---


# Question
Title: Converting 8 bit binary to a hexadecimal pair as unsigned char
I have a function:

```
void Epd::SendData(unsigned char data) {
  digitalWrite(dc_pin, HIGH);
  SpiTransfer(data);
}

```

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:

```
SendData(0x03);
SendData(0x1f);

```

To get those two values (`0x03` and `0x1f`) I am converting the decimal value of `799` to binary: `1100011111` and then adding `0` at the beginning to make sure my binary result is 16 digits long: `0000 0011 0001 1111`. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the `SendData` function.

I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the `SendData` function:

```
void Epd::SendDecAsData(int dec) {
  int binary[16];
  for (int i = 0; i < 16; i++) {
    binary[i] = dec % 2;
    dec = dec / 2;
  }

  int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
  int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
  int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
  int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

  String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
  String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

  SendData(val1); // error because I'm sending `String` instead of `unsigned char`
  SendData(val2);
}

```

I need help converting those strings (`val1`, `val2`) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to `String`).

# Answer
As StarCat suggested, I can just send decimal values using the same function `SendData` I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.

This is the function I used to send decimal data in 8-bit pairs:

```
void Epd::SendDecAsData(int dec) {
  if (dec == 0) {
    SendData(0);
    SendData(0);
  } else {
    SendData((dec-1) / 256);
    SendData((dec-1) % 256);
  }
}

```
> 1 votes

---
Tags: string
---


# Question
Title: 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.

```

# Answer
> 1 votes
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'

---
Tags: arduino-uno
---


title: How do I use a photoresistor?

text:
# Question
Title: How do I use a photoresistor?
I found this project and it seemed simple but now I don’t know. Please help. I tried changing the code and the wires but nothing happened.

```
int photoSensorPin = A0;
int redLedPin = 3;
int greenLedPin = 5;
int blueLedPin = 6;
int redLedVal = 0;
int greenLedVal = 0;
int blueLedVal = 0;
boolean isLedOn = false;

int brightness = 1023;
int darkThreshold = 50;
int changeColorTime = 900000;

long lastUpdate=0;

void setup()
{
    randomSeed(analogRead(1));
}

void loop()
{
    getBrightness();
    if (brightness < darkThreshold) {
        if (!isLedOn) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        } else if (millis() > lastUpdate + changeColorTime) {
            LedOn();
            isLedOn = true;
            lastUpdate = millis();
        }
    } else {
        LedOff();
        isLedOn = false;
    }
    delay(1000);
}

int getBrightness()
{
    brightness = analogRead(photoSensorPin);
    return brightness;
}

void LedOn()
{
    redLedVal = random(1,128);
    greenLedVal = random(1,128);
    blueLedVal = random(1,128);

    analogWrite(redLedPin,redLedVal);
    analogWrite(greenLedPin,greenLedVal);
    analogWrite(blueLedPin,blueLedVal);
}

void LedOff(){
    analogWrite(redLedPin,0);
    analogWrite(greenLedPin,0);
    analogWrite(blueLedPin,0);
}

```

# Answer
You forgot to set set the pins to output mode. In `setup()`, add:

```
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(blueLedPin, OUTPUT);

```

If that doesn't work, then you will need some debugging. Add also this to `setup()`:

```
Serial.begin(9600);

```

and this to `loop()`:

```
Serial.println(brightness);

```

Look at the values printed. Do they vary significantly when the lighting conditions change? If not, check the wiring of the LDR (it is fine in your schematic). Do they go below and above `darkThreshold`? If not, then change your threshold.
> 1 votes

# Answer
How fast does this project need to be for it to be useful? A photo resistor can take as much as a second to react to bright to dark conditions.

> Photoresistors also exhibit a certain degree of latency between exposure to light and the subsequent decrease in resistance, usually around 10 milliseconds. The lag time when going from lit to dark environments is even greater, often as long as one second. This property makes them unsuitable for sensing rapidly flashing lights

Consider testing the code by connecting A0 to 5 volts to simulate a bright condition. Then connect A0 to ground to simulate a dark condition.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: 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!

# Answer
> 1 votes
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:

1. Initial detection.
2. 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.
3. If the detection is still there, wait for the remainder of the time for your "long" detection.
4. 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.
5. 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.

---
Tags: arduino-ide
---


# Question
Title: 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=A1*sin(w1*t+phi1), V2=A2*sin(w2*t+phi2) and V3=A3*sin(w3*t+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?

# Answer
> 1 votes
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.

---
Tags: arduino-uno, c++, power, signal-processing
---


# Question
Title: 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.

```

# Answer
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*.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: 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.

# Answer
> 4 votes
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.

---
Tags: arduino-mega
---


# Question
Title: 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.

# Answer
There may be a couple of issues to consider:

1. 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.)
2. 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.)

3. 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.
4. 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.
5. 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.)
> 1 votes

---
Tags: i2c, mpu6050
---


# Question
Title: 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

# Answer
> 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. :)
> 3 votes

---
Tags: arduino-uno, bluetooth, hc-05, rx-pin
---


# Question
Title: Pro micro Wire.endTransmission() does not return
I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each. Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44). By debugging the code, I found out that endTransmission does not return. Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?

Thanks!

```
#include <Wire.h>

void setup() {
  Serial.begin (115200);
  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  Wire.begin();
}  // end of setup

void loop() {
  byte count = 0;
  for (byte i = 1; i < 120; i++)
  {
    Serial.println(i);
    Wire.beginTransmission (i);
    Wire.endTransmission ();
    delay(10);
  }
}

```

# Answer
Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines
> 2 votes

---
Tags: i2c, arduino-pro-micro, atmega32u4
---


title: Problemm with the MPU6050 library

text:
# Question
Title: 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.

# Answer
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.
> 1 votes

---
Tags: arduino-mega, c++, mpu6050
---