# Question
Title: Arduino on breadboard, and then soldered using a board made on Eagle but won't work
So I'm looking to create an arduino clone to mount on one of my robots. I started off making the arduino on a breadboard, using the instructions found on Arduino's own website and I succeeded. It works as well, I've checked it with the "blink" project.

I then drew the schematic in Eagle:

Next, I created a board and routed it, giving the following result:

Finally, I transferred it onto a copper clad, soldered it, but it doesn't work. Tried pretty much everything I could think of but there seems to be something wrong and I cant work out what it is.

Can someone please help?

Hassan

# Answer
> 8 votes
I haven't worked out why it's "not working", but some comments on your PCB:

1. Your crystal is too far from the clock pins
2. Your crystal capacitors are most definitely too far from the crystal
3. There are no decoupling capacitors on your Vcc / AVcc pins

Your crystal should be right next to the pins on the chip that it is connected to, and the capacitors for it should be immediately next to that. The layout you have at the moment, if it actually works, will be radiating huge amounts of EMI and would immediately fail any emissions test you'd care to perform.

Without decoupling capacitors on the power pins the chip may not function properly.

**Edit: I have just found your main mistake**

You haven't linked the output of your regulator sub-circuit to Vcc. Power gets regulated but goes nowhere.

---
Tags: arduino-uno, pcb-design
---


title: Pro Mini Fuse Repair

text:
# Question
Title: Pro Mini Fuse Repair
It looks like I broke my Arduino (Compatible) Pro Mini board using AtmelStudio to change the fuses. I was having trouble with speed and using some basic sketches. For example, the LED blink was on for 2 seconds and off for 2 seconds instead of 1 second. I tried to change the fuses to Ext Clock + 65 ms, and now I can't use the thing at all. Cannot enter programming mode. Any ideas?

# Answer
Sounds like you broke your fuses.

You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it). If that doesn't work then the only way to fix it is with a "High Voltage Programmer".

Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898
> 1 votes

---
Tags: arduino-pro-mini, fuses
---


title: Sampling Rate of Arduino Uno

text:
# Question
Title: Sampling Rate of Arduino Uno
It might be a stupid question but, I am currently using Arduino Uno with the 16MHz processor, what is maximum sampling rate of data available to me if I want to read data of a sensors such as accelerometer?

# Answer
I have a page about I2C. The speed of I2C depends on a number of things, such as the I2C clock (which you can change) and also how many data bytes are in a "packet". There is a fixed overhead of the device address in each packet.

A broad rule-of-thumb would be around 4700 bytes per second for a single-byte payload at the default clock rate. You may also need to spend time asking for a reading. I haven't read the datasheet (which you didn't link).

The datasheet for the MPU6050 may give you more information about how fast it can respond.
> 0 votes

---
Tags: arduino-uno, analog-sampling
---


# Question
Title: Troubleshooting duplicate libaries (Arduino motor shield and stepper motor)
I have tried a software. It work flawless on the first laptop in a fresh install arduino IDE environment with the libraries I imported.

However when I copy the exact same program over. I get lot of errors and tried to clean up some of the old libraries from earlier programs. Then rerun the compiler; got even more errors and I am not sure what to do except completely clean everything including older libraries that I may need to keep around for older programs.

My includes are as following:

```
#include <AccelStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

```

Error from the Arduino IDE from the second laptop is as following:

```
Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

Invalid library found in C:\Users\B Family\Documents\Arduino\libraries\examples: C:\Users\B Family\Documents\Arduino\libraries\examples

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\libraries\Adafruit_Motor_Shield_V2_Library-master\utility/Adafruit_MS_PWMServoDriver.cpp:28: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWM(unsigned char, unsigned int, unsigned int)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::write8(unsigned char, unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::reset()'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::begin()'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::read8(unsigned char)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

libraries\utility\Adafruit_MS_PWMServoDriver.cpp.o: In function `Adafruit_MS_PWMServoDriver::Adafruit_MS_PWMServoDriver(unsigned char)':

C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: multiple definition of `Adafruit_MS_PWMServoDriver::setPWMFreq(float)'

libraries\Adafruit_Motor_Shield_V2_Library-master\utility\Adafruit_MS_PWMServoDriver.cpp.o:C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire/Wire.h:77: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling.

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

```

# Answer
The diagnostics tell you *exactly* what is wrong! You have multiple copies of the same library, probably because you installed it at different times from different places. The diagnostics even tell you which libraries are duplicates. Remove them and everything will work fine!

While we are at it: another source of duplicate definitions is badly written .h files that *define* (as opposed to only *declaring*) external symbols. Those you have to deal with as they happen, there is no global solution.
> 0 votes

---
Tags: arduino-ide, library, arduino-motor-shield, stepper
---


# Question
Title: I²C between 2 Arduinos sends additional receive event
I hooked up two Arduino Nanos with I²C, using 3 wires between GND \<-\> GND, A4 \<-\> A4, A5 \<-\> A5Ω and 1kΩ pull-up resistors on A4 & A5.

When I use the following code to communicate between them I get a weird empty receive event.

### master.cpp

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

#define SERIAL_BAUD 9600

#define I2C_SLAVE_ADDRESS 8

void setup () {
    Wire.begin();
    Serial.begin(SERIAL_BAUD);
}

void getFromState (unsigned char state) {
    Wire.beginTransmission(I2C_SLAVE_ADDRESS);
    Serial.print("s");
    Serial.print(Wire.write(state));
    Serial.print("e");
    Serial.print(Wire.endTransmission());
    delay(5000);
    Wire.requestFrom(I2C_SLAVE_ADDRESS, 2);
    int c = (unsigned char) Wire.read();
    Wire.flush();
    Serial.print("r");
    Serial.println(c);
    Wire.endTransmission();
}

void loop () {
    Serial.println("loop");
    getFromState(0);
    delay(10000);
    getFromState(1);
    delay(10000);
}

```

### slave.cpp

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

#define SERIAL_BAUD 9600

#define I2C_ADDRESS 8

unsigned char state = 0;

void requestEvent () {
    Serial.print("Request ");
    Serial.println(state);
    Wire.write(state);
}

void receiveEvent (int amount) {
    Serial.print("a");
    Serial.print(amount);
    Serial.print("r");
    state = (unsigned char) Wire.read();
    Serial.println(state);
}

void setup() {
    Serial.begin(SERIAL_BAUD);
    Wire.begin(I2C_ADDRESS);
    Wire.onRequest(requestEvent);
    Wire.onReceive(receiveEvent);
}

void loop() {
    delay(10);
}

```

### Serial Output Master After 1.5 Loops

```
loop
s1e0r0
s1e0r1
loop
s1e0r0
s1e0

```

### Serial Output Slave After 1.5 Loops

```
a1r0
Request 0
a0r255
a1r1
Request 0
a0r255
a1r0
Request 0
a0r255
a1r1

```

### Question

Why is there an empty receive event `a0r255` after every request? Is that normal? Am I doing something wrong? Is this some sort of hardware issue?

EDIT: I opensourced this project here, take a look if you want to!

# Answer
> 1 votes
The main culprit that is causing your problem is the second

```
Wire.endTransmission();

```

after your `requestFrom`. That causes the previous `startTransmission()` to be repeated with no data in it - thus giving you a second `receiveEvent` call with no data.

# Answer
> 2 votes
Your code has several issues:

For the master:

* Your I2C transactions should be quick and not delayed with `Serial.print()`s like in `getFromState()`
* You requested 2 bytes from the slave but you are reading only one from the buffer. `Wire.flush()` flushes the *outgoing* buffer, not the receive buffer. Use `while (Wire.read() != -1);` instead.
* Its also advised that you use `Wire.available()` to iterate through the receive buffer when `read()`ing; its how you check if anything was received at all and how many bytes were received.
* After using `requestFrom()`, you shouldn't call `endTransmission()`. Its self-contained.

For the slave:

* You should never call `Serial.print()` or `delay()` in `requestEvent()` or `receiveEvent()`; both functions are called from within ISRs and ISRs are meant to execute quickly and return.
* You are requesting 2 bytes from the slave in your master code, whereas your slave's `requestEvent()` writes only one byte.
* In `receiveEvent()`, again its best to use either `Wire.available()` to iterate through the RX buffer or you use the variable `amount`. This way, you read everything in the buffer; you can also flush the RX buffer like I showed you before.

Finally those delays are rather long; 10ms would do, if they are even needed at all.

---
Tags: i2c, arduino-nano
---


# Question
Title: Arduino Uno Constantly Resets with WiFi and 4 Relay Module
I am using an Arduino Uno with a 4 relay module (found here: http://www.amazon.com/JBtek-Channel-Module-Arduino-Raspberry/dp/B00KTEN3TM?ie=UTF8&psc=1&redirect=true&ref\_=oh\_aui\_detailpage\_o04\_s00) and an Adafruit CC3000 WiFi breakout board. However, once I connect the power source, the board just constantly cycles on and off, e.g. about 1 second per cycle. Could this have to do with too much current being drawn? Or that the current output of the digital pins isn't enough for all of the relay inputs? I'm new with this, but I am sure all of the pins are appropriately connected.

EDIT: If I use the USB connector (5V 1A) instead of the external power supply, I can connect 1 or 2 of the relays without problem, but must do so AFTER the wifi has already connected to the network, otherwise the wifi chip will never connect. Also, if I toggle the relays a few times, the wifi becomes unresponsive. I suspect a current issue maybe?. Any ideas? Thanks!

# Answer
It Will be a power issue you need to supply power direct to the relay modules VCC independent of the arduino, ensure the earths are connected and just use the digital outputs from the arduino to control the relays. Digital low normally switches the corresponding relay on.
> 1 votes

---
Tags: arduino-uno, wifi, relay, adafruit
---


# Question
Title: arduino quadcopter freezing while reading MPU6050/RC Receiver
I am trying to build an Arduino Flight controller. I have an MPU6050 (Gyroscope/Accelerometer) on board that is helping me configure my stabilization software. I also have my ESC's, and receiver plugged in to my Arduino. At some point during the code running, receiving and processing data from the Gyroscope and Receiver, the Arduino Uno freezes and I am not sure what is causing this problem. Any advice on how to fix this is greatly appreciated.

I am also getting FIFO overflows.

```
#include <Servo.h>
#include <Wire.h>
Servo esc1;
Servo esc2;
Servo esc3;
Servo esc4;
byte last_channel_1, last_channel_2, last_channel_3, last_channel_4, last_channel_5;
int receiver_input_channel_1, receiver_input_channel_2, receiver_input_channel_3;
int receiver_input_channel_4, receiver_input_channel_5;
unsigned long timer_1, timer_2, timer_3, timer_4, timer_5;
int reciever1, reciever2, reciever3, reciever4, reciever5;
int pastreciever1, pastreciever2, pastreciever3, pastreciever4, pastreciever5;
bool keycode;
int avg1, avg2, avg3, avg4;
int i;
const int avglen = 8;
int reciever1avg[avglen], reciever2avg[avglen], reciever3avg[avglen], reciever4avg[avglen];
int landingspeed = 1140;
int requestedspeed = 1400;
int autothrottle;
int motor1change, motor2change, motor3change, motor4change;
int yawchange, rollchange, nickchange;
int wait;
int set;
unsigned long interval=5000; // the time we need to wait
unsigned long previousMillis=0; // millis() returns an unsigned long.
unsigned long timer = 0;

//#define printdata

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;
#define OUTPUT_READABLE_YAWPITCHROLL
#define LED_PIN 13
bool blinkState = false;
bool dmpReady = false;
uint8_t mpuIntStatus;
uint8_t devStatus;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;
float euler[3];
float ypr[3];
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };
volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

float initialGyroX;
float initialGyroY;
float initialGyroZ;
const int autopilotkey = 1150;
int deg_x;
int deg_y;
int deg_z;
int requiredspeed;

void setup()
{
  //Arduino (Atmega) pins default to inputs, so they don't need to be explicitly declared as inputs
  PCICR |=  (1 << PCIE0);    // set PCIE0 to enable PCMSK0 scan
  PCMSK0 |= (1 << PCINT0);  // set PCINT0 (digital input 8) to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT1);  // set PCINT1 (digital input 9)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT2);  // set PCINT2 (digital input 10)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT3);  // set PCINT3 (digital input 11)to trigger an interrupt on state change
  PCMSK0 |= (1 << PCINT4);  // set PCINT4 (digital input 12)

  pastreciever1 = 1058;
  pastreciever2 = 1058;
  pastreciever3 = 1058;
  pastreciever4 = 1058;
  wait=0;
  set=0;
  keycode = false;

   esc1.writeMicroseconds(1000);
   esc2.writeMicroseconds(1000);
   esc3.writeMicroseconds(1000);
   esc4.writeMicroseconds(1000);

   esc1.attach(9);
   esc2.attach(6);
   esc3.attach(5);
   esc4.attach(3);

  #ifdef printdata
  Serial.begin(115200);
  #endif

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24;
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif
    mpu.initialize();

    #ifdef printdata
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
    #endif
    devStatus = mpu.dmpInitialize();
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setXAccelOffset(-2580);
    mpu.setYAccelOffset(2567);
    mpu.setZAccelOffset(1920);
    //Serial.println("The timer has begun.");
   if (devStatus == 0)
   {
    #ifdef printdata
        Serial.println(F("Enabling DMP..."));
        #endif
        mpu.setDMPEnabled(true);
        //Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        #ifdef printdata
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        #endif
        dmpReady = true;
        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)
        #ifdef printdata
        Serial.print(F("DMP Initialization failed (code "));
        #endif
        //Serial.print(devStatus);
        //Serial.println(F(")"));
    }
}

/*void ascend()
{
  Serial.println("Ascending.");
  for (autothrottle = landingspeed; autothrottle<requestedspeed; autothrottle++)
  {
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    delay(100);
    //gyro auto-level code??
    if ((avg3 != autothrottle)&&(avg3 < autothrottle));
    { }
    if ((avg3==requestedspeed)||(avg3>requestedspeed)||(avg1>1532)||(avg1<1472))
    {
      break; //go back to reciever input
    }
  }
}

void descend()
{
  Serial.println ("Descending.");
  for (autothrottle = avg3; autothrottle>landingspeed; autothrottle--)
  {
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    esc1.writeMicroseconds(autothrottle);
    delay(100);
    //Gyro autolevel code??
    do
    { } while ((avg3 != autothrottle)||(avg3>autothrottle));
    if ((avg3 == autothrottle)||(avg3<autothrottle)||(avg1>1532)||(avg1<1472))
    {
      break; //go back to reciever input
    }
  }
}*/

void loop()
{
   print_signals();
   motor1change=0;
   motor2change=0;
   motor3change=0;
   motor4change=0;

   if (wait==0)
   {
    delay(20000);
    //XBee.write the weather
   }
   wait=1;
   if (set==6)
   {
    initialGyroX = (ypr[1] * 180/M_PI)-0.34;//X
    initialGyroY = (ypr[2] * 180/M_PI)-0.5;//Y
    initialGyroZ = ypr[0] * 180/M_PI;//Z
    #ifdef printdata
    Serial.print ("STORED:");
    Serial.print("\t");
    Serial.print (initialGyroX);
    Serial.print("\t");
    Serial.print (initialGyroY);
    Serial.print("\t");
    Serial.println (initialGyroZ);
    #endif
    }

    //Automatic Take-off
    /*if ((set>=6)&&(average3<1300)&&(average4<1300)&&(average2<1300)&&(average1>1700))
    {
      Serial.println("Ascending..");
      ascend();
    }*/

   //Nick (Go forward/backward)------------------------------------------
   if(avg2 > 1532)
   {
    nickchange = (avg2 - 1532)/2;
    motor1change=motor1change+nickchange;
    motor2change=motor2change-nickchange;
    motor3change=motor3change-nickchange;
    motor4change=motor4change+nickchange;
   }
   if (avg2 < 1494)
   {
    nickchange = (1494-avg2)/2;
    motor1change=motor1change-nickchange;
    motor2change=motor2change+nickchange;
    motor3change=motor3change+nickchange;
    motor4change=motor4change-nickchange;
   }
   //Yaw-------------------------------------------------------------------
   if (avg1 > 1510)
   {
    yawchange = (avg1 - 1510)/2;
    motor1change=motor1change+yawchange;
    motor2change=motor2change-yawchange;
    motor3change=motor3change+yawchange;
    motor4change=motor4change-yawchange;
   }
   if (avg1 < 1470)
   {
    yawchange = (1470 - avg1)/2;
    motor1change=motor1change-yawchange;
    motor2change=motor2change+yawchange;
    motor3change=motor3change-yawchange;
    motor4change=motor4change+yawchange;
   }
   //Roll------------------------------------------------------------------
   if (avg4 > 1532)
   {
    rollchange = (avg4 - 1532)/2;
    motor1change=motor1change+rollchange;
    motor2change=motor2change+rollchange;
    motor3change=motor3change-rollchange;
    motor4change=motor4change-rollchange;
   }
   if (avg4 < 1472)
   {
    rollchange = (1472 - avg4)/2;
    motor1change=motor1change-rollchange;
    motor2change=motor2change-rollchange;
    motor3change=motor3change+rollchange;
    motor4change=motor4change+rollchange;
   }

    if (!dmpReady) return;
    while (!mpuInterrupt && fifoCount < packetSize) {
       }
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();
    fifoCount = mpu.getFIFOCount();
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        mpu.resetFIFO();
        #ifdef printdata
        Serial.println(F("FIFO overflow!"));
        #endif
    } else if (mpuIntStatus & 0x02) {
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
            //Print Data
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            /*Serial.print("XYZ:\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[2] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[0] * 180/M_PI);*/
        //#endif

//Stabilization----------------------------------------------------------------------------
if ((keycode==true)&&(avg3>autopilotkey))
{
   //X Axis----------------------------------------------------------
  if ((ypr[1]* 180/M_PI)>(initialGyroX + 2))
  {
    deg_x = initialGyroX - (ypr[1] * 180/M_PI);
    requiredspeed = (-4.5*deg_x);
    #ifdef printdata
    Serial.print ("GyroX++: ");
    #endif
    //Serial.println(requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
  if ((ypr[1]* 180/M_PI)<(initialGyroX - 2))
  {
    deg_x = initialGyroX - (ypr[1] * 180/M_PI);
    requiredspeed = (4.5*deg_x);
    #ifdef printdata
    Serial.print("GyroX--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
  //Y Axis------------------------------------------------------------
  if ((ypr[2] * 180/M_PI)>(initialGyroY + 2))
  {
    deg_y = initialGyroY - (ypr[2] * 180/M_PI);
    requiredspeed = (-4.5*deg_y);
    #ifdef printdata
    Serial.print ("GyroY++: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
   if ((ypr[2] * 180/M_PI)<(initialGyroY - 2))
  {
    deg_y = initialGyroY - (ypr[2] * 180/M_PI);
    requiredspeed = (4.5*deg_y);
    #ifdef printdata
    Serial.print ("GyroY--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
  //Z Axis--------------------------------------------------------------
  if ((ypr[0]* 180/M_PI)>(initialGyroZ + 4))//decrease
  {
    deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
    requiredspeed = (-1*deg_z);
    #ifdef printdata
    Serial.print ("GyroZ++: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change-requiredspeed;
    motor2change=motor2change+requiredspeed;
    motor3change=motor3change-requiredspeed;
    motor4change=motor4change+requiredspeed;
  }
  if ((ypr[0]* 180/M_PI)<(initialGyroZ - 4))//increase
  {
    deg_z = initialGyroZ - (ypr[0] * 180/M_PI);
    requiredspeed = (1*deg_z);
    #ifdef printdata
    Serial.print ("GyroZ--: ");
    #endif
    //Serial.println (requiredspeed);
    motor1change=motor1change+requiredspeed;
    motor2change=motor2change-requiredspeed;
    motor3change=motor3change+requiredspeed;
    motor4change=motor4change-requiredspeed;
  }
 }
}
  motor1change=constrain(motor1change, -100, 100);
  motor2change=constrain(motor2change, -100, 100);
  motor3change=constrain(motor3change, -100, 100);
  motor4change=constrain(motor4change, -100, 100);
  #ifdef printdata
   //Elevation------------------------------------------------------------
   Serial.print ("Motor Changes (1-4): ");
   Serial.print (motor1change);
   Serial.print (" ");
   Serial.print (motor2change);
   Serial.print (" ");
   Serial.print (motor3change);
   Serial.print (" ");
   Serial.println (motor4change);
  #endif
   if (avg3>1150)
   {
   esc1.writeMicroseconds((avg3+7)+motor1change);
   esc2.writeMicroseconds((avg3+7)+motor2change);
   esc3.writeMicroseconds(avg3+motor3change);
   esc4.writeMicroseconds(avg3+motor4change);
   }
}

//This routine is called every time input 8, 9, 10 or 11 changed state
ISR(PCINT0_vect){
  //Channel 1=========================================
  if(last_channel_1 == 0 && PINB & B00000001 ){         //Input 8 changed from 0 to 1
    last_channel_1 = 1;                                 //Remember current input state
    timer_1 = micros();                                 //Set timer_1 to micros()
  }
  else if(last_channel_1 == 1 && !(PINB & B00000001)){  //Input 8 changed from 1 to 0
    last_channel_1 = 0;                                 //Remember current input state
    receiver_input_channel_1 = micros() - timer_1;      //Channel 1 is micros() - timer_1
  }
  //Channel 2=========================================
  if(last_channel_2 == 0 && PINB & B00000100 ){         //Input 10 changed from 0 to 1
    last_channel_2 = 1;                                 //Remember current input state
    timer_2 = micros();                                 //Set timer_3 to micros()
  }
  else if(last_channel_2 == 1 && !(PINB & B00000100)){  //Input 10 changed from 1 to 0
    last_channel_2 = 0;                                 //Remember current input state
    receiver_input_channel_2 = micros() - timer_2;      //Channel 3 is micros() - timer_3
  }
 //Channel 3=========================================
  if(last_channel_3 == 0 && PINB & B00001000 ){         //Input 11 changed from 0 to 1
    last_channel_3 = 1;                                 //Remember current input state
    timer_3 = micros();                                 //Set timer_4 to micros()
  }
  else if(last_channel_3 == 1 && !(PINB & B00001000)){  //Input 11 changed from 1 to 0
    last_channel_3 = 0;                                 //Remember current input state
    receiver_input_channel_3 = micros() - timer_3;      //Channel 4 is micros() - timer_4
  }
  //Channel 4=========================================
  if(last_channel_4 == 0 && PINB & B00010000 ){         //Input 12 changed from 0 to 1
    last_channel_4 = 1;                                 //Remember current input state
    timer_4 = micros();                                 //Set timer_5 to micros()
  }
  else if(last_channel_4 == 1 && !(PINB & B00010000)){  //Input 12 changed from 1 to 0
    last_channel_4 = 0;                                 //Remember current input state
    receiver_input_channel_4 = micros() - timer_4;      //Channel 5 is micros() - timer_5
  }
}

//Subroutine for displaying the receiver signals
void print_signals()
{
  //Constrain
  reciever1 = constrain(receiver_input_channel_1, 1000, 2100);
  reciever2 = constrain(receiver_input_channel_2, 1000, 2100);
  reciever3 = constrain(receiver_input_channel_3, 1000, 2100);
  reciever4 = constrain(receiver_input_channel_4, 1000, 2100);
  reciever5 = constrain(receiver_input_channel_5, 1000, 2100);

  set=set+1;

  //AVG 1-4-----------------------------------------------------
  for (i=0; i<avglen-1; i++)
  {
    reciever1avg[i]=reciever1avg[i+1];
  }
  reciever1avg[avglen-1]=reciever1;
  avg1=0;
  for (i=0; i<avglen; i++)
  {
    avg1+= reciever1avg[i];
  } avg1/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever2avg[i]=reciever2avg[i+1];
  }
  reciever2avg[avglen-1]=reciever2;
  avg2=0;
  for (i=0; i<avglen; i++)
  {
    avg2+= reciever2avg[i];
  } avg2/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever3avg[i]=reciever3avg[i+1];
  }
  reciever3avg[avglen-1]=reciever3;
  avg3=0;
  for (i=0; i<avglen; i++)
  {
    avg3+= reciever3avg[i];
  } avg3/=avglen;

  for (i=0; i<avglen-1; i++)
  {
    reciever4avg[i]=reciever4avg[i+1];
  }
  reciever4avg[avglen-1]=reciever4;
  avg4=0;
  for (i=0; i<avglen; i++)
  {
    avg4+= reciever4avg[i];
  } avg4/=avglen;

  //Activate Autopilot
  if ((avg1==pastreciever1)&&(avg2==pastreciever2)
    &&(avg3==pastreciever3)&&(avg4==pastreciever4)&&(avg3>autopilotkey))
  {
    keycode=true;

  } else {keycode=false;}

  pastreciever1 = avg1;
  pastreciever2 = avg2;
  pastreciever3 = avg3;
  pastreciever4 = avg4;

```

# Answer
> 1 votes
This can happen in I2C sometimes. Basically the controller asks the sensors for data but there may be a bit error in the address. If so the sensor thinks you are talking to another chip, meanwhile your I2C master code waits for a reply, forever.

To fix this problem I would recommend the use of a watchdog timer. You can find the many examples online of how to set this up.

---
Tags: arduino-uno, mpu6050
---


title: Two or More Arduinos Handshaking

text:
# Question
Title: Two or More Arduinos Handshaking
research would show that there are numerous ways for two arduinos to talk to one another. But i was looking for a 'basic robust protocol' (..it doesn't sound basic ....I know!), to allow for two arduinos to talk to one another. The idea is , Arduino One(slave), is linked to a sensor and it reads data from the sensor and sends the data to Arduino Two on 'request' of the data by Arduino Two(master). Arduino Two would have to 'request' for the data from Arduino One, before it can read the data, if its available. A popular method on most sites (e.g https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/shaking-hands-part-1) is the use of the method below. I added a comment in search of clarity.

```
              void establishContact()
                     {  //This while loop does baffle me as it suggests that
                        //while there is nothing in serial, send A???
                        while (Serial.available() <= 0)
                       {
                         Serial.println("A");   // send a capital A
                         delay(300);
                       }
                     }

```

Now this method was used in handshaking between Arduino and processing. This method was called on the Arduino sketch. On the processing sketch, a method there just checks to see if 'A' was received. If it is, it reads in the data from serial, clears the serial buffer and writes 'A' back to Serial. I tried using this method on both of my arduinos as i felt it was 'basic' enough, but it didn't work at all. Does anyone has a better idea on how my arduinos could handshake?.

# Answer
> 2 votes
That while loop makes perfect sense. It' basically nudging the other end repeatedly until it replies with something - anything.

It's like sitting next to someone and poking them in the ribs every 300ms until they respond to you. Once they have responded you can then react to that response - be that to run very fast or tell them your important news.

The idea of handshaking like that is all to do with synchronisation. It ensures that both ends are ready for communication at the same time. Once synchronised you know, to a high probability, that what you are sending will be interpreted properly, and any replies you get back will be correct.

For basic communication between two Arduinos it's really not necessary.

The simplest call-and-response protocol involves Arduino A sending a single byte as a request and Arduino B replying with a single byte. It is up to you what those bytes represent, but ASCII letters for requests are ideal since they are understandable by a human, and numbers between 0 and 255 or -128 and +127 fit in to one byte (unsigned or signed respectively). Should you want bigger numbers being sent back then the reply will have to be delimited in some way. The simplest way of doing that is to format the response as ASCII data and send it with a CR and/or LF.

Something like:

```
if (Serial.available()) {
    char command = Serial.read();
    switch (command) {
        case 'T':
            Serial.println(temperature);
            break;
        case 'P':
            Serial.println(pressure);
            break;
    }
}

```

The master end then sends either 'T' or 'P' to request temperature or pressure. It then reads characters up to a line feed and stores them in a string which it can then convert into the desired numeric data type depending on what temperature and pressure are (integer or floating point).

---
Tags: arduino-uno, serial, arduino-due
---


title: Resistor on SPI Chip Select Pin

text:
# Question
Title: Resistor on SPI Chip Select Pin
I'm working on a modular CANBUS system for offroad racing. The idea right now is that the main Arduino (1284p at the moment) will be the only one connected to CANBUS, and other modules will have their own atmega's that will communicate with the master over I2C. They will not be physically on the same PCB, but will be physically within inches of each other. One module will have 8 MAX31865 IC's for interfacing with RTD's. The 31865 is not compatible with 5V microcontrollers, which right now we planned on running the Atmega's at 5V. Since the IC's are SPI, they can all share a MOSI, MISO, and CLK bus, so only two channels of a hex converter. For the Chip Select pin, would it be acceptable to use a resistor to decrease the voltage instead of using an additional 8 channels of hex converting?

What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's and just using a hex converter on SDA/SCL for the I2C communication to the master? What atmega I use for this is flexible.

# Answer
> 1 votes
> using a hex converter on SDA/SCL for the I2C communication to the master

I2C is not straight forward for level shifting. The I/O pins operate in *open drain* mode. That is, they don't send out any voltage of their own, they just pull down (like a button) the signals pulled up by resistors.

To level shift you have to read the state of those lines and then replicate that open drain connection to the signals of a different voltage.

But that is not all of course. I2C is a bidirectional protocol on a single data line. That means that data goes in both directions on the data line, so your level shifter has to be able to work in both ways.

There are special I2C level shifter chips available that do that exact thing. Some people sell them on breakout boards if you google around.

But with all that said, if you run your I2C bus purely at 3.3V it should work quite happily with both 3.3V and 5V devices. To do so you need to:

1. Use external pullup resistors (~3.3KΩ) to 3.3V
2. Disable the Arduino's idiotic use of the internal pullup resistors on the I2C pins (will need modification of the Wire library)

In short: It is possible to mix 3.3V and 5V I2C devices on a 3.3V I2C bus, but not on a 5V I2C bus.

# Answer
> 1 votes
> would it be acceptable to use a resistor to decrease the voltage

I don't see any big problem with using a voltage divider for chip select.

> What would the upsides/downsides be of using an atmega running at 3.3v for the module with the MAX31865's

At 3.3V you can only run at 13 MHz or less (so in practice, 8 MHz, unless you want to do a lot of fiddling around). This may or may not matter to you. At a lower voltage it uses less power which can be a plus, and you don't need to worry about level converters.

> and just using a hex converter on SDA/SCL for the I2C communication to the master?

Do you mean a level converter?

---
Tags: sensors, i2c
---


# Question
Title: Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0)
I am attempting to use an Arduino Uno+WiFly setup to send data to Thingspeak. I have tried a few libraries by now. But nearly all of them don't have a working WebClient example (WebServer works fine). I am using **Arduino 1.6.3 IDE** for Arduino UNO R3 + **Wifly-RN171 with Firmware 4.0**

The libraries I have tried (found through Google and forums):

1. https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries/Arduino

A ThingSpeak example is given but the execution stops when WiFly.begin() is called.
I tried WebClient and WebClient(Faster) examples from the same library and they are both stuck at the same line: WiFly.begin().
I believe this could be compatibility issue (WiFly firmware version/Arduino) but am unsure how to fix it.
**Note:** There seems to be a few versions for the SparkFun WiFly library from my search results. I tried whatever I found but only listed the latest one since if it is indeed a compatibility issue a newer version should be more likely to work.
2. https://github.com/Seeed-Studio/WiFi\_Shield

This one has a http example which I am attempting to use to send data to Thingspeak through http get/post. I am getting 'Bad Request' from their nginx server. Any help in the right direction will be much appreciated.
I hosted the sketch I tried here: codebender.cc/sketch:276925

p.s. I am not allowed to post \>2 links due to reputation so the last one is plain text.
p.s.s Can someone with higher reputation help me add the new tags {thingspeak, wifly, rn171}

# Answer
I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.

**My PHP Script**

```
<?php
$humidity=$_GET['humidity'];
$data = array("protocol"=>"v2", //Compose JSON stream
              "at"=> "now",
              "device"=>"DEVICE_NAME",
              "data" => array ("humidity" => trim($humidity)),
              "checksum" => "");
$data_string = json_encode($data);

$ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'carriots.apikey: YOUR_API_KEY',
    'Content-Length: ' . strlen($data_string))
);

$result = curl_exec($ch); //Send the stream

```

**Note**:

1. I switched to Carriots from ThingSpeak due to personal preference.
2. This is by no means a standard way to send stream to Carriots.This involves additional effort which slows down transmission of data but I decided that this setup will be enough for a hobby project.
3. A good understanding of how POST requests are built should allow me to skip the extra PHP script completely.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Do arduino librarys require the arduino to be connected to a computer?
The title pretty much explains my question. If I'm using a library for example one for an accelerometer does the arduino need to be connected to my computer because it's using a library? Or is the library uploaded to the arduino and there for can run with out a computer connected?

# Answer
> 1 votes
No. Arduino libraries (strictly speaking only the utilized parts) are permanently built-in parts of your compiled sketch. Effectively they are "statically linked" unlike the situation with modern RAM-based computer operating systems where compiled dynamic link library code may be separately loaded into memory for a program to call at runtime.

(This isn't even really a design choice, as the basic AVR Arduino's cannot load new program code into executable memory at runtime anyway - except by reflashing themselves like the bootloader does, which would be a bit slow compared to normal dynamic linking)

Of course if you have a library which is intended to perform *communication* with a computer, then that connection would probably be required for it to fully operate.

---
Tags: library
---


title: Why is my LED blinking?

text:
# Question
Title: Why is my LED blinking?
I have this simple push button schematic:

The idea is that the LED is on as long as the button stays pushed, with the switch closed.

The code is below:

```
int ledPin=10;
int switchPin=5;

void setup()

{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin,OUTPUT);

}
void loop()

{
  digitalWrite(ledPin,LOW);//DBG
  if (digitalRead(switchPin)==HIGH)
{
 digitalWrite(ledPin,HIGH);//DBG
 delay(500);
}
 if (digitalRead(switchPin)==LOW);
{
digitalWrite(ledPin,LOW);//DBG
delay(200);
}
}

```

As I keep the button pressed, **the LED blinks regularly**, instead of **staying on**. Why? I have tried using a capacitor between the switch and switchPin, with no change.

# Answer
> 1 votes
The beginning of your code in the loop:

```
void loop()  {
  digitalWrite(ledPin,LOW); //remove this line here
  if (digitalRead(switchPin)==HIGH)
{
     digitalWrite(ledPin,HIGH);//DBG
     delay(500);
}
 if (digitalRead(switchPin)==LOW);
 {
      digitalWrite(ledPin,LOW);//DBG
       delay(200);
     }
}

```

Before your first `if(digital read(switch pin) == HIGH)` you turn the LED off, and then you have a delay, which gives the blinking effect, remove that and it will not blink.

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


title: OLED with arduino?

text:
# Question
Title: OLED with arduino?
I recently bought a 0.96" Serial OLED Screen. I am not very experienced with this. I'm trying to display some text with the Arduino Uno. I installed the adafruit SSD1306 and GFX libraries but no luck. I've looked for tutorials for similar screens, but my screen has extra pins that others don't.

Mine has: `CS` `DC` `RST` `D1` `D0` `VCC` `GND`, others only have 4.

I don't know what each pin should be connected to. Does any one know how to get this to work? Is there a different library that I could use with this screen?

# Answer
> 2 votes
Yes, certain OLED screens do have different pinouts. For yours, the following would be your OLED's pinouts.

```
OLED ---- Arduino

D0-----------10

D1-----------9

RST----------13

DC-----------11

VCC----------5V

GND----------GND

```

The `CS` pin does not need to be plugged in.

As for the code, you can use this include from Smart Prototyping as an extra file, then have some simple code in your `loop` portion:

```
void loop()
{

LED_P8x16Str(23,0,"here is");

LED_P8x16Str(40,2,"example");

LED_P8x16Str(20,4,"text");

}

```

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


title: Keyboard input arduino speed

text:
# Question
Title: Keyboard input arduino speed
I have an Arduino clone of a Leonardo and I was just wondering how many keyboard commands I can send to the computer per second via USB. I'm not talking about the delay between send and receive (because that could vary between computer), I'm talking about the minimum possible time between something like stimulating a key press down and key press up as fast as possible.

# Answer
From my tests, it has been at least 1 millisecond, however, it can depend on what is running simultaneously on the Arduino.
> 1 votes

---
Tags: arduino-leonardo, time, keyboard
---


# Question
Title: Using an Arduino Weight Sensor, it fails to satisfy a while loop and I can't firgure out why
```
/*

 This example code uses bogde's excellent library: https://github.com/bogde/HX711
 bogde's library is released under a GNU GENERAL PUBLIC LICENSE

 The HX711 does one thing well: read load cells. The breakout board is compatible with any wheat-stone bridge
 based load cell which should allow a user to measure everything from a few grams to tens of tons.
 Arduino pin 2 -> HX711 CLK
 3 -> DAT
 5V -> VCC
 GND -> GND

 The HX711 board can be powered from 2.7V to 5V so the Arduino 5V power should be fine.

*/

#include "HX711.h"
#include <Servo.h>

float calibration_factor = -4050.0;

#define DOUT  3
#define CLK  2
Servo myServo;

HX711 scale(DOUT, CLK);

void setup() {
    Serial.begin(9600);
    Serial.println("Food Test");
    scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
    Serial.println("Readings:");
    myServo.attach(9);
    long zero_factor = scale.read_average(); //Get a baseline reading
    Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
    Serial.println(zero_factor);
}

void loop() {
    scale.set_scale(calibration_factor); //Adjust to this calibration factor

    if ((scale.get_units(), 1) <= 5) {
        Serial.print("whoa that is light, more food needed");
        myServo.write(90); // Open food hatch
        delay(2000);
        myServo.write(0);

        do {
            // Do nothing
            Serial.println("It is working somewhat");
            Serial.println(scale.get_units(), 1);
            delay(1000);
            // When weight exceeds 5 it should break out of this loop and go below
        } while ((scale.get_units(), 1) < 10);

        Serial.print("Closing the Hatch");
        myServo.write(0); // close food hatch
    } else {
        Serial.print("Something Went Wrong");
    }
}

```

Output:

```
It is working somewhat
10.6
It is working somewhat
10.9
It is working somewhat
10.5
It is working somewhat
6.9
It is working somewhat
-0.8

```

I will try to explain the problem as best as I can. I am using a scale library and the `scale.get_units()`,x returns a value as a float. The whole point is that a servo will open and stay open until a specified weight of 10lbs is reached. As seen in the do, while loop that's what I specify. It jumps into the if loop and then into the do while loop, and it continually prints out values of readings which is what I want. BUT, even when I reach over 10lbs it will not break out of the Do/while loop, essentially it never satisfies the while condition and I have no clue why. It prints out values over 10 but keeps reading values. I know the format isn't the best but any help would be greatly appreciated!!

# Answer
> 1 votes
It looks to me like you have an extra bracket in there that you don't want.

At the moment your structure is:

```
if {
    do {
    }
} while...

```

As it stands your sketch won't compile. The unbalanced brackets prevent it. Remove the excess one so that the `while` is associated with the `do` not the `if` and report back.

---

# Part II

The main cause of your problem is the strange bit of code you have in your `if`s and `while`s.

```
if ((scale.get_units(), 1) <= 5) {

....

} while ((scale.get_units(), 1) < 10);

```

In both of those you have the bit `(scale.get_units(), 1)` which is completely meaningless. The comma operator in C calls (or evaluates) both sides, and then returns the right hand side. So that calls `scale.get_units()` and then returns 1. 1 has always been, and will always be, less than 10, so the `while` never ends.

I don't know what you were hoping to achieve by having the `, 1` in there, but you should delete it from every place you have it.

---
Tags: serial, sensors
---


# Question
Title: Why is the result shorter than expected when I do longString.toCharArray(bigCharArr, longLength)?
I'm running this on a Particle Photon, but I think the issue is just me failing at C++. I'm trying to retrieve some JSON data from a HTTP API, convert it to JSON, and then extract a few values for display on the screen. I convert the String to a char array for the JSON parser, but it seems to only grab the first 10 characters of the String (unless I manually set length to a number shorter than 10), and then of course, the JSON parser fails.

Here's the relevant bit of code:

```
int str_len = response.body.length() + 1;
tft.print("Length: "); tft.println(str_len);
char char_array[str_len];
response.body.toCharArray(char_array, str_len);

```

`response.body` is a big JSON string, but `char_array` is always just the first 10 characters of it: `{"metadata`

Another thing I noticed just now that might be related, `str_len` is usually reported to be ~500 characters, but when I hit the same URL in a browser it ends up more like ~1500 characters. Neither are pretty-printed, so I'm not sure what the discrepancy is.

Here's my complete code, except I removed the base64'd username and password from the Authorization header:

```
#include "HttpClient/HttpClient.h"
#include "SparkJson/SparkJson.h"
#include "Adafruit_mfGFX/Adafruit_mfGFX.h"
#include "Adafruit_SSD1351_Photon/Adafruit_SSD1351_Photon.h"

// OLED - You can use any (4 or) 5 pins
#define sclk A3
#define mosi A5
#define dc   D7
#define cs   A2
#define rst  D5

// Color definitions
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

// Option 1: Hardware SPI - uses some analog pins, but much faster
Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, rst);

// Option 2: Software SPI - use any pins but a little slower
//Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, mosi, sclk, rst);

HttpClient http;

// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
    //  { "Content-Type", "application/json" },
    { "Authorization", "Basic <snip>" }, // base64encode(username:password)
    { "Accept" , "application/json" },
    { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup(void) {

    tft.begin();

    tft.fillScreen(BLACK);
    tft.setCursor(0,0);
    tft.setTextSize(0);
    tft.setTextColor(WHITE);

    // http://twcservice.mybluemix.net/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US
    request.hostname = "twcservice.mybluemix.net";
    request.port = 80;
    request.path = "/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US";
    //request.body = "{\"key\":\"value\"}";
    http.get(request, response, headers);

    tft.print("Status: ");
    tft.println(response.status);

    //tft.println("Response Body: ");
    //tft.println(response.body);

    int str_len = response.body.length() + 1;
    tft.print("Length: "); tft.println(str_len);
    char char_array[str_len];
    response.body.toCharArray(char_array, str_len);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(char_array);

    if (root.success()) {
        tft.print("Current Temperature: ");
        const char* temp = root["observation"]["imperial"]["temp"];
        tft.println(temp);
    } else {
        tft.setTextColor(RED);
        tft.println("parseObject() failed");

        tft.setTextColor(GREEN);
        uint32_t freemem = System.freeMemory();
        tft.print("Free memory: ");
        tft.print(freemem/1024);
        tft.println("k");

        tft.setTextColor(WHITE);
        tft.println(char_array);

        tft.setTextColor(CYAN);
        tft.println(response.body);
    }
}

void loop() {

}

```

The actual printout on the screen is smething like

```
Status: 200
Length: 501
parseObject() failed
Free memory: 59k
{"metadata
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_

```

Finally, here's an example of the JSON response I'm trying to parse:

```
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_time_gmt":1460310025,"obs_time":1460307900,"obs_time_local":"2016-04-10T13:05:00-0400","wdir":160,"icon_code":26,"icon_extd":2690,"sunrise":"2016-04-10T07:06:23-0400","sunset":"2016-04-10T20:11:13-0400","day_ind":"D","uv_index":3,"uv_warning":0,"wxman":"wx4400","obs_qualifier_code":null,"ptend_code":2,"dow":"Sunday","wdir_cardinal":"SSE","uv_desc":"Moderate","phrase_12char":"Cloudy/Wind","phrase_22char":"Cloudy/Wind","phrase_32char":"Cloudy/Wind","ptend_desc":"Falling","sky_cover":"Cloudy","clds":"OVC","obs_qualifier_severity":null,"vocal_key":"OT48:OX2690","imperial":{"wspd":20,"gust":24,"vis":10.000,"mslp":1018.7,"altimeter":30.09,"temp":48,"dewpt":27,"rh":43,"wc":41,"hi":48,"temp_change_24hour":11,"temp_max_24hour":44,"temp_min_24hour":27,"pchange":-0.10,"feels_like":41,"snow_1hour":0.0,"snow_6hour":0.0,"snow_24hour":0.0,"snow_mtd":1.2,"snow_season":21.3,"snow_ytd":21.3,"snow_2day":0.7,"snow_3day":0.8,"snow_7day":0.9,"ceiling":7400,"precip_1hour":0.00,"precip_6hour":0.00,"precip_24hour":0.00,"precip_mtd":1.10,"precip_ytd":11.76,"precip_2day":0.29,"precip_3day":0.30,"precip_7day":0.96,"obs_qualifier_100char":null,"obs_qualifier_50char":null,"obs_qualifier_32char":null}}}

```

Any idea what's going on?

# Answer
> 1 votes
It turns out that the HttpClient library has a fixed response length limit of 1024 bytes and whatever it was doing after it hit that limit is what caused all of the trouble.

Forking the library and increasing the limit as recommended at https://community.particle.io/t/issues-with-string-char-array-length-json-parsing/21980 solved the issue.

---
Tags: string, array, http
---


title: voltage output at digital pins vs. load

text:
# Question
Title: voltage output at digital pins vs. load
I am trying to convert the signal from digital pin 2 on my Uno to 3.3V. I set up a voltage divider with 3 x 1000 ohm resistors. When connected to ground and 5V the divider circuit generates 3.3V correctly, with a calculated input current of 1.7mA. However I connect it to a digital pin, the digital pin voltage drops from 4.8V to .37V. I thought the digital pins were to support 40mA, I was assuming 40mA at the 5V supply voltage. Is my Uno malfunctioning?

Thanks

# Answer
Just figured out I didn't have the pin mode set, it works fine now, thanks.
> 1 votes

---
Tags: arduino-uno, pins, voltage-level
---


# Question
Title: Managing 80 ~ 90 accelerometers with Arduino
If one were to want to keep track of data from 80 - 90 accelerometers using arduino, what would be the best way to go about this challenge?

# Answer
> 1 votes
1) Use the I2C address select inputs as an "enable". If you run out of I/Os before running out of bus time, drive the enables from an I/O expandander. If your accelerometers are SPI, drive or use the expander to drive the chip selects.

2) Use a tree of slave MCUs (Arduino or otherwise) reading a number of accelerometers, extracting and batching the useful data, and reporting only that upstream to a master. Probably use whichever of I2C or SPI your accelerometers are not using (SPI can be much faster, so hopefully that).

Some accelerometer / gyro parts have an on-board processor which you may be able to program to do some of the data extraction for you.

You could also consider using an FPGA to collect the data. A commonly available one with enough I/O pins to have a dedicated connection to each accelerometer (and so read them all in parallel) would probably also have the internal resources to implement an Arduino-class soft core processor, if not better.

---
Tags: accelerometer, multiplexer
---


title: Controlling HC-05 from a sketch

text:
# Question
Title: Controlling HC-05 from a sketch
Hi I am making a sketch and circuit with a HC-05 BT receiver to upload sketches via Bluetooth to my Uno. This requires giving AT commands from the sketch. I would like to see the response from the HC-05 but so far I haven't got it to work. I want to view the response via the standard serial connection and serial monitor. The commands from the sketch are not being recognized by the HC-05 and I would like to see the HC-05 response to troubleshoot it.

If you have a minute would you mind giving me a tip? I would greatly appreciate it. See the ArdProgramModeOn() and Off functions at the end.

Thanks

```
int ATModePin = 2;  // pin for HC-05 AT comand mode
int HC05powerPin = 3;  // pin for powering HC-05 when high
char btserialrx;  // data through from bt connection
char myChar; // data through serial port connection
#define rxPin 8 // HC-05 bt serial pin
#define txPin 9 // HC-05 bt serial pin

#include <**SoftwareSerial**.h>
**SoftwareSerial** btSerial(rxPin, txPin); // RX, TX

void setup() {
  pinMode(ATModePin, OUTPUT);
  pinMode(HC05powerPin, OUTPUT);
  pinMode(5, OUTPUT);
  **Serial**.begin(9600);
  btSerial.begin(115200);

  digitalWrite(HC05powerPin, HIGH);
  delay(2000);
  }

void loop() {

  while (btSerial.available()) {
    btserialrx = btSerial.read();
  }

  if(btserialrx == '1'){  // change to upload / reset mode
    **Serial**.println("switching to upload mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
  else if (btserialrx == '2'){  // change to normal mode
    **Serial**.println("switching to normal mode");
    ATModeOn();
    ArdProgramModeOn();
    ATModeOff();
    btserialrx = '0';
  }
}

void ATModeOn(){  // reset HC-05 and change HC-05 to AT Command Mode
  digitalWrite(5, HIGH);
  digitalWrite(ATModePin, HIGH); // AT command mode on upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ATModeOff(){  // reset HC-05 and return HC-05 to std. operation
  digitalWrite(5, LOW);
  digitalWrite(ATModePin, LOW); // AT command mode off upon reset
  delay(2000);
  digitalWrite(HC05powerPin, LOW); // hc-05 off
  delay(2000);
  digitalWrite(HC05powerPin, HIGH); // hc-05 on
  delay(2000);
}

void ArdProgramModeOn(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,0");  // Arduino reset mode upon HC-05 connection for programming
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    **Serial**.print(myChar);
  }
  delay(4000);
}

void ArdProgramModeOff(){
  btSerial.println("AT");
  delay(1000);
  btSerial.println("AT+POLAR=1,1");  // Arduino normal mode no reset upon HC-05 conection
  delay(1000);
  btSerial.println("AT+POLAR?");  // Arduino reset mode upon HC-05 connection for programming
  delay(2000);
  while (btSerial.available()) {  // Show responses from HC-05
    myChar = btSerial.read();
    **Serial**.print(myChar);
  }
  delay(4000);
}

```

# Answer
Unless you've manually set the btSerial speed, you need to be at the default for AT commands which is 38400 -\> btSerial.begin(38400);

If you want to read regular Serial communication, you'll need to monitor 9600 -\> btSerial.begin(9600);

If you are unable to to send commands, I feel as if you wouldn't have changed the default speeds.

I used this link as a reference with my project: Modify The HC-05 Bluetooth Module Defaults Using AT Commands

Lastly, you didn't mention whether or not you soldered a jumper wire to PIN 32 for your ArdProgramOff/On. Another reference for you as well: DIY Arduino Bluetooth Programming Shield

Hope my answer helps! Good luck!
> 2 votes

---
Tags: sketch, hc-05
---


# Question
Title: Where can I find a hardware manual (or documentation) for Arduino Uno & ATMega328P?
Where can I find a hardware manual (documentation or a book) for Arduino board?

As far as I know, all hardware details are dispersed (or scatter) in different tutorials.

# Answer
The Arduino Uno is little more than an ATmega328P microcontroller. In most cases you will be interested by the documentation of the microcontroller itself. Anyway, here are both:

Alberto (aka PighiXXX) has published nicer versions of the Arduino Uno pinout:
> 6 votes

# Answer
For the hardware part, you can refer to the schematic. It shows all the components so you can find their datasheets for detailed study.

UNO schematic

But to me, if you're just using the board but not designing your own board or writing libraries for the board, I don't think this is necessary. Stick to application level or IO-level and only really dig into the hardware when you're blocked when doing things like using all timers, low-power mode, interrupt with Serial...
> 3 votes

---
Tags: arduino-uno, documentation
---


title: Arduino OOP and [this] keyword

text:
# Question
Title: Arduino OOP and [this] keyword
Lets say I have a sketch called **mysketch.ino** with these contents:

```
String globalString = "ThisisGlobal";
void setup(){}
void loop(){}

```

How can I pass **THIS** sketch `mysketch.ino` as an object or its reference to a `.h` file named `StringChanger.h` with the following contents, so that `StringChanger.h` can change somevariables belonging to `mysketch.ino`.

```
class StringChanger{
   template <typename T> // or type of mySketch.ino i don't know what i'm doing
   void changeString(T t) {  //a Reference Or Object Or Whatever
      t.globalString = "GotYouAndChangedYou";
   }
}

```

I wan't to have simple usage in the `mySketch.ino`. For instance:

```
#include "StringChanger.h"

StringChanger change(**this**);  // perhaps default empty constructor here

String globalString = "ThisisGlobal";

void setup(){
    change.changeString(); // perhaps pass reference to **this** here
}
void loop(){}

```

How can I accomplish this (give a class an object so that it can change some value of that object) in general and not neccesarily in this context. Errors I currently get:

```
invalid use of 'this' in non-member function
invalid use of 'this' at top level.

```

# Answer
A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.

Your example seems to be trying to make things incredibly complex when they don't need to be.

There are a number of ways of referencing things in one file from another - whether or not they are in a class. The simplest is to use the `extern` keyword. This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."

```
// Sketch
String myString = "foo";

// Library
extern String myString;
// ... later on ...
myString = "bar";

```

Of course, that means that the name of the variable is fixed and cannot change. So you can pass the variable to whatever it is you want to use that variable in. That could be as simple as passing it to your "changer" function:

```
// Sketch
String myString = "foo";
StringChanger change;
// ... later ...
change.changeString(myString);

// Library
class StringChanger {
    public:
        void changeString(String &stringToChange) {
            stringToChange = "bar";
        }
};

```

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:

```
// Sketch
String myString = "foo";
StringChanger change(myString);
// ... later ...
change.changeString();

// Library
class StringChanger {
    private:
        String *_string;
    public:
        StringChanger(String &string) {
            _string = &string;
        }
        void changeString() {
            *_string = "bar";
        }
}

```

And there's a myriad of other ways of doing it.
> 1 votes

---
Tags: c++, arduino-ide, library, sketch, safety
---


# Question
Title: MQ4 gas sensor is not working with Arduino UNO
I am trying to detect LPG leakage by using MQ4 gas sensor. I have made this circuit

My Arduino code is

```
int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);
  Serial.println(sensorValue, DEC);
  delay(100);
}

```

On my serial monitor, I am getting values like

```
307
277
289
282
283
283
260
248
265
285
308
278
278
315
321
316
327

```

These values are not getting change even after putting sensor near gas lighter. Did I made any mistake in circuit or this sensor could be faulty ? Any help is appriciated.

# Answer
> 1 votes
That is what I would expect to see with one of these sensors.

I'm not sure on the wiring, I think you *may* be wrong. Have a read of http://playground.arduino.cc/Main/MQGasSensors#readdatasheet and see if you agree.

Did you leave the sensor to warm up? It takes a few minutes (from memory) and until its warm it won't give you a proper reading.

An MQ4 should be able to detect Methane, butane and propane, so was your lighter using on of these gasses? When it does detect the target gas, the number will go up, and stay up for a while.

Another thing you can try is blowing on the sensor, the results will vary depending on what you have been eating, but it should shift one way or another.

If it still doesn't work then buzz out your connections, just to triple check, and re-read the manual.

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


# Question
Title: Use object of LiquidCrystal class within another class
I am quite new to C++ and hope that I don't bore you too much with my question.

I want to use an object of LiquidCrystal Class in another class called "Display\_ManagerClass". I followed the instructions of the 2nd alternative in the following link:

Use object of other class within class

Unfortunately, I receive a linker error.

.ino-file:

```
#include "Licht_Manager.h"
#include "Display_Manager.h"
#include "Zeit_Manager.h"

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

void setup()
{

    Licht_Manager.init();
    Display_Manager.init(&lcd);
}

void loop()
{
    Display_Manager.showText("Hello", "World");
    while (1)
    {
        Licht_Manager.blink(1);
    }
}

```

Display\_Manager.h:

```
#ifndef _DISPLAY_MANAGER_h
#define _DISPLAY_MANAGER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <LiquidCrystal/src/LiquidCrystal.h>

class Display_ManagerClass
{
    protected:

    public:
        //void init();
        void init(LiquidCrystal* _p_lcd);
        void showText(String DisplayText1, String DisplayText2);
    private:
        LiquidCrystal* p_lcd;

};

extern Display_ManagerClass Display_Manager;

#endif

```

Display\_Manager.cpp:

```
#include "Display_Manager.h"

void Display_ManagerClass::init(LiquidCrystal* _p_lcd)
{
    p_lcd = _p_lcd;
    p_lcd->clear();
}

void Display_ManagerClass::showText(String DisplayText1, String DisplayText2)
{
    p_lcd->clear();
    p_lcd->setCursor(0,0);
    p_lcd->print(DisplayText1);
    p_lcd->setCursor(0,1);
    p_lcd->print(DisplayText2);
}

Display_ManagerClass Display_Manager;

```

I receive the following errors:

```
Display_Manager.cpp.o:In function `Display_ManagerClass::init(LiquidCrystal*)
Display_Manager.cpp:clear()
Display_Manager.cpp.o:In function `Display_ManagerClass::showText(String, String)
Display_Manager.cpp:clear()
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

```

I made sure that the correct directory of the library is set up in the project properties. The library also works in the normal way, but in combination with the class it doesn't.

I work with Atmel Studio 7 in combination with VisualMicro, Arduino IDE 1.6 and Arduino Uno.

Thank you in advance.

# Answer
> 1 votes
You must also include `LiquidCrystal.h` in your sketch. That way the IDE will know to include it in the list of files to compile and link with your sketch.

---
Tags: arduino-uno, lcd, class
---


title: Resetting millis() and micros()

text:
# Question
Title: Resetting millis() and micros()
I want to know how much time has elapsed since a certain event, and I do not want to use any external timers. It seems logical to reset an internal timer whenever the event occurs (using an interrupt). Unfortunately, as far as I can tell, `millis()` and `micros()` cannot be manually reset. Obviously, I could save a time stamp whenever the event occurs; however, I want to avoid overflow problems (`micros()` will overflow every ~71 minutes, and `millis()` will overflow every ~50 days).

Is there a way to manually reset these built-in counters? If not, how can I manage the overflow?

# Answer
`millis()` and `micros()` overflow periodically. However, this is not a problem: as long as you compare durations instead of timestamps you can forget about the overflows.

The liked answer also gives the trick for resetting `millis()`. Can be handy for testing purposes, but *you do not need this* to handle the millis() rollover problem. Notice that there is no clean way to reset `micros()`: it relies on a `static` variable, i.e. a variable private to the file defining it.
> 6 votes

# Answer
Overflow is never really an issue if you always calculate time difference. (Unless the time difference is more that 50 days.)

```
unsigned long previousTime = millis();
... wait for some event to happen ...
unsigned long elapsedTime =  millis() - previousTime;

```

Even if `previousTime` was before the overflow, and `millis()` is after the overflow (so essentially `millis()`\<`previousTime`), `elapsedTime` will still be the correct value.

This is because the calculation itself will also overflow. Since `millis()`\<`previousTime`, the result would be negative, but the type of the variable is `unsigned`, so it wraps around. I hope that makes sense.

Just don't ever do something like `if( millis() > (previousTime+1000) )`

If you still want to reset millis, you can use the following:

```
extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;

void setup(){
  //Setup stuff
}

void loop(){
  //Do stuff
  //--------

  //Change Millis
  setMillis(new_value);
}

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}

```
> 5 votes

# Answer
> It seems logical to reset an internal timer whenever the event occurs (using an interrupt).

No it doesn't. You don't reset your clock to 00:00 when you put a cake in the oven do you?

What you do is note the time. Then periodically you subtract the start time from the current time, giving you the elapsed time. When time is up, you remove the cake from the oven.

---

Think about it for a minute. What if you wanted to time **two** events? Setting millis back to zero would hardly work then, would it? Setting it to zero for the second event would corrupt your timing for the first event.

However *noting the time* each one starts, and comparing the time *now* to the start time, will work for any number of events.

---

For more details see my post about millis() overflow ... a bad thing?
> 0 votes

---
Tags: programming, time, millis
---


title: digitalPinToInterrupt() doesn't work

text:
# Question
Title: digitalPinToInterrupt() doesn't work
I am working on a protection circuit with 2 raindrop sensors which would be hooked onto the arduinos 2 interrupt pins and as soon as they detect water they shut some relays off, turn a red led on and exit() the main program.

These sensors I have order are working fine as regular input pins with the following code:

```
// lowest and highest sensor readings:
const int sensorMin = 0;     // sensor minimum
const int sensorMax = 1024;  // sensor maximum

void setup() {
  // initialize serial communication @ 9600 baud:
  Serial.begin(9600);
}
void loop() {
  // read the sensor on analog A0:
    int sensorReading = analogRead(A0);
  // map the sensor range (four options):
  // ex: 'long int map(long int, long int, long int, long int, long int)'
    int range = map(sensorReading, sensorMin, sensorMax, 0, 3);

  // range value:
  switch (range) {
 case 0:    // Sensor getting wet
    Serial.println("Flood");
    break;
 case 1:    // Sensor getting wet
    Serial.println("Rain Warning");
    break;
 case 2:    // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below.
    Serial.println("Not Raining");
    break;
  }
  delay(1);  // delay between reads
}

```

I will use the digital output not the analog but this doesn't change much. For the digital the pin is up at 5V at start and will be put to LOW once water is detected by the sensor.

I using the mega right now for breadbording but micro will be the final board.

Both the mega+micro should have 2,3 as interrupt pins:

```
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based   0, 1, 2, 3, 7

```

I have modified the following code and tried all conditions:

```
LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.

```

It doesn't respond to any (the same time as I said the pin works fine as regular input).

Here in the setup I know that I am not using

```
attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);

```

but

```
attachInterrupt(interruptPin, myISR, FALLING);

```

that is because the IDE doesn't recognize this function. Is there any problem with the code? If I understand interrupts correctly I don't even need to check for that if ( ISRRan ) to break off the while loop, once the interrupt comes in the ardu SHOULD be running my interrupt function and immediately run the protection code then abort.

```
byte interruptPin = 0;  // your interrupt pin
volatile boolean ISRRan = 0;  // this variable is set in your ISR to trigger a break in the while loop
byte C = 0;  // this is just the counter var for the while loop

void setup() {
 attachInterrupt(interruptPin, myISR, FALLING);
}

void myISR() {
 ISRRan = 1;
 // do other things in the ISR
}

void loop() {
 while ( C < 10 ) {
   if ( ISRRan ) {
     break;
   }
   //doing something inside the while loop
 C++;
 }
 // do other things outside of the while loop
 ISRRan = 0;  // Reset for whatever reason
}

```

# Answer
I have solved this.

The problem was with the pinout indeed.

```
attachInterrupt(0, myISR, FALLING);

```

will use the DIGITAL PIN 2

I was using attachInterrupt 2, that's all.
> 2 votes

---
Tags: interrupt
---


# Question
Title: How to reduce current from a AC TO DC power supply for arduino use
I have a AC to DC converter that was originally used for recharging the PSP, I stripped the 2 wires of the output and was wanting to use it for my arduino instead of using a 9V battery, it's output is 5V 2000MA, is there a way to reduce the current in order to use it for the arduino and im guessing the 5V is enough to power it...right? Im kinda new to electronics and the arduino so any help is much appreciated :D. Thanks, Liam.

# Answer
You don't need to reduce the current.

2000MA (2 amps) means the power supply is CAPABLE of supplying this (without overheating). Anything less than this, and your device will work perfectly.

Your Arduino will DRAW a certain number of milliamps (amps), this is the amount of current that will ACTUALLY run through your circuit.
> 4 votes

---
Tags: arduino-uno, power, voltage-level, current, electronics
---


title: 5V Trinket only outputting 3.3V?

text:
# Question
Title: 5V Trinket only outputting 3.3V?
Unless my multimeter is on the fritz, it would seem my 5V Adafruit Trinket is only outputting 3.3V when connected w/ DC power.

When connected via USB, totally fun. Full 5V. But if I disconnect that and connect a 9V wall adapter, the output of the 5V pinout is just giving me 3.3V.

Is that even possible?

I noticed the issue b/c my program wasn't running properly when connected via the DC adapter (but ran just fine via USB). So I tested the voltage and sure enough, 3.3V all around at basically every +/- connection.

Any ideas?

# Answer
> 3 votes
Unfortunately I do not have the ability to comment. What I can suggest is to look at the small 5 pin regulator and look at its markings. If the IC is marked with "QT33" then adafruit has stupidly soldered the wrong chip onto your trinket board. If it says "QT50" then the regulator is not at fault.

---
Tags: voltage-level, adafruit
---


# Question
Title: Is Gsm antenna effect on microcontroller working?
in my embedded system I used patch antenna and Atmega 328 microcontroller,but somehow it causes the abrupt function of a microcontroller or reset. how can it be solved?

# Answer
> 3 votes
There are 3 possible causes that I can think of (it's difficult to say more without further details):

* SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)
* Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.
* Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.

---
Tags: arduino-uno, gsm
---


# Question
Title: I am trying to connect the PS3 controller with the Arduino Uno using a USB Host Shield. Getting stuck at 'PS3 Bluetooth Library Started'
I did the research for similar issues and found that I had to enable debug. I did the following attempts:

Changes to settings.h - enabled debugging by change from 0 to 1

Getting the following compiling error:

```
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: In member function 'void USBH_MIDI::parseConfigDescr(byte, byte)':
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:298:63: error: 'PrintEndpointDescriptor' was not declared in this scope
                                 PrintEndpointDescriptor(epDesc);
                                                               ^
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: At global scope:
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:421:80: error: no 'void USBH_MIDI::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR*)' member function declared in class 'USBH_MIDI'
 void USBH_MIDI::PrintEndpointDescriptor( const USB_ENDPOINT_DESCRIPTOR* ep_ptr )
                                                                                ^
exit status 1
Error compiling for board Arduino/Genuino Uno.

```

# Answer
> -1 votes
At the risk of stating the bleeding obvious you need to define "PrintEndpointDescriptor()". I'm sorry but I can't give you a definitive answer to your problem, only generic steps that should solve it.

This almost certainly means you have either missed a include file out or there is a pre-processor flag that is disabling or maybe not enabling that bit of code.

Search through the files in the library and see if there are any pre-processor flags that affect compilation and if so this function. Have a search on Google for the filename and function name, see that others say.

Another possible solution is look for a readme in the library, or comments in the files that say you need another library including first. In fact if you are including multiple libraries try changing the order of inclusion.

One last cause could be that the function is within a namespace. This means you either need to fully qualify the function call (namespace::class::function), or use the horrible using command.

---
Tags: bluetooth, shields
---


title: Is this bluetooth setup good?

text:
# Question
Title: Is this bluetooth setup good?
I am trying to do this tutorial http://www.instructables.com/id/Chappie-Self-Balancing-Robot/ on building a self-balancing robot with uno. However, I bothered by the Bluetooth wiring. I've done Arduino projects with Bluetooth before and all the Hc-05 wirings I've seen have it connected to the Tx and Rx pins.Currently, I have my Bluetooth module wiring like this : with http://cdn.instructables.com/FSK/AI30/HMMFE6UO/FSKAI30HMMFE6UO.MEDIUM.jpg. Will the different wiring need a different implementation, the code I see on the chappie instructable link does not have any pin mentions but I'm not sure. Is the chappie wiring fine? should I change my wiring? should I change my code? I'm confused.

# Answer
> 0 votes
Which code are you reading? At step 5 he wrote

> Complete code can be found on the GITHUB.

The sketch file (here is the direct link) has the following lines:

```
const int rxpin = 11; // pin used to receive (not used in this version)
const int txpin = 4; // pin used to send to LCD

SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

```

This means that the bluetooth is using a software serial on pins 11 and 4.

I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to `blue` with `Serial`.

---
Tags: arduino-uno, programming, bluetooth, wires
---


# Question
Title: Is Arduino reliable for serious tasks, such as medical machines?
I'm just getting started with Arduino, and it has a LOT of uses, however, I would like to know how reliable is it? Can it be used for medical purposes (Measure vital signs, or to help surgeons perform surgeries), if it depends on the board, which one is the most accurate and reliable?

I know most robotic tasks will rely on the quality of the servo to interpret the Arduino commands, and sensors, and even the coding/logic, but we can replace/recode all of those things, but when it comes to the main board it gets more complicated

# Answer
You should NOT trust using an Arduino for life safety measures (medical purposes).

This discusses the reliability of an Arduino pretty well- https://electronics.stackexchange.com/questions/15535/reliability-of-the-arduino-platform-for-industrial-use
> 3 votes

---
Tags: sensors, robotics
---


title: Compiler doesn't like function code

text:
# Question
Title: Compiler doesn't like function code
I am getting this error from the Visual Studio compiler (I use the Visual Studio add-in Visual Micro for Arduino).

> ModelRailroadCrossingSignalController.ino:In function 'void loop() ModelRailroadCrossingSignalController.ino:210:15: error: too few arguments to function 'Adafruit\_VS1053\_FilePlayer onSignalSound(Adafruit\_VS1053\_FilePlayer, const char\*) :onSignalSound() ModelRailroadCrossingSignalController.ino:note declared here :Adafruit\_VS1053\_FilePlayer onSignalSound(Adafruit\_VS1053\_FilePlayer mp, const char\* fileName) { Error compiling project sources

Here is the function and loop (all the defines and instances left out for brevity, they aren't the issue

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

signalEntrySensor = checkEntrySensor();
if (signalEntrySensor == true) {
    if (crossingSignalInOperation == false)
    {
        Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"Trainxng.mp3");  //all other functions are called in the sound routine?
        if (debugMode)
        {
            Serial.println("Sound byte called");
        }
        while (mp.playingMusic) {
            // file is now playing in the 'background' so now's a good time
            // to do something else
            offRoadPower();
            lowerSignalArms();
            onSignalSound();
            startSignalFlashers();
            crossingSignalInOperation = true;
        }
    }
}

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
// Play the train crossing sound file
if (debugMode)
{
    Serial.println(F("Playing track - "));
    Serial.print(fileName);
}
//all sound files are on the micro sd card on the music player shield
if (!mp.startPlayingFile(fileName)) {
    Serial.println(F("Could not open file "));
    Serial.print(fileName);
    while (1);
}
return mp;  }

```

I'm a C# guy, not ever using C++ until now, but this code should certainly work, not sure why the function is not compiling.

# Answer
> 0 votes
The clue is in the error...

> too few arguments to function 'Adafruit\_VS1053\_FilePlayer onSignalSound(Adafruit\_VS1053\_FilePlayer, const char\*)

You have defined the function as this:

```
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

```

And yet you then try and call it like this:

```
onSignalSound();

```

Spot the mismatch?

I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.

---
Tags: programming, arduino-mega
---


# Question
Title: Standalone chipset, power regulation & pinout
I have succesfully (or so the ide says) burned a bootloader on an ATMega328P-PU chipset, and uploaded my sketch on it.

It appears a voltage regulation is absolutely needed, if I want to solder a pcb with the standalone chip, rather than an arduino. Is that correct? Can I build one out of my starter kits parts (assortment of transistors, diodes, zeners, resistors and capacitors)?

In the meantime, I would like to make sure the chispet is functional. Can I power it from GND/5V of an arduino? Will it take care of that power regulation?

If I can, what is the correspondance between the arduino pins, and the ATMega328P-PU pins? I have this page here : http://www.learningaboutelectronics.com/Articles/Atmega328-pinout.php referencing the chipset pinout. Am I correct in assuming there is a correspondance with the arduino pinout in the reading order of this chart, ie. :

PD0 to PD7 are Rx, Tx, digital pins 2 to 7 on the arduino, PB0 to PB5 are digital pins 8 to 13, and PC0 to PC5 are A0 to A5 on the arduino?

Thanks for reading.

# Answer
> 1 votes
Voltage regulation is needed if the voltage you are providing to the chip is outside (or can drift outside) the allowed range for the chip to operate.

At the upper limit that is 5.5V. The lower limit is 1.8V. Note that at lower voltages you can only reliably run at lower clock speeds.

If your power source is between those two voltages (say a 3.4V LiPo battery) then you don't need a regulator.

If your power source is above 5.5V (say a 9V PP3 battery \[urgh\]) then you definitely need a regulator.

A proper regulator is quite a complex device, and it is highly unlikely that you have the components to make one. A simple, very inefficient one, though, can be made using a resistor and a 5V Zener diode if you have one.

Until you have your own regulator of whatever form, yes, you can power the chip from the 5V pin of the Arduino.

The pin mapping for the chip -\> Arduino IO numbers is in the file `pins_arduino.h` for the Uno variant in the IDE. In the top of that file is this handy drawing:

```
// ATMEL ATMEGA8 & 168 / ARDUINO
//
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+
//
// (PWM+ indicates the additional PWM pins on the ATmega168.)

```

---
Tags: power, pins
---


title: Start program on PC using Arduino

text:
# Question
Title: Start program on PC using Arduino
I want to create arduino sketch that start program on my computer (i.e., browser) when I push button on Arduino itself.

Is it possible to make it using Arduino uno? I already know how to make a serial connection between PC and Arduino and use Processing software, but as I know, Processing cannot interact with another programs.

# Answer
> 2 votes
Processing is just Java. If Java can do it Processing can do it.

And Java can do it.

Just ask Google about the Java `ProcessBuilder` class.

# Answer
> 1 votes
You can also make the Arduino look like a keyboard/mouse to the PC and then reproduce some key combo that will perform the action you want. See reference here.

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


title: ATmega328p simple shortcircuit button

text:
# Question
Title: ATmega328p simple shortcircuit button
I am trying to get a simple button (GPIO shortcircuit) to work. I have chosen Pin D0 as input and Pin D7 as output. It works fine in an Arduino sketch but I can't get it to run in pure C. What am I doing wrong? I bet I got the bits all wrong...

My code:

```
DDRD = 0b11111110; // set all port D pins to Output besides pin 0, which is set to input
PORTD = 0b11111111; // set all D pins to WRITE / PULL-UP
int a = PIND & 1; // a is 0 or 1, depending on whether pins D0 and D7 are physically connected

```

It doesn't work though, `a` is never zero, whether the pins are connected or not.

Here is my complete code sample, where the on board LED depends on my pins connection state:

```
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
 DDRB |= _BV(DDB5);
 DDRD = 0b11111110;
 PORTD = 0b11111111;

     while(1) {
        int a =  PIND & 1;
        if(a != 0)
             PORTB |= _BV(PORTB5); // blink on
         else
             PORTB &= ~_BV(PORTB5); // blink off
         _delay_ms(1000);
    }
}

```

# Answer
The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).

The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.

So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.

Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.

Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).
> 4 votes

---
Tags: arduino-uno, pins
---


# Question
Title: Digital pin output voltage, not triggering 71mA relay coil
I have a relay (VRS4H-S-DC5V-C), for which the triggering voltage required is 5V Min. If I directly use the 5V voltage of Arduino I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.

Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?

# Answer
The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.

Just google for "Arduino relay driver circuit" and you will get various options.

This is pretty close to your setup.
> 5 votes

---
Tags: arduino-nano, relay
---


title: Not being able to use pushbutton

text:
# Question
Title: Not being able to use pushbutton
I've been trying to detect a push button based on this tutorial, but due to my lack of skills/knowledge I haven't been able to make it work, could you guys point out what I'm doing wrong?

Any help is appreciated

*My project on 123d circuits*

***My code:***

```
void setup() {
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, HIGH);
  Serial.begin(9600);
}

void loop() {
  trigger();
}

void trigger(){
  if (digitalRead(2) == HIGH) {
    Serial.println("Hey");
    //turn();
  }
}

```

# Answer
You seem to be suffering from three problems here:

1. A lack of understanding how the button's pins are configured
2. A lack of understanding of how breadboard works
3. A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground. Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.
> 3 votes

---
Tags: button, digital
---


# Question
Title: Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing
I followed this guide to program AtTiny using Arduino as ISP. The problem is that it has some file missing:

```
java.io.FileNotFoundException: C:\...\arduino-1.6.8\hardware\attiny\variants\platform.txt

```

The attiny directory is clone of this repository. How do I make it work?

# Answer
* Open the "Preferences" dialog in the Arduino IDE.
* Click on the symbol next to "Additional Board Manager URLs"
* Paste the following into the box (possibly on a new line under any existing URLs), then click OK.

```
https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

```

Note that you can click on the circled link for a list of boards. This will open in your web browser. You may have to switch to your browser to notice it.

* Click OK to close the Preferences dialog box.
* In the Tools menu / Board select the Boards Manager:
* Scroll down until you see the Attiny entry (or the one for the board you want), click on it to select it, and then click "Install".
* Once done, close the Board Manager dialog box.
* You should now be able to select Attiny from the Boards menu:
* Now in the Tools menu you can select which Attiny you want to use:
* Notice you can also select the appropriate clock speed in an adjacent menu item.
* To program the Attiny you will need a suitable ISP (In System Programmer) such as the AVRISP programmer, or the USBtinyISP programmer.
> 3 votes

# Answer
The way of adding boards has changed in the newer version.

Try finding a tutorial for 1.6, or download the older 1.0 version.
> 1 votes

---
Tags: arduino-ide, attiny
---