# Question
Title: Arduino turns LEDs off when set 'high', opposite direction as coded
I've got a function that decreases over time (1000 / 60 seconds) and by touching a softPotentiometer you can increase that value. By every increment of 200 a LED is lid. So for 0-200, 1 LED; 201-400, 2 LEDs; etc. And since it decreases over time while doing nothing, if it drops below a certain value, a LED is shut off.

However, I've got a (amateur) coded set up, but somehow it lids the LEDs in the opposite direction. In a way that, I've coded it that if it's above 800, lid 5 LED's. However, it will only lid one LED when it's dropped below the 800, in the area of 601-800.

That's exactly the opposite of what I want. So what am I doing wrong here?

---

My code:
*And with amateur, I mean that I didn't use arrays and therefor write everything multiple times..*

```
int cleanCount = 1000;
int IsItWorkingLED = 13;
int softpotPin = A0; //analog pin 0
int LED1 = 1;
int LED2 = 2;
int LED3 = 4;
int LED4 = 5;
int LED5 = 7;

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
        pinMode(1, OUTPUT);
        pinMode(2, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(7, OUTPUT);

           digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)

}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF TOUCHED
        digitalWrite(IsItWorkingLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // Drain 5 times as fast
    }
    else if (softpotReading > 980) { // IF NOT DTOUCHED
        digitalWrite(IsItWorkingLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconds
    }
    else {      // Als er een fout optreed..
        Serial.println("Something wrong!");
        digitalWrite(IsItWorkingLED, HIGH);
        delay(250);
        digitalWrite(IsItWorkingLED, LOW);
        delay(250);
    }

        if (cleanCount >= 0 && cleanCount <= 200) {
           Serial.println("Knal 1 LED aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 201 && cleanCount <= 400) {
           Serial.println("Knal 2 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 401 && cleanCount <= 600) {
           Serial.println("Knal 3 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 601 && cleanCount <= 800) {
           Serial.println("Knal 4 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 801 && cleanCount <= 1000) {
           Serial.println("Knal 5 LEDs aan");
           digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
        }
        else {
          Serial.println("Just..do nothing");
        }

}

```

# Answer
If your LEDs are connected anode to +5, cathode to i/o pin, they would behave this way. Cathode to ground, anode to i/o would behave as you expect.
> 6 votes

# Answer
Try reversing the if statements. You say:

> I've coded it that if it's above 800, lid 5 LED's.

And your code is: `(softpotReading < 980) { // IF TOUCHED`

The code describes: `IF softpotReading IS SMALLER THAN 980, DO{ code.. }`

---

In dutch (as OP is dutch, and to be honest his English somehow confuses me a bit, to be sure it's not the other way around also):

Ik denk dat je de IF statements verkeerd om hebt. Je beschrijft dat bij een waarde hoger dan 800 de ledjes aan gaan...

Echter staat in je code `(softpotReading < 980) { // IF TOUCHED` Wat dus zal betekenen dat de code wordt uitgevoerd als die \< (kleiner dan) 980 is.

---

```
    if (softpotReading > 980) { // IF TOUCHED
    digitalWrite(IsItWorkingLED, HIGH);
    ++cleanCount;
    Serial.println(cleanCount);
    delay(16); // Drain 5 times as fast
}
else if (softpotReading <= 980) { // IF NOT DTOUCHED
    digitalWrite(IsItWorkingLED, LOW);
    --cleanCount;
    Serial.println(cleanCount);
    delay(64); // 1000 / 60 seconds
}

```
> 0 votes

---
Tags: led
---


title: Overloading function loop

text:
# Question
Title: Overloading function loop
I want to introduce a boolean that is the first iteration of loop and then false every subsequent iteration. I want it invisible, so I have to modify loop in some way. Is that possible?

# Answer
The way to do this isn't to overload the loop function, the way to do this is to abuse the linker and replace main().

The main.cpp file that gets used in the Arduino make prototypes main as `int main(void)`. On my system at least the linker prefers the longer prototype, so you can just do this:

```
int main(int argc, char* argv[])
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    //The one shot loop...
    loop();
    if (serialEventRun) serialEventRun();
    //Put whatever else you need to do between before the unending loop here.

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

Both get compiled, but the `int main(int argc, char* argv[])` prototyped version gets linked as the entry point, so your "invisibile" code gets executed.
> 2 votes

---
Tags: core-libraries
---


title: Arduino Mega 2560: Busted Atmega 16U2

text:
# Question
Title: Arduino Mega 2560: Busted Atmega 16U2
I just bought an Arduino Mega2560 R3 and it doesn't connect to my Laptop. The connection is somewhat random, sometimes it connects and sometimes it doesn't.

Can someone help me identify whats the problem?

When it gets connected I can upload sketches.

I would like to remove the Atmega 16U2 and replace it with ftdi USB to Serial, would it be possible?

# Answer
You can use your USB/Serial adapter to program the 2560 as the Arduino uses the 16u2 as the same thing to program the mega. You shouldn't remove the 16u2, just wait till you get the programmers and reflash the 16u2 with its firmaware and it will work, I actually had the same problem where the DFU didn't work and the 16u2 stopped responding, after reflashing the firmware it worked. The firmaware can be found under(as of 1.6.0):

`...\Arduino\hardware\arduino\avr\firmwares\atmegaxxu2\MEGA-dfu_and_usbserial_combined.hex`

You need to connect the Serial pins on the FTDI and Mega in the below fashion:

```
 FTDI           MEGA
 GND<----------->GND
 CTS<----------->GND
 VCC<----------->VCC
 TXD<----------->RX0
 RXD<----------->TX0
 RTS/DTR<---||-->RST

```

The Capacitor between the `DTR` pin and `RST` pin are needed this should be 100nF.

> I have bought an I |SP programmer but it will take 3 weeks to reach and no I dont have another arduino, TBH I'm scared to buy another one... – echo\_salik

If you are buying clones, those will more than likely give issues as they will be cutting back on costs in places, i.e. QC checks.
> 1 votes

---
Tags: arduino-mega, usb
---


# Question
Title: Serial Monitor breaks normal behaviour of Nano + NRF24l01
Couldn't find any other post that mentions Serial Monitor crippling the normal workflow of the NRF24l01, so here it goes.

I have two Arduino Nano, both with NRF24l01 attached, and an RF24 library working. Both NRF24l01 have 10uF caps soldered on them. One is only sending data, another is receiving only. Both of them flash LED on, successful transmission and successful receiving respectively.

When I run both devices, i see both LEDs flashing, so one succeeds in sending, and another one in receiving. But whenever I try to open Serial Monitor in my Arduino 1.6.1 software, the LEDs flash only every forth of fifth time of expected, and in my Serial Monitor I can see only 1 of 4 or 5 packets received (though received correctly).

Any ideas what I could have done wrong? Could Serial Monitor somehow interfere with Nano talking to NRF24l01?

The code follows, it's simple.

Sender

```
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Successfull Sending Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openWritingPipe(pipe);

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    // counter data to be sent
    unsigned long counter = 0;

    void loop(void)
    {

      // Increase the counter and send it
      counter++;
      printf("Sending counter = %lu...", counter);

      if (radio.write( &counter, sizeof(unsigned long) ))
      {
        printf("ok...\n\r");
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
      else
        printf("failed.\n\r");

      // Try again 1s later
      delay(1000);
    }

```

Receiver

```
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Receiver Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openReadingPipe(1,pipe);

      //
      // Start listening
      //

      radio.startListening();

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    unsigned long counter;

    void loop(void)
    {
      // if there is data ready
      if (radio.available())
      {
        while( radio.available() ) {
          radio.read( &counter, sizeof(unsigned long) );
          // Dump the payloads until we've gotten everything
          printf("Got payload %lu...\n\r", counter);
        }
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
    }

```

# Answer
The reason for the Monitor being unable to work properly seems to be the length of the usb cable or a faulty usb port on my computer. I had a usb-cable extender, to which another (this time short) usb cable of my Arduino Nano was attached. It seemed to work fine while I was uploading things to Nano, but a quick serial exchange was, perhaps, not possible.Another usb port, or bypassing the usb cable extender brings everything back to normal.

This is a solution, while I still had no reason, how debugging through serial could influence that much on the chip behaviour itself, until now. I just thought it may well be the same power problem, as FTDI chip both powers the radio (even with the capacitor I installed!) and talks to computer through my long usb cable. If it starts talking, there could be no power for RF24 for a longer period than could be saved by my capacitor.
> 1 votes

---
Tags: serial, arduino-nano, nrf24l01+
---


# Question
Title: Installing Ports for Arduino Nano on Mac OS X Yosemite
Just starting with Arduino and have gotten stuck at the first hurdle: trying to connect an Arduino Nano with my Mac Book Pro which runs 10.10. I can't seem to find the right port as all suggestions have bluetooth in the name and none with USB anything. Also the post list does not change when I plug/unplug the Arduino. Looking at http://arduino.cc/en/guide/macOSX#toc3 it says that I need to install FTDI software to get the USB port to show, however, having done this it still does not work. Any suggestions?

Thanks, Calum

# Answer
> 2 votes
Had exactly the same problem. Also using 10.10 and just got an Arduino. What worked for me was using a different cable. The one that came with my Arduino Uno only provided power not data. If you have a printer, it might have the right cable, just test it quickly.

Edit: In addition, whilst trying to find solutions, I also installed 64bit mac FTDIUSBSerialDriver\_v2\_2\_18.dmg. I'm not sure if it made a difference. As after installing it and using the original cable the problem persisted.

# Answer
> 0 votes
Are you using a USB hub? I had problems with my MBP when the Arduino was on a hub. Attached directly to the mac it was fine.

---
Tags: osx
---


# Question
Title: How to know which Arduino to choose: Nano, Micro or Pro Micro?
I'm puzzled at the moment with which one to choose.

* Form-factor plays a significant role in my project, so I prefer the smaller boards mentioned in the title to fuller boards like the UNO, MEGA, etc.
* I have an RC522 RFID read/write module and would like to use it without having to deal with level switching, as the RFID module requires 3.3V.

What can you advise?

Thank you in advance!

# Answer
> 2 votes
I'm currently using inexpensive Arduino Nano boards running GRBL for a couple of little CNC machines. The version I have uses an ATmega328 running at 5V and they work *very* well.

They may be available with 3.3V regulator instead of 5V - I don't know and I preferred to have 5V anyway.

The nano boards that I have look to be a complete Arduino: one side of the board has the ATmega and voltage regulator, the other side of the board has the USB interface chip and some LEDs.

You can purchase Chinese-made nano boards very inexpensively. Look on eBay for sellers offering free International shipping.

# Answer
> 1 votes
I have used the ProMicro and the nano for a few projects and they are both great boards. I had a little bit of trouble getting the Pro Micro up and running but SparkFun has a great tutorial that should give you plenty of information to get that board up and running. If it's between those three boards, I would suggest the Pro Micro.

You could also consider the Pro Mini (https://www.sparkfun.com/products/11114). You will need an FTDI programmer for it (https://www.sparkfun.com/products/9873) but don't be discouraged by that. It's really straightforward to use. The cost is about the same as the Pro Micro and there are no special drivers required to get your computer talking to the Pro Micro. The Pro Mini with the FTDI basic "just works". One disadvantage to the Pro Micro is that you won't be able to power it over USB unless you leave the FTDI attached to it...but like most Arduinos you can just power it over a pin with a wide range of voltages.

Really any of the boards you mentioned will do the job.

Another board that's even smaller than the ones you mentioned would be the trinket or pro trinket by Adafruit. Similar to the pro micro, you need some additional drivers but Adafruit is really good about providing tutorials.

If you don't want to worry about external programmers and additional drivers and you want to power over usb get the Micro. If you are powering off of a battery and need to wire it up anyway and are willing to do a little bit of configuration on your computer consider the Pro Micro or the trinket.

---
Tags: arduino-nano, arduino-mini
---


title: Running C for arduino

text:
# Question
Title: Running C for arduino
Is there a compiler that I can use to run C on an arduino or any other way so that I can upload C programs to my arduino?

# Answer
Perhaps you should look into here https://github.com/arduino/Arduino/wiki/Build-Process

Arduino uses avr-gcc compiler. Basically, it is a C compiler.

There is an step by step on how to customize this process using an avr-gcc compiler of your own here http://www.wikihow.com/Write-Arduino-Software-in-C

But I best recommend you downloading the arduino IDE on the official website to get things going. It has all the serial pairing stuff you don't really need to know to get started.

Hope it helps.
> 2 votes

---
Tags: arduino-uno, c, avr-gcc
---


# Question
Title: Uploading over Bluetooth Low Energy - bootloader not responding
I'm working on sketches uploading over BLE. I had to write my own uploader (looking at avrdude sources with one eye) so i can change uploading behaviour as needed and it's working over USB just perfect but it does not get response from bootloader if trying over Bluetooth LE.

My hardware:

* Arduino Uno (and i'm having Arduino Mega2560)
* HM-10 BLE module

As HM-10 does not support DTR/RTS i had to add my own software reboot:

In brief: it reads incoming bytes on interrupt event and compares to reset command passed in ble\_setup. If it's equal then it uses watchdog timer to reboot the board. If it's not equal it stores byte in byffer, then sketch loop() just returns incoming byes back ("echo").

```
#include <avr/wdt.h>

const char *ble_reset_cmd;
int ble_reset_index = 0;
int ble_available = 0;       // chars available
int ble_byte;                // income buffer as 1 char
int *ble_bytes = &ble_byte;  // income buffer
boolean delete_ble_bytes = false;

//#define BLE_DEBUG

// reboot Arduino board using Watchdog timer
void reboot() {
//    #ifdef BLE_DEBUG
    Serial.println("rebooting ...");
//    #endif

//    digitalWrite(13, HIGH);
//    delay(2000);

    wdt_enable(WDTO_15MS);
    while(1) { };
}

void ble_setup(int baud, const char *reset_cmd) {
    Serial.begin(baud);
    ble_reset_cmd = reset_cmd;
}

int Serial_available() {
    return ble_available;
}

int Serial_read() {
    if (ble_available < 0)
        return -1;

    int inByte = ble_bytes[--ble_available];
    if (ble_available == 0 && delete_ble_bytes) {
        // restore buffer as 1 char buffer
        delete[] ble_bytes;
        ble_bytes = &ble_byte;
        delete_ble_bytes = false;
    }
    return inByte;
}

void serialEvent() {
    if (Serial.available() <= 0)
        return;

    int inByte = Serial.read();
    if (inByte == ble_reset_cmd[ble_reset_index]) {
        // entered char is cmd character

        if (ble_reset_cmd[++ble_reset_index] == 0)
            reboot();

        #ifdef BLE_DEBUG
        Serial.write("ble_index = ");
        Serial.print((byte)ble_reset_index);
        Serial.write('\n');
        #endif

    } else {
        // entered char is NOT cmd character

        if (ble_reset_index > 0) {
            // got character not from cmd, so we should to return characters
            // starting ble_reset_cmd until current index and then this character

            ble_available = ble_reset_index + 1;
            ble_reset_index = 0;

            #ifdef BLE_DEBUG
            Serial.print("Copy ");
            Serial.print((byte)(ble_available - 1));
            Serial.println(" bytes");
            #endif

            // recreate input buffer using cmd characters
            ble_bytes = new int[ble_available + 1];
            delete_ble_bytes = true;
            ble_bytes[0] = inByte;
            for (int i=0; i<(ble_available-1); i++) {
              ble_bytes[i + 1] = ble_reset_cmd[ble_available - i - 2];
            }
            ble_bytes[ble_available] = 0; // null-terminated array

            #ifdef BLE_DEBUG
            Serial.print("input buffer now contains ");
            Serial.print(ble_available);
            Serial.println(" bytes");
            #endif

        } else {

            #ifdef BLE_DEBUG
            Serial.println("ble_index = 0");
            #endif

            // pass inByte next ...
            ble_available++;
            ble_byte = inByte;
        }

    }
}

// -----------------------------------

int led = 13;
int ledHIGH = 0;

void setup() {
  ble_setup(9600, "AT+RESET");
  Serial.print("ready\n");
  pinMode(led, OUTPUT);
}

void loop() {
  while (Serial_available() > 0) {
    int inByte = Serial_read();

//    Serial.write('>');
//    Serial.write(inByte);
//    Serial.write('\n');
    ledHIGH = 1- ledHIGH;
    digitalWrite(led, ledHIGH);
    Serial.write(inByte); // echo
  }
}

```

As i said it's working good for USB uploading: right after rebooting bootloader waits for upload commands and start to reply:

```
015-04-07 21:22:10.860 Apploader[11226:303] Apploader v0.1
2015-04-07 21:22:12.772 Apploader[11226:303] DTR/RTS supported by Serial, resetting
2015-04-07 21:22:13.075 Apploader[11226:303] draining ...
2015-04-07 21:22:13.327 Apploader[11226:303] drain done
2015-04-07 21:22:13.328 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.328 Apploader[11226:303] draining ...
2015-04-07 21:22:13.723 Apploader[11226:303] drain done
2015-04-07 21:22:13.724 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.724 Apploader[11226:303] draining ...
2015-04-07 21:22:13.977 Apploader[11226:303] drain done
2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.980 Apploader[11226:303] Send: A [0x41]  . [0x81]   [0x20]
2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x04]
2015-04-07 21:22:13.985 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.985 Apploader[11226:303] Send: A [0x41]  . [0x82]   [0x20]
2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x04]
2015-04-07 21:22:13.989 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.989 Apploader[11226:303] Send: B [0x42]  . [0x86]  . [0x00]  . [0x01]  . [0x00]  . [0x01]  . [0x01]  . [0x01]  . [0x03]  . [0xff]  . [0xff]  . [0xff]  . [0xff]  . [0x00]  . [0x80]  . [0x04]  . [0x00]  . [0x00]  . [0x00]  . [0x80]  . [0x00]   [0x20]
2015-04-07 21:22:13.996 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.997 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.997 Apploader[11226:303] Send: E [0x45]  . [0x05]  . [0x04]  . [0xd7]  . [0xc2]  . [0x00]   [0x20]
2015-04-07 21:22:14.000 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:14.001 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:14.003 Apploader[11226:303] Send: P [0x50]   [0x20]
2015-04-07 21:22:14.004 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:14.008 Apploader[11226:303] Recv: . [0x10]

```

But when trying over BLE bootloader stops listening in 200ms and then launches sketch, i can see sketch setup() started as it prints "ready". Also i can see it actually reboots the board as it sends "rebooting".

```
015-04-07 21:23:30.287 Apploader[11253:303] Apploader v0.1
2015-04-07 21:23:30.296 Apploader[11253:1503] CBCentralManager state is 5
2015-04-07 21:23:31.297 Apploader[11253:303] BleSerialDevice: open()
2015-04-07 21:23:31.298 Apploader[11253:303] Waiting for peripheral to be discovered ...
2015-04-07 21:23:31.591 Apploader[11253:1503] Found peripheral: <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
2015-04-07 21:23:31.593 Apploader[11253:1503] Stop scanning
2015-04-07 21:23:31.595 Apploader[11253:1503] Connecting to <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
2015-04-07 21:23:32.025 Apploader[11253:1503] Connected to peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
2015-04-07 21:23:32.041 Apploader[11253:1503] Discovered services for peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
2015-04-07 21:23:32.042 Apploader[11253:1503] Discovered service <CBService: 0x103701450>
2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x1037015f0>
2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x103701630>
2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristics for service <CBService: 0x103701630>
2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristic <CBCharacteristic: 0x1037005c0>
2015-04-07 21:23:32.045 Apploader[11253:1503] Subscribed to Rx value
2015-04-07 21:23:32.046 Apploader[11253:303] Connected successfully
2015-04-07 21:23:33.342 Apploader[11253:303] BleSerialDevice: open()
2015-04-07 21:23:33.343 Apploader[11253:303] already connected, exiting
2015-04-07 21:23:33.343 Apploader[11253:303] DTR/RTS supported by Serial, resetting
2015-04-07 21:23:33.594 Apploader[11253:303] Within interval
2015-04-07 21:23:33.595 Apploader[11253:303] Perform reset
2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
2015-04-07 21:23:33.647 Apploader[11253:303] Skip draining after reset
2015-04-07 21:23:33.648 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:33.648 Apploader[11253:303] Draining for 200 ms ...
2015-04-07 21:23:33.649 Apploader[11253:303] Start reading
2015-04-07 21:23:33.712 Apploader[11253:1503] Rx value received 15 bytes: r [0x72] e [0x65] b [0x62] o [0x6f] o [0x6f] t [0x74] i [0x69] n [0x6e] g [0x67]   [0x20] . [0x2e] . [0x2e] . [0x2e] . [0x0d] . [0x0a]
2015-04-07 21:23:33.713 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]
2015-04-07 21:23:33.780 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:33.850 Apploader[11253:303] Finish reading
2015-04-07 21:23:33.851 Apploader[11253:303] Drained 21 bytes
2015-04-07 21:23:33.852 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:33.853 Apploader[11253:303] Draining for 200 ms ...
2015-04-07 21:23:33.853 Apploader[11253:303] Start reading
2015-04-07 21:23:33.982 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
2015-04-07 21:23:33.983 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.054 Apploader[11253:303] Finish reading
2015-04-07 21:23:34.055 Apploader[11253:303] Drained 2 bytes
2015-04-07 21:23:34.056 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:34.056 Apploader[11253:303] Reading 1 bytes ...
2015-04-07 21:23:34.057 Apploader[11253:303] Start reading
2015-04-07 21:23:34.057 Apploader[11253:303] _characterRead = false
2015-04-07 21:23:34.184 Apploader[11253:1503] Rx value received 1 bytes: . [0x00]
2015-04-07 21:23:34.185 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.186 Apploader[11253:303] Finish reading
2015-04-07 21:23:34.186 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
2015-04-07 21:23:34.186 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.186 Apploader[11253:303] Recv: . [0x00]
2015-04-07 21:23:34.187 Apploader[11253:303] stk500_getsync() attempt 1 of 5: not in sync: resp=0x00

```

Once again - bootloader stops listening in 200 ms instead of 1-1.5 secons as over USB:

```
2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
...
2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]

```

I expect bootloader to reply with 0x14 0x10 as over USB:

```
2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]

```

As you can see later communication over Bluetooth is working good, as i receive exactly what was sent (0x30 0x20)

So when sketch is launched it's ok.

My ideas what's wrong:

1. baud rate

Since serial.begin(N) is invoked after bootloader stops and launch sketch bootloader by default uses another baud rate? Is it correct? HM-10 default daud rate is 9600 and in sketch i also use 9600.

2. wrong wire connection?

Bluetooth-arduino: rx -\> tx tx -\> rx Since its working for sketch i believe it's ok. Do i need any capacitors or resistors?

Any thoughts are highly appreciated!

**UPDATE**:

It seems i've found Uno bootloader source code and bootloader baud rate is 19200 by default

```
/* set the UART baud rate */
/* 20060803: hacked by DojoCorp */
//#define BAUD_RATE   115200
#ifndef BAUD_RATE
#define BAUD_RATE   19200
#endif

```

**UPDATE2**:

I'm in stuck as in this tutorial 115200 is used: http://makezine.com/projects/diy-arduino-bluetooth-programming-shield/

in step 8. "build the programmer circuit" R1 2.2K is set on arduino rx pin. Why? Another thing i can't understand is that SoftwareSerial baud rate is set to 38400 but BT module baud rate is set 115200 using "AT" command. why?

# Answer
> 1 votes
It seems that's the reason why bootloader does not wait:

```
// Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
    if (! (ch &  _BV(EXTRF))) // if its a not an external reset...
        app_start();  // skip bootloader

```

Now i have another question ;) How to reboot arduino board from the sketch to jump into bootloader waiting for upload command?

# Answer
> 2 votes
The bootloader used on the Uno is optiboot. But it contains the same "feature" of skipping straight to the application program if the reset source wasn't external.

You could remove this feature and reprogram the bootloader to the chip (using an external programmer).

Alternatively you can use a dirty trick, and jump into the bootloader right after this check of the reset source happens. It happens to be right in the beginning, so not much has happened. The problem is that optiboot makes the assumption that the system is in a freshly reset state. So either you can write a flag to EEPROM to indicate that you just made an intentional WDT reset, or you can jump and hope for the best(not really recomendable).

You could also write a routine to reset the system to the same state as after a reset. But it might not be trivial since there are a lot of reserved memory addresses that Atmel (the manufacturer of AVR's the microcontroller used on the uno, mega, and others) recommends you never write to. So basically you would have to more or less manually set a lot of registers to their reset default (usually zero), in the right order (eg. first tri-state / set pins to input).

You can jump to the bootloader using this inline assembler code:

```
asm volatile ("jmp 0x7e00");

```

Optiboot fits in 512 bytes = 256 AVR words. The bootloader address can be found in the datasheet Table 27-13. Boot Size Configuration, ATmega328/328P. It is printed in the datasheet as the word address, but the avr-as assembler takes the byte address. Word address 0x3f00 * 2 = 0x7e00 byte address.

You can also see the address in optiboot\_atmega328.lst where code starts at byte address 0x7e00.

In order to jump past the boot source check we find the first address in optiboot\_atmega328.lst that comes after the check. It is 0x7e0a. We then modify our bootloader jump:

```
asm volatile ("jmp 0x7e0a");

```

You will want to make this jump first thing after a reset. We want to skip the Arduino initialization code. As per suggestion by user Comintern in another question you can write a `main` routine with a longer prototype to make the linker prefer it over the one shipped with Arduino:

```
int main(int argc, char** argv) {
  if (/* is your bootloader reset flag set in EEPROM */) {
    // first clear the flag
    // ...

    // Jump to bootloader, after reset source check (optiboot on atmega328)
    asm volatile ("jmp 0x7e0a");
  }

  // Else proceed same as Arduino main
  init();

  #if defined(USBCON)
      USBDevice.attach();
  #endif

  setup();

  //The one shot loop...
  loop();
  if (serialEventRun) serialEventRun();
  //Put whatever else you need to do between before the unending loop here.

  for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
  }

  return 0;
}

```

Note:

Using these jumps depends on your bootloader being exactly the one referenced. AFAIK that is the one the Uno ships with, but that could change in the future.

The code is untested.

The `main` overwrite trick depends on the linker exhibiting this behaviour which I think is also prone to change (it could be guaranteed by c/c++ standard, I don't know that).

---
Tags: arduino-uno, bluetooth, uploading, bootloader
---


# Question
Title: Find external router IP from Arduino Yun inside router network
I want two Arduino Yuns in different private networks to communicate, i.e., behind two distinct routers of which at least one does *not* have dynamic DNS, so its external IP may change from time to time.

To be reachable, this Yun could forward its router's external IP to the other Yun which has a fixed DNS name. But for this to work, it must be able to determine its router's external IP.

* How can the Yun find out that the external IP of the router has changed? The Yun will be runnning all the time.
* If the external router IP has changed (i.e., my Fritz.Box disconnects in the night and may receive a different IP when it reconnects), how can the Yun determine the new external IP?

If this is not the right place to ask, I'm happy for pointers to somewhere else (Server Fault SE forum?).

# Answer
> 0 votes
You can write a program that updates its own external IP every couple of minutes/hours, or when it doesn't get a response from another Yún/PC/server.

You can use this link (or find another site of the web that gives you your external IP address): http://www.realip.info/api/p/realip.php

This link has a beautifully formatted information that you can easily extract. I have a similar solution on one of my servers that have a dynamic IP...

---
Tags: arduino-yun
---


title: Why use .h files with .cpp?

text:
# Question
Title: Why use .h files with .cpp?
At school, our teacher always taught us to use .hpp (C++ Header files) with our .cpp (C++ files). But Arduino seems to use .h files (with .cpp links?).

---

When someone is programming in C (without C++ compiler) they have the chance to get linked to a .cpp file through a .h file?

* So why isn't a .cpp file always with a .hpp file?
* What are the drawbacks of using .hpp files with your .cpp files?

This is not to start a discussion on what's best, please provide an answer with arguments that are not based on "what you like to do more".

# Answer
The extension you use for a header file doesn't technically matter because the compiler never sees it. You could name it with the extension `.this-is-a-header-file` and it would probably still work.

The compiler only handles the C/C++ source files, typically named `.c` and `.cpp`. However, before that happens, the preprocessor goes through and looks for any `#include` lines. When it sees one, it basically copies the entire contents of the included file into the source file before it gets compiled.

This is normally used to include header files. However, the preprocessor doesn't know or care about different programming languages. All it does is process the raw text so there's nothing stopping you from including any text file you like, with any name or extension.

Choosing to use `.h` or `.hpp` is mostly just personal preference. You could certainly argue that it lets you (as a programmer) distinguish between C/C++ code more easily.

However, the reason why `.h` is more common is probably that C and C++ code is mixed so freely. You can generally compile C code as C++ without any problems, in which case it's the context (rather than the file itself) that tells you if it's C or C++. It's also possible to write a library in C++ which only exposes a C interface, meaning it could be used by C programs.

You could definitely include a C++-specific header file in a C program by mistake. All that would happen is that the compiler wouldn't understand the contents of that header file. Sensible development environments don't link to a project/library when it sees a `#include` directive (the Arduino IDE is the only one which does this, as far as I'm aware).
> 14 votes

---
Tags: programming
---


# Question
Title: Serial structure data transfer between an Arduino and a Linux PC
I use the Arduino compatible chipKIT WF32 board. I want to transfer structure data between my board and a Linux PC. Can I do it like the following?

```
struct data d;
char *tx = (char*)d;
Serial.print(tx);

```

Even if the above code works, the data type size in Arduino and on Linux will vary. Is there a way to serialize the data, like Protocol Buffers on Arduino?

# Answer
> 0 votes
The following solution isn't strictly portable, but it should work as long as both ends are little-endian (most platforms).

You can use the GCC attribute `packed` to tell the compiler not to pad the fields like this:

```
struct __attribute__ ((packed)) my_struct {
  char c;
  int32_t n;
};

```

Then you can send your struct like this:

```
Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

```

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use Python over C/C++ you can use the `struct` module to unserialize the data.

---

I just googled your product and the MIPS processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if `int`s keep their value after transmit. Also remember to use explicit size types such as int16\_t, uint64\_t, etc.

# Answer
> 0 votes
I usually send structures from arduino via serial port to PC ~~and use the memcpy function to do it.~~ Let's say you have the struct data d (*as pointed by the comments the memcpy as unnecessary. Use cast or union*):

```
 struct data state;
 len = sizeof(state);
 Serial.write((uint8_t *)&state,len);

```

It is useful to create a starting and ending character to delimit your important data and make sure you receive all data and good information. Let me give you one of my recent work example:

```
...

void send_state(){
 len = sizeof(state);
 Serial.write('S');
 Serial.write((uint8_t *)&state, len);
 Serial.write('E');
 return;
}
...

```

In this example the struct state is preceded with "S" (start) and succeeded with "E". Then in python, for example, you can get the data using the unpack function. In my case:

```
...

# wait for data from arduino
myByte = port.read(1)
if myByte == 'S':
    data = port.read(39)
    myByte = port.read(1)
    if myByte == 'E':
        # is  a valid message struct
        new_values = unpack('<c6BH14B4f', data)

...

```

See if arduino sends data in little endian. The one I have used to send it.

---
Tags: serial, arduino-ide, chipkit
---


# Question
Title: Problem with deploying matlab simulink mode to Arduino UNO
I encounter a problem when deploy matlab simulink model to Arduino UNO

Following shows the error

```
*The call to realtime_make_rtw_hook, during the after_make hook generated  the following error:
The build failed with the following message: The system cannot find the path specified
The build process will terminate as a result.
The build failed with the following message: The system cannot find the path specified。
Component: Simulink | Category: Block error*

```

When type \>\> getenv('path')

```
ans =

C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\MathWorks\runtime\win64;E:\MathWorks\bin;E:\MathWorks\polyspace\bin;C:\Program Files\MATLAB\R2014b\runtime\win64;C:\Program Files\MATLAB\R2014b\bin;C:\Program Files\MATLAB\R2014b\polyspace\bin;C:\Program Files\Microsoft Windows Performance Toolkit\

```

I did not see anything wrong with the path. I tried to solve the problem following the "http://www.mathworks.com/matlabcentral/answers/168555-what-does-the-path-in-the-system-cannot-find-the-path-specified-refer-to". However it does not work.

Anyone know how to solve it?

OS:Win8.1 Matlab 2014b 64bit

# Answer
> 0 votes
Right click on your MATLAB shortcut and click "run as administrator". See if helps. Then do all the necessary steps and see if it happens again.

Also test with x86 version. I have seen lots of these kinds of error with x64 version. Always had compiling related issues with MATLAB x64 and Simulink!

---
Tags: arduino-uno, matlab
---


# Question
Title: Is it possible for a HC-05 Bluetooth module to have multiple slaves
For a project I am interested in using the HC-05 Bluetooth module to control five LEGO Mindstorms Bricks simultaneously. For this to work the Bluetooth module will obviously have to be paired / connected with the five bricks at the same time. This means that the HC-05 Bluetooth module will have to be master in the piconet and the five bricks the slaves.

Is there anyone who has any experience with using the Arduino Uno and HC-05 Bluetooth module to send data to multiple, connected, slaves? If not, are there any alternative Bluetooth modules? And if Bluetooth modules compatible with the Arduino Uno cannot connect to multiple slaves at the same time, are there other ways that an Arduino can control multiple Bluetooth slaves at the same time?

# Answer
After some research, it looks like multiple slaves aren't possible with this particular module.

According to Wikipedia the Bluetooth technology allows a master to communicate with 7 slaves, but this option isn't implemented in the HC-05.
> 1 votes

---
Tags: bluetooth
---


# Question
Title: Alternative Way to Power Components on an Arduino
I have very limited knowledge regarding electronics. Please help me cure my ignorance on the subject of robotics.

I want to power the Arduino Uno R3, US-015 ultrasonic sensor, and the L298N motor controller from a single power source (7.2v). However, I'm not sure if this diagram is correct. If it is functional, will it last that way?

If this diagram is deemed wrong, please suggest alternatives with one power source.

Advance thanks to those who would reply. Elaborate answers would be very much appreciated. :D

**Edit:** Since it's deemed incorrect, I'm going to power Arduino through the DC barrel jack and power the L298N motor controller through the Vin and the ultrasonic sensor from the Arduino 5v output. Is it wise to do this?

# Answer
Using a motor controller to power an Arduino or analog peripherals is probably unwise as the source is liable to be noisy.

Better, probably, is to power the Arduino from the 7.2V supply via a noise filtering resistor into the Arduino's **Vin** terminal.
**NBNBNB** 7.2V input **MUST** be to Arduino Vin.

Use a small series resistor from 7.2V to Vin and a large filter cap at Vin to ground. Then power the sensor from Arduino 5 V output.

Voltage drop in series resistor from 7.2V to Vin must drop under 2V.
Rmz is \<= Vdrop / Iload
For say 50 mA load Rseries = V/I = 2V max / 0.05 = 40 Ohms . For 100 mA R \<= 2/.1 20 Ohms.
So probably try about 22 Ohms to start.
If Vdrop is \> 2V a smaller R is needed.
If Vdrop is \<\< 2V increase R.

For the capacitor at Vin - the larger the better.
100 uF good. 1000 uF better.

Resistor power dissipation is I^2 x R.
So at even 100 mA Pres = 0.1^2 x 22R = 0.22W
A 1/2 Watt resistors would suffice. A 1 W resistor would do no harm and would tolerate the heat better.

---

The 22 Ohm resistor and large capacitor form an RC (Resistor + Capacitor) noise filter.
This greatly reduces motor noise which appears on the 7.2V line.
This is very standard practice in real world installations like this.
An inductor based filter can be better but RC should suffice.
> 2 votes

---
Tags: arduino-uno, power, motor, arduino-motor-shield
---


# Question
Title: Arduino voltage drop while communicating with another Arduino
I have an Arduino Uno rev 3 and an Arduino Nano in my Setup. I want to create a proof of concept, where one Arduino triggers the other via the Digital IOs. Arduino 1 sets a blinking signal on a digital pin (500ms delay between high/low), which is received by arduino 2. If the signal is high, Arduino 2 triggers a LED (digital pin to LED+; LED- over 330 Ohm resistor to ground), so the signal gets looped through somehow. The grounds of the two Arduinos are connected, too.

Code Arduino #1:

```
void setup() {
  DDRD |=_BV(PD7); //Sets Digital Pin 7 as Output
}

void loop() {
 PORTD |=_BV(PD7); // equivalent with digitalWrite(7, HIGH);
 delay(500);
 PORTD &=~_BV(PD7); // equivalent with digitalWrite(7, LOW);
 delay(500);
}

```

Code Arduino #2:

```
void setup() {
  DDRD &=~_BV(PD7); //Sets Digital Pin 7 as Input
  DDRD |=_BV(PB0); //Set Digital Pin 8 as Output
}

bool set = false;

void loop() {
  if((PIND&_BV(PD7))==_BV(PD7)) { //true if digital pin 7 is set
    if(!set) {
      //PORTB |= _BV(PB0);
      digitalWrite(8, HIGH);
      set = true;
    }
  } else {
    //PORTB &=~_BV(PB0);
      digitalWrite(8, LOW);
    set = false;
  }

}

```

But instead of emitting a bright light, which can be seen if connecting the blinking signal directly to the LED, it emits a faint light. The voltmeter also shows an significant Voltage drop. Whilst the digital pin should have a voltage of ~5V when set to HIGH (never reached because of inner resitance inside the arduino), it measures about 1.6-1.8V. I also switched the both Arduinos which showed the same result, so it shouldn't be a hardware defect.

Thanks in Advance!

# Answer
the line `DDRD |=_BV(PB0);` should be `DDRB |=_BV(PB0);` currently PB0 is set as an input so when you set it high it is just turning on the pull-up resistor, which is basically adding another ~10k in series with the LED, hence the dim light.
> 3 votes

# Answer
A couple of delays in the Arduido #2 if(!set) { } else { } might allow the LED to stay on long enough to be seen.

At the moment this is rapidly switching the LED whenever the digital pin7 is set.
> 0 votes

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


# Question
Title: Questions Concerning Arduino Compatible Boards
I've seen an Arduino-compatible board called Bluno from DFRobot. I'm curious if a shield, specifically the DFRobot motor shield can be connected to the Bluno.

Can anyone confirm if it can be connected with a shield?

# Answer
The Bluno is identical to the Uno, except the USB-to-serial chip, also supports BT. So it won't be a problem.
> 1 votes

---
Tags: arduino-uno, bluetooth, arduino-motor-shield, robotics, electronics
---


title: Overriding main function in Leonardo

text:
# Question
Title: Overriding main function in Leonardo
I've trying to write my code in plain C++ dropping out the Arduino's IDE. Although I've succeed in compiling the code, whenever I try to upload it to the board it doesn't run, seems that it stucks at some unknown point.

After that, everytime I try to upload a new code to the board it stops responding and avrdude throws this message:

```
$ ino upload -m leonardo -p /dev/ttyACM1
/dev/ttyACM1 doesn't exist. Is Arduino connected?

```

It doesn't matter if I unplug and then plug again the board, that message is still showing up.

In order to restart the board, I open the Arduino IDE and then I upload any sketch, then the board comes to live again.

The first time I tried overriding the main() function and the program didn't run I thought it was the tool I was using at that moment, *arduino.mk*, the one that was doing something strange.

Then I tried the *ino* tool, but the result was the same.

I don't think *avrdude* is failing because it actually uploads the .hex to the board.

My original main() code was:

```
#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    pinMode(LED_PIN, OUTPUT);

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);
    }
    return 0;
}

```

Then I tried to mimic the one that comes with Arduino:

```
#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    pinMode(LED_PIN, OUTPUT);

#if defined (USBCON)
    USBDevice.attach();
#endif

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);

        if (serialEventRun) serialEventRun();
    }
    return 0;
}

```

Sadly, with both codes the board gets stucked at some point.

While I figure out how to solve this issue I've been exercising this solution inside a sketch:

```
const int LED_PIN = 13;

void setup() {
}

void loop() {
    pinMode(LED_PIN, OUTPUT);

    while (1)
    {
        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);
    }
}

```

Any ideas that led me to a solution? Thank you!

# Answer
**Solved!**

It was a (big) silly mistake of my own. I overloocked the init() function right after entering the main() function. I'm shure it initializes the hardware and the entire system, so my board stucks when I skipped it.

So my code now looks like this:

```
#include <Arduino.h>

const int LED_PIN = 13;

int main(void)
{
    init();

#if defined (USBCON)
    USBDevice.attach();
#endif

    pinMode(LED_PIN, OUTPUT);

    while (1)
    {

        digitalWrite(LED_PIN, HIGH);
        delay(100);
        digitalWrite(LED_PIN, LOW);
        delay(900);

        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```

BTW, the mix: Arduino + Vim + ino, rocks! Now I can do whatever I want from the console :)
> 2 votes

---
Tags: arduino-leonardo
---


title: Infrared TV Remote to Arduino

text:
# Question
Title: Infrared TV Remote to Arduino
On the hardware side of things, what is involved in making the Arduino receive signals from a TV Remote? What kind of infrared receiver is needed? Do TV remotes use some kind of channels, encoding, or encryption requiring special receivers or else additional programming work to decrypt the signals?

# Answer
The most common (not sure what others are used) carrier frequency is 38khz. You need an IR receiver tuned to that frequency to get the signal from the remove. See this page for way more information.

There is no encryption or special receivers needed as long as the carrier frequencies match.

That's really all the hardware you need. On the software side of things, you read this signal and decode it. There's a neat little library for doing exactly that. It's called Arduino IRemote.

It even has an example sketch which tells you just what the decoded value is of whatever button you pressed so you can use that in your other programs.
> 3 votes

# Answer
Responding to TV remotes is surprisingly simple, because they typically all work on exactly the same principle, with no concept of channels or encryption.

What you need is an IR receiver module, which you can buy fairly cheaply from many electronics suppliers. Anything intended to work with remote controls should be suitable. The important part is that it will work with ~38 kHz signals.

It will typically be a 3 pin component. Many are able to operate at 5 volts, which means you can usually connect the IR module's voltage and ground pins directly to the Arduino's power supply. The data (or signal) pin can typically be connected straight to any GPIO pin. Always check the component's data sheet though. It will often recommend using some additional components (e.g. resistor and capacitor) to smooth out power fluctuations. That shouldn't be necessary for a small project though.

When an IR signal is detected, the module will usually output a series of pulses on the data pin. These will be digital pulses, so there's no need to use an analog-to-digital converter. What matters is typically either the length of each pulse (Pulse Width Modulation), or the length of the gap between consecutive pulses (Pulse Distance Modulation).

The timings of the pulses/gaps will be very fast; usually in the region of 400 to 2000 microseconds. That means it's probably too fast to try to detect them using repeated calls to `digitalRead()`. Instead, there is a core Arduino function called `pulseIn()`. When it's called, it will wait for a pulse to arrive on the specified GPIO pin. It will then return the approximate length of the pulse. You can detect high pulses for PWM, or low pulses for PDM.

Precise timing values will vary considerably, so you can ignore small variations. The key is to categorise each pulse as short or long, corresponding to a binary 0 or 1. A good starting point is to consider anything below 1000 usec as short, and everything else as long. Check what timings you actually receive though, and adjust that value accordingly.

Call `pulseIn()` repeatedly, storing each result. Keep going until no more pulses arrive (you will need to give it a timeout after which it gives up waiting, e.g. 10,000 usec or more).

Your TV remote will output a unique sequence of short/long pulses for each button, typically 32 bits or less (possibly with extra pulses at the beginning/end). All you need to do is figure out which sequence corresponds to each button. You could store that information in a lookup table, and respond accordingly when a sequence is recognised.
> 3 votes

# Answer
A simple IR diode like this can receive raw IR data. There are several chips which are designed to decode these signals, such as this one.

----------------

Ir Diode ------------------------------- Ir Decoder
> 1 votes

# Answer
I used TSOP1738 which is easily available at cheap price and I recorded values from more than 10 remotes and it worked very well.

Here is a file which contain recorded values of a Videocon DTH setup box's remote
> 1 votes

---
Tags: remote-control, ir
---


# Question
Title: Ultimate GPS Logger Shield : Soft Serial Sketch Error
Im using a OSEPP Uno R3 Plus to connect with a Ultimate GPS Logger Shield. I am currently working through the Adafruit Ultimate GPS Logger Shield pdf. When connecting in Soft Serial Mode and loading a parsing sketch. In the com window my values are showing but unreadable. I have included an image. Any help is appreciated.

# Answer
> 1 votes
jfpoilpret \> My apologies for not including enough information and details. But your comments did lead to me resolving my issue. I did not change my baud rate to match the baud rate of the source code and the script is working now. Appreciated.

---
Tags: tinygps
---


# Question
Title: Anyone have the Maplin N97DG bluetooth shield working?
I went & impulse-bought a Maplin Bluetooth shield yesterday.

It comes with a little tiny book containing examples, and uses the softwareserial library in these; I can load them, and get the Arduino \<-\> PC communication going OK, however there appears not to be a response from the bluetooth part of the device. The LED lights much as the booklet says it should. I did see it return some odd characters one time, just the once..

Given that the system appears to be alive, I don't want to give up & take it back; however the output from Google is not promising, and my trial to date isn't either - so I'm looking for positive news that this product does actually work for someone somewhere?

I'm using the built-in serial in the IDE to talk to it, not X-CTU as they suggest (as they don't do a Linux version).

# Answer
> 1 votes
I've just got mine working, in about 3 hours.

The first example I've never got working. The SAT+RESET worked first time... and I was then able to pair.

An easier module is the HC-05. That by default goes straight to discovery mode, and makes things alot easier.

I have more success with the serial monitor in Arduino studio, rather than X-CTU.

The point of the sheild is to prototype, or the shield you have to use in your production project. If you are doing the former, then there is little point in using the shield as you would have to change the code to fit the hardware.

It seems a thorough product, probably too involved.

---
Tags: arduino-uno, bluetooth, softwareserial
---


title: EEPROM value reverting to 255

text:
# Question
Title: EEPROM value reverting to 255
When I write '13' to the EEPROM and read it straight after it works correctly.

However when I comment out the write part of the code and try to just read the data, the value is no longer 13 as it used to be but reverts back to 255. Whats going on?

I am running a standalone atmega328 on a breadboard with a 16mhz crystal, programmed by a Nano R3.

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

//EEPROM.write(1,13);
}

void loop() {
scoreBinary();

}

void scoreBinary(){

int score= EEPROM.read(1);

if(score==13){
digitalWrite(2,HIGH);
}
delay(10000);
}

```

# Answer
> 4 votes
By default the EEPROM in the MCU is erased (to 0xff) when the chip is erased before flash is written to. If you want to prevent this then you will need to program EESAVE in the fuse bits, which is bit 3 in the high fuse byte of the '328.

---
Tags: atmega328, eeprom
---


# Question
Title: MP3 Shield stacked on DMX Shield - Arduino Uno
We are using Arduino Uno revision 3, with TinkerKit DMX Shield rev. 4 and Sparkfun Mp3 Shield.

We uploaded the Mp3 Shield example called FilePlayer and after we open the serial monitor, the interface is there and working. The problem is that it won't output the music from the SD card.

If we ONLY stack the Mp3 Shield onto Arduino, it works.

Is there some king od incompatibility between the DMX and Mp3 Shield, and if there is, what would be the solution, maybe some kind of bypass, since we aren't that familiar with what pins the DMX shield uses for it's purpose. ATM the Tinkerit site is down so we can't acess the TinkerKit DMX Shield datasheet.

# Answer
> 1 votes
Yes, overlapping is a problem, by default the MP3 Shield uses digital pins 2(DREQ),6(mp3CS),7(mp3DCS),8(RST),9(SD-CS),11(MOSI),12(MISO),13(SCK)

The Tinkerkit DMX Master Shield R4 uses 2(RE-ENn),3(VTX),4(VRX),5(DE-EN),6(D6)

So there are conflicts with D2 DREQ vs RE-ENn and D6 mp3CS vs D6.

The DMX Master Shield basically converts the UNO's serial to DMX. If nothing is at first included into the Sketch for this, then the problem is with only D6. Leave this jumper OFF. And I suspect the MP3 Shield will work stacked.

To use them together you can move the pins, as demonstrated at https://www.youtube.com/watch?v=behMgV3tUr4. Noting that is for different pins. And of course you will need to subsequently change their definition, in the sketch.

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


title: 7-Segment Common Anode

text:
# Question
Title: 7-Segment Common Anode
I accidently bought a "Common Anode" 7-segment display instead of a "Common Cathode".

I understand that the polarity of the leds within the display is 'reversed'. So instead of putting the common pin on GND I have to put it to 5v (with current limiting resistor)

My questions on this are:

1. Can I still use only one current limiting resistor on the common pin? Instead of a resistor on every segment pin.
2. Can I use the pins from arduino to drive it (withouth pull-up/pull-down?) By making the signal `LOW` the current will flow from 5V common anode to the arduino and thus the segment wil light?
3. Can I still use a shift register to drive the segment led? (By inversing the outputs (in software))

---

**Obviously I would like to have wiring more like this** (but then I would ofcourse change the GND line to a 5V line.

---

**The wiring below is the worst-case wiring I can think of.**

^ So can I avoid this, when using a `Common Anode 7-segment display` or am I forced to buy a `Common Cathode 7-segment display`?

# Answer
You can use a single resistor on the common pin if you want. The problem is that lighting up multiple segments at the same time will substantially reduce the brightness of each one. You could work around that by lighting each segment one at a time in very quick succession though.

It should be possible to control the display directly from the IO pins by setting them LOW. In this configuration, they will be **sinking** current (rather than **sourcing** it). It depends on the specification of the display and on what resistor you use though.

Basically, try to keep the current **below 20mA** and it should be OK (assuming you're using a standard 5V Arduino). For example, if each segment has a forward voltage drop of 2V, you would want to use a resistor of around 180 Ohm.

Controlling the display directly from a shift register is probably not possible, although once again it depends on its specification. Shift registers usually aren't designed to sink enough current so you'll need something like a transistor on each output.
> 3 votes

# Answer
Sorry about the crudity of my image, but you don't always need those transistors. Peter has already said so, but I wanted to explain a bit further.

The only thing is that you need to set a pin to LOW to light up the led, and HIGH to turn it off. Just use a `!` to make your code more intuitive if your like. So e.g. `digitalWrite(segmentA, !HIGH)`

Some limitations. A pin can sink up to 40mA (no problem here), but the total sink current for the digital pins `0` to `4` shouldn't exceed 100mA. The same goes for pins `5` to `13`. And the same goes for the analog pins. So either limit the current through the leds to around 10mA, or make sure no more than 5 leds are lit at the same time, or connect half of the segments to on of the above mentioned groups, and the other half another (f.y.i. analog pins can be used just like digital pins).
> 4 votes

# Answer
Peter and Gerben have already said what is needed , but I wish to explain things even further.
A normal small 7-Segment display consumes only **70-80mA** when all segments are HIGH.So you can use the Arduino directly without damaging it. Also note, depending on the quality of the project, you could either use a common resistor for all segments, or use separate ones. Separate ones will give much brighter light and better quality.
A medium size one will require max consumption of around **400mA** current, so use cheap transistors.
A large size one will require max consumption of upto **1.5-2A** current , so use MOSFETS or other high current Transistors.
An Extra Large one will require max consumption of upto **10-25A** current, so use good MOSFETS or maybe even Relays.
***Usage**
Small- Wrist watches
Medium- Small clocks
Large- Big clocks
Extra Large- Very big clocks like ones in Railway stations
*
> 1 votes

---
Tags: led, electronics
---


# Question
Title: Communicate with custom usb slave device with DUE?
I have a arduino due which i know has usb host mode. The usb library that comes with the due supports mouse and keyboard.

I have another usb device (diacnostic tool) id like to talk to, it use a: USB Com Board Driver ( Multi-instance ) TI USBN9604 "Universal Serial Bus Full Speed Node Controller with Enhanced DMA Support" datasheet: www.ti.com/lit/ds/symlink/usbn9603.pdf

Ive also logged the raw byte usb traffic between windows and it when operating and would like to try sending some of those same calls to the device with the due.

Where do i start ?

Example Capture:

```
    000000: PnP Event: Device Connected (UP), 12.04.2015 09:14:51.390 (1. Device: USB Com Board Driver ( Multi-instance ))
The USB device has just been connected to the system.
000001: Bulk or Interrupt Transfer (DOWN), 12.04.2015 09:15:14.953 +23.562 (1. Device: USB Com Board Driver ( Multi-instance ))
Pipe Handle: 0x8639885c (Endpoint Address: 0x6)
Send 0x1b bytes to the device
 40 05 17 C0 00 09 02 00 AA 00 00 00 00 00 00 00
 00 00 00 00 00 00 00 00 16 06 12

```

# Answer
i found what i needed here: http://arduino.cc/en/Reference/USBHost and https://github.com/felis/USB\_Host\_Shield\_2.0
> 1 votes

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


# Question
Title: How to make universal remote controller?
I am trying to make simple TV remote using Arduino.

I got this link from Google for making a remote.

Code uploaded perfectly on my device. But all it does is blink a the LED on pin 13.

I hope I have got right code. I have tested it on my TV at home. Is that the correct way of testing it?

IR receiver I have is TSOP-15

P.S. I am completely new to Arduino

The below shown is my Arduino board(induino r3)

# Answer
As you've stated in your question, the TSOP-15 is a receiver. That means it detects infrared signals rather than sending them out.

To make a remote control with that code, you need a simple infrared light emitting diode.

It's also important to note that you need to know what signals to send. Different TVs will have different IR codes, depending on the manufacturer. That information can be detected using your receiver module along with your TV's proper remote control.
> 1 votes

---
Tags: ir, remote-control, testing, induino
---


# Question
Title: What board to use to send a text message via an arduino board
I am fairly new to arduino boards and I was wondering which board to use. I was looking into the edison board because it has built in wifi and bluetooth.

# Answer
> 2 votes
The GSM Shield will suit your needs. This is a *shield*, meaning that is a board that will go **on top** of another Arduino board (e.g UNO, Leonardo, ..., choose whatever you'll need).

This is what it will look like:

To send SMS you'll also need a working **SIM card** and the **GSM library** to program the shield. On the previously linked page there are some tutorials to follow in order to check the basic functioning of the setup.

# Answer
> 2 votes
Another option is the Spark Core or Photon. It's not an Arduino but it's very close. I have Arduino sketches that I have ported right over with no modification.

The Spark boards are internet-connected and you can send text messages or emails using IFTTT. It's also going to be a lot more cost effective than an Arduino plus wifi shield, particularly if you can wait until June for the $19 Photon to ship.

You could also use a Raspberry Pi connected to the internet to just do the email part but that's a little more trouble than it's worth.

# Answer
> 0 votes
Actually, you should use a Raspberyy Pi if your project involves complex processing in it.
But if the project is very simple, just use one of those Spark Core or Photon.
Using an Arduino and a Sheild to do it is certainly **not** a good idea, as the Pi is much faster in processing and costs about the same.

---
Tags: arduino-galileo, edison
---


# Question
Title: Detect movement on moving robot? PIR Sensor
I am working on a human following robot project and I am trying to achieve this with 1 Ultrasonic sensor that makes sure the robot won't crash into something and 3 PIR sensors that will detect human movement.

The robot has an Ultrasonic Sensor and a PIR sensor attached to the front and a PIR sensor attached to the right side and another PIR sensor attached to the left side.

If the front PIR reads HIGH, then the robot will move forward. If the left or right PIR reads HIGH, then the robot will start turning in a 360 degree motion to the left/right side and will keep on doing so until the front PIR reads HIGH, and the robot moves forward again.

I am currently working with this build and I am having issues with the sensors. Sometimes they read HIGH when they shouldn't and sometimes they read LOW when they should be reading HIGH.

So my question is, what can I do to help the PIR sensors with getting the correct reading and is it possible to do so while the robot is turning?

Also, how will calibration work here? Am I able to let the robot turn slowly in 360 degree motion so the 3 PIR sensors will be calibrated with the rooms surrounding or is this a dumb question? If so I'm sorry, I am pretty new to PIR sensors.

---

UPDATE:

Thanks for the help everyone. I have now replaced the side PIR sensors with Ultrasonic sensors. I have kept the front PIR sensor though. It is working a lot better than with the side PIR sensors and I thank you all for your input.

# Answer
> 1 votes
Basically you have a robot and sensors that can detect movement. There is one caveat though. For the PIR sensors to (non false-positive) detect motion, they have to be stationary (as far as I know).

So with only these PIR sensors it's unlikely that you can track something well. Tracking something would be done best by using a range/proximity sensor.

---

The image below, seems to be a cute robot, with eyes. You could take 3 sensors and place them under an angle (one forward, one forward/left and one forward/right) \[picture 2\]. Or just have one that rotates (will be more difficult) \[picture 1\].

You would want the robot to start following anything that comes close (or when one of the sensors sees a difference in distance. And then the robot will try to keep that distance, brake when he gets closer, drive when he gets further.

If that's working, you can implement the sensors at the side, that if suddenly he loses track of the object/person, he'll adjust his alignment so that the middle sensor sees it again. This could also be done by simpler sensors \[picture 3\]

When the robot gets to close, and the other object doesn't try to run for quite a time, you can make him check for another target. (With a PIR or by rotating and stopping rotating to check range/pir)

I believe this solution is more applicable as with only PIR sensors, as it's usefull to know the range when you're following something. You don't want to bash into it.

# Answer
> 0 votes
Try using ***heat detectors**(technically speaking, **Infrared sensors**)* (along with \>1 Ultrasonic sensors and PIR motion sensors for greater accuracy) with 1 ultrasonic sensor. Comment if you want more help.

---
Tags: arduino-mega, sensors, robotics
---


title: Getting started

text:
# Question
Title: Getting started
so I am not a newbie to computers or programming. I regularly program in C# and Java, know quite a bit about computer hardware and operating systems. But I am bored of writing stupid calculators or game bots. I want something exciting and something that involves physical hardware. So I want to get into electronics and micro-controllers. I was wondering how I should go about this? Any topics I should read first? How electrics work maybe? Any guides I should skim over? I plan to buy the Arduino starter kit and a load of components, along with a soldering iron etc soon; but want to get reading now. I do not need to go right into the advanced stuff but I like to know how things work before I use them; not just "plug this wire here to do this". Any help is much appreciated.

# Answer
The best way to get started is surely by reading a book, I would recommend

Besides, there are many tutorials on YouTube also to start with.

But books are just one thing. Arduino or electronics is more about getting a hands on experience. Even if you have read a hundred times on how to blink a LED it is difficult to do it when doing it on hardware. So the best thing for you is to work with small small codes.

Say initially just blinking a LED(thats like the HelloWorld of electronics) and then moving on two patterns with LED. As you get used to the IDE and the hardware move on to more challenging projects like simple DC motor control or servo control. Try and make your own projects with your imagination. The challenges which you face teaches you more than any book. Then move on to serial and wireless communication and try working with a few sensors on the ADC and start making small projects.
> 3 votes

# Answer
A quick search on Amazon found a number of basic books on electronics. I'm not familiar with any of them to recommend one of them. But "plug this wire here to do this" isn't a bad way to start - you'll probably have some questions about what this component is for or why they had you connect it the way they did. That will give an immediate direction to your studying which in turn will bring in some more questions and more information.

If you really want some basics ahead of time (noting that I don't know what will be basic for you), you might search for Ohm's Law (voltage and current through a resistor), and Kirchoff's Laws (voltage and current in electric circuits), and follow any leads that look interesting. Look up some common components that you'd find in a starter kit, like resistors, capacitors, and LEDs. But things will begin to get "real" for you once you have parts in hand and start using them to make some basic stuff like making lights blink or fade, motors turn, and buzzers buzz.
> 2 votes

---
Tags: arduino-uno, programming, electronics
---


title: Use same ground with 2 wires?

text:
# Question
Title: Use same ground with 2 wires?
So I have 3 ground pins, but I need 4 motors on my Arduino. Can I connect multiple motors to the same ground pin?

# Answer
> 2 votes
You can do it as long as the current isn't excessive. I don't think there are any specs available, but the connector and the width / thickness of the copper tracks on the PCB will be the limiting factor.

# Answer
> 2 votes
All ground is internal connected.
But anyway, you CANNOT use the Arduino's power to power a motor, you will need an external power source.And again, you will connect the external power source's ground to the Arduino's ground.

# Answer
> 1 votes
You can connect multiple components to a single ground pin. IF you are using a breadboard, be sure to put the wire going to the go

---
Tags: pins
---


title: Problems with L293D

text:
# Question
Title: Problems with L293D
The motor are not rotating in the above circuit . Or rather the Voltage between the two Motor Terminal is zero. I have checked the Pin 10 & 11 and Pin 12 & 13. They are fine and produces desired Voltage.

When I have earlier connected the circuit only to one motor then it worked\[ there were no motor right, Pin 12 and Pin 13\]. But now, it's not.

What's the problem? The code in the arduino is as follows:

```
const int echo = 7;// connected to ultrasonic sensor's echo
const int trig = 8;// connected to ultrasonic sensor's trig
const int Right1 = 10;
const int Right2 = 11;
const int Left1 = 12;
const int Left2 = 13;
void setup() {
  pinMode(echo, INPUT_PULLUP);
  pinMode(trig, OUTPUT);
  pinMode(Right1, OUTPUT);
  pinMode(Right2, OUTPUT);
  pinMode(Left1, OUTPUT);
  pinMode(Left2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);
  int duration = pulseIn(echo, HIGH);
  int cm = microsecondsToCentimeters(duration);
  if (cm > 4)
  {
    digitalWrite(Right1, HIGH);
    digitalWrite(Right2, LOW);
    digitalWrite(Left1, HIGH);
    digitalWrite(Left2, LOW);
  }
  else
  {
    digitalWrite(Right2, HIGH);
    digitalWrite(Right1, LOW);
    digitalWrite(Left1, LOW);
    digitalWrite(Left2, HIGH);
  }
  delay(50);
  Serial.println(cm);
}
long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

```

# Answer
Try these steps

1. Increase the delay of 50ms to a longer time.

If that fails to work try,

2.Running the motor by just directly connecting the terminal to the 9V battery which you are using.

If the motor runs then most probably the motor requires more current than what the L293D can output which as per the data sheet is 600mA. A solution to this would be using a higher current motor driver like L298N.

If the motor doesn't run directly by the battery then well change the battery to one which can supply enough current.
> 1 votes

---
Tags: arduino-uno, motor, h-bridge
---


title: Servo Keeps Trying to Turn

text:
# Question
Title: Servo Keeps Trying to Turn
I currently have a servo wired to my Arduino and have imported the Servo.h. Here is my sketch:

```
#include <Servo.h>

Servo s1;
Servo s2;

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

  s1.attach(8);
  s2.attach(9);
}
int pos = 0;
void loop()
{
  pos = 0;
  if(s1.read() != pos)
    s1.write(pos);
  if(s2.read() != pos)
    s2.write(pos);

  delay(1000);
}

```

The problem is that even when my servos are at the position 0 it still tries to turn and I hear it trying. What do I have to do to tell it to stop turning once it is already at the desired position?

So this is my second bit of code:

```
s1.write(0);
  delay(5000);
  s1.write(100);
  delay(5000);
  s1.write(180);
  delay(5000);

```

When I write them to 100/180 (or any number) they are silent after the turn, but when I write them to 0 I hear them keep trying to turn...

# Answer
The reason they keep trying to turn is mechanical. The physical stop in the gears is hit before the encoder/potentiometer reaches its end point.

You can make the servo stop fidgeting by completely relaxing it if you want. just use

```
s1.detach();
s2.detach();

```

and your arduino will stop sending any signal.

Bear in mind that "reading" the value of a servo in arduino gives you the servo's current set point, not its current location. Your code in unfortunately unaware of a servo's actual location. With that in mind, setting your servo to go to 0, waiting for it to get there with a delay, and then detaching it will have the desired effect, but since it will not maintain position and you will need to reattach it to function again, using 1 or 2 as your far left endpoint is likely the better option.
> 2 votes

# Answer
A common reason is could be because your servo cannot operate at a PWM signal of 0ms. For conservative limits, you should stay between 100ms and 2800ms even for very high quality servos. With lower quality servos that do not specify maximum and minimum values, conservative limits are 700ms to 2400ms.
> 0 votes

---
Tags: servo
---


# Question
Title: General Question about fast Serial Communication and Arduino
I'm looking for a fast (and safe, in terms of stability) way to send sensor data from an Arduino UnoR3 in real time to a Computer (in my case a MacBook Pro) with a sample rate of at least 1kHz.

I tried following:

* Sending sensor values with the related timestamp (in microseconds): I use 7 bytes for each sample \[1 Header byte, 2 bytes for the sensor value (10/(16)bit-Int), and 4 bytes for a 32-bit unsigned long (time in microseconds)\] and send them right away.
* On the receiving end i mainly use Processing (Im relatively new to Processing though): Reading the bytes in, converting them in integers and safe them in a file or plot them.

For sampling rates of 1sample/10ms my code runs smooth and i even can plot the data in "real-time".

For higher frequencies i ran into following problems:

* If i want to plot things, my peripherals freeze and program stops after some time. I have no clue why... maybe serial buffer overflow??
* If i just save the data in a text file (without plotting) it works but with a delay of around 20-30seconds on total sampling times of 10seconds (10000 samples). Meaning that somewhere seems to be a bottleneck and i cant keep up with the sent samples from the Arduino. Is it possible that the serial bus is the bottleneck here? How can i speed things up? (I'm working with a baudrate 115200bits/s and also 230400bits/s)

How can i improve this while still be able to process data in almost real-time (e.g plotting). Is this even possible or do you recommend logging the data in a text file first and then plot?

Will it helps to send the data in packages (10samles = 70bytes)?

I added a timestamp on each sample, since i observed some delay between the actual sensor measurement and the input on the receiving end. I thought that would allow me to plot and postprocess accurately in "real"-time (with a little delay). Any other ideas?

I would appreciate some input and advice!

Thanks in advance!

# Answer
> 1 votes
You are sending data at ~70kbps. Provided you use serial rate greater than this (115.2 kbps or faster on the Arduino) there should be no problem, assuming you samples are processed quickly enough. This seems to be the case.

Your problem seems to be on the Mac. With a quad core CPU on a fast multitasking machine this should not be an issue. If you are having problems this would be in how you are processing the data. I am not familiar with `Processing` but you could do this in any language. You need to separate the data logging from the processing and display task. This could be as simple as running a logger and piping the data into a display program.

This is not an Arduino issue (or even a Mac issue), you should ask on https://stackoverflow.com/. NOTE if you want help there you will need to give more detail of the code you are running in the Mac.

---
Tags: arduino-uno, serial, communication, processing-lang
---


# Question
Title: How to send the MFRC522 RFID module into sleep mode?
I'm trying to get the power consumption of a MFRC522 RFID module down, currently while running it consumes about 4mA. There should be a way to put it into sleep mode, I just can't find any documentation on it. I'm using the module with a arduino currently if that helps; and this is the module itself : MFRC522

# Answer
http://www.nxp.com/documents/data\_sheet/MFRC522.pdf

Look at section `8.6.2 Soft power-down mode`.
> 1 votes

---
Tags: arduino-uno, power, rfid, sleep
---


title: Memory Problems on Arduino Uno

text:
# Question
Title: Memory Problems on Arduino Uno
I am doing a project using Arduino UNO, cc3000 WIFI chip, micro SD card shield, and a TTL serial camera in order to make a security system that will post a picture online (not enough processing power for video) when motion is detected on the camera.

Thankfully, the hardware works after a few shortcomings, but my program seems to be taking up 97% of the Flash storage.

Also, I am looking for a better way to transfer the image than saving it 32 bits at a time and then waiting about 10 sec so the HTTP request will send it to the server.

One thing I do know is that I have tested all the hardware and those functions are working. My problem is in the logic.

Any help appreciated! (Image is around 13KB and UNO only has 2kb of dynamic memory).

My full code is here: https://www.dropbox.com/s/arxa253mxwvqtg1/HomeProj.rtf?dl=0

```
void loop(void)
{
    cam.setMotionDetect(true);

    while (1) {
        if (cam.motionDetected()) {
            Serial.println("Motion!");

            cam.setMotionDetect(false);
            if (! cam.takePicture())
                Serial.println("Failed to snap!");
            else
                Serial.println("Picture taken!");

            uint16_t jpglen = cam.frameLength();
            Serial.print(jpglen, DEC);
            Serial.println(" byte image");

            char filename[13];
            strcpy(filename, "IMAGE00.JPG");
            for (int i = 0; i < 100; i++) {
                filename[5] = '0' + i/10;
                filename[6] = '0' + i%10;
                // create if does not exist, do not open existing, write, sync after write
                if (! SD.exists(filename)) {
                    break;
                }
            }

            File imgFile = SD.open(filename, FILE_WRITE);
            while(jpglen > 0) {
                uint8_t *buffer;
                uint8_t bytesToRead = min(32, jpglen);
                buffer = cam.readPicture(bytesToRead);
                imgFile.write(buffer, bytesToRead);

                //Send Request
                Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
                if (client.connected()) {
                    Serial.println("Connected!");
                    client.println("POST /upload HTTP/1.0");
                    client.println("From: Arduino");
                    client.println("Host: fierce-chamber-5675.herokuapp.com");
                    client.println("Content-Type: image/jpeg");
                    client.println("Content-Length: " + 32);
                    client.print("Connection: close");
                    client.println();
                    for(int i = 0; i < 32; i++) {
                        client.print(buffer[i], HEX);
                    }
                    client.println();
                } else {
                    Serial.println(F("Connection failed"));
                    return;
                }
                client.close();

                Serial.println(F("-------------------------------------"));
                jpglen -= bytesToRead;
            }
            imgFile.close();
            cam.resumeVideo();
            cam.setMotionDetect(true);
        }
    }
}

```

# Answer
You are running a wireless TCP stack, an SD card interface, and a web camera with some sort of motion detection, on a less than $20 computer? I think you should congratulate yourself and move on to the next project.

I believe you are asking too much to add more to it. At $20 a pop, I would think about adding another UNO if you really do want to add more functionality. Let the 2 talk via serial, with one processing the video, the other processing the wireless. The TCP part uses a considerable amount of resources, both memory and processing power.
> 1 votes

---
Tags: arduino-uno, wifi, sd-card, memory-usage
---


title: Infra Red Send Hex Code

text:
# Question
Title: Infra Red Send Hex Code
I am using an arduino nano with the standard arduino IR remote library. For now I am using the Irrecord sketch. However, I want to have some pre - programed codes for remotes I don't have. I found this site which apparently has the hex of an endless number of remotes. When I use the regular IR decode, the hex of any remote I use, is only a couple of characters. However at this site the typical amount is at least 100.

This is the hex for a Toshiba model's sleep command:

0000 006c 0022 0002 0157 00ab 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0040 0016 0016 0016 0040 0016 0040 0016 0040 0016 0040 0016 0040 0016 0040 0016 0016 0016 0040 0016 0040 0016 0016 0016 0040 0016 0016 0016 0040 0016 0016 0016 0016 0016 0016 0016 0016 0016 0040 0016 0016 0016 0040 0016 0016 0016 0040 0016 0040 0016 0040 0016 05f0 0157 0055 0016 0e52

So, finally after all that if you are still with me my question is, how would I send that command with the IRRemote library.

# Answer
That seems to be pronto hex format for codes. A quick google showed this explanation: http://www.remotecentral.com/features/irdisp2.htm and this sample code: https://gist.github.com/probonopd/5793692
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Using Arduino to show images in Serial Monitor
Some time ago I came across a Vedic in which a person has hacked an optical mouse's camera and displayed the image in the Serial Monitors.
My question:
How to use Serial Monitor to display an image captured by the Arduino

# Answer
> 1 votes
Based on this guide, he doesn't actually display the images on the serial monitor, only the image data for each pixel.

Then another program (Javascript and some HTML) on the PC side collects the data and converts it to a greyscale image.

---
Tags: sensors, arduino-ide
---


title: Responding to a broken laser beam?

text:
# Question
Title: Responding to a broken laser beam?
Firstly, I must apologise as I'm a complete noob but the Arduino kits / lego pieces are fantastic and I can't stop tinkering. Unfortunatley my knowledge does not match my passion.

I picked up a laser from Amazon: FamilyMall(TM) KY-008 Laser Transmitter Module 650nm 5V Diode For Arduino AVR PIC.

I'm wondering what the middle pin is good for and if I can somehow manage to detect and respond to the beam being broken?

Thanks for looking. :)

# Answer
Without a data sheet or the device on hand not sure what the middle pin is used for. On the topic of detecting a broken beam the item you purchased is purely an emitter, in order to detect the beam being broken there are two main ways, using a photodetector on the "opposite end" of the beam but this means having wires trailing the same path as the laser beam, alternatively you could mount a mirror where the beam lands and reflect it back to a photodetector mounted close to the laser diode. You would them use the arduino to detect the state of the photodetector.
> 1 votes

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


# Question
Title: Adafruit Music Maker Shield - Retrieve song names from SD Card
I am currently working on a project that plays music for you. My question for this thread is, is it possible to retrieve the names of the songs within the micro SD card that is inserted into the shield?

Currently I am renaming the song files to track001, track002, track003, etc. As can be seen in the following code:

```
const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

```

That is how am I currently playing music with this shield. I am not too happy with this as I would like to be able to insert different micro SD cards into the shield without having to rename them to track00X or without having to change the code every time to match the song names.

So, is it possible to code it to retrieve the song names from the SD card instead of having to specify their name in the code?

Below you can see my full code:

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

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)

#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

int volume = 20;
const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

int songNumber = 0;

void setup()
{
  Serial.begin(9600);
  musicPlayer.begin();
  SD.begin(CARDCS);
  musicPlayer.setVolume(volume, volume);
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);
}

void loop()
{
  // Lower Volume
  if (musicPlayer.GPIO_digitalRead(7) == HIGH)
  {
    if (volume < 70)
    {
      volume = volume + 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Increase Volume
  if (musicPlayer.GPIO_digitalRead(6) == HIGH)
  {
    if (volume > 0)
    {
      volume = volume - 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Start Music Player
  if (musicPlayer.GPIO_digitalRead(5) == HIGH)
  {
    if (! musicPlayer.playingMusic)
    {
      musicPlayer.startPlayingFile(songs[songNumber]);
    }
  }

  // Pause / Resume
  if (musicPlayer.GPIO_digitalRead(4) == HIGH)
  {
    if (! musicPlayer.paused())
    {
      musicPlayer.pausePlaying(true);
    }
    else
    {
      musicPlayer.pausePlaying(false);
    }
    delay(500);
  }

  // Prev Song
  if (musicPlayer.GPIO_digitalRead(3) == HIGH)
  {
    if (songNumber - 1 >= 0)
    {
      songNumber = songNumber - 1;
    }
    else
    {
      songNumber = arraySize - 1;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);

    delay(500);
  }

  // Next Song
  if (musicPlayer.GPIO_digitalRead(2) == HIGH)
  {
    if (songNumber + 1 < arraySize)
    {
      songNumber = songNumber + 1;
    }
    else
    {
      songNumber = 0;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);
    delay(500);
  }
}

```

If this is possible and someone reading this knows how to do so, I would truly appreciate it if you explained it to me and even provided an example or even edit my own code if you want. Thank you! :)

# Answer
> 1 votes
The adafruit library was is similar to the prior SFEMP3shield library (disclosure I am the main author of that). That said either library can work on either Adafruit or SFE shield or breakout board. AdaFruit's library is cleaner re-write. But in doing so it is minimal in its functions. The SFE library demonstrates many more features of the VS1053 chip.

That said; the ./Example/fileplayer.ino does exactly what you are asking. The directory command lists out the files with an enumerating number. Entering 0\[number\] plays that file. This is how I broke away from "track###.mp3", without having to implement a command prompt parser. And it also allows other file formats.

The bulk of this feature is in the LOOP() and not in the constrained to the library. So one can cut and paste it into a sketch using the Adafruit library in place of the SFEMP3 or any sketch with an SdCard. That said it would actually be easier to replace the play file calls and include in the FilePlayer.ino example. Or just use it straight up.

The SFEmp3 library is bit overwhelming because it supports so many features of the VS1053. And uses a different SdCard library, which is more upto date than the IDE's SD". While the Adafruit library is a very nice re-write and cleans much hte confusing #define's making it much easier code to read, it is not as feature rich. But most feature beyond play and stop are not really needed.

Good luck.

---
Tags: arduino-uno, shields, adafruit
---


title: Arduino Uno + 2 Monster Motor Shields

text:
# Question
Title: Arduino Uno + 2 Monster Motor Shields
I've got an Arduino Uno and two Sparkun's Monster Motor Shields. The aim is to control 4 motors.

There is no problem to control 2 DC motors with single motor shield. There's a manual on how to do it .

But how can I control all of motors (address commands to each of them) when I stack motor shields one on one?

Thanks in advance.

# Answer
Not really the answer to your question, but an alternative solution, which has proven to work in my case. We were working on a line-following robot with an ATMega 328P (Same as arduino, but withouth shields) and thus we wired an shield directly. For the shield we used, we only needed 4 inputs (pwm left, pwm right, direction left, direction right). Try to find out what your shield is using, on which pin, and you can drive the shield directly withouth stacking them (as they then would use the same pin).

---

My alternative solution would be to use 1 driver. And wire the motors parrallel. If you choose to use 1 shield, you can stack it. But for other shields you have to check which pins to use. There is no drawback on using one shield, the only thing is that the motor driver will draw more current, but they're basically designed for this.
> 1 votes

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


# Question
Title: Scope error in arduino PinChangeInt library
```
#include<PinChangeInt.h>
#define SensorPin 2

int ledPin = 10;
int BuzzerPin = 12;
volatile byte blip = 0;

void blipcount(){
  blip++;
};

void setup() {
   // put your setup code here, to run once:
   pinMode(SensorPin,INPUT);
   pinMode(ledPin,OUTPUT);
   pinMode(BuzzerPin,OUTPUT);
   PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);
   Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   if(digitalRead(SensorPin)==HIGH){
      digitalWrite(ledPin,HIGH);
      digitalWrite(BuzzerPin,HIGH);
      Serial.print("blipcoun:\t");
      Serial.println(blip,DEC);
   }

   if(digitalRead(SensorPin)==LOW){
      digitalWrite(ledPin,LOW);
      digitalWrite(BuzzerPin,LOW);
   }
}

```

I am using arduino uno for a project.I need to record when my sensor gives a high value but i need it to read only falls in pulses.The program is giving error as

```
Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno"

Sense.ino: In function 'void setup()':

Sense.ino:14:38: error: 'blipCount' was not declared in this scope

Error compiling

```

please tell me what is the problem with the function.

The library link is https://code.google.com/p/arduino-pinchangeint/downloads/list

tested the code on both 1.72 and 2.19

# Answer
> 1 votes
You have a typo:

```
PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);

```

Should be:

```
PCintPort::attachInterrupt(SensorPin,blipcount,FALLING);
                                         ^

```

Note the lower-case "c".

---
Tags: arduino-uno
---