# Question
Title: Adafruit IO example won't compile, library required is correct version
I have Arduino IDE 1.8.5 installed, and also Adafruit IO Arduino 2.6.0 and Adafruit MQTT Library 0.20.0.

With the Adafruit IO lib comes a set of examples, and I wanted to use example adafruitio\_07\_digital\_out as a starting point for a project on an Adafruit HUZZAH ESP8266.

It won't compile. I get

```
#error "This sketch requires Adafruit MQTT Library v0.17.0 or higher. Please install or upgrade using the Library Manager."

```

which I find strange. I've tried installing 0.17.0 instead of 0.20.0, but that doesn't help.

Is there anything I can do to get this to work? The suggested solution of using the Library Manager to install the required package is obviously not working.

# Answer
It turns out that the problem was that I had installed the Arduino IDE through the windows app store. Uninstalling it, downloading it through a browser, and using the same code works just fine.
> 0 votes

---
Tags: adafruit
---


# Question
Title: How to connect an Arduino Micro to MPU-6050
So I'm trying to connect my Arduino micro to the MPU-6050. I was using this tutorial:

https://diyhacking.com/arduino-mpu-6050-imu-sensor-tutorial/

This tutorial worked with my Arduino Uno but not the Micro. When I try to run the Serial Monitor it just says "Initializing I2C Devices".

Is it the code that's not allowing to run it on the Arduino Micro or it needs a different setup than the Arduino Uno? Thanks!

```
   // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
  I2Cdev device library code is placed under the MIT license
  Copyright (c) 2012 Jeff Rowberg

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
  ===============================================
*/

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
   ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
   ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

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

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

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

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

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  // (115200 chosen because it is required for Teapot Demo output, but it's
  // really up to you depending on your project)
  Serial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
  // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
  // the baud timing being too misaligned with processor ticks. You must use
  // 38400 or slower in these cases, or use some kind of external separate
  // crystal solution for the UART timer.

  // initialize device
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();

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

  // wait for ready
  Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again

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

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(220);
  mpu.setYGyroOffset(76);
  mpu.setZGyroOffset(-85);
  mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

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

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

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

  // configure LED for output
  pinMode(LED_PIN, OUTPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
    // other program behavior stuff here
    // .
    // .
    // .
    // if you are really paranoid you can frequently test in between other
    // stuff to see if mpuInterrupt is true, and if so, "break;" from the
    // while() loop to immediately process the MPU data
    // .
    // .
    // .
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

#ifdef OUTPUT_READABLE_QUATERNION
    // display quaternion values in easy matrix form: w x y z
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    Serial.print("quat\t");
    Serial.print(q.w);
    Serial.print("\t");
    Serial.print(q.x);
    Serial.print("\t");
    Serial.print(q.y);
    Serial.print("\t");
    Serial.println(q.z);
#endif

#ifdef OUTPUT_READABLE_EULER
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetEuler(euler, &q);
    Serial.print("euler\t");
    Serial.print(euler[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(euler[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(euler[2] * 180 / M_PI);
#endif

#ifdef OUTPUT_READABLE_YAWPITCHROLL
    // display Euler angles in degrees
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);
#endif

#ifdef OUTPUT_READABLE_REALACCEL
    // display real acceleration, adjusted to remove gravity
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetAccel(&aa, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
    Serial.print("areal\t");
    Serial.print(aaReal.x);
    Serial.print("\t");
    Serial.print(aaReal.y);
    Serial.print("\t");
    Serial.println(aaReal.z);
#endif

#ifdef OUTPUT_READABLE_WORLDACCEL
    // display initial world-frame acceleration, adjusted to remove gravity
    // and rotated based on known orientation from quaternion
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetAccel(&aa, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
    mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
    Serial.print("aworld\t");
    Serial.print(aaWorld.x);
    Serial.print("\t");
    Serial.print(aaWorld.y);
    Serial.print("\t");
    Serial.println(aaWorld.z);
#endif

#ifdef OUTPUT_TEAPOT
    // display quaternion values in InvenSense Teapot demo format:
    teapotPacket[2] = fifoBuffer[0];
    teapotPacket[3] = fifoBuffer[1];
    teapotPacket[4] = fifoBuffer[4];
    teapotPacket[5] = fifoBuffer[5];
    teapotPacket[6] = fifoBuffer[8];
    teapotPacket[7] = fifoBuffer[9];
    teapotPacket[8] = fifoBuffer[12];
    teapotPacket[9] = fifoBuffer[13];
    Serial.write(teapotPacket, 14);
    teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
#endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
  }
}

```

\** code with `attachInterrupt(digitalPinToInterrupt(2), dmpDataReady, RISING);`\**

# Answer
> 2 votes
That IMU and library require an interrupt to work correctly. It is programmed to use interrupt 0 with this line in the setup function: `attachInterrupt(0, dmpDataReady, RISING);` This is not the proper way to do things since it cannot be transferred between arduinos. On the Uno, interrupt 0 is pin 2 but on the Micro interrupt 0 is pin 3. So the simple solution is to move the wire from pin 2 to pin 3. The correct way to fix it is to change the line to this: `attachInterrupt(digitalPinToInterrupt(2), dmpDataReady, RISING);`

# Answer
> 1 votes
I used interrupt 4 on pin 7 and it worked great! Just had to change the interrupt pin designation to "7" in the code....

# Answer
> 1 votes
I've just been through a similar issue, and here's what worked for me.

Following @mwwalk's instruction I changed the interrupt pin to digital Pin 7. After uploading the code to the Arduino Micro it would get past `Initializing I2C devices...` but end up showing `MPU6050 connection failed`. This is because `mpu.testConnection()` was unsuccessful.

To fix this I changed the connections for SCL and SDA on the MPU-6050 to digital pin 3 and digital pin 2 on the Arduino. These aren't the same as the pins shown in the diagram in the tutorial (A5 and A4).

The pin mapping for the Arduino Micro lists Digital Pin 2 as the SDA pin and Digital Pin 3 as the SCL pin. Connecting SDA to Digital Pin 2 and SCL to Digital Pin 3 worked for me.

# Answer
> 0 votes
Wait and be patient. It is initializing the sensor. Have you even waited for like 10 seconds? I bet not.

1. Run it and let it wait for 10 seconds.
2. Add `while(!Serial);` right after `Serial.begin(115200);`.
3. Set the baud rate to 115200. It works better in my opinion.
4. Any other devices connected to your I2C constellation? If yes, remove all for testing purposes
5. If it still doesn't work, reboot your PC.

---
Tags: arduino-ide, arduino-micro, mpu6050
---


# Question
Title: DC motors not running using PWM and L298N motor driver
I'm just beginning to understand Arduino. Please bear with me. I have a collision avoidance car running on Arduino Uno, WB291111 L298N motor driver, SG90 servo, Arduino Shield v5, and HC-SR04 ultrasonic sensor. Also, I have the entire setup running on 8.4v batteries. If I just use HIGH/LOW on the motors, it will run without any problems. But if I use the PWM to run the motors on different speeds, it will NOT run at all. The sensor and servo works, but not the motors. See my codes below. Let me know if you need further details. Any help is greatly appreciated.

```
#include <Servo.h>
#include <NewPing.h>

//our L298N control pins
const int enA = 10;
const int in1 = 6;
const int in2 = 7;

const int enB = 9;
const int in3 = 4;
const int in4 = 5;

//sensor pins
#define trig_pin A2
#define echo_pin A1

#define maximum_distance 500
boolean goesForward = false;
int distance = 100;

NewPing sonar(trig_pin, echo_pin, maximum_distance);
unsigned int uS;

#define SERVO_PIN 11
Servo servo_motor;

void setup(){
  Serial.begin(115200);
  pinMode(enA, OUTPUT);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  servo_motor.attach(SERVO_PIN);

  servo_motor.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop(){

  int distanceRight = 0;
  int distanceLeft = 0;
  delay(50);

  if (distance <= 20){
    moveStop();
    delay(300);
    moveBackward();
    delay(200);
    moveStop();
    delay(300);
    distanceRight = lookRight();
    delay(200);
    distanceLeft = lookLeft();
    delay(200);

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

int lookRight(){
  Serial.print("Look Right");
  servo_motor.write(50);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(115);
  return distance;
}

int lookLeft(){
  Serial.print("Look Left");
  servo_motor.write(170);
  delay(500);
  int distance = readPing();
  delay(100);
  servo_motor.write(115);
  return distance;
  delay(100);
}

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

}

void moveStop(){
  Serial.print("Stop");

  digitalWrite(in3, LOW);
  digitalWrite(in1, LOW);
  digitalWrite(in4, LOW);
  digitalWrite(in2, LOW);
}

void moveForward(){

  //if(!goesForward){

    //goesForward=true;

    Serial.print("Forward");

    digitalWrite(in1, HIGH);
    digitalWrite(in3, HIGH);

    digitalWrite(in2, LOW);
    digitalWrite(in4, LOW);

    analogWrite(enA, 250);
    analogWrite(enB, 250);

  //}
}

void moveBackward(){

  //goesForward=false;

  Serial.print("Backward");

  digitalWrite(in2, HIGH);
  digitalWrite(in4, HIGH);

  digitalWrite(in1, LOW);
  digitalWrite(in3, LOW);

}

void turnRight(){
  Serial.print("Right");

  digitalWrite(in1, HIGH);
  digitalWrite(in4, HIGH);

  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);

  delay(200);

  digitalWrite(in1, HIGH);
  digitalWrite(in3, HIGH);

  digitalWrite(in2, LOW);
  digitalWrite(in4, LOW);

}

void turnLeft(){
  Serial.print("Left");

  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);

  digitalWrite(in1, LOW);
  digitalWrite(in4, LOW);

  delay(200);

  digitalWrite(in1, HIGH);
  digitalWrite(in3, HIGH);

  digitalWrite(in2, LOW);
  digitalWrite(in4, LOW);
}

```

# Answer
According to the Servo reference page it's not possible to use Servo library and PWM outputs on the pins 9 and 10.

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.
> 1 votes

---
Tags: motor, l298n
---


title: Designing around Output pin limitations

text:
# Question
Title: Designing around Output pin limitations
I'm new to Arduino and am working on a project with my son. We are using the LillyPad USB board (schematic) to drive a bunch of LEDs (LED Datasheet). Our project is based loosely off of the 'Turn Signal Biking Jacket'.

Our project calls for 7-11 LEDs in parallel on a single circuit. In the 'Turn Signal' project the LEDs are driven off of a **pair** of output pins (1 HIGH and 1 LOW). In a circuit that looks like this...

simulate this circuit – Schematic created using CircuitLab

Is this ideal? Would it make more sense to connect the LED-chain to Vcc and have the return line connected to a single output set to LOW (to turn on the lights)?

If we were to have 3-4 of these LED-chains on at once, do I have to be concerned with total draw on the microcontroller?

Help? Thoughts?

# Answer
> 1 votes
If you know the forward voltage of the LEDs you can easily do some calculations.

For a typical red LED the forward voltage is around 2V. Other colours vary. So we can work out that, at 5V supply, each LED with its own 150R resistor, would take:

```
     V    5-2
I = --- = --- = 20mA
     R    150

```

With 11 LEDs in parallel on at once that would be 0.02 * 11 = 220mA.

**That is far more than the 25mA an IO pin is able to supply, so you will damage the Arduino doing it like that.**

Instead you will need to switch each chain of LEDs with a transistor of some form. I'd choose a logic-level N-channel MOSFET as a "low-side" switch:

simulate this circuit – Schematic created using CircuitLab

Now your Arduino doesn't care about the current - all it sees is the MOSFET.

If your LED forward voltages are less than 2.5V you can also chain them together to halve the current:

simulate this circuit

Since the forward voltage is now double you use a smaller resistance to set the current (R=V/I, where V is 5-2Vf).

---
Tags: pins, electronics, current, voltage
---


title: Array, hexadecimal and serial write

text:
# Question
Title: Array, hexadecimal and serial write
I am trying to write a pice of code which send to a receiver the frequency to listen.

As per its documentation, it should receive the following sequence:

> Example with **123.456** MHz
>
> Command to send (frequency converted in 4 bytes, followed by 2 instruction bytes
>
> 0x**12** 0x**23** 0x**56** 0x00 0x01

To be able to memorize six frequencies, I fill an array:

```
uint32_t mem_freq[6] = {
   0x121050,
   0x126500,
   0x120500,
   0x121700,
   0x121825,
   0x118700,
};

```

My concern is that when I do :

```
Serial.write(mem_freq[mem_index]);
//Serial.write(0x00);
//Serial.write(0x01);

```

Only 1 byte is sent, and it's hard to debug as the serial console displays only ascii characters.

When I use Serial.print instead, mem\_freq\[2\] shows correctly 0x120500

After Majenko's answer, I tried this:

```
Serial.print(0x123456 >> 16,HEX);
Serial.print(0x123456 >> 8,HEX);
Serial.print(0x123456,HEX);
Serial.print(0x00,HEX);
Serial.print(0x01,HEX);

```

And it outputs:

> 12123412345601

Is this normal ?

# Answer
You need to manually split your values into bytes. You can either do that by storing them as individual bytes (as shown by Ignacio), or by using bit shifting:

```
Serial.write(mem_freq[mem_index] >> 16);
Serial.write(mem_freq[mem_index] >> 8);
Serial.write(mem_freq[mem_index]);

```

That sends the bits 16-23 (0x12) then bits 8-15 (0x10) followed by bits 0-7 (0x50).
> 1 votes

# Answer
That's because you need to use an array of arrays, and send three bytes.

```
uint32_t mem_freq[6][3] = {
  {0x12, 0x10, 0x50},
   ...
};

 ...
  Serial.write(mem_freq[mem_index], 3);
 ...

```
> 0 votes

---
Tags: serial, array
---


# Question
Title: Turn on each of the LEDs in order, by setting the cycle delay to 100 milliseconds
I have a tutorial to finish and I don't know the code I have to use to make all (4 LEDs) to turn on in order. So this is my code and my simulation. Thanks in advance!

My Code:

```
void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100); // Wait for 100 millisecond(s)

  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(9, LOW);
  digitalWrite(6, LOW);
  delay(100); // Wait for 100 millisecond(s)
}

```

EDITED: I have to follow this one. I guess my simulator is correct.

# Answer
> 2 votes
I see in your second diagram that you are controlling the ground side of the LEDs. digitalWrite(PinNumber, HIGH) will turn an LED OFF, digitalWrite(PinNumber, LOW) will turn an LED ON. Using delay() in a sketch should be avoided.

```
void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(6, OUTPUT);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
}

void loop(){
  digitalWrite(13, LOW);
  delay(100);
  digitalWrite(12, LOW);
  delay(100);
  digitalWrite(9, LOW);
  delay(100);
  digitalWrite(6, LOW);
  delay(100);
  digitalWrite(13, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(6, HIGH);
  delay(100);
}

```

# Answer
> 1 votes
Your code switches them all ON and OFF simultaneously.

What I read from your question is you want to turn them on in order. In this case, use a simple state diagram. This means you have to create variable (preferably an enumeration), e.g.:

```
enum EState { FIRST_ON, SECOND_ON, THIRD_ON, FOURTH_ON };

EState _state;

```

You can better use better names than FIRST\_ON, ..., but I do not know what your lights mean.

In the setup, you initialize \_state, e.g.

```
_state = FIRST_ON;

```

Than in the loop you check and change the state:

```
switch (_state)
{
case FIRST_ON:
    digitalWrite(13, HIGH); // Assuming this is the first light
    digitalWrite(12, LOW); // Put the others off
    ...
    ...
    _state = SECOND_ON; // Set the next state
    break;

case SECOND_ON:
    digitalWrite(13, LOW); // Assuming this is the first light
    digitalWrite(12, HIGH); // Put the second LED on
    .. // Put the third/fourth off
    _state = THIRD_ON; // Set the next state
    break;

    // Do the same for THIRD_ON and FOURTH_ON

default: // in all other cases
     break; // Should not happen
}

delay(100: // Wait for 100 milliseconds

```

Note, to not complicate the example, I've written out (mostly) the lines like you:

```
digitalWrite(13, HIGH);
digitalWrite(12, HIGH);
digitalWrite(9, HIGH);
digitalWrite(6, HIGH);

```

However, since these are almost copies (4 in the state diagram), it is best to write a separate function:

```
void SwitchLedsOn(int led1State, int led2State, int led3State, int led4State)
{
  digitalWrite(13, led1State);
  digitalWrite(12, led2State);
  digitalWrite(9, led3State);
  digitalWrite(6, led4State);
}

```

Now you can use in the first state case:

```
case FIRST_ON:
    SwitchLedsOn(HIGH, LOW, LOW, LOW); // Switch only first on
    break;

```

And do similar with the other states.

# Answer
> 1 votes
add this to loop() end

```
 digitalWrite(13, HIGH);
 delay(100);
 digitalWrite(12, HIGH);
 delay(100);
 digitalWrite(9, HIGH);
 delay(100);

```

---
Tags: arduino-uno, programming, led
---


# Question
Title: Create a sketch that allows me to run a DC motor and LED sequence at the same time
I need a program created that will both run a DC motor and an LED sequence at the same time. The image is what the DC motor code should do.

```
/*
-==:: 3 Volts DC Motor Driver with Dual 555 Timer IC ::==-
  * Control Pin from 555 IC is needed to STOP the motor
  * Trigger Pin from 555 IC is needed to drive forward or backward
  * PWM on Trigger Pin is used to set the speed
  * Note : Forward and Backward is interchangeable via Motor connection.
 */

int controlPin = 2; // 555 pinout 5
int triggerPin = 3; // 555 pinout 2

// the setup routine runs once when you press reset:

void setup()  {
  pinMode(controlPin, OUTPUT);
  pinMode(triggerPin, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop()  {
//  move FORWARD;
    digitalWrite(controlPin, HIGH);
    digitalWrite(triggerPin, HIGH); //full speed
    delay(3000);
//    PWM testing to control motor speed
//    analogWrite(triggerPin, 128+70); //minimum speed (128+70)
//    delay(3000);

//  STOP;
    digitalWrite(controlPin, LOW);
    digitalWrite(triggerPin, HIGH);
    delay(3000);

//  move BACKWARD;
    digitalWrite(controlPin, HIGH);
    digitalWrite(triggerPin, LOW); //full speed
    delay(3000);

//    PWM testing to control motor speed

//    analogWrite(triggerPin, 128-70); //minimum speed (128-70)
//    delay(3000);

//  STOP;
    digitalWrite(controlPin, LOW);
    digitalWrite(triggerPin, HIGH);
    delay(3000);
}

```

As for the LED code I have no idea. I just found this code on the web. The important thing is that the codes execute at the same time continuously.

# Answer
> 0 votes
As stated in the comments, the Arduino can only execute 1 command at a time. There is no real multi-threading on this hardware. But you can to the work in sequence so fast, that you won't notice the difference with motors or LEDs. Here it is important to use non-blocking code, which doesn't block the execution of other code, when it is only waiting (the `delay()` function is just busy waiting).

For doing anything non-blocking (as setting LEDs or changing the state of a motor) you can use the `millis()` function. Refer to the `BlinkWithoutDelay` example from the Arduino IDE. For a very simple sequence (as blinking) you can directly use the code from the example. Basically you use a timestamp, which holds the last time, the blink code was executed. On every iteration of the `loop()` function you check, if a certain time has passed since the timestamp have been taken. If so, execute the code again and update the timestamp:

```
unsigned long timestamp=0;
void loop(){
  if(millis()-timestamp > 500){
    digitalWrite(led_pin,!digitalRead(led_pin));
    timestamp = millis();
  }
}

```

This code would toggle the led\_pin each 500ms.

For coding complex sequences you can make a state machine. For this you create a numeric state variable. In the `loop()` function you use a `switch`-`case`-statement, to execute the right code for each state of your programm. Also directly in the `loop()` function you change the state variable depending on the time through the above code. This would look somewhat like this:

```
int state = 0;
unsigned long timestamp = 0;
void loop(){
  if(millis() - timestamp > 1000){
    state++;
    timestamp = millis();
  }

  switch(state){
    case 0:
      digitalWrite(led_pin,!digitalRead(led_pin));
      //  move FORWARD;
      digitalWrite(controlPin, HIGH);
      digitalWrite(triggerPin, HIGH); //full speed
      break;
    case 1:
    case 2:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 3:
      digitalWrite(led_pin,!digitalRead(led_pin));
      // stop moving
      digitalWrite(controlPin, LOW);
      digitalWrite(triggerPin, HIGH);
      break;
    case 4:
    case 5:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 6:
      digitalWrite(led_pin,!digitalRead(led_pin));
      //  move BACKWARD;
      digitalWrite(controlPin, HIGH);
      digitalWrite(triggerPin, LOW); //full speed
      break;
    case 7:
    case 8:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 9:
      digitalWrite(led_pin,!digitalRead(led_pin));
      // stop moving
      digitalWrite(controlPin, LOW);
      digitalWrite(triggerPin, HIGH);
      break;
    case 10:
    case 11:
      digitalWrite(led_pin,!digitalRead(led_pin));
      break;
    case 12:
      state = 0;
      break;
  }
}

```

This code would toggle the led\_pin every second and also doing the moto sequence `3s forward, 3s stop, 3s backwards, 3s stop`. This sequence loops forever.

When you only want to let the led blink continuously, it would be easier to exclude this part of the code from the state machine, but I wanted to show how this principle would work (for example if you want to include a complex blinking sequence).

---
Tags: programming
---


# Question
Title: A SoftwareSerial library for SAMD boards
So I've got three boards that I'm using to test this (modified) code:

```
int sensor1Pin = A0;
int sensor2Pin = A1;
int sensor3Pin = A2;

float sensors[] = {0,0,0};

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

void loop(){

sensors[0] = analogRead(sensor1Pin);
sensors[1] = analogRead(sensor2Pin);
sensors[2] = analogRead(sensor3Pin);

Serial.print(sensors[0]);
Serial.print(",");
Serial.print(sensors[1]);
Serial.print(",");
Serial.println(sensors[1]);
}

```

An Uno, a Feather M0, and an MKR1000. The code will only work on the Uno because it's AVR-based whereas the other two boards are SAMD. When running on a feather, you get this error:

```
/home/ghylama/Arduino/libraries/SoftwareSerial_master/SoftwareSerial.cpp:260:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
     #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

```

However, the resolution of the Uno is too low for my purposes (its DAC has a resolution of 10, whereas I need a resolution of 12, minimum). Are there any libraries/workarounds that I can use for this purpose?

I've tried SoftwareSerial, NeoSWSerial, and this one.

# Answer
I will restate the problem as I have understood it: You want more Serial objects, aka more UART ports.

On your Adafruit Feather M0 with its SAMD21G18 Cortex-M0+ MCU, you have six SERCOM peripherals which you can arbitrarily configure to be a UART, I2C or SPI port. Each peripheral can have its connections routed to several different pins on the board. It is a very versatile piece of hardware.

Don't use a SoftwareSerial library made for AVR MCUs when you have the hardware. Adafruit's guide shows how you can reconfigure those SERCOMs to get additional `Serial` objects.

https://learn.adafruit.com/using-atsamd21-sercom-to-add-more-spi-i2c-serial-ports?view=all#creating-a-new-serial
> 2 votes

---
Tags: arduino-uno, softwareserial, adafruit
---


# Question
Title: Changing outputs infinitely for no reason
Im a student and working on a arduino project for IoT competition and me and my team have built a house and I made this code below. For some reason when I upload it to my Arduino MKR1000 it constantly turns D6 and D8 on and right after their both on it turns them off and so on for ever. I cant figure out why is it doing that because its only these 2 but not the rest of them.

Quick help would be appreciated.

Please note that I'm by any means a PRO at this but I do know my share about programming.

```
        //Definiramo ispis na serial port
#define BLYNK_PRINT Serial

//Ucitavamo biblioteke
#include <SPI.h>
#include <WiFi101.h>
#include <BlynkSimpleMKR1000.h>

// Autorizacijski kod za aplikaciju Blynk
char auth[] = "Token";

// Podatci za WiFi
char ssid[] = "SSID";
char pass[] = "PASSWORD";

// ----- Inicializacija ledica -----
const int ledBorDim = 2;
const int ledKuh = 6;
const int ledTrp = 7;
const int ledKup = 8;
const int lediceUlaz = 9;
const int ledSpav = 10;

// ----- Inicializacija gumbova -----
const int gumbKuh = 11;
const int gumbKup = 12;
const int gumbSpav = 13;
const int gumbBor = 14;

// ----- Kontrolne varijable -----
int stanjeLedKuh = 0;
int stanjeLedKup = 0;
int stanjeLedBor = 0;
int stanjeLedSpav = 0;

int gumbStanjeKuh = 0;
int gumbStanjeSpav = 0;
int gumbStanjeBor = 0;
int gumbStanjeKup = 0;

//Led kuhinja
BLYNK_WRITE(V3)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("ledKuh = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(ledKuh, HIGH);
    stanjeLedKuh = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledKuh, LOW);
    stanjeLedKuh = 0;
  }
}

//Ledica za kupaonicu
BLYNK_WRITE(V5)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("ledKup = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(ledKup, HIGH); //Promjena stanja na izlazu arduina
    stanjeLedKup = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledKup, LOW); //Promjena stanja na izlazu arduina
    stanjeLedKup = 0;
  }
}

//Paralelni spoj ledica na ulazu
BLYNK_WRITE(V6)
{
  int pinValue = param.asInt(); //Pinvalue postavljamo da bude vrijednost ono sto postavimo na aplikaciji
  Serial.print("lediceUlaz = "); //Ispis na ekran trenutno stanje
  Serial.println(pinValue);
  if (pinValue == 1)
  {
    digitalWrite(lediceUlaz, HIGH); //Promjena stanja na izlazu arduina
  } if (pinValue == 0)
  {
    digitalWrite(lediceUlaz, LOW); //Promjena stanja na izlazu arduina
  }
}

//Dimmer za Boravak
BLYNK_WRITE(V1)
{
  int pinValue = param.asInt(); //Ucitamo vrijednost
  Serial.print("Dimmer vrijednost: "); //Ispisemo na serial
  Serial.println(pinValue);
  analogWrite(ledBorDim, pinValue); //Na izlaz postavljamo vrijednost
  if (pinValue == 0)
  {
    Blynk.virtualWrite(V50, 1);
    stanjeLedBor = 0;
  } else if (pinValue > 0)
  {
    Blynk.virtualWrite(V50, 0);
    stanjeLedBor = 1;
  }
}

BLYNK_WRITE(V50)
{
  int pinValue = param.asInt();
  if (pinValue == 1)
  {
    analogWrite(ledBorDim, 255);
    Blynk.virtualWrite(V1, 255);
    stanjeLedBor = 1;
  } if (pinValue == 0)
  {
    digitalWrite(ledBorDim, LOW);
    Blynk.virtualWrite(V1, 0);
    stanjeLedBor = 0;
  }
}

void gumbKuhinja()
{
  gumbStanjeKuh = digitalRead(gumbKuh);
  if (gumbStanjeKuh == LOW)
  {
    if(stanjeLedKuh == 1)
    {
      digitalWrite(ledKuh, LOW);
      Blynk.virtualWrite(V3, 0);
      Serial.println("Ledica na V3/D6 je LOW");
      stanjeLedKuh = 0;

    } else if (stanjeLedKuh == 0)
    {
      digitalWrite(ledKuh, HIGH);
      Blynk.virtualWrite(V3, 1);
      Serial.println("Ledica na V3/D6 je HIGH");
      stanjeLedKuh = 1;

    }
    delay(500);
  }
}

void gumbKupaonica()
{
  gumbStanjeKup = digitalRead(gumbKup);
  if (gumbStanjeKup == LOW)
  {
    if(stanjeLedKup == 1)
    {
      digitalWrite(ledKup, LOW);
      Blynk.virtualWrite(V5, 0);
      Serial.println("Ledica na V5/D8 je LOW");
      stanjeLedKup = 0;

    } else if (stanjeLedKup == 0)
    {
      digitalWrite(ledKup, HIGH);
      Blynk.virtualWrite(V5, 1);
      Serial.println("Ledica na V5/D8 je HIGH");
      stanjeLedKup = 1;
    }
    delay(500);
  }
}

void gumbSpavaca()
{
  gumbStanjeSpav = digitalRead(gumbSpav);
  if (gumbStanjeSpav == LOW)
  {
    if(stanjeLedSpav == 1)
    {
      digitalWrite(ledSpav, LOW);
      Blynk.virtualWrite(V6, 0);
      Serial.println("Ledica na V6/D10 je LOW");
      stanjeLedSpav = 0;
    } else if (stanjeLedSpav == 0)
    {
      digitalWrite(ledSpav, HIGH);
      Blynk.virtualWrite(V6, 1);
      Serial.println("Ledica na V6/D10 je HIGH");
      stanjeLedSpav = 1;
    }
    delay(500);
  }
}

void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == LOW)
  {
    if(stanjeLedBor == 1)
    {
      analogWrite(ledBorDim, 0);
      Blynk.virtualWrite(V1, 0);
      Serial.println("Ledica na V1/D2 je 0");
      stanjeLedBor = 0;
    } else if (stanjeLedBor == 0)
    {
      analogWrite(ledBorDim, 255);
      Blynk.virtualWrite(V1, 1);
      Serial.println("Ledica na V1/D2 je 255");
      stanjeLedBor = 1;
    }
    delay(500);
  }
}

void setup()
{

  pinMode(ledBorDim, OUTPUT);
  pinMode(ledKuh, OUTPUT);
  pinMode(ledKup, OUTPUT);
  pinMode(lediceUlaz, OUTPUT);
  pinMode(ledSpav, OUTPUT);

  pinMode(gumbKuh, INPUT);
  pinMode(gumbKup, INPUT);
  pinMode(gumbSpav, INPUT);
  pinMode(gumbBor, INPUT);

  // Debug console
  Serial.begin(9600);
  //Povezivanje na WiFi i na aplikaciju Blynk
  Blynk.begin(auth, ssid, pass);
}

void loop()
{
  Blynk.run();
  gumbKuhinja();
  gumbKupaonica();
  gumbSpavaca();
  gumbBoravak();
}

```

Serial outpout:

```
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255
Ledica na V6/D10 je LOW
Ledica na V1/D2 je 0
Ledica na V6/D10 je HIGH
Ledica na V1/D2 je 255

```

Little label reading D14 means that that pin isnt suppoast to go to D4 but to D14 of the MKR1000 but since i dont have that board in the program im stuck with arduino Uno.
Short explanation of the code... We build a house out of styrofoam and placed 6 Led's around and almost all can be controlled from the Blynk app on my device. Also there are 4 buttons controlling 4 Led's. I have it setup so that when i press a button it changes the state of a particular LED and then sets the appropriate value on the app (If LED is on then set app value to 1). Pretty much that that about this code. Sorry if you cant understand but I had to write it in my native language since this is going to be a compettition and I was told that they wouldn't like if the code was in english for some reason.

# Answer
> 2 votes
You had the following general problem:

The code you were using was configuring a pin into `INPUT` mode and reading the value on it. On this pin you conencted a button **without extern pullup or pulldown resistor**. This means that if the button is **not pressed**, it is not connected to anything and thus a **floating pin**. You cannot realibly read the value of the floating pin, as its voltage level may be on pretty much anything. It picks up interference like an antenna.

To solve this the button pin must be pulled to known voltage level if it is not connected (aka button is not pressed). We achieve this by using a resistor which is on one end connected to the button pin and on the other end connected to either VCC (+5V) or GND (0V). This has the effect that when the button is not pressed, the resistor pulls the voltage level of this pin up (if connected to VCC), or down if connected to GND.

We can either attach a resistor (e.g. 10K Ohm) in the circuit or active the internal (weak) pull-up resistors in our microcontroller. In Arduino, this is achieved by using `pinMode( buttonPin, INPUT_PULLUP)`.

In this circuit with `INPUT_PULLUP` on D2, we have:

* if the button is not pressed down, no connection to GND is made. The activated pull-up resistor will pull the voltage level of D2 to HIGH
* if the button is pressed down, it makes a connection to GND and overrides the pullup resistor. Pin D2 now reads LOW.

The logic can of course also be inverted -- you can use a PULLDOWN resistor and instead of connecting the button to GND on the other side connect it do 5V. This make the button read LOW when unpressed and HIGH pressed.

So the modified code must be changed from

```
  pinMode(gumbKuh, INPUT);
  pinMode(gumbKup, INPUT);
  pinMode(gumbSpav, INPUT);
  pinMode(gumbBor, INPUT);

```

to

```
  pinMode(gumbKuh, INPUT_PULLUP);
  pinMode(gumbKup, INPUT_PULLUP);
  pinMode(gumbSpav, INPUT_PULLUP);
  pinMode(gumbBor, INPUT_PULLUP);

```

and the logic which detects a button pressed must be changed to trigger an action when the pin is LOW (because a PULLUP is used, button reads LOW when pressed, HIGH else).

So from code of the form

```
void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == HIGH)
  {
    /* LED toggling and debouncing */
    delay(500);
  }
}

```

To

```
void gumbBoravak()
{
  gumbStanjeBor = digitalRead(gumbBor);
  if (gumbStanjeBor == LOW)
  {
    /* LED toggling and debouncing */
    delay(500);
  }
}

```

Also I recommend you to watch this youtube video to learn more about floating pins and pullup/pulldown resistors: Pull up Resistor Tutorial

---
Tags: mkr1000, iot, blynk, cpp
---


title: Interrupt crashes code when implemented

text:
# Question
Title: Interrupt crashes code when implemented
I've got a mini weather-station with a Davis Anemometer Vantage Pro that uses a reed switch to detect rotations. Using the rotations it then can convert to MPH. When using it alone, I have no problem measuring the wind speed. It measures the rotations over a 3 second period, and finds the average wind speed over those 3 seconds; however, when implemented into a group of code that also writes Temperature, Humidity, and Accelerometer data to an SD card, it crashes my code. For the sake of keeping this comment shorter, I am using code from http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed, and am implementing into the code below. It's a big chunk, but the important stuff should be the ISR\_rotation and enabling interrupts at the start of the loop.

```
// going to include all the libraries we need and definitions
#include "SD.h" //sd card
#include"SPI.h" //sd card
#include "SHT1x.h" //temp/humid
#include <Wire.h> //accelerometer
#include <Adafruit_MMA8451.h> //accelerometer
#include <Adafruit_Sensor.h> //accelerometer
#include <math.h> //for wind speed
//define pins and functions
#define dataPin 6 //data pin for temp/humid
#define sckPin 7 //serial clock for temp/humid
#define WindSensorPin (2) //pin for wind sensor
SHT1x th_sensor(dataPin, sckPin); //caling sht1x.h
Adafruit_MMA8451 mma = Adafruit_MMA8451(); //calling the accelerometer library

//WindSpeed stuff
volatile unsigned long Rotations; // cup rotation counter used in interrupt routine
volatile unsigned long ContactBounceTime=0; // Timer to avoid contact bounce in interrupt routine
float WindSpeed; // speed miles per hour

//SD card stuff
const int chipSelect = 10;
String dataString =""; // holds the data to be written to the SD card
File sensorData;

//Temp/Humid stuff
float humid; // humidity value
float temp_c; // temperature value

void setup(){
  // Open serial communications
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  pinMode(chipSelect, OUTPUT); //sd writing
  pinMode(WindSensorPin, INPUT); //wind data
  attachInterrupt(digitalPinToInterrupt(WindSensorPin), isr_rotation, FALLING);//""wind interrupt""

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
  // don't do anything more:
  return;
  }
  //accelerometer setup
  if (! mma.begin()) {
    Serial.println("Couldnt start");
    while (1);
  }
  Serial.println("MMA8451 found!");
  mma.setRange(MMA8451_RANGE_2_G);
  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");
}

//
void loop(){
  //This interrupt portion is for incrementing Rotations
  Rotations = -22; // Set Rotations count to 0 ready for calculations
  //interrupts(); // Enables interrupts
  //delay (3000); // Wait 3 seconds to average
  //noInterrupts(); // Disable interrupts
  //convert to mp/h using the formula V=P(2.25/T) where T is the delay in seconds
  //V = P(2.25/3) = P * 0.75
  //WindSpeed = Rotations * 0.75;

  //read the temperature/humidity sensor
  humid=th_sensor.readHumidity();
  temp_c=th_sensor.retrieveTemperatureC();

  //read the 'raw' data in 14-bit counts for accelerometer
  //mma.x for x direction, mma.y for y direction, mma.z for z direction
  mma.read();
  //Convert 14 bit to SI units (m/s^2)
  sensors_event_t event;
  mma.getEvent(&event);
  delay(3000);
  WindSpeed = Rotations * 0.75;
  //read the wind speed data

  //build the data string
  dataString = String(temp_c) + "," + String(humid) + "," + String(event.acceleration.x) + "," + String(event.acceleration.y) + "," + String(event.acceleration.z);// + "," + String(WindSpeed); //to CSV
  saveData(); // save to SD card
  //for testing with serial monitor to see if we are obtaining correct values
  Serial.print("Temperature: ");
  Serial.print(temp_c);
  Serial.print(", Humidity: ");
  Serial.println(humid);
  Serial.print(" X: ");
  Serial.print(event.acceleration.x);
  Serial.print(" Y: ");
  Serial.print(event.acceleration.y);
  Serial.print(" Z: ");
  Serial.println(event.acceleration.z);
  Serial.print("Rotations: ");
  Serial.println(Rotations);
  delay(3000);
}

//
void saveData(){
if(SD.exists("data.csv")){ // check the card is still there
  // now append new data file
  sensorData = SD.open("data.csv", FILE_WRITE);
  Serial.println("Data written");
    if (sensorData){
    sensorData.println(dataString);
    sensorData.close(); // close the file
    }
  }
else{
  Serial.println("Error writing to file/Card removed");
  }
}

// This is the function that the interrupt calls to increment the rotation count
void isr_rotation () {
if ((millis() - ContactBounceTime) > 15 ) { // debounce the switch contact.
  Rotations++;
  ContactBounceTime = millis();
  }
}

```

When any wind information and interrupts are commented out, I have no problem at all with writing to SD card and getting the correct data from the accelerometer and sht10. I must be doing something wrong with the interrupt, but I'm not sure. I've read to not include any serial prints, delays, keep em short, etc. and it works alone. It crashes right after running the setup (before it can serial print any information), which makes me believe it's something with the interrupt. I've tried commenting out noInterrupts() and it returns trash data for rotations, so that's not usable. In case it's important, the memory usage is in the 60% range, so that shouldn't be relevant.

Thanks for any help or advice you have.

EDIT: After totally removing the interrupt() and noInterrupts() portion, I get trash data for rotations that changes depending on the debounce timing (higher debounce limit=fewer triggered rotations). I seem to get a constant Rotations range of 20-23 that does pretty accurately depict how many rotations I add (for example spinning 8 times gets me around 30). I also prettied it up the code a little bit.

# Answer
Your basic flaw is that you turn interrupts off (prior to commenting those lines out), and then attempt to use the SD card which almost certainly will want to use interrupts.

Your technique of turning interrupts on, and then doing a big delay, is not one I like. I comment on that sort of thing in my page about interrupts, in particular in reply #10. The essence of that reply is:

---

## Timing an interval

I have seen example code suggesting you count things for a second by turning interrupts off for a second and then on again. I don't recommend this, because for one thing, you can't do serial prints if interrupts are off.

### Example (not recommended):

```
volatile unsigned long events;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  events++;
  }   // end of eventISR

void setup ()
  {
  Serial.begin(115200);
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }   // end of setup

void loop ()
  {
  events = 0;       // reset counter
  interrupts ();    // allow interrupts
  delay (INTERVAL); // wait desired time
  noInterrupts();   // stop interrupts

  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of loop

```

(This is effectively what your code does).

That may work for simple situations, but turning interrupts off means that the Serial prints won't work until they are turned on again (which they may not be in a more complex sketch).

It is better to use the millis() result and just detect when the time limit is up.

### Improved sketch:

```
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

```

In loop() here we wait for the interval (1 second in this case) to be up, otherwise we return, effectively doing nothing. You could of course do other things instead of just returning.

If the time is up we display the count.

If counting is not currently active (and presuming we want it to be active) we remember the start time, reset the counter to zero, and let it start counting up.

That code seemed to work OK up to 100 kHz, although the counts were getting a bit inaccurate. You can do more precise timings by using the hardware counters / timers. Details at my Timers and counters page.
> 0 votes

---
Tags: interrupt, sd-card
---


# Question
Title: Arduino with Ultrasonic sensor integrated but vibration motor not working according to the code
Here's my code after editing the measurement had error. Now the ultrasonic measurement is working but the vibration motor is not vibrating.

```
#define trigPin1 8
#define echoPin1 7
#define motorPin1 13

long duration, distance, UltraSensor;

void setup()
{
  Serial.begin(9600); // to use the serial monitor.
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  //pinMode(motorPin1, OUTPUT);

}

void SonarSensor(int trigPin, int echoPin)
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) / 29.1;
  delay(100);
}

void loop()
{
  SonarSensor(trigPin1, echoPin1);
  UltraSensor = distance;
  Serial.print(distance); // print out the distance on Serial Monitor
  Serial.println("cm");
//
  if (distance <= 60 && distance >= 45) // Checking the distance, you can change the value
  {
    digitalWrite(motorPin1, HIGH); // motor on
    delay(200);
    digitalWrite(motorPin1, LOW); // motor off
    delay(200);
  }
  else if(distance < 45 && distance >=30)
  {
    digitalWrite(motorPin1, HIGH); // when greater than 100cm
    delay(100);
    digitalWrite(motorPin1, LOW);
    delay(100);
  }
  else if(distance < 30)
  {
   digitalWrite(motorPin1, HIGH);
   delay(50);
   digitalWrite(motorPin1, LOW);
   delay(50);
  }
  else
  {
    digitalWrite(motorPin1, LOW);
  }
}

```

# Answer
> 0 votes
I think you have to uncomment the line that defines the motor as an output device.

//pinMode(motorPin1, OUTPUT);

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


title: Electric meter pulse counting using LLC

text:
# Question
Title: Electric meter pulse counting using LLC
I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.

http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/ https://jonarcher.info/2014/03/arduino-based-electricity-monitor/

And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.

But I wanted to have a different setup, and what I am thinking is:

1. inside the electric meter, tap into the blinking LED
2. From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
3. From the LLC, connect it to the Arduino
4. Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?

If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

# Answer
> 0 votes
When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)

A good way to get electrical isolation is with an opto-coupler, also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.

You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-uno, led, voltage-level, electricity, voltage-protection
---


title: Pro Mini atmega168 voltage woes

text:
# Question
Title: Pro Mini atmega168 voltage woes
I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?

I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

# Answer
> 2 votes
Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.

---
Tags: arduino-pro-mini, battery
---


# Question
Title: RGB LED strip green LEDs cannot be dimmed to less than 50%
I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs. They cannot be dimmed to less than 50%, because they will simply turn off.

I have this test code in my setup:

```
Serial.write("dimming green test started");
for(int x = 255; x > 0; x--) {
    analogWrite(greenPin,x);
    Serial.write(" - g:");
    Serial.print(x);
    delay(6);
  }
  Serial.println();
  Serial.write("dimming green test done");
  Serial.println();

```

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable. I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.

**Are green LEDs not dimmable? Or is this just an optical effect?**

(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V)

# Answer
> 2 votes
`analogWrite` only works on pins that support PWM. Those are the pins with the `~` next to it.

On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.

---
Tags: arduino-uno, led, led-strip
---


# Question
Title: simultaneously read 16 hall sensor and maximum current allowed by Arduino
My question is about maximum current allowed by Arduino.

I know it's 200mA in Arduino and 40mA in every pin (lower in arduino mini). Just wondering if simultaneously read 16 hall sensor (than can be all activated at the same time) is too much. My calculation is 200 / 16 = 12.5 mA máximum current I can drive to a pin from a sensor, but it's enough to read the sensor? Specs from 3144 hall sensor says it outputs 25mA when activated. Can I put a resistante between output's sensor and Arduino pin?

I'm planning to use Arduino mini and sensor hall 3144.

Sorry for my english, and thanks in advance!

p.s: The original idea was read all 64 sensors with one Arduino, but breaking it into several arduinos is easiest as my electronics knowledge is seriously limited :)

# Answer
Since this sensor doesn't need to be driven directly from a pin, the maximum current for one pin is not important here. The hall sensor uses two of it's pins as supply voltage. The output pin is an Open-Collector pin. So it will be connected to GND trough a transistor depending on the magnetic field. If you use an external pullup resistor (as connection between OUTPUT and positive supply voltage), you get somewhat like a voltage divider. Since the hall sensor seems to behave as a switch, there will only be two possible states. When the magnetic field is low, the transistor doesn't let the current flow. The pullup resistor can pull the pin to the positive supply voltage (5V -\> 1 as digital value). If the magnetic field is high enough, the transistor will open the connection to GND. Now a maximum of 25mA of current can flow throw it to GND. The voltage of the pin is now determined by the voltage divider the transistor and the pullup resistor build. You can calculate the virtual "resistance" of the transistor in this state with Ohm's law

> R = U/I

(R is resistance, U is voltage and I is current) With 5V supply voltage and 25mA current you get a resistance of 200 Ohm. Since you just want to use the sensor as a switch, you only have to ensure, that the pin cannot be pulled to a significantly greater value than 0V. **So grab a resistor, that is significantly higher than 200 Ohm and use it as pullup resistor.** Keep in mind, that you always must use the pullup resistor with the supply voltage, that runs the Arduino. A higher voltage can fry the Arduinos components.

Then you connect this pin to a digital pin of the Arduino, which you configure as INPUT. In this state the pin has a high impedance, so that the current, that flows into it, is really small (it CAN source 25mA, but it does not have to. The current depends on your external circuit). So this isn't something you have to bother about.

This leaves us with the supply current, that the sensor needs to work. In the datasheet it says, that at a supply voltage of 8V the supply current is at maximum 9mA. For 16 sensors this gives us a total of 144mA, which is still comfortable inside the 200mA the Arduino can provide. So you should be able to drive all of them safely.

That said, if you want to add more components, that draw current, it might be better so source the current you need not over the Arduino but directly from your power source (if this is possible for you). Depending on the current you may need, it can also be good, to get an external voltage regulator (if your supply doesn't directly give you 5V), that can provide enough current.
> 2 votes

# Answer
As Gerben mentioned in a comment, you could set up a matrix of the sensors.

Since the 3144 effectively is a switch to ground (when the magnet comes close it pulls the data line low) you would wire them up like a keypad matrix. I recently did an answer about a keypad matrix. If you wanted 64 sensors you would only need 16 Arduino pins (8 for the rows and 8 for the columns).

The keypad matrix I described already drives the rows low, so that is the right polarity for the sensors. You would just need a pull-up for the columns, say 10k. The sensor then just has to sink 5/10000 amps (0.5 mA) which is well within spec.

The supply voltage to the sensors can be provided independently of the Arduino (however 5V would be reasonable). Since the sensors apparently usually consume 4.4 mA, then 64 would consume 282 mA, which is probably quite reasonable to supply from the Arduino 5V pin.

The diodes mentioned in the keypad matrix answer are probably a sensible precaution if you are likely to have more than one sensor activated at once.
> 0 votes

---
Tags: pins, current
---


# Question
Title: DS18B20 sending variable via Enthernet shield
I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.

I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:

```
sensors.requestTemperatures();
Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

```

I am sending data via ethernet shield, and important part is:

```
 client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

```

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...

Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

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

Use `dtostrf`

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

```

Note: `dtostrf` returns char pointer to `tStr`

The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values

```
Resolution     Arguments to dtostrf
 9             5, 1                  -nn.n
10             6, 2                  -nn.nn
11             7, 3                  -nn.nnn
12             8, 4                  -nn.nnnn

```

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in

For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use `5,1` for the format
> 3 votes

---
Tags: arduino-uno, data-type, ds18b20, convert
---


# Question
Title: Does the position in which you mount an IMU matter?
Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.

When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project? I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?

For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

# Answer
If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.

It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.

Bottom line is: if you can line them up, things get simpler.
> 4 votes

---
Tags: accelerometer, gyroscope, magnetometer, imu
---


# Question
Title: Pause running program using a pushbutton
I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?

Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?

Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.

Here's my code at the moment (sorry, it's not very clean):

```
int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}

```

# Answer
The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button. You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing. In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons. And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.
> 1 votes

# Answer
I would just use a pin interrupt and if the button is pressed the interrupt routine sets a flag (ie flag=1). Then in you loop just have a statement that says calls a function that is just a while loop which waits until flag variable is 0 again. The interrupt function just toggles the flag variable every time the button is pushed. So first time button is pressed the program loops and the second time the button is pressed program execution leaves the routine and goes back to your loop().
> -1 votes

---
Tags: arduino-uno, code-review
---


# Question
Title: How do I calibrate an ESC after connecting it to an Arduino?
I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.

Before we get there, here's the list of parts I'm using:

* Arduino Uno (genuine)
* 6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.
* Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.
* Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.

Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run. The code I'm using just sends the signal sent by the signal monitor.

I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.

Any pointers or things I could be doing wrong?

```
int value = 0;
Servo myservo;
void setup() {
    firstESC.attach(9);    // attached to pin 9
    Serial.begin(9600);
}
void loop() {
    myservo.writeMicroseconds(value);
    if(Serial.available())
        value = Serial.parseInt();    // Parse an Integer from Serial
}

```

and the one here:

```
#include <Servo.h>
#define MAX_SIGNAL 2000
#define MIN_SIGNAL 700
#define MOTOR_PIN 9
Servo motor;
void setup() {
    Serial.begin(9600);
    Serial.println("Program begin...");
    Serial.println("This program will calibrate the ESC.");

    motor.attach(MOTOR_PIN);

    Serial.println("Now writing maximum output.");
    Serial.println("Turn on power source, then wait 2 seconds and press any key.");

    motor.writeMicroseconds(MAX_SIGNAL);

    // Wait for input
    while (!Serial.available());
    Serial.read();

    // Send min output
    Serial.println("Sending minimum output");
    motor.writeMicroseconds(MIN_SIGNAL);
}
void loop() {
}

```

^shamelessly copied from the internet

# Answer
> 1 votes
The is a standard with RC connectors, that is Black always goes to ground white/orange goes to the signal and red/brown goes to 5V.

I don't know if you have made a typo, but you need to connect the white to D9 and the black to GND. Here is a instructables post, it describes using a brushed ESC step two reiterates the colour code standard.

You would also need a rotary encoder or shaft encoder to tell the distance moved, there are lots of ways to achieve this from simple(coded disk and IR arrangement) to custom made PCB add-ons.

# Answer
> 0 votes
Calibration can be done by sending the low throttle and high throttle values through the Serial monitor.Here's an instructable i have made using NODEMCU.Check this out.May be it helps.

---
Tags: arduino-uno, servo
---


# Question
Title: sending 16 bit command via SPI to a NCV7719 (half bridge)
I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?

```
#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  pinMode(10,OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(8,HIGH);
  SPI.begin();

}

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

  //pulling pin low to decide to write to device
  digitalWrite(10,LOW);

  //function to send information
  //truning on half bridge 4
  SPI.transfer(0000010000000000);
delay(500);
  //finish transfering data
  digitalWrite(10,HIGH);

}

```

# Answer
SPI writes in 8-bit bytes. So the writes need to look like this:

```
  SPI.transfer(0b00000100);  // first byte
  SPI.transfer(0b00000000);  // second byte

```

Possibly in the other order depending on which byte the device expects first.
> 1 votes

---
Tags: spi, h-bridge
---


# Question
Title: Trigger external interrupt on Arduino Uno R3 with an LED and a button
I want to cause the external interrupt on digital pin 2 (`PD2` on ATmega328). I have chosen *any logic change* mode. Here is my code:

```
void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}

ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

```

Here is how I connect things.

*NOTE:* I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

The problem is when I push the button no interrupt occurs. What am I doing wrong?

# Answer
> 1 votes
Pin 2 is pulled up by internal R then pulled up when button is pressed? Connect button to GND.

---
Tags: arduino-uno, interrupt
---


title: Why my loop stop working

text:
# Question
Title: Why my loop stop working
i have an arduino, an RTC (time), a DHT (humidity and temp sensor), oled screen (128x32 ; microoled 1306) and 4 relais ;

all seems to work perfectly for hours, but sometime (1 or 2 per day..) everything stop working ;

* screen i frozen on last info displayed
* relais stay stuck in a random position (somtimes turning everythings ON (on=LOW with thoses relay.))

i obviously made a mistake, but don t know what... what can cause a loop to stay stuck randomly ??? plz save me :)

**EDIT =\> A REWORK OF THAT TERRIBLE CODE AVAILABLE IN ANSWER, THE PROBLEM IS STILL THERE**

```
// GND GND
// A4 SCL
// A5 SDA
// VCC  5V

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: A7+

// YL-39 + YL-69 humidity sensor
const byte humidity_sensor_pin = A1;
const byte humidity_sensor_vcc = 6;

// ecran SDA / SDL
// RELAIS Pin D8
// RELAIS2 Pin D9
// RELAIS3 Pin D10
// RELAIS4 Pin D11

// Relais reboot D5 ?

#include <SimpleDHT.h>
#include <Wire.h>
#include "U8glib.h"
#include "RTClib.h"

const int pinDHT11 = 7;
 SimpleDHT11 dht11;

RTC_DS1307 RTC;
U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);

const int relay = 8; // Light
const int relay2 = 9; // Wind
const int relay3 = 10; // Heat
const int relay4 = 11; // Humidity

// Time Variable
DateTime InitTime ;
int InitHour;

const int startHour = 20;
const int startMin = 01;
const int startTime = startHour *100 + startMin;
const int endHour = 8;
const int endMin = 01;
const int endTime= endHour *100 + endMin;
const int maxWind = 5;
const int startWind = 05;
int lastWind ;

const int dayMinTemp = 18;
const int dayMaxTemp = 20;
const int nightMinTemp = 16;
const int nightMaxTemp = 19;

const int minhum = 50;

void drawInit(DateTime InitD){
String text = String(InitD.day());
  text += " ";
text += String(InitD.month());

String text2 = String(InitD.hour());
  text2 += ":";
text2 += String(InitD.minute());
text2 += ":";
text2 += String(InitD.second());

 u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);

}
void drawTemp(float temp, int hum, int nowT){
String text = "Temp: ";
  text += temp;
    text += "*C";
String text2 = "Hum: ";
  text2 += hum;
    text2 += "% :";
    text2 += nowT;

 u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void draw(String staT, String endT, String nowT){
String iotxt;
if (digitalRead(relay) == LOW){iotxt="On";}else{iotxt="Off";}

String text = "S: ";
  text += staT;
  text += " E: ";
  text += endT;
String text2 = "H: ";
  text2 += nowT;
//  text2 += " L: ";
//  text2 += iotxt;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void drawerror(String error){
  String text = "err mod: ";
  text += error;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);

}

void draw2(int nowTime){
  String iotxt;
  String hottxt;
  String lumtxt;
    String humtxt;

if (digitalRead(relay) == LOW){lumtxt="On";}else{lumtxt="Off";}
if (digitalRead(relay2) == LOW){iotxt="On";}else{iotxt="Off";}
if (digitalRead(relay3) == LOW){hottxt="On";}else{hottxt="Off";}
if (digitalRead(relay4) == LOW){humtxt="On";}else{humtxt="Off";}

String text = "Hot: ";
  text += hottxt;
  text += " Lum: ";
  text += lumtxt;

String text2 = "Hum: ";
  text2 += humtxt;
  text2 += " Win: ";
  text2 += iotxt;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void setup () {

 pinMode(relay, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 pinMode(relay4, OUTPUT);
 digitalWrite(relay, HIGH);
 digitalWrite(relay2,HIGH);
 digitalWrite(relay3,HIGH);
 digitalWrite(relay4,HIGH);

    Serial.begin(9600);
    Wire.begin();

    if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  RTC.begin();

   DateTime now = RTC.now();
 InitTime = now ;
InitHour =  now.hour()*100 + now.minute();
}

void loop () {

 byte temperature = 0;
  byte humidity = 0;

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

    u8g.firstPage();
  do {
    drawerror("DHT");
  } while( u8g.nextPage() );
delay(3000);

    return;
  }else{

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

// Relay Chaleur
if (digitalRead(relay)==LOW){
if((int)temperature < dayMinTemp){
   digitalWrite(relay3,LOW);
   //  Serial.print("HEAT : On");

  }else{digitalWrite(relay3,HIGH);
     //  Serial.print("HEAT : Off");
}
  }else{
    if((int)temperature < nightMinTemp){
   digitalWrite(relay3,LOW);
     //   Serial.print("HEAT : On");

}else{
      digitalWrite(relay3,HIGH);
   //  Serial.print("HEAT : Off");

      }
    }
// fin relay chaleur

  if (! RTC.isrunning()) {
    drawerror("RTC");}else{

   DateTime now = RTC.now();

int nowTime= now.hour()*100 + now.minute();

// § WIND
if(now.minute() >= startWind && now.minute() <= startWind+maxWind ){
      digitalWrite(relay2,LOW);
     // Serial.println("Wind ON");
      lastWind = nowTime;

  }else if(now.minute()>startWind+5 || now.minute()<startWind){
          digitalWrite(relay2,HIGH);
    //  Serial.println("Wind OFF");
      }

// § END WIND

// START humidity
if(int(humidity)<minhum){
      digitalWrite(relay4,LOW);

  }else{    digitalWrite(relay4,HIGH);
  }
//
// § LIGHT START

if(startTime<endTime){
  if(startTime <= nowTime && endTime >= nowTime){
      digitalWrite(relay,LOW);
    //  Serial.println("Light ON");
  }else{
      digitalWrite(relay,HIGH);
//      Serial.println("Light OFF");
}}else{
  if(endTime <= nowTime && startTime >= nowTime){

      digitalWrite(relay,HIGH);
  //    Serial.println("Light OFF");
  }else{
          digitalWrite(relay,LOW);
    //  Serial.println("Light ON");
    }}

//  if(nowTime >= startTime && nowTime <= 2359){
//            digitalWrite(relay, LOW);
//            Serial.println("Light ON");
//            }
//       else if(nowTime  < endTime ){
//            digitalWrite(relay, LOW);
//            Serial.println("LIGHT ON");}
//       else if(nowTime  >= endTime && nowTime  < startTime){
//            digitalWrite(relay, HIGH);
//            Serial.println("Light OFF");}
//      }
      // § LIGHT END

u8g.firstPage();
  do {
    draw(String(startTime),String(endTime),String(nowTime));
  } while( u8g.nextPage() );
delay(3000);

u8g.firstPage();
  do {
    drawInit(InitTime);
  } while( u8g.nextPage() );
 delay(3000);

u8g.firstPage();
  do {
    draw2(nowTime);
  } while( u8g.nextPage() );
 delay(3000);
u8g.firstPage();
  do {
    drawTemp(float(temperature), int(humidity),int(NowT));
  } while( u8g.nextPage() );
 delay(3000);
    }}}

```

# Answer
While it makes logical sense to use the `String` type to hold strings of text, it's really a very poor choice for a low-RAM device like an Arduino.

You are using the string concatenation operator (`+`) a lot. The `String` type handles this by grabbing a new block of RAM that is equal to the sum of the 2 strings you are concatenating, puts the new string in that RAM, and marks the previous block of RAM that held one of the strings as empty and available for re-use.

The problem is that when you keep concatenating bits to the same string variable, it has to keep finding longer and longer continuous blocks of RAM into which to put the new string. All the previous blocks that are "available" for use, are also too short, as they are all the length of previous strings prior to your new, longer string requirement.

As @Majenko noted, this means your RAM is "swiss cheese" -- full of holes that can't be used by the program for more strings.

One solution is to avoid the `String` variable type and instead use what are called *C-Style Strings* \- arrays of `char` type. It's a whole new, old world of doing things, and can be more challenging than the `String` type, but it has a distinct advantage of not shredding the device's RAM.

The *C-style string* world is ruled by monsters like `strnlen()` and `strncpy()`, and making sure you have remembered to allocate enough RAM at the start of your program, and making sure you null-terminate your array.

Of the myriad tutorials and descriptions on using C-style strings, one is at https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
> 3 votes

# Answer
after rewrite all code, rewire all relay, bypass the relay card (using another relay), the problem is still there, but i finally found other people with the same problem, and the solution seem to be adding a "snubber" on each relay, i m waiting for it and will give u a return if it work : link to arduino forum for a common problem
> 0 votes

---
Tags: arduino-nano
---


title: Stop Arduino Timer after some seconds

text:
# Question
Title: Stop Arduino Timer after some seconds
I'm building a basic program that when a button is pressed, a buzzer comes on.

I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).

Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.

```
// Setting The Pin Numbers
const int touchsensor = 2;     // the number of the touchsensor pin
const int buzzer =  4;         // the number of the LED pin

// variables:
int touchsensorState = 0;      // variable for reading the touchsensor status

void setup() {
  // initialize the buzzer as an output:
  pinMode(buzzer, OUTPUT);
  // initialize the touchsensor as an input:
  pinMode(touchsensor, INPUT);
}

void loop() {
  // read state of the pushbutton value:
  touchsensorState = digitalRead(touchsensor);

  // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
  if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
  } else {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
  }
}

```

# Answer
You set a `timestamp = millis()` when the button is pushed and then you disable the buzzer only when `millis() - timestamp > timeout`

```
if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
    timestamp = millis();
}
if(millis() - timestamp > timeout) {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
}

```
> 2 votes

# Answer
You can time this with the `millis()` function. Refer to the BlinkWithoutDelay example from the Arduino IDE.

Then you set a timestamp, when the button is pressed:

```
if(touchsensorState == HIGH) timestamp = millis();

```

And then you are checking this timestamp against the current time:

```
if(millis() - timestamp > duration){
  digitalWrite(buzzer, HIGH);
} else {
  digitalWrite(buzzer, LOW);
}

```

`duration` is the timespan during which the buzzer should stay on after the button was released. If you want to turn it of, regardless of the button state, you can add a boolean flag to your if-statement, to set the timestamp only, when the button was pressed first:

```
if(!button_pressed && touchsensorState == HIGH){
  timestamp = millis();
  button_pressed = true;
}

```

In this case you have to reset the `button_pressed` variable to `false`, when you are turning of the buzzer in the `millis()`-else-statement
> 0 votes

---
Tags: timers, arduino-yun, buzzer
---


title: Read CID from SD card with ESP8266

text:
# Question
Title: Read CID from SD card with ESP8266
I would like to get the serial numbers of SD cards, with follow code:

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

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

cid_t cid;  // *****at the top with the other globals (for get cid)

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println();

  // *****list all files in the card with date and size
  //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  //root.openRoot(volume);
  //root.ls(LS_R | LS_DATE | LS_SIZE);

  card.readCID(&cid);
  Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

}

void loop(void) {

}

```

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".

Also, I would like to get the complete CID like this:

```
CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

```

# Answer
> 0 votes
`cid_t` is a structure that has all sorts of information in it in different formats. The serial number (`psn`) is just a 32-bit unsigned integer. You can print it as hex by printing it as hex.

```
Serial.println(cid.psn, HEX);

```

If you want to get the raw data of the structure (which I assume may correspond to the raw data read from the card, but don't quote me on that) you can access the struct as 8-bit values:

```
uint8_t *p = (uint8_t *)&cid;
for (int i = 0; i < sizeof(cid); i++) {
    Serial.print("0x");
    Serial.print(p[i], HEX);
    Serial.print(" ");
}
Serial.println();

```

# Answer
> 0 votes
To print the serial number in hex Serial.println accepts a format parameter:

```
Serial.println(cid.psn, HEX);

```

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:

```
uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
Serial.println(*(cid+3), HEX); // print the 4th byte

```

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.

---
Tags: esp8266, sd-card
---


# Question
Title: Can't identify + or - in the 5v USB wall adapter, does it matter?
I want to power the UNO with the USB power adapter (the charger of a phone), the adapter delivers 5.0 volts and comes from the wall (in the photo a regulator is added). However, the legs of the USB adapter look the same, can I plug it to the wall indistinctly like I do when I charge the phone, or do I need to know which leg is + and which one is - ? (I don't have measurement equipment).

# Answer
Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).

The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.
> 4 votes

# Answer
It does not matter which orientation you plug it into the mains plug.

The power supply produces the same 5V regardless, and the USB plug has a fixed/standard polarity on the pinout.
> 2 votes

---
Tags: power, usb
---