# Question
Title: Is it possible to split project into several folders?
It is possible to split the project into server files. However, it looks like they all must be in the same folder with the.ino file.

Is it possible to split project into several folders? I’ve got several git repositories which I want to use in the same project and I can’t use them as libraries. Each repository must have its own folder…

# Answer
I will try to give an answer as it is not easy to understand what you mean.

Probably it is also better if you know how the Arduino IDE works, before try to make complex projects.

Short answer: **Yes, it is possible**

Normally, you have an ino-file, some other files and many libraries. If you want create something for your project, you can just create a folder inside the library folder.

But this is not what you want right?

You can create many folders inside your project and include any header inside your folders just with
`#include "subfolder/yourfile.h"`

The files will not be opened with your Arduino IDE.

You can also create your "mini library", so the compiler will compile it with your project. This library need to be in a subfolder called `src`. At this point it will be converted and compiled for your project.

Simple working example:
**testsub.ino**

```
#include "src/test.h"
Test *test = new Test();
void setup(){
  Serial.print(test->number());
}
void loop(){
}

```

Create a subfolder `src` and place your files:
**test.h**

```
class Test
{
public:
  Test();
  int number();
};

```

and
**test.cpp**

```
#include "test.h"
Test::Test() {
}
int Test::number() {
  return 95;
}

```

If you want another "library", you can create another subfolder called `src`.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2
I would like to create a custom Arduino board based on the Arduino Due. Upon looking at the Due's schematics under the documentation tab there are some stuff that i do not need and removed them. the last thing that i want removed is the ATMEGA16U2. This part just takes so many components that i want it removed.

I would like to build my code using the arduino IDE and with the 16u2 gone i do not know a way how to upload my codes.

This seems to be possible since under the documentations there is a native usb port of the due that is directly connected to the SAM3X8E,

from here on out im lost what how do i upload my code to the same sam3x8E

Special tools that i have that might be usefull:

* J-link EDU Mini
* USB to UART

My Current draft schematics:

# Answer
> 1 votes
Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).

There are two ways of entering the bootloader:

1. Wipe the flash with the ERASE button (or trigger from 16U2).
2. Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.

You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.

---
Tags: arduino-due
---


title: Adafruit motorshield v2.3 not working

text:
# Question
Title: Adafruit motorshield v2.3 not working
I want to connect my adafruit motor shield v2.3 to a touch board from bare conductive so that the motor turns when one of the electrodes is touched.

I've tested the touch part and that isn't a problem so i tested the motor shield on my arduino uno. I am using the DCMotorTest example and when uploading it doesn't give any errors. The shield is getting powered, but the motor isn't turning.

The motor does turn when connected to a 9v battery. The motor doesn't turn when connected to motor shield without external power and VIN jumper connected.enter image description here The motor doesn't turn when connected to motor shield with external power with and without VIN jumper connected.

```
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
---->   http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}

```

https://i.stack.imgur.com/uzsEb.jpg

# Answer
> 1 votes
You have two possibilities of powering the shield according to the adafruit documentation.

A: power the Arduino over the power plug (not the USB plug) of the Arduino and set the VIN jumper.

B: Leave the VIN jumper off and power over the power connector of the shield.

Don't try other possibilities. They may kill the shield or the Arduino.

The reason your motor doesn't turn is because you switched it off `myMotor->run(RELEASE);` immediately after you switched it on `myMotor->run(FORWARD);`.

# Answer
> 2 votes
I just used a different motor-shield and it works now, thank you all for your replies and research in this!

---
Tags: arduino-uno, motor, adafruit, arduino-motor-shield, bare-conductive
---


title: Stuck in a loop using IR Receiver

text:
# Question
Title: Stuck in a loop using IR Receiver
I am new to Arduino Programming and I have bought an Arduino UNO , Ultrasonic Sensor (HC-SR04), A Piezo Buzzer, IR Receiver (VS1838B) and a RGB LED....

I wrote a program to Calculate Distance form the Ultrasonic Sensor to an object and a Processing Sketch to Display the results.

Now I want to use the IR Receiver to increase the Distance Threshold which makes the buzzer beep...I mean I want to press 1 in my remote to keep the distance about 5 cm after which the buzzer beeps, and when I press 2 the distance becomes 10 cm and so on...I want to stop everything when I press 0 in my remote...

I have already found out the hex codes of my remote buttons but the program makes the task harder... Please help me with the program that I have already written :-

```
#include <NewTone.h>
#include <IRremote.h>

const int rec = 9;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  irrecv.enableIRIn();
  Serial.begin(9600);
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if (results.value != BUTTON_0)
    {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distanceCm = duration * 0.034 / 2;
      distanceInch = duration * 0.0133 / 2;
      dur = duration / 10000;

      Serial.print(distanceCm);
      Serial.print("  cm ");
      Serial.print("                         ");
      Serial.print(distanceInch);
      Serial.print(" Inch ");
      Serial.print("                         ");
      Serial.print(dur);
      Serial.print(" Seconds");
      Serial.print("\n");
    }

    if (results.value == BUTTON_0)
    {

      noNewTone(buzPin);
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }

    if (results.value == BUTTON_1)
    {

      if (distanceCm <= 5)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 10 && distanceCm > 5)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_2)
    {

      if (distanceCm <= 10)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 20 && distanceCm > 10)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_3)
    {

      if (distanceCm <= 30)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 50 && distanceCm > 30)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_4)
    {

      if (distanceCm <= 100)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 200 && distanceCm > 100)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }
    irrecv.resume();
  }
}

```

I am using the "IRremote.h" and "NewTone.h" Libraries....

The main problem is that the "irrecv.resume();" pauses the program and waits for the IR input but I want the program to run continuously till I give an IR Input...

I request you to help me with the program.

---

I edited my program to this and this worked:-

```
#include <NewTone.h>
#include <IRremote.h>

const int rec = 2;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop()
{
  if (irrecv.decode(&results))
  {

    do
    {
      if (results.value == BUTTON_0)

      {

        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }

      if (results.value == BUTTON_1)
      {
        sonic();

        if (distanceCm <= 5)
        {
          red();
        }
        else if (distanceCm <= 10 && distanceCm > 5)
        {
          blue();
        }
        else
        {
          green();
        }

      }

      if (results.value == BUTTON_2)
      {
        sonic();
        if (distanceCm <= 10)
        {
          red();
        }
        else if (distanceCm <= 20 && distanceCm > 10)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_3)
      {
        sonic();
        if (distanceCm <= 30)
        {
          red();
        }
        else if (distanceCm <= 50 && distanceCm > 30)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_4)
      {
        sonic();
        if (distanceCm <= 100)
        {
          red();
        }
        else if (distanceCm <= 200 && distanceCm > 100)
        {
          blue();
        }
        else
        {
          green();
        }

      }
    }
    while (digitalRead(rec) == 1);

    irrecv.resume();
  }
}

void sonic()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034 / 2;
  distanceInch = duration * 0.0133 / 2;
  dur = duration / 10000;

  Serial.print(distanceCm);
  Serial.print("  cm ");
  Serial.print("                         ");
  Serial.print(distanceInch);
  Serial.print(" Inch ");
  Serial.print("                         ");
  Serial.print(dur);
  Serial.print(" Seconds");
  Serial.print("\n");
}

void green()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 255);
  analogWrite(bluePin, 0);
}

void blue()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 255);
}

void red()
{
  NewTone(buzPin, 2000);
  analogWrite(redPin, 255);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

```

But now the problem is I need to press the IR Remote button two times because when I press once the program moves to the `irrecv.resume();` command and waits for another IR Input and I need to press the button again.

Can this be solved (with only one press)?

# Answer
> 0 votes
Your code becomes more readable, if you use functions with return values.

For example, something like this structure

```
unsigned int limit; // 0 = off, else limit in cm  ...
void loop() {
  if (irrecv.decode(&results)) {
      byte key = getIRKey(results.value); // 0 , 1, 2, etc.,  0xFF for unknown
      irrecv.resume();
      switch (key) {
         case 0: limit = 0; break;
         case 1: limit = 5; break;
         ...
         default: break; // wrong key does not change limit
      }
  }
  if (limit) {
     unsigned int dist = sonic(); // returns the measured distance or 0
     if (dist && dist < limit) NewTone(buzPin, 2000);
     else noNewTone(buzPin); // off: too far
  } else noNewTone(buzPin); // off: no check
}

```

This code should not block. Have fun modifying sonic() and creating the other helper function.

# Answer
> 0 votes
1. You really should use switch-case.
2. irrecv.resume() does not halt the code.

Your program is running fine. It seems like you want to make sensor readings continuously and act only when you press the button. Am I right?

---
Tags: arduino-uno
---


title: EEPROM page rotates while writing to it

text:
# Question
Title: EEPROM page rotates while writing to it
The following code intends to read from serial port and write the data byte by byte to a 24LC01B EEPROM.

```
// 24LC01B PINS
// Pin 1, A0: float
// Pin 2, A1: float
// Pin 3, A2: float
// Pin 4, VSS: GND
// Pin 5, SDA: Arduino A4
// Pin 6, SCL: Arduino A5
// Pin 7, WP: Write/Protect = GND
// Pin 8, VCC: +5

#include <Arduino.h>
#include <Wire.h>

// I2C Bus address of 24LC256 EEPROM;
// if more than one eeprom, they will have different addresses (h/w configured);
#define EEPROM_ADDR 0x50
byte m_addr = 0;

#define MAX_ADDRESS 128

byte eeprom_write(byte address, byte *data, byte len)
{
    byte r = 0;
    for(byte i=0; i<len; )
    {
        Wire.beginTransmission(EEPROM_ADDR | m_addr);
        Wire.write(address + i);
        byte l = len > 8 ? 8 : l;
        Wire.write(data+i, l);
        r |= Wire.endTransmission();
        delay(3);
        i += l;
    }
    return r;
}

byte eeprom_read(byte address, byte *data, byte len)
{
    Wire.beginTransmission(EEPROM_ADDR | m_addr);
    Wire.write(address);
    byte tr = Wire.endTransmission();
    if(tr)
        return tr;

    Wire.requestFrom((uint8_t)(EEPROM_ADDR | m_addr), len);
    byte avail = Wire.available();
    if(avail < len)
        return 0xFF;

    for(int i=0; i < len; i++)
    {
        // store data in raw bcd format
        data[i] = Wire.read();
    }
    return 0;
}

void setup()
{
    Wire.begin();
    Serial.begin(9600);
    delay(500);
    Serial.println("Type something to store in EEPROM");
}

byte i = 0;

void loop()
{
    if(Serial.available())
    {
        byte data = Serial.read();
        int rc = eeprom_write(i, &data, 1);
        if(rc==0)
        {
            Serial.print("EEPROM[0x");
            Serial.print(i, HEX);
            Serial.print("] = 0x");
            Serial.print(data, HEX);
            Serial.print(" (");
            Serial.print((char)data);
            Serial.print(")");
            Serial.println();

            Serial.println("Reading from EEPROM:");
            for(byte j=0;j<MAX_ADDRESS;j++)
            {
                if(byte rc=eeprom_read(j, &data, 1))
                {
                    Serial.print("Error in reading from EEPROM (rc=0x");
                    Serial.print(rc, HEX);
                    Serial.println(")");
                }
                else
                {
                    Serial.print(data, HEX);
                    Serial.print(' ');
                    if((j + 1) % 8 == 0 && j != MAX_ADDRESS - 1)
                        Serial.print("| ");
                }
            }
            Serial.println("");
        }
        else
        {
            Serial.println("Write error.");
        }
        i++;
    }
}

```

Every time I write one byte to the EEPROM, I read back the data on it. The result is a bit disappointing for me. I understand that `24LC01B` has a page size of 8 bytes. But, it does not make sense to me why the bytes withing the page rotate right every time I write into it

```
Type something to store in EEPROM
EEPROM[0x0] = 0x61 (a)
Reading from EEPROM:
61 4 4F 0 80 0 80 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x1] = 0x62 (b)
Reading from EEPROM:
4 62 4 4F 0 80 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x2] = 0x63 (c)
Reading from EEPROM:
80 4 63 4 4F 0 80 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x3] = 0x64 (d)
Reading from EEPROM:
0 80 4 64 4 4F 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x4] = 0x65 (e)
Reading from EEPROM:
80 0 80 4 65 4 4F 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x5] = 0x66 (f)
Reading from EEPROM:
0 80 0 80 4 66 4 4F | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x6] = 0x67 (g)
Reading from EEPROM:
4F 0 80 0 80 4 67 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x7] = 0x68 (h)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x8] = 0x69 (i)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 69 4 4F 0 80 0 80 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x9] = 0x6A (j)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 6A 4 4F 0 80 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xA] = 0x6B (k)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 4 6B 4 4F 0 80 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xB] = 0x6C (l)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 4 6C 4 4F 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xC] = 0x6D (m)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 0 80 4 6D 4 4F 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xD] = 0x6E (n)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 0 80 4 6E 4 4F | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xE] = 0x6F (o)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4F 0 80 0 80 4 6F 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xF] = 0x70 (p)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x10] = 0x71 (q)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 71 4 4F 0 80 0 80 4 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x11] = 0x72 (r)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 4 72 4 4F 0 80 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF

```

# Answer
The global variable `data` is a byte variable. But in the read and write function you use it as an byte array (`data[i]` or 'data +i'). That's not OK, but also not an error in the case you use length 1 ;-).

In your read function you performed a so called random read action that must be terminated by a STOP signal on the I2C bus. This can be forced by:

```
// ...

for(int i=0; i < len; i++)
{
    // store data in raw bcd format
    data[i] = Wire.read();
}

Wire.endTransmission(true);

return 0;

// ...

```

It's just a guess.

Writing single bytes must also be ended by a STOP condition but you used

```
r |= Wire.endTransmission();

```

that does not send a STOP signal.

Again you can force it with:

```
r |= Wire.endTransmission( true );

```

I'm not a Wire lib wizard, so I had read the Arduino documentation. Hopefully I understood it correctly.
> 1 votes

# Answer
Your problem is

`byte l = len > 8 ? 8 : l;`

in the `eeprom_write()` function.

You wrote `byte NumberOfBytes = len > 8 ? 8 : NumberOfBytes;` and that will leads to an undefined behavior.

And for the future, if you want to write more than 1 Byte it is not important how many byte you write in a block but that the addresses are all located on the same eeprom page.

`((address / pagesize) == ((address + length) / pagesize)` must be true
> 0 votes

---
Tags: c++, eeprom
---


# Question
Title: Only print when the button is pressed and not being pressed anymore
I have an Arduino and a microswitch that I want to use to know when the switch is initially being pressed (get "OnsetTime" on Serial) and when the switch is not being pressed anymore (get "OffsetTime" on Serial).

Imagine a bird sitting on the switch. I want to get an output "OnsetTime" when the bird first sits on the switch and an output "OffsetTime" when the bird flies away from the switch.

Right now, I have an output that constantly prints out "OnsetTime" when the switch is pressed. I would appreciate it if anybody can help me figure out how can I implement the below code to get the outputs only when the switch is initially pressed and not being pressed anymore.

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

void loop() {
  if (digitalRead(7) == HIGH) {
    Serial.println("OnsetTime");
    }
}
    //Serial.println("GetOffsetTime");

```

# Answer
If you want to be simple, you can use this library. The code will be

```
#include <ezButton.h>

ezButton button(7);  // create Button object that attach to pin 7;

void setup() {
  Serial.begin(9600);
  button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop() {
  button.loop(); // MUST call the loop() function first

  if(button.isPressed())
    Serial.println("OnsetTime");

  if(button.isReleased())
    Serial.println("GetOffsetTime");
}

```

If you want to understand in depth, You can see the code and instruction in this tutorial
> 1 votes

# Answer
You can save the value of the switch read to compare it on the next loop. This way you're able to detect changes.

```
int lastValue;

void setup() {
  pinMode(7, INPUT);
  lastValue= digitalRead(7);

  Serial.begin(9600);
}

void loop() {
  int currentValue = digitalRead(7);
  if (lastValue != currentValue) {
    lastValue = currentValue;

    if (currentValue == HIGH) {
      Serial.println("OnsetTime");
    } else {
      Serial.println("OffsetTime");
    }
  }
}

```

Please be aware that switches bounce. If you see multiple messages at each mechanical change, insert a `delay(...)`.
> 1 votes

---
Tags: arduino-uno, serial, button
---


# Question
Title: What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2?
Arduino Uno Wifi rev2 includes an ECC608 crypto accelerator chip.

Even their documentation states "As for the WiFi connection, that's made secure with the new ECC608 crypto chip accelerator."

My question is: **how exactly the ECC608 is used?** I'd like to see the sources the Arduino makes the "WiFi secure" with it.

# Answer
The library for the chip is ArduinoECCX08. It is used by the ArduinoBearSSL library. The ArduinoBearSSL is used by the ArduinoIoTCloud library and Arduino\_OAuth library. .
> 1 votes

---
Tags: arduino-uno-wifi
---


# Question
Title: PC not recognizing Arduino when working with a class and MIDIUSB library
I've recently bought an Arduo Due to create some sort of a Midi controller together with the MIDIUSB library.

I have create a simple a test program with 1 potentiometer (without the use of a class) to test the MIDIUSB library and everything works fine, so I decided to expanded my program to make it work with more than 1 potentiometer (with the use of a class).

However my pc stopped recognizing my Arduino as a MIDI device with my updated code. When I upload my previous example code it all works fine. I get no compile errors or whatsoever. I don't understand what I'm doing wrong. If anybody could explain me what I'm doing wrong or could give me a solution you would be a hero since I can't really work further if this issue doesn't get resolved. Thanks!

Here is my code for Custom\_MIDI\_controller\_V2.ino:

```
#include "MIDIUSB.h"
#include "Class.h"
#define TOLERANCE 8

byte NUMBER_POTS = 5;

Pot PO0(A0, 1, 14);
Pot PO1(A1, 1, 15);
Pot PO2(A2, 1, 16);
Pot PO3(A3, 1, 17);
Pot PO4(A4, 1, 18);

Pot *POTS[] = {&PO0, &PO1, &PO2, &PO3, &PO4};

void setup() {

}

void loop() {
  for (int i = 0; i < NUMBER_POTS; i++) {
    int potValue = POTS[i]->getValue();
      if(potValue != 255) {
        controlChange(POTS[i]->_channel, POTS[i]->_control, potValue);
        MidiUSB.flush();
      }
   }
}

void controlChange(byte channel, byte control, byte value) {
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
}

```

Here is my Class.cpp code:

```
#include "Arduino.h"
#include "Class.h"

#define TOLERANCE 8

Pot::Pot(int pin, int channel, int control) {
  _pin = pin;
  _channel = channel;
  _control = control;
  _value = analogRead(_pin);
  _oldValue = _value - 10;
}

int Pot::getValue() {
  int diff = abs(_value - _oldValue);
  if(diff > TOLERANCE)
  {
    _oldValue = _value;
    return map(_value, 0, 1023, 127, 0);
  } else {
    return 255;
  }
}

```

And this is my header Class.h code:

```
#ifndef Class_h
#define Class_h
#include "Arduino.h"

class Pot
{
  public:
    Pot(int pin, int channel, int control);
    int getValue();
    int _pin;
    int _channel;
    int _control;
    int _value;
    int _oldValue;
};

#endif

```

# Answer
You need to take care with constructors in C++. They get called during the global variable initialisation phase of the execution, which happens before `main()` gets called.

`main()` calls the routines that initialise and configure the peripherals and such in the chip, and by having `analogRead()` in your constructor (which is itself another error I will mention below) there is a good chance (I don't know the full initialisation sequence of that chip though) that it will never complete, and thus your program hangs at that point.

Your `analogRead()` doesn't want to be in the constructor, anyway, since that will only execute once when the object is constructed. Instead you want to have `analogRead()` called at the point you need to get the analog value. In your code that would be at the start of `int Pot::getValue()`.
> 1 votes

---
Tags: usb, arduino-due, midi
---


title: 1.7MHz Square wave generator

text:
# Question
Title: 1.7MHz Square wave generator
```
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

```

I got it from here, look down to the answers

This program supposed to generate a square-wave of frequency around 1.7MHz but it is not working for me. I have tried the simulation on Proteus 8 and there is no output. Only one error shows during the compilation which is the 'loop' function is missing, I have added one and still there is no output. Please somebody help me.

# Answer
> 1 votes
In the `setup` there is some settings for timer2, but no change of prescaller, so the timer stays stopped.

Obviously it was started by calling `soundBuzzer()` somewhere in code. But this function name is now kinda misleading. Just set prescaller in the `setup` and it should be working.

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno & Wemos (0.66” Across) OLED Shield
As I wrote in title, I have Arduino Uno and Wemos (0.66” Across) OLED Shield which i bought along wemos d1 mini.

For some reason I want to use it with uno. but there are just 0.96 tutorials internet and I don't know which pins to connect. I would appreciate any help.

PINS UNDER blue stick are

TX RX D1 D2 D3 so on..

# Answer
The first thing I see when googling "0.66 lolin oled" is the link to https://wiki.wemos.cc/products:d1\_mini\_shields:oled\_shield and their Get started guide. This yields the libraries to be used with it:
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Why does attaching Nokia 5110 LCD make my otherwise fine MKR1000 disconnect USB after 15 secs?
This problem just started after 3 days of working on a project.

I am using Arduino IDE in Windows 10.

When I go to upload "Blink," everything works fine. I connect the USB (sometimes I have to change the port from COM6 to COM5) and upload and it blinks. All good. Well, one weird thing: sometimes I'll upload Blink when it's COM5 and then after the upload I'll notice that the Arduino has switched to COM6. So I have to go in and manually update the Port.

But after I switch to whichever Port has MKR1000 listed on it and go to upload my other more complicated program that uses WiFi and the Nokia 5110 LCD, it seems to throw the Arduino for a loop. All of a sudden it either won't upload properly or say port cannot be found and starts disconnecting from the port about 15 seconds after I connect it, and I'm not able to upload anything.

Anyone have any clues what might be going on? Thank you.

Adding some information about the connections from NOKIA 5110 (also using a breadboard in between):

RST: to pin 6 on MKR1000
CE: to pin 4 on MKR1000
DC: to pin 7 on MKR1000
Din: to pin 3 on MKR1000
Clk: to pin 5 on MKR1000
VCC:to VCC on MKR1000
BL: to VCC on MKR1000
GND: to GND on MKR1000

# Answer
The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.

A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by **double clicking the reset button on board**.

This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.
> 0 votes

# Answer
Are you powering MKR1000 via USB? That only gives you about 1/2 amp of total current. I wonder if you're exceeding the available current of your power source. Add up the peak current requirements of your Arduino, (with WiFi active) the LCD, etc.
> 0 votes

---
Tags: lcd, usb, port-mapping
---


title: Servomotor AND Button

text:
# Question
Title: Servomotor AND Button
I am having trouble trying to make servomotor and button work together. The button code here below works fine when alone in a separate code but when it is transferred to the code with the servomotor function in it, it doesn't work.

Is there anything I need to be wary of when integrating the button code here to the preexisting code?

```
#include <Servo.h> // Library required for the servomotor (Make sure to download)
#include <Button.h> // Library required for the microswitch (Make sure to download)

// Parameters for the experiment
// Note: 1000 is one second
char Experiment = 'Acclimatization';
char Bird_Name = 'birdname here';
int Frequency = 30 * 1000; // The motor moves every x seconds
int Frequency_Deviation = 5 * 1000; // There are x second deviations plus and minus from the frequency set above
int Duration = 3 * 1000;  // The food is uncovered for x seconds

int servoPin = 9; // Declare the servomotor pin (Can be varied from setup to setup)
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

Servo Servo1;

void setup() {
   Servo1.attach(servoPin);
   //analogWrite(servoPin, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println("OnsetTime");
   if(button.isReleased())
    Serial.println("OffsetTime");

   // Calculate the acclimatization parameters below
   delay(random(Frequency-Frequency_Deviation,Frequency+Frequency_Deviation)); // Calculates frequency (See paramaters above)
   Servo1.write(0); // Starts from 0 degrees
   delay(Duration); // Duration that the food is uncovered (See parameters above)
   Servo1.write(75); // Goes to the x degrees
}

```

# Answer
Short answer: You have a blocking delay interrupting your button debounce time of 100ms.

Your button library has a debounce time of 100ms. This means you must be holding the button down for more that 100ms before it will register as pressed.

You have a 3 second blocking delay at the end of your loop. When you call `delay(XX)`, your processor *cannot do anything* during this time (like check for a button), it's just waiting.

Think about how the code is running. In your main loop, you are calling the function `button.loop()`, and it's checking to see if your button is pressed. If it's pressed, it's starts a timer (your debounce). The goal of this timer is for another 100ms to pass by with your button still being pressed to make sure you actually pressed it. `Button.isPressed()` fails, and it moves to its next set of instructions, which is move the servo and wait 3 seconds, during which time it *cannot check the button*. Then it starts all over again, and it calls `button.loop()` again. This all happens MUCH faster than 100ms. From the start of `void loop()` to the time it takes for it to wind back up at the 3 second blocking delay is in the nano seconds. This never gives your button library the 100ms of "pressed down" button it needs for `button.isPressed()` to return true.

I suggest spending some time looking at the behind the scenes of your button library and see how the debounce works. You can do that, or you can use the example debounce sketch off the main arduino website and learn how that works. The next thing you'd want to do is to learn how to make your code "wait" without using the blocking call `delay()`. This is done by using timers with millis(). A good way to learn this is the example arduino sketch "Blink Without Delay".

Hope that clears some things up.
> 1 votes

---
Tags: arduino-uno, motor, button
---


# Question
Title: Controlling Multiple Brushless Motors with Arduino
I'm working on making an FPV racing drone as an introductory project to using Arduino. I need to be able to control four brushless motors using an Arduino Uno.

First of all, does anyone have any recommendations for motor type and ESC type? But my real question is: how can I power all four motors using one battery? What components do I need to buy? I've tried searching the internet for the answer but I can't find my specific use case, although it doesn't seem like it's uncommon at all.

# Answer
> 1 votes
Arduino really isn't the best processor for a drone. It can certainly be done however. You can buy a MultiWii flight controller which is based around an Arduino Mega and functions as a drone flight controller.

You can't just ask which motors and ESCs to use. How heavy is your drone? How fast does it need to fly? Is there a payload? To figure out which motors to use, go watch some videos by FliteTest or a multitude of other videos online suggesting how to build a drone. You can certainly power everything off one battery. Again, watch some videos on how multirotor drones are made.

Takeway: An Arduino is a very poor choice for making a flight controller, and there quite a few components needed to build a drone, so watch some videos and learn how!

---
Tags: arduino-uno, motor
---


# Question
Title: How to connect accelerometer, GPS, microphone and a GSM module to a Arduino?
I am a noob in the Arduino world and have only started reading about it. I have zero experience with Arduino some suggestions to increase my level will also be highly appreciated. But I have a lot of ideas, I want to work on.

I want to measure the velocity and noise levels with the GPS coordinates of a moving vehicle and send it to my phone using gsm or wifi. Should I include a small LCD also? again suggestions will be highly appreciated.

# Answer
> 1 votes
It depends.

If you are a beginner, do it in steps:

* Get an Arduino Uno
* Get a feeling for MCUs connecting a LED and resistor.
* Connect the buzzer and get it working.
* Disconnect it, connect the display and get it working.
* Same for one sensor.
* Than try multiple sensors.
* Than play with the WIFI module.
* Than combine everything.

The key is to split up your (for a beginner) big project into smaller easier to handle projects.

If you want to add an LCD, depends fully on YOUR requirements; we don't know exactly what you want. If you send all data via WIFI in principle the receiver can display it, but maybe you have a good reason to display it on a display.

---
Tags: arduino-uno, arduino-mega, arduino-ide, arduino-leonardo, electronics
---


# Question
Title: Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits
I recently got to code my own driver for the One-Wire-Bus specifically with the ubiquitous DS18B20 temperature sensor in mind for an application.

I am running that code on an Arduino Mega 2560. Programming is done in Atmel Studio 7 and an AVR ISP mk2.

In the version as-of yesterday see here I get missing binary digits while trying to send the `0x55` One-Wire-Command (i.e. Match-Rom-Code). It appears like it where the least significant two bits that are missing (Oscilloscope capture).

Today I tried to sort out that bug and "fixed" it by counting to 9 instead of 8 (even though I can't explain why this should work, it should rather break stuff \[turns out it does\]...) and subtracting 1 from my index variable. (See file "OneWire.c" line 83 and following for the old version). Todays version is here (compare file "OneWire.c" line 81 and following).

In the new version (as-of today) I am able to get the `0x33` opcode (i.e. Send-Rom-Command) transmitted as wanted and get the ID of my specific sensor on the bus (atleast my oscilloscope shows the correct waveform). In the newer version I do the following chain of operations:

* get the ID of the single sensor I have connected at the moment
* send the Match-Rom-Command (just because that is something actually meaningful to do)
* send the 64-Bit Rom-Code after that (or atleast what ever the statemachine of the getID function did end up writing in the output parameter)
* send the `0x44` opcode (i.e. start temperature conversion)

This scenario yields me no correct Rom-code being sent on the bus, one byte more on the bus and another single bit too much on the bus for the temperature-conversion opcode. The Match Rom Code command does get transfered as supposed to and does not yield any extraneous or missing bits (no scope capture for that since that would not be possible to get into one shot that shows it all \[at a workable scaling\]...).

I would highly apprechiate anyone looking at my code and trying to figure out what is going wrong here since I am completely in the dark right now.

Before anybody asks:

I specifically did not want to use the readily available One-Wire-Libraries as they tend to be bloated and heavily rely on the delay function, which is fine if you are doing little else with your chip but not else. Since I have multiple sensors to read out (not yet but as soon as I got the drivers working) have to do some post processing on the raw data (i.e. put some sort of math to it) and transmit that data on a usually slow interface (I2C, Serial, you name it), which all takes time (and all that \[periodically and as fast as possible of-course\] on a poor 8-Bit Micro that runs at a underwhelming 16MHz...), I decided to keep polling and delay()-uses to a minimum and rather rely (heavily?) on a timer interrupt and a series of Statemachines...

It is not at all obvious to me why the code does act in that way.

# Answer
> 0 votes
I managed to find the bug and fix it. I was missing that after the reset pulse the master must be in RX mode for atleast 480us no matter what, even if the presence pulse did occur and even if it's rising Edge did appear already. This mistiming did lead to the missing bits that were corrected with sending more bits until now (which in turn lead to the extraneous bits later on in the transmission).

---
Tags: arduino-mega, ds18b20, 1-wire
---


# Question
Title: High-frequency PWM on an Adafruit Feather M0
I'm trying to get a Bluefruit Feather M0, which has a SAMD21G on it, to do high-frequency PWM by accessing timer registers directly, rather than using the Arduino API to do PWM at ~1 kHz or ~500 Hz. Actual frequency isn't important at this stage, I just want a lot more than 1 kHz.

I found an example for an MKR1000, based on a similar processor. I've adapted it as shown below. Comparing the Adafruit pinout with the original code and with the datasheet, it's apparent that the pin numberings are different and that pin 11, which is the only one of the two example pins that is accessible, is on TCC0 here and not TCC1.

The only change I see that I needed to make is to duplicate all the TCC1 setup in `setupTimers()` and the TCC1 duty cycle control in `loop()` for TCC0. Yet on the scope, I see no PWM output. I then tried setting pin 13 to PWM as well, so I'd see it on the on board LED. Still nothing. I'm somewhat stuck now.

Does anyone have any ideas?

```
void setup() {
    // put your setup code here, to run once:
    setupTimers();
    Serial.begin(9600);
}

void loop() {
    // put your main code here, to run repeatedly:
    int t = 0;
    Serial.println("\nRunning PWM 0 to 100%");
    for (t = 0; t < 1000; t = t + 1) {
        REG_TCC1_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC1->SYNCBUSY.bit.CC1);                // Wait for synchronization
        REG_TCC0_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
        while (TCC0->SYNCBUSY.bit.CC1);                // Wait for synchronization
        delay(1);
        Serial.print(".");
    }

    delay(2000);
}

// Output PWM 24Khz on digital pin D3  and D11 using timer TCC1 (10-bit resolution)
void setupTimers() {
    REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor N=1: 48MHz/1=48MHz
        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
        GCLK_GENCTRL_GENEN |         // Enable GCLK4
        GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
        GCLK_GENCTRL_ID(4);          // Select GCLK4
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Enable the port multiplexer for the digital pin D3 and D11  **** g_APinDescription() converts Arduino Pin to SAMD21 pin
    PORT->Group[g_APinDescription[3].ulPort].PINCFG[g_APinDescription[3].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[11].ulPort].PINCFG[g_APinDescription[11].ulPin].bit.PMUXEN = 1;
    PORT->Group[g_APinDescription[13].ulPort].PINCFG[g_APinDescription[13].ulPin].bit.PMUXEN = 1;

    // Connect the TCC1 timer to digital output D3 and D11 - port pins are paired odd PMUO and even PMUXE
    // F & E specify the timers: TCC0, TCC1 and TCC2
    PORT->Group[g_APinDescription[2].ulPort].PMUX[g_APinDescription[2].ulPin >> 1].reg = PORT_PMUX_PMUXO_E;  // D3 is on PA11 = odd, use Device E on TCC1/WO[1]
    PORT->Group[g_APinDescription[11].ulPort].PMUX[g_APinDescription[11].ulPin >> 1].reg = PORT_PMUX_PMUXE_F; // D11 is on PA08 = even, use device F on TCC1/WO[0]
    PORT->Group[g_APinDescription[13].ulPort].PMUX[g_APinDescription[13].ulPin >> 1].reg = PORT_PMUX_PMUXE_E; // Try the LED.. doesn't work with E or F

    //Actually, pin 11 on the Feather is on PA16. Still even, not sure of the significance, but it's now TCC0/WO[6] and still port F.
    //All the stuff further down is about TCC1!

    // Feed GCLK4 to TCC0 and TCC1
    REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TCC0 and TCC1
        GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
        GCLK_CLKCTRL_ID_TCC0_TCC1;   // Feed GCLK4 to TCC0 and TCC1
    while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC1_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC1->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC1_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC1->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC1_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC1->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC1_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC1->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC1_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC1->SYNCBUSY.bit.ENABLE);              // Wait for synchronization

    //Do everything again for TCC0

    // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
    REG_TCC0_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
        TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
    while (TCC0->SYNCBUSY.bit.WAVE);               // Wait for synchronization

    // Each timer counts up to a maximum or TOP value set by the PER register,
    // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
    REG_TCC0_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
    while (TCC0->SYNCBUSY.bit.PER);                // Wait for synchronization

    // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
    REG_TCC0_CC1 = 500;                             // TCC1 CC1 - on D3  50%
    while (TCC0->SYNCBUSY.bit.CC1);                   // Wait for synchronization
    REG_TCC0_CC0 = 500;                             // TCC1 CC0 - on D11 50%
    while (TCC0->SYNCBUSY.bit.CC0);                   // Wait for synchronization

    // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
    REG_TCC0_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
        TCC_CTRLA_ENABLE;             // Enable the TCC0 output
    while (TCC0->SYNCBUSY.bit.ENABLE);              // Wait for synchronization
}

```

# Answer
For your specific problem: the Feather's `D11` is the SAMD's `PA16` and on `TCC0/WO[6]` (use `REG_TCC0_CCB2` and `PORT_PMUX_PMUXE_F`), and also on `TCC2/WO[0]` (use `REG_TCC2_CCB0` and `PORT_PMUX_PMUXE_E`).

An easier way: I have made a high-frequency-PWM library for this (called Arduino\_SAMD21\_turbo\_PWM), and I have implemented the pin table for the Adafruit Feather M0.

I haven't tested it though, mainly because I don't have an Adafruit Feather M0. Still, feel free to have a try.

The pin mapping table itself for the Adafruit Feather M0, which AFAIK has the same pin mappings as the Arduino Zero, is here on Github; maybe it can help as well.
> 2 votes

---
Tags: pwm, adafruit, arduino-zero, samd21g, feather
---


# Question
Title: Why is my MPU6050 DMP failing to initialize but I can still get raw accel values from MPU6050
I have been using MPU6050 modules for some time now for yaw measurements using the integrated DMP chip. Everything has gone swimmingly until yesterday, when my initialization code started reporting that I can connect to my MPU6050 chip but DMP init has failed with code 1.

Thinking I had somehow blown up the DMP chip (don't know how, as there is no direct connection), I replaced the module, but got the same result, with three different MPU6050 modules.

As an experiment, I modified my code to read raw Z-axis acceleration values instead of DMP quaternions, and this was successful. Plotting the values in Excel showed that the values responded as expected when I manually rotated the sensor around the Z-axis.

So now I know I can connect to the MPU6050 module and read sensor values, but I somehow lost the ability to use the DMP. Any ideas as to why this might be happening?

Here are two versions of my code. The first version is the original, and the second one has been modified to just show the Z-axis acceleration values.

TIA,

Frank

Version 1 (original):

```
// Visual Micro is in vMicro>General>Tutorial Mode
//
/*
    Name:       MPU6050_DRV8871_NoiseTest.ino
    Created:    12/8/2019 10:20:28 AM
    Author:     FRANKNEWXPS15\Frank
*/

/*
    Name:       Adafruit DRV8871 Motor Driver Test.ino
    Created:    5/30/2019 6:43:18 PM
    Author:     FRANKWIN10\Frank
*/
//#include <Adafruit_INA219.h>
#pragma region INCLUDES
#include <elapsedMillis.h>
#include <PrintEx.h> //allows printf-style printout syntax
#include "MPU6050_6Axis_MotionApps_V6_12.h"  //changed to this version 10/05/19
#include "I2Cdev.h" //02/19/19: this includes SBWire.h
#include <NewPing.h> //added 01/15/15
#pragma endregion INCLUDES

StreamEx mySerial = Serial; //added 03/18/18 for printf-style printing
elapsedMillis   sinceLastNavUpdateMsec; //added 10/15/18 to replace lastmillisec

//MPU6050 mpu(0x69); //06/23/18 chg to AD0 high addr on 2-motor robot
MPU6050 mpu(0x68); //06/23/18 chg to AD0 high addr on 2-motor robot

void(*resetFunc) (void) = 0; //added 12/08/19 to handle MPU6050/I2C reset failure issue

#pragma region MPU6050_SUPPORT
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU. Used in Homer's Overflow routine
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

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

//RTC/FRAM/MPU6050 status flags
bool bMPU6050Ready = true;
bool dmpReady = false;  // set true if DMP init was successful
volatile float global_yawval = 0; //updated by GetIMUHeadingDeg()
const uint16_t MAX_GETPACKET_LOOPS = 100; //10/30/19 added for backup loop exit condition in GetCurrentFIFOPacket()
uint8_t GetCurrentFIFOPacket(uint8_t* data, uint8_t length, uint16_t max_loops = MAX_GETPACKET_LOOPS); //prototype here so can define a default param
bool bFirstTime = true;
#pragma endregion MPU6050 Support

// Basic sketch for trying out the Adafruit DRV8871 Breakout

#define MOTOR1_IN1 9
#define MOTOR1_IN2 10
#define MOTOR2_IN1 6
#define MOTOR2_IN2 5

const int INTER_STEP_DELAY_MS = 100;

const int NAV_UPDATE_INTERVAL_MSEC = 200;

const int MIN_MOTOR_SPEED = 60; //empirically determined

enum MotorStates
{
    MOTOR_FWD_INCREASING,
    MOTOR_FWD_DECREASING,
    MOTOR_REV_INCREASING,
    MOTOR_REV_DECREASING
};

enum MotorStates motState = MOTOR_FWD_INCREASING;
const int MOTOR_SPEED_MAX = 255;
//const int MOTOR_SPEED_MAX = 100;
const int MOTOR_SPEED_MIN = 60; //empirically determined
int motor_speed = 0;
int pgmloops = 0;

void setup() {
    Serial.begin(115200);
    Wire.setClock(50000);

    // initialize MPU6050 added 09/03/18
    Serial.println(F("Initializing MPU6050 ..."));
    mpu.initialize();

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

    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    ////12/03/19 settings from calibration routines
    //mpu.setXGyroOffset(58);
    //mpu.setYGyroOffset(20);
    //mpu.setZGyroOffset(12);
    //mpu.setXAccelOffset(1618);
    //mpu.setYAccelOffset(3046);
    //mpu.setZAccelOffset(4554);

    //12/16/19 settings from calibration routines
    mpu.setXAccelOffset(-3066);
    mpu.setYAccelOffset(2658);
    mpu.setZAccelOffset(872);
    mpu.setXGyroOffset(167);
    mpu.setYGyroOffset(-26);
    mpu.setZGyroOffset(73);

    // make sure it worked (returns 0 if successful)
    if (devStatus == 0)
    {
        //12/06/19 no longer needed; cal vals already acquired
        // Calibration Time: generate offsets and calibrate our MPU6050
        //mpu.CalibrateAccel(6);
        //mpu.CalibrateGyro(6);
        //Serial.println();
        //mpu.PrintActiveOffsets();

        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

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

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
        bMPU6050Ready = true;
        mySerial.printf("\nMPU6050 Ready at %2.2f Sec\n", millis() / 1000.f);
    }
    else
    {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));

        bMPU6050Ready = false;
    }

    Serial.println("DRV8871 test");

    pinMode(MOTOR1_IN1, OUTPUT);
    pinMode(MOTOR1_IN2, OUTPUT);
    pinMode(MOTOR2_IN1, OUTPUT);
    pinMode(MOTOR2_IN2, OUTPUT);

    //ina219.begin();
    //mySerial.printf("Speed\tVolts\tMAmps\tMWatts\n"); //column headers
    mySerial.printf("Speed\n"); //column headers

    TCCR2B = (TCCR2B & B11111000) | B00000011; // for PWM frequency of 980.39 Hz on pins 3,11

    sinceLastNavUpdateMsec = 0;
}

void loop()
{
    if (sinceLastNavUpdateMsec >= NAV_UPDATE_INTERVAL_MSEC)
    {
        if (pgmloops % 50 == 0)
        {
            bFirstTime = false;
            mySerial.printf("Min\tYaw\tState\tSpd\tfifoC\tIloops\Oloops\n");
        }

        sinceLastNavUpdateMsec -= NAV_UPDATE_INTERVAL_MSEC;

        //12/10/19 added connection test and reset global 'GetPacket' params
        bool getYawResult = false;
        fifoCount = 0;
        GetPacketLoopCount = 0;
        OuterGetPacketLoopCount = 0;
        global_yawval = 999;
        if (mpu.testConnection())
        {
            getYawResult = GetIMUHeadingDeg(); //updates global_yawval if successful
        }
        else
        {
            mySerial.printf("MPU6050 Not Connected!\n");
        }

        if (getYawResult == 0)
        {
            mySerial.printf("MPU6050 and/or I2C failure - Stopping Test!\n");
            mySerial.printf("min\tyaw\tfifoC\tICount\tOCount\n");
            mySerial.printf("%3.2f\t%3.2f\t%d\t%d\t%d\n",
                millis() / 60000.0,global_yawval, fifoCount, GetPacketLoopCount, OuterGetPacketLoopCount);
            //resetFunc(); //this should completely reset the Arduino so we can start over

            //stop motor 1
            analogWrite(MOTOR1_IN1, 0);
            analogWrite(MOTOR1_IN2, 0);

            //stop motor 2
            analogWrite(MOTOR2_IN1, 0);
            analogWrite(MOTOR2_IN2, 0);
            while (1); //stop the system so I can see failure readout
        }

        mySerial.printf("%3.2f\t%3.2f\t%d\t%d\t%d\t%d\t%d\n",
            millis() / 60000.0, global_yawval,motState,motor_speed,fifoCount, GetPacketLoopCount,
            OuterGetPacketLoopCount);

        //Motor speed/dir management
        switch (motState)
        {
        case MOTOR_FWD_INCREASING:
            // ramp up forward
            digitalWrite(MOTOR1_IN1, LOW);
            digitalWrite(MOTOR2_IN1, LOW);
            motor_speed = (motor_speed > MIN_MOTOR_SPEED) ? motor_speed : MIN_MOTOR_SPEED;
            //if (motor_speed <= MIN_MOTOR_SPEED)
            //{
            //  //Serial.println("give it a whack to start!");
            //  analogWrite(MOTOR1_IN2, MIN_MOTOR_SPEED);
            //  analogWrite(MOTOR2_IN2, MIN_MOTOR_SPEED);
            //}
            //else
            {
                analogWrite(MOTOR1_IN2, motor_speed);
                analogWrite(MOTOR2_IN2, motor_speed);
            }
            motor_speed++;
            if (motor_speed >= MOTOR_SPEED_MAX)
            {
                motState = MOTOR_FWD_DECREASING;
            }
            break;
        case MOTOR_FWD_DECREASING:
            // ramp down forward
            digitalWrite(MOTOR1_IN1, LOW);
            digitalWrite(MOTOR2_IN1, LOW);

            analogWrite(MOTOR1_IN2, motor_speed);
            analogWrite(MOTOR2_IN2, motor_speed);

            motor_speed--;

            if (motor_speed <= MOTOR_SPEED_MIN)
            {
                motState = MOTOR_REV_INCREASING;
            }
            break;
        case MOTOR_REV_INCREASING:
            digitalWrite(MOTOR1_IN2, LOW);
            digitalWrite(MOTOR2_IN2, LOW);

            motor_speed = (motor_speed > MIN_MOTOR_SPEED) ? motor_speed : MIN_MOTOR_SPEED;
            //if (motor_speed <= MIN_MOTOR_SPEED)
            //{
            //  //Serial.println("give it a whack to start!");
            //  analogWrite(MOTOR1_IN1, MIN_MOTOR_SPEED);
            //  analogWrite(MOTOR2_IN1, MIN_MOTOR_SPEED);
            //}
            //else
            {
                analogWrite(MOTOR1_IN1, motor_speed);
                analogWrite(MOTOR2_IN1, motor_speed);
            }

            motor_speed++;

            if (motor_speed >= MOTOR_SPEED_MAX)
            {
                motState = MOTOR_REV_DECREASING;
            }
            break;
        case MOTOR_REV_DECREASING:
            digitalWrite(MOTOR1_IN2, LOW);
            digitalWrite(MOTOR2_IN2, LOW);

            analogWrite(MOTOR1_IN1, motor_speed);
            analogWrite(MOTOR2_IN1, motor_speed);

            motor_speed--;

            if (motor_speed <= MOTOR_SPEED_MIN)
            {
                motState = MOTOR_FWD_INCREASING; //start over
            }
            break;
        default:
            break;
        }

        pgmloops++;
        if (pgmloops == 1000)
        {
            pgmloops = 0;
        }
    }

}

void PrintTelemetryData(int spd)
{

    ////get current, voltage, power readings
    //shuntvoltage = ina219.getShuntVoltage_mV();
    //busvoltage = ina219.getBusVoltage_V();
    //current_mA = ina219.getCurrent_mA();
    //power_mW = ina219.getPower_mW();
    //loadvoltage = busvoltage + (shuntvoltage / 1000);
    //mySerial.printf("%d\t%2.2f\t%2.2f\t%2.2f\n",
    //  spd, loadvoltage, current_mA, power_mW);
    mySerial.printf("%d\n", spd);
}

bool GetIMUHeadingDeg()
{
    //Purpose: Get latest yaw (heading) value from IMU
    //Inputs: None.  This function should only be called after mpu.dmpPacketAvailable() returns TRUE
    //Outputs:
    //  returns true if successful, otherwise false
    //  global_yawval updated on success
    //Plan:
    //Step1: check for overflow and reset the FIFO if it occurs. In this case, wait for new packet
    //Step2: read all available packets to get to latest data
    //Step3: update global_yawval with latest value
    //Notes:
    //  10/08/19 changed return type to boolean
    //  10/08/19 no longer need mpuIntStatus

    bool retval = false;

    int flag = GetCurrentFIFOPacket(fifoBuffer, packetSize, MAX_GETPACKET_LOOPS); //get the latest mpu packet

    if (flag != 0) //0 = error exit, 1 = normal exit, 2 = recovered from an overflow
    {
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        //compute the yaw value
        global_yawval = ypr[0] * 180 / M_PI;

        //if (global_yawval == 180)
        //{
        //  mySerial.printf("erroneous yaw value detected!");
        //  return false;
        //}
        retval = true;
    }

    return retval;
}

uint8_t GetCurrentFIFOPacket(uint8_t* data, uint8_t length, uint16_t max_loops)
{
    max_loops = max(10, max_loops); //added 12/04/19 to ensure we loop at least 10 times. This really IS a hard-coded number!

    fifoCount = mpu.getFIFOCount();

    GetPacketLoopCount = 0;
    int max_outer_loops = 10;

    //11/10/19 I have seen this fail with fifoC > 28 on occasion, so now I loop max 10 times
    OuterGetPacketLoopCount = 0;
    while (fifoCount != packetSize && OuterGetPacketLoopCount < max_outer_loops)
    {
        mpu.resetFIFO();
        delay(1);

        fifoCount = mpu.getFIFOCount();
        GetPacketLoopCount = 0;

        while (fifoCount < packetSize && GetPacketLoopCount < max_loops)
        {
            GetPacketLoopCount++;
            fifoCount = mpu.getFIFOCount();
            delay(2);
        }

        OuterGetPacketLoopCount++;
    }

    //if we get to here, there should be exactly one packet in the FIFO
    if (OuterGetPacketLoopCount < max_outer_loops)
    {
        mpu.getFIFOBytes(data, packetSize);
        return 1;
    }
    return 0; //failed to get a good packet
}

```

Version 2 (modified to read raw Z-axis accel:

```
// Visual Micro is in vMicro>General>Tutorial Mode
//
/*
    Name:       MPU6050_DRV8871_NoiseTest.ino
    Created:    12/8/2019 10:20:28 AM
    Author:     FRANKNEWXPS15\Frank
*/

/*
    Name:       Adafruit DRV8871 Motor Driver Test.ino
    Created:    5/30/2019 6:43:18 PM
    Author:     FRANKWIN10\Frank
*/
//#include <Adafruit_INA219.h>
#pragma region INCLUDES
#include <elapsedMillis.h>
#include <PrintEx.h> //allows printf-style printout syntax
#include "MPU6050_6Axis_MotionApps_V6_12.h"  //changed to this version 10/05/19
#include "I2Cdev.h" //02/19/19: this includes SBWire.h
#include <NewPing.h> //added 01/15/15
#pragma endregion INCLUDES

StreamEx mySerial = Serial; //added 03/18/18 for printf-style printing
elapsedMillis   sinceLastNavUpdateMsec; //added 10/15/18 to replace lastmillisec

//MPU6050 mpu(0x69); //06/23/18 chg to AD0 high addr on 2-motor robot
MPU6050 mpu(0x68); //06/23/18 chg to AD0 high addr on 2-motor robot

void(*resetFunc) (void) = 0; //added 12/08/19 to handle MPU6050/I2C reset failure issue

#pragma region MPU6050_SUPPORT
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU. Used in Homer's Overflow routine
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

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

//RTC/FRAM/MPU6050 status flags
bool bMPU6050Ready = true;
bool dmpReady = false;  // set true if DMP init was successful
volatile float global_yawval = 0; //updated by GetIMUHeadingDeg()
const uint16_t MAX_GETPACKET_LOOPS = 100; //10/30/19 added for backup loop exit condition in GetCurrentFIFOPacket()
uint8_t GetCurrentFIFOPacket(uint8_t* data, uint8_t length, uint16_t max_loops = MAX_GETPACKET_LOOPS); //prototype here so can define a default param
bool bFirstTime = true;
#pragma endregion MPU6050 Support

// Basic sketch for trying out the Adafruit DRV8871 Breakout

#define MOTOR1_IN1 9
#define MOTOR1_IN2 10
#define MOTOR2_IN1 6
#define MOTOR2_IN2 5

const int INTER_STEP_DELAY_MS = 100;

const int NAV_UPDATE_INTERVAL_MSEC = 200;

const int MIN_MOTOR_SPEED = 60; //empirically determined

enum MotorStates
{
    MOTOR_FWD_INCREASING,
    MOTOR_FWD_DECREASING,
    MOTOR_REV_INCREASING,
    MOTOR_REV_DECREASING
};

enum MotorStates motState = MOTOR_FWD_INCREASING;
const int MOTOR_SPEED_MAX = 255;
//const int MOTOR_SPEED_MAX = 100;
const int MOTOR_SPEED_MIN = 60; //empirically determined
int motor_speed = 0;
int pgmloops = 0;

void setup() {
    Serial.begin(115200);
    Wire.setClock(50000);

    // initialize MPU6050 added 09/03/18
    Serial.println(F("Initializing MPU6050 ..."));
    mpu.initialize();

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

    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    ////12/03/19 settings from calibration routines
    //mpu.setXGyroOffset(58);
    //mpu.setYGyroOffset(20);
    //mpu.setZGyroOffset(12);
    //mpu.setXAccelOffset(1618);
    //mpu.setYAccelOffset(3046);
    //mpu.setZAccelOffset(4554);

    //12/16/19 settings from calibration routines
    mpu.setXAccelOffset(-3066);
    mpu.setYAccelOffset(2658);
    mpu.setZAccelOffset(872);
    mpu.setXGyroOffset(167);
    mpu.setYGyroOffset(-26);
    mpu.setZGyroOffset(73);

    // make sure it worked (returns 0 if successful)
    if (devStatus == 0)
    {
        //12/06/19 no longer needed; cal vals already acquired
        // Calibration Time: generate offsets and calibrate our MPU6050
        //mpu.CalibrateAccel(6);
        //mpu.CalibrateGyro(6);
        //Serial.println();
        //mpu.PrintActiveOffsets();

        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

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

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
        bMPU6050Ready = true;
        mySerial.printf("\nMPU6050 Ready at %2.2f Sec\n", millis() / 1000.f);
    }
    else
    {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));

        bMPU6050Ready = false;
    }

    Serial.println("DRV8871 test");

    pinMode(MOTOR1_IN1, OUTPUT);
    pinMode(MOTOR1_IN2, OUTPUT);
    pinMode(MOTOR2_IN1, OUTPUT);
    pinMode(MOTOR2_IN2, OUTPUT);

    //ina219.begin();
    //mySerial.printf("Speed\tVolts\tMAmps\tMWatts\n"); //column headers
    mySerial.printf("Speed\n"); //column headers

    TCCR2B = (TCCR2B & B11111000) | B00000011; // for PWM frequency of 980.39 Hz on pins 3,11

    sinceLastNavUpdateMsec = 0;
}

void loop()
{
    if (sinceLastNavUpdateMsec >= NAV_UPDATE_INTERVAL_MSEC)
    {
        if (pgmloops % 50 == 0)
        {
            bFirstTime = false;
            mySerial.printf("Min\tYaw\tState\tSpd\tfifoC\tIloops\Oloops\n");
        }

        sinceLastNavUpdateMsec -= NAV_UPDATE_INTERVAL_MSEC;

        //12/10/19 added connection test and reset global 'GetPacket' params
        bool getYawResult = false;
        fifoCount = 0;
        GetPacketLoopCount = 0;
        OuterGetPacketLoopCount = 0;
        global_yawval = 999;
        if (mpu.testConnection())
        {
            getYawResult = GetIMUHeadingDeg(); //updates global_yawval if successful
            float Zaccel = mpu.getAccelerationZ();
            mySerial.printf("Zaccel = %3.2f\n", Zaccel);
        }
        else
        {
            mySerial.printf("MPU6050 Not Connected!\n");
        }

        //if (getYawResult == 0)
        //{
        //  mySerial.printf("MPU6050 and/or I2C failure - Stopping Test!\n");
        //  mySerial.printf("min\tyaw\tfifoC\tICount\tOCount\n");
        //  mySerial.printf("%3.2f\t%3.2f\t%d\t%d\t%d\n",
        //      millis() / 60000.0,global_yawval, fifoCount, GetPacketLoopCount, OuterGetPacketLoopCount);
        //  //resetFunc(); //this should completely reset the Arduino so we can start over

        //  //stop motor 1
        //  analogWrite(MOTOR1_IN1, 0);
        //  analogWrite(MOTOR1_IN2, 0);

        //  //stop motor 2
        //  analogWrite(MOTOR2_IN1, 0);
        //  analogWrite(MOTOR2_IN2, 0);
        //  while (1); //stop the system so I can see failure readout
        //}

        //mySerial.printf("%3.2f\t%3.2f\t%d\t%d\t%d\t%d\t%d\n",
        //  millis() / 60000.0, global_yawval,motState,motor_speed,fifoCount, GetPacketLoopCount,
            //OuterGetPacketLoopCount);

        //Motor speed/dir management
        switch (motState)
        {
        case MOTOR_FWD_INCREASING:
            // ramp up forward
            digitalWrite(MOTOR1_IN1, LOW);
            digitalWrite(MOTOR2_IN1, LOW);
            motor_speed = (motor_speed > MIN_MOTOR_SPEED) ? motor_speed : MIN_MOTOR_SPEED;
            //if (motor_speed <= MIN_MOTOR_SPEED)
            //{
            //  //Serial.println("give it a whack to start!");
            //  analogWrite(MOTOR1_IN2, MIN_MOTOR_SPEED);
            //  analogWrite(MOTOR2_IN2, MIN_MOTOR_SPEED);
            //}
            //else
            {
                analogWrite(MOTOR1_IN2, motor_speed);
                analogWrite(MOTOR2_IN2, motor_speed);
            }
            motor_speed++;
            if (motor_speed >= MOTOR_SPEED_MAX)
            {
                motState = MOTOR_FWD_DECREASING;
            }
            break;
        case MOTOR_FWD_DECREASING:
            // ramp down forward
            digitalWrite(MOTOR1_IN1, LOW);
            digitalWrite(MOTOR2_IN1, LOW);

            analogWrite(MOTOR1_IN2, motor_speed);
            analogWrite(MOTOR2_IN2, motor_speed);

            motor_speed--;

            if (motor_speed <= MOTOR_SPEED_MIN)
            {
                motState = MOTOR_REV_INCREASING;
            }
            break;
        case MOTOR_REV_INCREASING:
            digitalWrite(MOTOR1_IN2, LOW);
            digitalWrite(MOTOR2_IN2, LOW);

            motor_speed = (motor_speed > MIN_MOTOR_SPEED) ? motor_speed : MIN_MOTOR_SPEED;
            //if (motor_speed <= MIN_MOTOR_SPEED)
            //{
            //  //Serial.println("give it a whack to start!");
            //  analogWrite(MOTOR1_IN1, MIN_MOTOR_SPEED);
            //  analogWrite(MOTOR2_IN1, MIN_MOTOR_SPEED);
            //}
            //else
            {
                analogWrite(MOTOR1_IN1, motor_speed);
                analogWrite(MOTOR2_IN1, motor_speed);
            }

            motor_speed++;

            if (motor_speed >= MOTOR_SPEED_MAX)
            {
                motState = MOTOR_REV_DECREASING;
            }
            break;
        case MOTOR_REV_DECREASING:
            digitalWrite(MOTOR1_IN2, LOW);
            digitalWrite(MOTOR2_IN2, LOW);

            analogWrite(MOTOR1_IN1, motor_speed);
            analogWrite(MOTOR2_IN1, motor_speed);

            motor_speed--;

            if (motor_speed <= MOTOR_SPEED_MIN)
            {
                motState = MOTOR_FWD_INCREASING; //start over
            }
            break;
        default:
            break;
        }

        pgmloops++;
        if (pgmloops == 1000)
        {
            pgmloops = 0;
        }
    }

}

void PrintTelemetryData(int spd)
{

    ////get current, voltage, power readings
    //shuntvoltage = ina219.getShuntVoltage_mV();
    //busvoltage = ina219.getBusVoltage_V();
    //current_mA = ina219.getCurrent_mA();
    //power_mW = ina219.getPower_mW();
    //loadvoltage = busvoltage + (shuntvoltage / 1000);
    //mySerial.printf("%d\t%2.2f\t%2.2f\t%2.2f\n",
    //  spd, loadvoltage, current_mA, power_mW);
    mySerial.printf("%d\n", spd);
}

bool GetIMUHeadingDeg()
{
    //Purpose: Get latest yaw (heading) value from IMU
    //Inputs: None.  This function should only be called after mpu.dmpPacketAvailable() returns TRUE
    //Outputs:
    //  returns true if successful, otherwise false
    //  global_yawval updated on success
    //Plan:
    //Step1: check for overflow and reset the FIFO if it occurs. In this case, wait for new packet
    //Step2: read all available packets to get to latest data
    //Step3: update global_yawval with latest value
    //Notes:
    //  10/08/19 changed return type to boolean
    //  10/08/19 no longer need mpuIntStatus

    bool retval = false;

    int flag = GetCurrentFIFOPacket(fifoBuffer, packetSize, MAX_GETPACKET_LOOPS); //get the latest mpu packet

    if (flag != 0) //0 = error exit, 1 = normal exit, 2 = recovered from an overflow
    {
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        //compute the yaw value
        global_yawval = ypr[0] * 180 / M_PI;

        //if (global_yawval == 180)
        //{
        //  mySerial.printf("erroneous yaw value detected!");
        //  return false;
        //}
        retval = true;
    }

    return retval;
}

uint8_t GetCurrentFIFOPacket(uint8_t* data, uint8_t length, uint16_t max_loops)
{
    max_loops = max(10, max_loops); //added 12/04/19 to ensure we loop at least 10 times. This really IS a hard-coded number!

    fifoCount = mpu.getFIFOCount();

    GetPacketLoopCount = 0;
    int max_outer_loops = 10;

    //11/10/19 I have seen this fail with fifoC > 28 on occasion, so now I loop max 10 times
    OuterGetPacketLoopCount = 0;
    while (fifoCount != packetSize && OuterGetPacketLoopCount < max_outer_loops)
    {
        mpu.resetFIFO();
        delay(1);

        fifoCount = mpu.getFIFOCount();
        GetPacketLoopCount = 0;

        while (fifoCount < packetSize && GetPacketLoopCount < max_loops)
        {
            GetPacketLoopCount++;
            fifoCount = mpu.getFIFOCount();
            delay(2);
        }

        OuterGetPacketLoopCount++;
    }

    //if we get to here, there should be exactly one packet in the FIFO
    if (OuterGetPacketLoopCount < max_outer_loops)
    {
        mpu.getFIFOBytes(data, packetSize);
        return 1;
    }
    return 0; //failed to get a good packet
}

```

# Answer
So, it turns out that the problem was located squarely between the programmer's ears, as usual.

As part of another experiment to use an I2C sniffer program to find out why the MPU6050 was failing intermittently, I had added the following line to my setup() function

```
Wire.setClock(50000);

```

To slow the I2C clock down enough so that a sniffer program could keep up. Apparently the slower than normal I2C clock speed was enough to screw up the DMP Initialization process.

The funny (weird, not 'ha ha') thing was the way I discovered this was by adding some 'Serial.print()' statements into the loop that writes the DMP firmware onto the DMP chip at each startup. For some reason, the print statements allowed the load to succeed, even with the lower I2C clock speed. Boy was I surprised!

Even weirder is that I could not substitute a 'delay(x)' in place of the print statement; any delay (even as small as 'delay(1);') caused the DMP load to fail, while a print statement worked fine.

Once I saw there was something weird going on with the rate at which the load operations were being executed, I remembered about the 'Wire.SetClock(50000)' command and commented it out to go back to the default I2C rate. Voila\` problem solved!

I have NO clue as to why the DMP firmware load is clock speed sensitive, and even less clue why the print statements allowed the load to complete, but I'm back in business now, so I'm going to file this one in the "Who knew?" category and move on ;-)

Frank
> 1 votes

---
Tags: arduino-mega, mpu6050
---


# Question
Title: Porting "far" flash memory access from Arduino Mega to Due
I have a project that runs on the Arduino Mega 2560 which takes up almost the complete amount of flash memory available (https://github.com/fredlcore/bsb\_lan/blob/master/BSB\_lan.ino). Because of this, I'm planning on migrating the project to the Arduino Due.

My main problem at the moment is to port those functions that access flash memory in the "far" memory area (\>64k) for which on the one hand various \_PF functions (like strncpy\_PF) are provided, and on the other hand a dummy "pointer" type uint\_farptr\_t (which is actually uint32\_t) is available.

My problems now are twofold:

1. While the \_PF functions have specific definements for the Due which under "normal" circumstances should work without changes in the code, they expect different variable types. For example, strncpy\_PF takes uint\_farptr\_t (i.e. uint32\_t) as argument for src on the Mega, it expects a const char * on the Due. Compilation thus results in lots of errors.
2. For the Mega to be able to access char arrays (which are 16 Bit on the Mega) above 128k, I need a rather dirty workaround (see function calc\_enum\_offset() in the code linked above). Basically I need to take the memory address of a 16 Bit char pointer and make some calculations to get the final address from which I read the strings. On the Mega, I can do these calculations on the basis of uint\_farptr\_t and then read from the calculated memory address with pgm\_read\_byte\_far() for example. On the Due, however, pgm\_read\_byte\_far(addr) is translated to (\*(const unsigned char \*)(addr)). Again, the uint32\_t type does not fit this.

Do you have any suggestions on how I should tackle these issues with the least amount of code?

# Answer
> 1 votes
The Due, being ARM, is a von Neumann architecture. That means that it has no concept of "progmem", "near" or "far" pointers, etc. There are no \_P or \_PF variant functions, but the Arduino core provides simple stubs as a convenience.

Instead all "flash" memory access is just simple memory accesses using `const`.

The best thing you can do is to use preprocessor macros to select between AVR and ARM code:

```
#if defined(__AVR__)
    strncpy_PF(buffer, enumstr+c, sizeof(buffer));
    buffer[sizeof(buffer)-1] = 0;
    outBufLen+=sprintf(outBuf+outBufLen,"%d - %s",val,buffer);
#else
    outBufLen += sprintf(outBuf + oufBufLen, "%d - %s", val, cmdtbl[i].enumstr);
#endif

```

In fact, given the huge amount of "hackiness" involved in that program with regards the `cmdtbl`, and the massive amounts of code that just aren't needed on the Due, it may be better to start a fresh program that is Due specific and delete the swathes of unneeded code.

---
Tags: arduino-mega, arduino-due, memory-usage, flash, memory
---


# Question
Title: Error with led Blinking (avrdude: ser_open(): can't set com-state)
I am new with Arduino and I made something very basic and I don't know why it is not working . I placed the positive led in pin 13 and the negative in GND and wrote this code :

```
#define LED 13
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

I verified if it 's connected to Arduino Uno and when I upload the code I have this errors :

```
Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM4"
An error occurred while uploading the sketch

```

Sometimes IDE has problems ? What I did wrong ?

# Answer
> 0 votes
You do not have a problem with LED blinking (although there seems a resistor missing for your led), but with uploading a sketch.

Hard test: switch off your computer, remove USB cable, switch on computer, check the COM port appearing when connecting the Arduino via USB cable. Then start IDE and try upload again.

Eventually something else was blocking the COM port.

---
Tags: arduino-uno
---


# Question
Title: Which arduino will be suitable with bill acceptor
I want to connect a bill acceptor (protocol ID003) and 3 switches and an Ethernet shield to Arduino. I am building a system that accepts bill and pass on the information to our software. Which Arduino will be the best choice, we need something which will have lot of code and also communication should be fast.

1. ARDUINO MEGA 2560 REV3
2. ARDUINO DUE
3. Arduino Uno REV3

**--Edit--**

This is I want to create:

A bill acceptor connected with arduino. Arduino has 3 buttons. (1. Play button, 2. redeem cash button. 3rd is not necessary).

When user login on machine, I get the details of user account through an API.

When user inserts money in bill acceptor, it enables the play button and add money in users account (If user already has money in account, button will be enabled). User can play until his account is not empty (i.e. if user has 200 in account, he can play 10 times). User can earn or lose money.

I have to send this transaction detail through an API. If user press redeem button, it will print a slip of account details (Total money in account)

**I am using Python.**

I need to know which arduino is suitable for this, Ethernet shield compatible with that arduino (I think I am going to use **ARDUINO MEGA 2560 REV3**, but I don’t know Ethernet shield compatible with this model).

Also I need some Idea how can I make this. This is first time I am using arduino and bill acceptor.

# Answer
> 1 votes
* Define 'lot of code', the Arduino Uno has 32 KB Flash, the Mega 256 KB.
* Define 'fast', the Uno/Mega are 16 MHz, the Due 48 MHz
* Three switches use 3 GPIO's, shouldn't be a problem on neither of them; the Mega has more GPIOs than the Uno, but both have plenty for your needs.
* The Ethernet shield are available for all three
* I don't know the 'bill acceptor', add a datasheet.

Conclusion: it depends on what is lot of code, and what is fast.

---
Tags: arduino-uno, arduino-mega, arduino-due
---


# Question
Title: Error code board and boards.txt? Formatting error? cannot verify alarm.txt or any
Arduino: 1.8.8 (Windows 10), Board: "Arduino/Genuino Uno"

Error reading file (E:\arduino\arduino-1.8.8\hardware\arduino\avr\**\boards.txt:0\**): **Invalid line format, should be 'key=value'**

Error compiling for board Arduino/Genuino Uno.\[/b\]

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

I was trying to do this experiment: http://wirebeings.com/arduino-intruder-alarm.html

but with Arduino Uno + geeetech iduino yun shield setup.

http://www.geeetech.com/wiki/index.php/Iduino\_Yun\_Shield

Please help (also short do you short the two pins properly?)

this is the board.txt file:

```
unoyun.name=Arduino Uno --Iduino Yún
unoyun.upload.via_ssh=true
unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true
unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F
unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

```

and this is the boards.txt file:

```
# See: http://code.google.com/p/arduino/wiki/Platforms

menu.cpu=Processor

##############################################################

yun.name=Arduino Yún
yun.upload.via_ssh=true

yun.vid.0=0x2341
yun.pid.0=0x0041
yun.vid.1=0x2341
yun.pid.1=0x8041
yun.vid.2=0x2A03
yun.pid.2=0x0041
yun.vid.3=0x2A03
yun.pid.3=0x8041

yun.upload.tool=avrdude
yun.upload.protocol=avr109
yun.upload.maximum_size=28672
yun.upload.maximum_data_size=2560
yun.upload.speed=57600
yun.upload.disable_flushing=true
yun.upload.use_1200bps_touch=true
yun.upload.wait_for_upload_port=true

yun.bootloader.tool=avrdude
yun.bootloader.low_fuses=0xff
yun.bootloader.high_fuses=0xd8
yun.bootloader.extended_fuses=0xfb
yun.bootloader.file=caterina/Caterina-Yun.hex
yun.bootloader.noblink=caterina/Caterina-Yun-noblink.hex
yun.bootloader.unlock_bits=0x3F
yun.bootloader.lock_bits=0x2F

yun.build.mcu=atmega32u4
yun.build.f_cpu=16000000L
yun.build.vid=0x2341
yun.build.pid=0x8041
yun.build.usb_product="Arduino Yun"
yun.build.board=AVR_YUN
yun.build.core=arduino
yun.build.variant=yun
yun.build.extra_flags={build.usb_flags}

##############################################################

uno.name=Arduino/Genuino Uno

uno.vid.0=0x2341
uno.pid.0=0x0043
uno.vid.1=0x2341
uno.pid.1=0x0001
uno.vid.2=0x2A03
uno.pid.2=0x0043
uno.vid.3=0x2341
uno.pid.3=0x0243

uno.upload.tool=avrdude
uno.upload.protocol=arduino
uno.upload.maximum_size=32256
uno.upload.maximum_data_size=2048
uno.upload.speed=115200

uno.bootloader.tool=avrdude
uno.bootloader.low_fuses=0xFF
uno.bootloader.high_fuses=0xDE
uno.bootloader.extended_fuses=0xFD
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F
uno.bootloader.file=optiboot/optiboot_atmega328.hex

uno.build.mcu=atmega328p
uno.build.f_cpu=16000000L
uno.build.board=AVR_UNO
uno.build.core=arduino
uno.build.variant=standard

##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude
diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude
diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L
diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino
diecimila.build.variant=standard

```

# Answer
nvm, apparently some guys suggesting utf-8 bom encoding change or something because I saw 1 question related to this

(it didn't work)

then I changed it to utf-8 encoding

(both done through notepad++)

it worked.
> 0 votes

# Answer
John Doe, thanks for the tip about utf-8.

I just ran into this exact problem. boards.txt had been hand-edited in Windows Notepad and saved as utf-8 and was throwing this error.

```
Arduino: 1.8.10 (Windows 10), Board: "Arduino/Genuino Uno"
loading hardware from C:\Program Files (x86)\Arduino\hardware:
loading package arduino: loading platform release:
Error reading file (C:\Program Files (x86)\Arduino
\hardware\arduino\avr\boards.txt:0):
Invalid line format, should be 'key=value'

```

I changed the text file format to ANSI and saved, and that fixed the problem, able to compile. At this point, guessing that maybe changing format merely cleaned up a defect, I saved again to utf-8, but it broke again. Thus back to ANSI.
> 0 votes

---
Tags: arduino-uno, arduino-ide, shields
---


title: GSM module not working after power off

text:
# Question
Title: GSM module not working after power off
I am making a project on gsm module(sim 900a unofficial shield), when I will send a SMS led will turn ON. after uploading code, module works fine, and led turned ON after sending message. But when I power off sim900a and Arduino, and power on back, it's not working, led not power up after sending message, when I reupload sketches it is working fine, means every time after power off I need to upload code again, I am learning c and don't have much knowledge? Is my code right? Or some other fault?

```
#include <SoftwareSerial.h> //software serial library for serial communication b/w arduino & GSM

    SoftwareSerial mySerial(8, 9);//connect Tx pin of GSM to pin 8 of arduino && Rx pin of GSM to pin no 9 of arduino

    int led = 7;
    String message;

    void setup()
    {
      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      delay(100);

      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      pinMode(led,OUTPUT);
      digitalWrite(led,LOW);
    }

    void loop()
    {
      if (mySerial.available()>0){
      message = mySerial.readString();
      }

      if(message.indexOf("ON") > -1){
          Serial.println("LED ON");
         digitalWrite(led,HIGH);
         }
        else if(message.indexOf("OFF") > -1){

          Serial.println("LED OFF");
          digitalWrite(led,LOW);

      }

      delay(10);
    }

```

Circuit diagram

# Answer
The GSM takes time to start up. Your program needs to be far more complex than the simple "Throw commands at it and hope" method you are using.

First you need to query the modem repeatedly until it responds. This is usually done with the `AT` command. A sequence would look like:

```
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Send: AT
(Wait for OK response or timeout)
Recv: OK

```

Once the modem has booted and is ready to receive commands you can start sending commands. You shouldn't just "print and delay" though like you are at the moment. Instead you should send the command and then examine the response to see if the command worked ("OK") or failed ("ERR").
> 2 votes

---
Tags: arduino-uno, gsm, home-automation
---