body:
I am using [Adafruit Neopixel Library][1] to work with a strand of 21 RGB LEDs.
AT this point only the first 16 light up. It is not a soldering problem, battery issue or a short.
[This][2] troubleshooting page suggests to

> "confirm that the number of LEDs in the LPD8806() constructor match the
> number of LEDs in the strip (both will be 32 if using the strandtest
> example and a single meter of LEDs)."

But looking at the library code below, I am not certain where to modify. Adafruit_Neopixel master zip has 2 files, which contain source code. One is [Adafruit_Neopixel.cpp][3] and the other [Adafruit_Neopixel.h][4].

Thank you.

  [1]: https://github.com/adafruit/Adafruit_NeoPixel
  [2]: https://learn.adafruit.com/digital-led-strip/troubleshooting
  [3]: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.cpp
  [4]: https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h

title: Adafruit Neopixel Library- only the first 16 LEDs respond

Answers: 3

body:
You don't modify the library at all. The page refers to the *constructor* which is the last line here:

<!-- language-all: lang-C++ -->

    #include <Adafruit_NeoPixel.h>

    #define PIN 6

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);

So that would send to 60 NeoPixels. Change the 60 to however-many you have.

To compare, try running my library [here](http://www.gammon.com.au/forum/?id=13357). That doesn't use the Adafruit library. Use the minimal demo code, and change PIXELS to be 21.

    #include <SPI.h>
    #include <NeoPixels_SPI.h>

    const unsigned int PIXELS = 8; // Number of pixels in the string

    void setup ()
      {
      ledsetup();
      showColor (PIXELS, 0xB2, 0x22, 0x22);  // firebrick
      } // end of setup

    void loop ()
      {
      } // end of loop

Note that you connect the NeoPixels data to pin D11 of your Uno in this case.

---

> @Paul 2000mAh at 3.7V Lipo battery

---

> according to the comment in the main question he's powering 21 LED's off a "2000mAh at 3.7V Lipo battery"

Yes, well let's look at the specs:

[![WS2812 specs][1]][1]

If you lose 0.2V over the first 8 LEDs you are under spec for the voltage.

  [1]: https://i.stack.imgur.com/9Ue3l.png

body:
> When something works, but not completely, it's often due to power issues.

Embedded things, microcontrollers/Arduino are fairly robust and "logical".
Hence, if your Arduino program works today, it'll work tomorrow.

Analog devices, or electricity is (in my eyes) often a bit vague. A chip can get enough power to run, but not enough to work properly.

**The NeoPixel**

Adafruit has an extremely elaborated [tutorial/userguide][1].

> Powering the NeoPixels

This also seems to fit your problem.

[![enter image description here][2]][2]

You could try powering the strip from the middle.
Since your voltage isn't stable, your amperage might not be as high and the resistance may be a little big. It's actually quite impressive that it works.

>  Each NeoPixel can draw up to 60 milliamps at full brightness.

2000mAh does not mean it can (always) deliver 2000mA. It depends on the "C" or discharge rating of the battery. So if your battery is rated 0.5 C it'll only be able to supply 1000mA (for 2 hours).

60*21 would be well over 1000mA, actually 60*16 is just below 1mA, so this would fit your problem.

> The voltage of a battery depends on how much charge it has.

Check google for: ["LiPo voltage drop"][3]

> If all else fails

There is a chance that that particular LED is broken. The signal will not continue to the other LED's and thus the light of the strip will end there.
Try to drive the LED's behind the LED that fails. (With the power supply closer).

I'm also not sure if you can supply 3.7V and then use 5V logic. Things like that would often break a microcontroller (when running on 3.3V, you usually can't receive 5V?)

  [1]: https://learn.adafruit.com/downloads/pdf/adafruit-neopixel-uberguide.pdf
  [2]: https://i.stack.imgur.com/rjnXI.png
  [3]: https://dlnmh9ip6v2uc.cloudfront.net/assets/6/7/4/7/9/5112a224ce395fb479000003.png

body:
With most led strips you can supply power from both ends if you are experiencing voltage drop.

You can do this with two separate power supply units if you don't have one unit that is capable of powering the entire strip.

I'm not sure if power is your entire problem, but if it is you could try this solution.

If it's a problem with the Neopixel library You could also try the excellent FastLED library and see if that helps you sort out your issues.


body:
Following is my code that i am trying to use it with Arduino Uno with ESP8266 module but my code stucked in setup function why is that.

    #include "ESP8266.h"
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(12,13);
    #define SSID        "abcd"
    #define PASSWORD    "87654321"
    #define HOST_NAME   "www.baidu.com"
    #define HOST_PORT   (80)

    ESP8266 wifi(mySerial);

    void setup(void)
    {
        Serial.begin(9600);
        Serial.print("setup begin\r\n");

        Serial.print("FW Version:");
        Serial.println(wifi.getVersion().c_str());

        if (wifi.setOprToStationSoftAP()) {
            Serial.print("to station + softap ok\r\n");
        } else {
            Serial.print("to station + softap err\r\n");
        }

    //    if (wifi.joinAP(SSID, PASSWORD)) {
    //        Serial.print("Join AP success\r\n");
    //
    //        Serial.print("IP:");
    //        Serial.println( wifi.getLocalIP().c_str());
    //    } else {
    //        Serial.print("Join AP failure\r\n");
    //    }
        delay(500);
        if (wifi.disableMUX()) {
            Serial.print("single ok\r\n");
        } else {
            Serial.print("single err\r\n");
        }

        Serial.print("setup end\r\n");

    }

    void loop(void)
    {
        uint8_t buffer[1024] = {0};

        if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
            Serial.print("create tcp ok\r\n");
        } else {
            Serial.print("create tcp err\r\n");
        }

        char *hello = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n";
        wifi.send((const uint8_t*)hello, strlen(hello));

        uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
        if (len > 0) {
            Serial.print("Received:[");
            for(uint32_t i = 0; i < len; i++) {
                Serial.print((char)buffer[i]);
            }
            Serial.print("]\r\n");
        }

        if (wifi.releaseTCP()) {
            Serial.print("release tcp ok\r\n");
        } else {
            Serial.print("release tcp err\r\n");
        }

        while(1);

    }

**On Serial Monitor i get the following continuously**

    setup begin
    FW Version:0018000902
    to station + softap ok
    singl

setup begin
    FW Version:0018000902
    to station + softap ok
    singl

title: Arduino UNO stuck in Setup function when interfacing UNO with ESP8266 module

Answers: 1

body:
> It's always a good idea to put a serial output in the setup of your code.

It seems that your Arduino resets itself.

But why?

I believe the problem would be with too little power for your ESP8266 and Arduino. When the ESP8266 wants to create a network connection, it takes a little more current, possibly leaving your Arduino without enough current to run on itself.

So your Arduino would shut down since the ESP8266 takes up all the current. Creating some kind of bootloop on your Arduino.

Please tell us how you powered the devices and how you connected them.
You might try using a separate power supply or a big capacitor on the Arduino's 5V+GND.


body:
This code is working, any ideas?

Please check the code - Bluetooth is connecting but the servo motors are not varying with respect to the app sliders.

<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>
    #include <Servo.h>
    Servo myservo1, myservo2, myservo3;

    int bluetoothTx = 1;
    int bluetoothRx = 0;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    void setup()
    {
      myservo1.attach(9);
      myservo2.attach(10);
      myservo3.attach(11);

      //Setup usb serial connection to computer
      Serial.begin(9600);

      //Setup Bluetooth serial connection to android
      bluetooth.begin(9600);
    }

    void loop()
    {
      //Read from bluetooth and write to usb serial
      if (bluetooth.available() >= 2 )
      {
        unsigned int servopos = bluetooth.read();
        unsigned int servopos1 = bluetooth.read();
        unsigned int realservo = (servopos1 * 256) + servopos;
        Serial.println(realservo);

        if (realservo >= 1000 && realservo < 1360) {
          int servo1 = realservo;
          servo1 = map(servo1, 1000, 1360, 0, 360);
          myservo1.write(servo1);
          Serial.println("servo 1 ON");
          delay(10);
        }

        if (realservo >= 1000 && realservo < 1360) {
          int servo2 = realservo;
          servo2 = map(servo2, 1000, 1360, 0, 360);
          myservo2.write(servo2);
          Serial.println("servo 2 On");
          delay(10);
        }

        if (realservo >= 1000 && realservo < 1360) {
          int servo3 = realservo;
          servo3 = map(servo3, 1000, 1360, 0, 360);
          myservo3.write(servo3);
          Serial.println("servo 3 On");
          delay(10);
        }
      }
    }

title: Arduino code for continuous rotation for 3 servos with Bluetooth

Answers: 2

body:
pins 0 and 1 are used by the arduino for serial communication. You cant use pins 0 & 1  and then use software serial as well.

If you do want to use softwareserial try this code https://gist.github.com/emil01/afedff4c3ba4625ebc75 Here i am using pins 2 & 3.

If you do not want to use software serial you can try this code https://gist.github.com/emil01/9a89800e383ec7f95b3f

In your code

      if (bluetooth.available() >= 2 )
      {
       unsigned int servopos = bluetooth.read();
       unsigned int servopos1 = bluetooth.read();

You are performing 2 consecutive read functions, this is not ideal as there can be data loss. A more ideal solution would be send a string with known string terminators and then parsing this string to get your required data.

For e.g. you could send

> S1:90\nS2:180\n

from this string you can clearly figure out the start and end of the string and accordingly manipulate the data for your need

body:
As pointed by @evolutionizer , you can't do SoftSerial + Serial (native) from pin 0 and pin 1. So the setup should be like this:

    #include <SoftwareSerial.h>
    #include <Servo.h>
    Servo myservo1, myservo2, myservo3;

    int bluetoothTx = 2;
    int bluetoothRx = 3;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    void setup()
    {
      myservo1.attach(9);
      myservo2.attach(10);
      myservo3.attach(11);

      //Setup USB serial connection to computer
      Serial.begin(9600);

      //Setup Bluetooth serial connection to android
      bluetooth.begin(9600);
    }

As for the movement for the servo, more information about data sent from Android is needed.
If the app is sending continuous value instead of sending only if the value is changed, you can do this trick:

    unsigned int lastpost;
    void loop()
    {
      //Read from bluetooth and write to usb serial
      if (bluetooth.available() >= 2 )
      {
        unsigned int servopos = bluetooth.read();
        unsigned int servopos1 = bluetooth.read();
        unsigned int realservo = (servopos1 * 256) + servopos;
        Serial.println(realservo);

        if (realservo >= 1000 && realservo < 1360 && realservo!=lastpost) {
          int servo1 = realservo;
          servo1 = map(servo1, 1000, 1360, 0, 360);
          myservo1.write(servo1);
          Serial.println("servo 1 ON");
          delay(10); //delay to wait servo rotate to desired position
          lastpost = realservo;
        }
    ...
      }
    ...
    }


body:
I'm trying to build my own 3D printer with [a guide][1] but I've got a problem with two of my CD/DVD motors: I don't know which settings to set in Marlin (`configuration.h`) because I can't find any datasheet for them.

So, I tried to set some values by my own, but I'm a little lost. That's why I'm asking for some help!

I'm using an **Arduino Mega 2560** (with Marlin firmware), a **RAMPS 1.4** and **x4 A4988 modules**.

 - The 1st motor has "**7810200082AC**" engraved on front and "**D5X08VF1D**" printed on the back.

 - The 2nd motor has "**05Z20P2B**" and "**092KPL201ACP**" printed on the back.

If I wasn't clear or some information is missing, please tell me!

[![Motors][2]][2]

  [1]: http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS
  [2]: https://i.stack.imgur.com/85RMP.jpg

title: Motors settings

Answers: 1

body:
I don't know your exact setup, but when it comes to steppers, you just need to know a few things:

- Meter the coils to get an impression, how much current you can induce.
- Limit the current on your driver as low as possible (<= 0.25 A possible?)
- Test
- Heighten the current, if the motor doesn't turn or stalls

Your motors are quite small, so I would assume, they run with less than 0.25 A at 12 V or 0.125 A at 24 V and so on.

If you limit the current, nothing can go wrong at all. Check the heat from time to time and make sure, your drivers lowers the current, whenever the given axis stands still.

When it comes to to resolution, I would not recommend to use more than 1/4 steps, which would result in 4*48/round steps on a standard stepper and provides very good resolution plus smooth motor action.


body:
I flashed an Arduino Nano compatible with ftdi_eeprom and the following config:

vendor_id=0x0403 # Vendor ID
product_id=0x6001  # Product ID

max_power=0  # Max. power consumption: value * 2 mA. Use 0 if self_powered = true.

###########
# Strings #
###########
manufacturer="FTDI"  # Manufacturer
product="Arduino Nano" # Product
serial="arduino_1"  # Serial

###########
# Options #
###########
self_powered=false # Turn this off for bus powered
remote_wakeup=false # Turn this on for remote wakeup feature
use_serial=true  # Use the serial number string

# Normally out don't have to change one of these flags
BM_type_chip=true   # Newer chips are all BM type
in_is_isochronous=false  # In Endpoint is Isochronous
out_is_isochronous=false # Out Endpoint is Isochronous
suspend_pull_downs=false # Enable suspend pull downs for lower power
change_usb_version=false # Change USB Version
usb_version=0x0200  # Only used when change_usb_version is enabled

########
# Misc #
########

filename="eeprom.new" # Filename, leave empty to skip file writing

My corresponfing `udev` rules work and I get `/dev/arduino_1` after connecting.

However. After the flash, everything seems to work, But: The TX-LED is constantly on. Even, when the device is not sending. Why?

**Update & solution**

First, I removed this line, because it threw warning messages (outdated)

    # BM_type_chip=true   # Newer chips are all BM type

Then I studied the [schematics][1] of the Nano and figured out, that `RX` and `TX`  LEDs are indeed connected to `CBUS0` and `CBUS1`. So, I added two lines to my config

      cbus0=RXLED
      cbus1=TXLED

Which had the effect, that now both `RX` and `TX` where constantly on. So, I finally read the [manual][2] which says on page 11, that the commands in question need a trailing `#`. I updated my config again:

    cbus0=RXLED#
    cbus1=TXLED#

**Extra:**

Indeed, I had to install `ftdi_eeprom` to get the job done

 apt-get remove ftdi-eeprom
 apt-get install swig libusb-1.0-0-dev libconfuse-dev doxygen
 git clone https://github.com/legege/libftdi.git
 cd libftdi.git
 cmake .
 make
 make install
 ftdi_eeprom/ftdi_eeprom --flash-eeprom myconfig.conf

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
  [2]: https://www.sparkfun.com/datasheets/IC/FT232R_v104.pdf

title: Risks of ftdi_eeprom? - TX always high after flashing

Answers: 1

body:
The `ftdi_eeprom` utility re-writes the entire EEPROM, not just the selected bits you have chosen.  That includes the "CBUS" pin configurations.

You need to check on the Nano's schematic which LED is connected to which `CBUSx` pin on the FTDI and set it accordingly.  You do that in your config using:

    cbus0=TXLED
    cbus1=RXLED

for example.

Possible settings for the CBUS pins are:

* TXDEN
* PWREN
* RXLED
* TXLED
* TXRXLED
* SLEEP
* CLK48
* CLK24
* CLK12
* CLK6
* IO_MODE
* BITBANG_WR
* BITBANG_RD
* SPECIAL

Except CBUS4 which only has the functions:

* TXDEN
* PWRON
* RXLED
* TXLED
* TX_RX_LED
* SLEEP
* CLK48
* CLK24
* CLK12
* CLK6

There is a chance that your pre-packages version of `ftdi_eeprom` doesn't support those settings, so you will need to download and compile the latest version from source from here: https://github.com/legege/libftdi

Also during testing I accidentally changed the VID of one of my boards thus rendering it unresponsive.  I did that by omitting the `0x` from the VID and PID numbers.  Extreme care should be exercised using thin utility.  I have submitted a patch to allow the specification of a default VID for recovery from such situations.


body:
I have a device which transmits USART with inverted polarity, and I would like to read data from it with the help of an Arduino. I use an Arduino Due, which has a SAM3X processor, so it should be able to invert the polarity without any external hardware.

The settings accessible from the Arduino SDK are minimalistic, `Serial.begin()` only allows to set the baudrate and start/parity/stop, nothing else.

In the SAM3X datasheet I found the "USART Mode Register", `US_MR`, which dedicates bit 23 (`INVDATA`) to invert the polarity.

[![USART Mode Register][1]][1]

Although it seems not to be documented anywhere, I found in a forum that to access the `US_MR` register, I have to use `UART->UART_MR`. I can read that register but cannot change it. The SAM3X datasheet mentions that this register might be write protected, and that the write protection can be cleared in the `US_WPMR` register.

However, the Arduino SDK doesn't seem to know about this register. I tried several possibilities,

    US_WPMR
    UART_WPMR
    WPMR
    UART->US_WPMR
    UART->UART_WPMR
    UART->WPMR

None of which are known.

The string `WPMR` is nowhere to be found in any of the files in my Arduino installation folder.

**EDIT:**

Interestingly, [the source code][2] for the UART class doesn't contain any reference to the WPMR. It just sets the required configuration registers without bothering with it.

    void UARTClass::begin( const uint32_t dwBaudRate )
    {
      // Configure PMC
      pmc_enable_periph_clk( _dwId ) ;
      // Disable PDC channel
      _pUart->UART_PTCR = UART_PTCR_RXTDIS | UART_PTCR_TXTDIS ;
      // Reset and disable receiver and transmitter
      _pUart->UART_CR = UART_CR_RSTRX | UART_CR_RSTTX | UART_CR_RXDIS | UART_CR_TXDIS ;
      // Configure mode
      _pUart->UART_MR = UART_MR_PAR_NO | UART_MR_CHMODE_NORMAL ;
      // Configure baudrate (asynchronous, no oversampling)
      _pUart->UART_BRGR = (SystemCoreClock / dwBaudRate) >> 4 ;
      // Configure interrupts
      _pUart->UART_IDR = 0xFFFFFFFF;
      _pUart->UART_IER = UART_IER_RXRDY | UART_IER_OVRE | UART_IER_FRAME;
      // Enable UART interrupt in NVIC
      NVIC_EnableIRQ(_dwIrq);
      // Enable receiver and transmitter
      _pUart->UART_CR = UART_CR_RXEN | UART_CR_TXEN ;
    }

However, when I try to change `UART_MR`, it remains the same.

  [1]: https://i.stack.imgur.com/wTr5I.png
  [2]: https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/cores/arduino/UARTClass.cpp

title: How to disable the write protection of the USART mode register?

Answers: 1

body:
Under Windows, Arduino puts the source code for hardware specific stuff in User\AppData\Local\Arduino, and not in the installation folder.

    /* -------- US_WPMR : (USART Offset: 0xE4) Write Protect Mode Register -------- */
    #define US_WPMR_WPEN (0x1u << 0) /**< \brief (US_WPMR) Write Protect Enable */
    #define US_WPMR_WPKEY_Pos 8
    #define US_WPMR_WPKEY_Msk (0xffffffu << US_WPMR_WPKEY_Pos) /**< \brief (US_WPMR) Write Protect KEY */
    #define US_WPMR_WPKEY(value) ((US_WPMR_WPKEY_Msk & ((value) << US_WPMR_WPKEY_Pos)))

I would guess unlocking / locking would take the format:

    ????->US_WPMR = (US_WPMR_WPEN | US_WPMR_WPKEY(0x555341));
    ????->US_WPMR = (~US_WPMR_WPEN & US_WPMR_WPKEY(0x555341));


body:
I've been messing around with accelerometers for Arduino for a school project. I bought the SODIAL GY-521 accelerometer + gyroscope module for Arduino. It uses de Invensense MPU 6050. I managed to connect it onto my board and successfully detect it, but it returns values of -1 on all output ports. I was expecting there to be a port for every axis of acceleration and rotation but it seems that this isn't the case. How should I connect the module into my Arduino, and how should I program the Arduino to read my data?

I tried to follow the Arduino Playground example but the result was as explained above.

Thank you for all answers.

title: Using 6 axis accelerometers

Answers: 2

body:
From [the Arduino playground](http://playground.arduino.cc/Main/MPU-6050):
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.

body:
I usually use the following connections for my MPU 6050:
Vcc: 3.3V
GND: Any arduino GND
SDA: A4
SCL: A5
AD0: GND(for address 68)/ 3.3V(for address 69)

I do not usually connect any of the other pins. For the code I usually use a wonderful library written by Jeff Rowberg which can be found here(http://www.i2cdevlib.com/devices/mpu6050#source). This library enables you to also use the Digital Motion Processor on board the MPU 6050 to give you prefiltered rotation data. It also has example code which should make things easy.

You can connect at most 2 MPU 6050s to the I2C port of the arduino by using different addresses for it. If you need to hook up more, you will require a multiplexer.

Hope this helps.


body:
Here is the code:

    void setup() {
      Serial.print("hi");
    }
    void loop() {
    }

The product is in [here][1].

I also installed the drivers.

  [1]: http://hobbycomponents.com/featured/98-arduino-compatible-nano-v30-with-free-usb-cable

title: My Arduino Nano clone doesn't show in the serial this simple code. Why?

Answers: 1

body:
You haven't "started" the serial interface.  Before you use the serial you need to tell it to initialize the hardware and how fast you want to communicate.

You need to add, for instance,

    Serial.begin(9600);

to your `setup()` function before you do your `Serial.print()`.


body:
    const int GSR=A0;
    int threshold=0;
    int sensorValue;

    void setup(){
      long sum=0;
      Serial.begin(9600);
      delay(1000);

      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);
      }

    void loop(){
      int temp;
      sensorValue=analogRead(GSR);
      Serial.print("sensorValue=");
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
      }

title: Why can't I see the serial plot with the following code for arduino?

Answers: 1

body:
The serial plotter requires just numbers and nothing else.

It can't understand the data in the format:

    sensorValue=49

It just expects:

    49

Remove the line

    Serial.print("sensorValue=");

and it will start working.


body:
About 3 years ago Sparkfun had a sale on Arduino Minis, so I bought 6 of them (3 x 3.3 V @ 16 MHz and 3 x 5 V @16 MHz). I used two of them for separate projects (everything worked flawlessly) then stored the rest. Then last night I grabbed one of the 5 V and 3.3 V Minis and tried to upload the Blinking LED program to them. But I kept getting this error:

    avrdude: stk500_recv(): programmer is not responding

I'm getting similar results on all of these computers: Mac OS X 10.10, Mac OS X 10.7, and Windows 7. I tested with default drivers and I tried installing fresh drivers based on the HardwareID's of the devices. I used both the newest version of Arduino IDE and a few older versions.

I've tried two different USB devices: [Sparkfun Basic FTDI](https://www.sparkfun.com/products/9873) and a [Generic USB to Serial PL2303 similar to this one](https://www.amazon.ca/Driver-USB-TTL-USB-STC-ISP-On-line-Program/dp/B00JN1BR9A). They both produce the same error, however the FTDI seems to be somewhat able to communicate since the RX & TX lights are flashing as well as the Arduino LED. With PL2303, the LED is lit constantly.

While searching last night, I found a few forums where people suggested things like hitting the reset button and selecting different Arduino boards in the IDE.

title: I can't get code transferred to my Arduino Mini Pro

Answers: 2

body:
Things have changed in the three years since you last used your FTDI board.

Most importantly avrdude has changed.

You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.

What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.

The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.

The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.

body:
For programming a Pro Mini, I find the CP2104 adaptor works better than the FTDI or PL2303 based units, on both Mac and PC. You can find the CP2104 adaptor from many sources, such as TxHang Electronic:

http://www.ebay.com/itm/USB-2-0-TTL-UART-6PIN-Module-Serial-Converter-CP2104-STC-PRGMR-Replace-CP2102-/200958955841?hash=item2eca165141

(You may need to install CP2104 software drivers on some platforms)
This is how I wire them together:

 - __CP2104_________PRO MINI__
   - DTR------------DTR
   - 3.3V--------- - * NOT USED (VCC)
   - 5V --------- - -* NOT USED  (VCC)
   - TXD------------RXD
   - RXD------------TXD
   - GND-----------GND

 Note: * While you may be able to power your (unloaded) Pro Mini from your CP2104 adaptor, it's better to use a separate supply that is appropriate for the version of the Pro Mini you use. Good luck. /DerrickA


body:
I am working with an LSM9DS1 IMU, and now specifically trying to program a wakeup feature into the system. My idea is to set the accelerometer at the lowest possible read rate, then when the accelerometer value exceeds a predefined level, to have the system wake up.

When programming the sensor, there is a register called INT_GEN_CFG_XL that has a "6-Direction detection for interrupt." I was wondering what this means. Does this perhaps calculate the magnitude of acceleration, and see if that goes above a predefined value? I can see the other interrupt generators are for 1-direction of each of the three axes, but I can't interrupt this one.

Here is a link to the [device datasheet][1]

  [1]: http://www.st.com/web/en/resource/technical/document/datasheet/DM00103319.pdf

title: Accelerometer Interrupt Meaning - Wakeup Function

Answers: 1

body:
The INT_GEN_CFG_XL 6-Direction detection interrupt apparently is aimed at detecting change of direction of travel, rather than an axis-combined acceleration level.

See the [LSM303](https://forum.pololu.com/t/design-qs-lsm303-sleep-to-wakeup-and-inertial-interrupts/4900/2) discussion at Polulu.com.  That page includes a link to [App Note CD00290365.pdf](http://www.st.com/web/en/resource/technical/document/application_note/CD00290365.pdf) for the LIS3DH.  Here is what that app note says, on page 27:

>There are two possible configurations for the 6D direction function:
>> • 6D movement recognition: In this configuration the interrupt is generated when the device moves from a direction (known or unknown) to a different known direction. ...
>>•  6D position recognition: In this configuration the interrupt is generated when the device is stable in a known direction. ...

With the LSM9DS1 that you are using, you can leave OR enabled, set separate X,Y,Z threshholds in INT_GEN_THS_X_XL, INT_GEN_THS_Y_XL, INT_GEN_THS_Z_XL, and set the “Enable interrupt generation on accelerometer's X axis high event” (sim. for Y and Z) bits in the INT_GEN_CFG_XL register.


body:
I want to know the basics of Arduino serial communications and connection with a Java application in Windows.

Can anybody provide me with a sample Java program that upon running just makes an Arduino pin high as well as the corresponding Arduino sketch, and some explanation on how the Arduino communicates with the Java app?

I am now starting with Arduino, and I have some experience with Java

I found this code on the net - will this work?

**Java code**

    package arduino;

    import jssc.SerialPort;
    import jssc.SerialPortException;

    public class Arduino {

    public static void main(String[] args) throws InterruptedException {

        SerialPort serialPort = new SerialPort("COM3");
        try {
            System.out.println("Port opened: " + serialPort.openPort());
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("o".getBytes()));
            Thread.sleep(1000);
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("f".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
      }
    }

**Arduino**

      void setup()   {
      Serial.begin(9600);
      pinMode(8, OUTPUT);
      digitalWrite(8,HIGH);
      delay(500);
      digitalWrite(8,LOW);
      }

      int incomingByte = 0;

      void loop()
      {
     // send data only when you receive data:
        if (Serial.available() > 0) {
               int text = Serial.read();
               Serial.println(text);
               if (text == 'o') {

                digitalWrite(8,HIGH);

               }

               if (text = 'f') {

                digitalWrite(8,LOW);

               }
         }

      }

title: Java + JSSC + Arduino + Windows

Answers: 2

body:
I managed to finish my project and here is the code

Useful information:

To prevent reset on serial port open and close

https://tushev.org/articles/arduino/22 /* Add a 10-100 μF capacitor between reset and GND

     JAVA

     /* FIRST IMPORT JSSC LIBRARY */

    package arduino;

    import java.util.Scanner;
    import jssc.SerialPort;
    import jssc.SerialPortException;

    public class Arduino {

    public static void main(String[] args) throws InterruptedException,     SerialPortException {

        Scanner scan = new Scanner(System.in);
        int nummer = 0;
     SerialPort serialPort = new SerialPort("COM4");

            while (true) {
                menu();
                 if (scan.hasNextInt()) {
                nummer = scan.nextInt();
            } else {
                System.out.println("verkeerde ingave");
            }
            switch (nummer) {
                case 0:
                    serialPort.openPort();//Open serial port
            Thread.sleep(1000);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

             serialPort.writeBytes("a".getBytes());//Write data to port
               serialPort.closePort();//Close serial port
                    break;
                case 1:
                     serialPort.openPort();//Open serial port
            Thread.sleep(1000);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
             serialPort.writeBytes("b".getBytes());//Write data to port
             serialPort.writeBytes("c".getBytes());//Write data to port
               serialPort.closePort();//Close serial port
                    break;

                     case 2:
                    serialPort.openPort();//Open serial port
            Thread.sleep(1000);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

             serialPort.writeBytes("d".getBytes());//Write data to port
               serialPort.closePort();//Close serial port
                    break;
                     case 3:
                    serialPort.openPort();//Open serial port
            Thread.sleep(1000);
            serialPort.setParams(SerialPort.BAUDRATE_9600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

             serialPort.writeBytes("e".getBytes());//Write data to port
               serialPort.closePort();//Close serial port
                    break;
            }

    }
    }

    public static void menu() {
        final String ANSI_CLS = "\u001b[2J";
        final String ANSI_HOME = "\u001b[H";
        System.out.print(ANSI_CLS + ANSI_HOME);
        System.out.flush();
        System.out.println("");
        System.out.println("    ************************************************************************************");
        System.out.println("    *      ***       ********   *******   **    **  *****  **      **      ******      *");
        System.out.println("    *     ** **      **    **   **    **  **    **   ***   ****    **    ***    ***    *");
        System.out.println("    *    **   **     *** ****   **     ** **    **   ***   ** **   **  **          **  *");
        System.out.println("    *   *********    **   **    **     ** **    **   ***   **  **  **  **          **  *");
        System.out.println("    *  **       **   **    **   **    **  **    **   ***   **   ** **    ***    ***    *");
        System.out.println("    * **         **  **     **  *******     ****    *****  **    ****      ******      *");
        System.out.println("    ************************************************************************************");
        System.out.println("");
        System.out.println("    By Emmanouil Perselis");
        System.out.println("");
        System.out.println("What would you like to do?");
        System.out.println("0.---");
        System.out.println("1.Toggle lights");
        System.out.println("2.Toggle air");
        System.out.println("3.---");
        System.out.println("4.---");

    }
     }

ARDUINO SCETCH

     int led = 13;
     int led1 = 2;
     int led2 = 4;
     int led3 = 7;
     int led4 = 8;
     void setup() {
       Serial.begin(9600);
       pinMode(led, OUTPUT);
       pinMode(led1, OUTPUT);
        pinMode(led2, OUTPUT);
        pinMode(led3, OUTPUT);
        pinMode(led4, OUTPUT);
     }

     void loop() {
       char i= Serial.read();

       if(i=='a'){////////////////
         if(digitalRead(led)){////////////
       digitalWrite(led, LOW);  ////////////
      }else if(!digitalRead(led))//////////
       digitalWrite(led, HIGH);  //////////
     }

      if(i=='b'){////////////////
         if(digitalRead(led1)){////////////
       digitalWrite(led1, LOW);  ////////////
      }else if(!digitalRead(led1))//////////
       digitalWrite(led1, HIGH);  //////////
     }

     if(i=='c'){////////////////
         if(digitalRead(led2)){////////////
       digitalWrite(led2, LOW);  ////////////
      }else if(!digitalRead(led2))//////////
       digitalWrite(led2, HIGH);  //////////
     }

     if(i=='d'){////////////////
    if(digitalRead(led3)){////////////
       digitalWrite(led3, LOW);  ////////////
      }else if(!digitalRead(led3))//////////
       digitalWrite(led3, HIGH);  //////////
     }

     if(i=='e'){////////////////
    if(digitalRead(led4)){////////////
       digitalWrite(led4, LOW);  ////////////
      }else if(!digitalRead(led4))//////////
       digitalWrite(led4, HIGH);  //////////
     }
    }

body:
I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).

The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:

    comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

The last parameter is DTR and its default is `true`, the second to last parameter is RTS (it defaults to `true` too). I set both of these parameters to `false` and my board reads commands from the computer without resetting.

I write this for other people who had this problem.


body:
I am trying to hook up my Neo-6M GPS module to my Arduino Uno but am having some trouble getting GPS data out of it.

The code being used was taken from the TinyGPS library. I have set the SoftwareSerial ports in the constructor to 2 and 3 (check images at bottom for reference). I set to the boad rate of the software serial so that it matches that of the Neo-6M. The datasheet for the module can be found [here][1].

The output that comes out of the Arduino serial monitor looks like this:

[![enter image description here][2]][2]

A new line is added to this every second, and when the line is added the TX light on the Arduino blinks. The 'Chars RX' 0 would indicate that the SoftwareSerial isn't reading any data at all from the module. I can't for the life of me figure out why this is happening! Any help would be much appreciated.

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    /* This sample code demonstrates the normal use of a TinyGPS object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */

    TinyGPS gps;
    SoftwareSerial ss(2, 3);

    static void smartdelay(unsigned long ms);
    static void print_float(float val, float invalid, int len, int prec);
    static void print_int(unsigned long val, unsigned long invalid, int len);
    static void print_date(TinyGPS &gps);
    static void print_str(const char *str, int len);

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

      Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
      Serial.println("by Mikal Hart");
      Serial.println();
      Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
      Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
      Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

      ss.begin(9600);
    }

    void loop()
    {
      float flat, flon;
      unsigned long age, date, time, chars = 0;
      unsigned short sentences = 0, failed = 0;
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

      print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
      print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
      gps.f_get_position(&flat, &flon, &age);
      print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
      print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      print_date(gps);
      print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
      print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
      print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
      print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
      print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
      print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
      print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

      gps.stats(&chars, &sentences, &failed);
      print_int(chars, 0xFFFFFFFF, 6);
      print_int(sentences, 0xFFFFFFFF, 10);
      print_int(failed, 0xFFFFFFFF, 9);
      Serial.println();

      smartdelay(1000);
    }

    static void smartdelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

    static void print_float(float val, float invalid, int len, int prec)
    {
      if (val == invalid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartdelay(0);
    }

    static void print_int(unsigned long val, unsigned long invalid, int len)
    {
      char sz[32];
      if (val == invalid)
        strcpy(sz, "*******");
      else
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartdelay(0);
    }

    static void print_date(TinyGPS &gps)
    {
      int year;
      byte month, day, hour, minute, second, hundredths;
      unsigned long age;
      gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
      if (age == TinyGPS::GPS_INVALID_AGE)
        Serial.print("********** ******** ");
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d d:d:d ",
            month, day, year, hour, minute, second);
        Serial.print(sz);
      }
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      smartdelay(0);
    }

    static void print_str(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartdelay(0);
    }

[![enter image description here][3]][3]
[![enter image description here][4]][4]

  [1]: https://www.u-blox.com/sites/default/files/products/documents/NEO-6_DataSheet_(GPS.G6-HW-09005).pdf
  [2]: https://i.stack.imgur.com/vgyg6.png
  [3]: https://i.stack.imgur.com/ZC2gm.jpg
  [4]: https://i.stack.imgur.com/fKjKk.jpg

title: Arduino SoftwareSerial not receiving data from Neo-6M GPS module

Answers: 1

body: Gray wire should be plug on pin2. `SoftwareSerial ss(2, 3);`  means pin2 for Receive(RX) and pin3 for Transmit(TX). The Transmit(TX) on Neo-6M should be connected to Receive(RX) on Arduino.


body:
I would like to be able to exclude from the auto-including process of the current project (without renaming the extension or delete it) a sketch with `pde` or `ino` extension that is used in certain circumstances only.

How can I do this?

I currently use Visual Micro to manage projects on Arduino.

title: How to exclude a ino/pde file from Arduino projects

Answers: 1

body:
One possible approach is to guard the body of that sketch with an `#ifdef ... #endif` pair, and use Visual Micro's  “Project Properties” to define (or not) a preprocessor symbol.  [If the .ino or .pde in question is used as a `#include` file, you would instead guard all the `#include` instances.]

Refer to the [“Project Defines”](http://www.visualmicro.com/page/User-Guide.aspx?doc=Project-Defines.html) page at visualmicro.com for how to define a preprocessor symbol and its value. [Via: Tools > Options > Visual Micro > Compiler > Show Build Properties]  Also see  [How do I add additional compiler switches in Visual Studio](https://arduino.stackexchange.com/q/13105).

If necessary, you can use other tests besides `#ifdef` to control compilation.  The first link above shows the following example.

    #if USBPORT > 3
    ....your code here....
    #endif


body:
I currently have a `for` loop that loops 300 times and then moves on.

Instead, I'd like that loop to run for a specific number of minutes, instead.

Here's the current loop, for reference.

<!-- language: c -->

    for(int i = 1; i<300; i++){
      if (kill() == true){ break; }

      strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
      strip.show();

      tone(TONE, notes[random(0,3)]);
      delay(100);
    }

Also, I have an RTC that's used elsewhere in the app, so real actual time is available for use if it makes sense to do that...though I'd love to know of a way to do it without an RTC module for future projects.

title: How do I run a loop for a specific amount of time?

Answers: 3

body:
You can use a variable that is incremented each time you perform the loop, then you need only to change the loop from using a `for` to a `while`.

For example:

       int incremented_variable = 0;
       int incremented_value = 100;
       int max_value = 1000;

       while(incremented_variable < max_value){
       if (kill() == true){ break; }

       strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
       strip.show();

       tone(TONE, notes[random(0,3)]);

       delay(100);
       incremented_variable = incremented_variable + incremented_value;
       }

-----
**EDIT:** I have just read your update on the question.

You can then use a while with a boolean flag that help you to end the loop or if you prefer, you can keep track of the time by calling the method: `millis()`.

body:
Using this example:

http://playground.arduino.cc/Code/ElapsedMillis

You could try something like:

    #include <elapsedMillis.h>

    elapsedMillis timeElapsed;
    unsigned int interval = 60000; //one minute in ms

    while(timeElapsed < interval){
        //do stuff
    }

Depending on how accurate you want to be, you might want to opt for a similar method using the RTC.

body:
Here is an example that will run for 5 minutes. Note that the loop will begin executing anytime before the time limit is up, including 1 msec before; it can't cut-off something happening at the 5-minute mark, meaning the timing precision will be limited to the duration of the code in the loop.

Update: My first suggestion had a bug related to the 50-some-odd days roll-over period of the millis() clock. This one is more robust:

    uint32_t period = 5 * 60000L;  // 5 minutes

    for( uint32_t tStart = millis();  (millis()-tStart) < period;  ){
       doStuff();
       moreStuff();
    }


body:
In the VirtualWire library, it is possible to encode the clock signal as the library is doing with 4b/6b coding. This is possible because VirtualWire uses convolutinal coding, where the *information is spread along the sequence*. But, is the same possible for linear *block* coding, such as LDPC/Hamming?

Otherwise, if it is not possible, then how would I best deal with the signal going out of sync with serial communication, given I want to use LDPC coding.

Lastly, the reason I am using serial communication is because I will have numerous nodes in my wireless mesh network, so to my knowledge, for the sake of: speed, power efficiency, scalability, *ease of implementation*, etc, serial communication works best. But has anyone had better luck with any other types of communication that can take care of the sync problem, while accounting for speed, power efficiency, scalability, etc?

**EDIT:** The way I am doing wireless communication is by using simple rf transceivers. There will by one transceiver per node and I am trying to create a stable channel between one node to another. The communication channel isn't very reliable without some error correction. And I don't want to use the existing VirtualWire's convolutional error correction. I want to use LDPC codes, developed by Radford Neal. My goal is to first create a stable channel from one Arduino to another. Then, I will implement the network.

title: Encoding clock signal into linear block codes

Answers: 0


body:
I'm searching for the fastest way to test if two integers are equal or differ by 4. The integers can be positive, negative and equal to zero. They are between -1000 and 1000 and are exclusively multiples of 4.

The simplest approach to test this should be this:

    if(x == y || x - y == 4 || x - y == -4)
    {
         //do something...
    }

But since I want to do this 4 times inside of a interrupt sub routine I wanted to know if there is a faster way to do this.

title: Fastest way to test if two integers differ by 4 or equal to each other

Answers: 2

body:
If you need to do the same comparison 4 times you can just put the result into a boolean variable.

    boolean b = (x == y || x - y == 4 || x - y == -4)

    if( b )
    {
         //do something...
    }

If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.

    void test(int x, int y)
    {
        if(x == y || x - y == 4 || x - y == -4)
      a8: 86 17        cp r24, r22
      aa: 97 07        cpc r25, r23
      ac: 39 f0        breq .+14      ; 0xbc <_Z4testii+0x14>
      ae: 86 1b        sub r24, r22
      b0: 97 0b        sbc r25, r23
      b2: 84 30        cpi r24, 0x04 ; 4
      b4: 91 05        cpc r25, r1
      b6: 11 f0        breq .+4       ; 0xbc <_Z4testii+0x14>
      b8: 04 96        adiw r24, 0x04 ; 4
      ba: 09 f4        brne .+2       ; 0xbe <_Z4testii+0x16>
        {
            asm ("wdr");
      bc: a8 95        wdr
      be: 08 95        ret

first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is `0`.

**EDIT**

As to Dave X's suggestion; using `if(abs(x-y)<=4)`

    void test(int x, int y)
    {
        if(abs(x-y)<=4)
      a8: 86 1b        sub r24, r22
      aa: 97 0b        sbc r25, r23
      ac: 04 96        adiw r24, 0x04 ; 4
      ae: 09 97        sbiw r24, 0x09 ; 9
      b0: 08 f4        brcc .+2       ; 0xb4 <_Z4testii+0xc>
        {
             asm("wdr");
      b2: a8 95        wdr
      b4: 08 95        ret

So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if `x==y`. So if 90% of the time x==y, the previous code will be faster 90% of the time.

As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If `-4 <= x-y < 0` the carry bit is set. Then it subtracts 9 (so it's like `(x-y)-5` because of the previous `+4`). If ` 0<= x-y <= 4` the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.

body:
>  test if two integers are equal or differ by 4

And

> are exclusively multiples of 4.

That would mean that when a=20, b should be 16, 20 or 24. (But can't be 17, 18, 19, 21, 22 or 23)

But you should check the most unlikely statement first. If it's likely to be well above x+4, check that first, if it's false, it'll just stop.

Ultimately you only have to check if it's less than x=y+4 or higher as x=y-4, this automatically includes x=y.
So checking if it's the same (which might be unlikely, might be redundant. Unless there is a very high chance of that being true.


body:
I am building a laser tag system with an Arduino in each gun.

I want the guns to be linked during game play for many different reasons:

  1. Start/Stop game
  2. Nearby teammates
  3. When a flag is captured
  4. etc.

I don't know how to link the guns to one another during game play because the field may be large (e.g. a park). Wifi has too short of a range, cellular would cost, linking to a phone via bluetooth would drain the phone battery (and require each player have a smart phone to play).

Can you think of another way to link the guns? Radio transmitters?

Thanks!

title: Link Arduinos over 5 acre laser tag field

Answers: 1

body:
You can use nRF24L01+

The chips offer:

 - Really high range with power amplifier (1km open field radius (776 acres if I'm right) , but fairly high power consumption 100-150mA @ 3.3V)
 - High range with PCB antenna (50-80m open field, low power consumption 14mA peak)
 - Low cost (0.8£-6£ a piece)
 - Many easy to use libraries available, possible to create a mesh network
 - High usable voltage range (direct Li-Po for example without step-up)


body:
When I connect a piezo (to pin 8), it causes the output of my RTC to go haywire and throw `165` errors into the results.

    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2165/165/165 165:37:4 // Connected piezo
    2016/3/25 13:36:4
    2165/165/45 13:36:4
    2165/165/165 25:36:4
    2016/3/25 13:36:4
    2165/165/45 13:36:4
    2016/3/25 13:36:4
    2165/165/45 13:36:4
    2165/165/165 165:165:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2165/165/165 37:36:4
    2016/3/25 13:36:4
    2165/165/27 13:36:4
    2016/3/25 13:36:4
    2165/165/165 25:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2165/165/165 25:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2165/165/165 25:36:4
    2165/165/165 25:36:4
    2016/3/25 13:36:4
    2016/3/25 13:36:4
    2165/165/165 25:36:4

Here's my current layout...

[![Photo of breadboard][1]][1]

Worth noting:

* Disconnecting the piezo instantly solves the problem.
* Connecting to any other pins also caused the issue.

Here is the Fritzing diagram

[![Fritzing diagram][2]][2]

 and schematic

[![Schematic][3]][3]

Here's the full code...

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 rtc;

    #define PIN 6
    #define TONE 8
    const int buttonPin = 7;

    long fadeTime = 1 * 60000L; // X minutes
    int colorStops = 256;
    int delaySpeed = fadeTime / colorStops;
    int notes[] = {262,294,330,349};
    int switchState = 1;         // variable for reading the pushbutton status
    int timeHour = 13;
    int timeMinute = 20;
    uint32_t alarmLength = 5 * 60000L; // 5 minutes

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, PIN, NEO_RGB);

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

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

      pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input

      strip.begin();
      strip.show();
    }

    void loop() {
      DateTime now = rtc.now();

      Serial.print(now.year(), DEC);
      Serial.print('/');
      Serial.print(now.month(), DEC);
      Serial.print('/');
      Serial.print(now.day(), DEC);
      Serial.print(" ");
      Serial.print(now.hour(), DEC);
      Serial.print(':');
      Serial.print(now.minute(), DEC);
      Serial.print(':');
      Serial.print(now.second(), DEC);
      Serial.println();

      if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 00){
        // Fade in light
        for(int i = 1; i<colorStops; i++){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(i,i,0));
          }
          strip.show();
          delay(delaySpeed);
        }

        // Play tone after light fully bright
        for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
          }
          strip.show();

          tone(TONE, notes[random(0,3)]);
          delay(100);
        }

        noTone(TONE);

        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
      }
    }

    bool kill() {
      if (digitalRead(buttonPin) == LOW) {
        noTone(TONE);

        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
        return true;
      }
      else {
        return false;
      }
    }

  [1]: https://i.stack.imgur.com/QKGnn.jpg
  [2]: https://i.stack.imgur.com/vu7bA.png
  [3]: https://i.stack.imgur.com/7fgN6.png

title: Piezo connection causing RTC to go haywire

Answers: 1

body:
Add

<!-- language: c -->

    pinMode(TONE,OUTPUT);

to `setup()` to fix the problem.


body:
My program reads the input and plays the appropriate note for 500 milliseconds. If I type in 'a', tone(8, 440, 500) will be called. I now want to add different note lengths so that in the future, I can play songs by sending code to Arduino. I was thinking that if 'a' is typed in, the program checks the next character. If it's a 1, it's a whole note. If it's a 2, it's a half note. My code doesn't work. What is wrong with it?

        if(Serial.available()>0){
        char character=Serial.read();
        if(character=='a'){
        char leng=Serial.read();
        if(leng=='1'){
        tone(8, 440, 1000);
        delay(1000);
        }
        else if(leng=='2'){
        tone(8, 440, 500);
        delay(500);
        }

        }
        }

title: How to Serial read two consecutive chars sent by computer to Arduino?

Answers: 1

body:
Presuming that code is the interior of `loop()`, your Arduino will spin until a character arrives, that is, until `Serial.available()>0` becomes true.

It then reads the character with `Serial.read()` and if it's an `'a'` immediately does another `Serial.read()`.  In general, some delay occurs between characters arriving via a serial interface.  Whenever the serial buffer is empty, an immediate `Serial.read()` will return -1 instead of an ASCII character.

To fix this problem, test for availability of a character before doing the second read.  For example, you could add

    while (!Serial.available()){}

before the read, to delay until a character is available.


body:
I want to use two ultrasonic sensors for counting incoming cars to a garage. What I want is: When both sensors detect the object then the counter should increase.

Can anyone help me and give me an example?

title: Using two ultrasonic sensors for counting cars when they enter to a garage

Answers: 1

body:
If you have two sensors, you use analogRead.

<!-- language: c -->

    int sensor1 = A0;
    int sensor2 = A1;
    int distance = 50; // or whatever you want here
    bool car_passing = false;

    void setup(){
        int counter = 0;
    }

    void loop(){
        if(analogRead(sensor1) < distance &&
           analogRead(sensor2) < distance &&
           !car_passing)
        {
            car_passing = true;
            counter++;
        }

        if(analogRead(sensor1) > distance){
            car_passing = false;
        }
    }

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.


body:
On Linux, if you have more than one USB TTY device, the USB port name (`/dev/ttyUSBx`) changes every time one is plugged in, and there's no easy way to know the new name without going and looking through dmesg.  [It's trivial to set up a udev rule that creates a custom symlink](http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/) so that my Arduino's FTDI can always be accessed through e.g., `/dev/ttyArduino`, and this is the standard procedure for persistent access to USB devices.

However, I can't make the IDE accept anything other than the `/dev/ttyUSBx` names.  Even directly editing `preferences.txt` is ignored.

Is there any way to instruct the IDE to use custom port names in order to access the Arduino through a symlink or other persistent name?

title: Can I specify custom port names in the Arduino IDE on Linux?

Answers: 2

body:
Consider using a device name of form ttyUSBnn, where nn is fairly large.  For example, in /dev you could say

    sudo ln -s ttyUSB1 ttyUSB77

Then, `ttyUSB77` shows up in the IDE's ports list and can be selected.

(I don't know how to set up that link using the `udev` system, but imagine it can be done.)

body:
Think the other way.

If your device has a port name, that is not supported by the IDE, you can create an additional (static) symlink `/dev/USBx` that you can identify and select in the arduino IDE.

And yes, it is quite easy to [make all of your arduinos unique][1] to udev.

  [1]: https://arduino.stackexchange.com/questions/3680/in-linux-how-to-identify-multiple-arduinos-connected-over-usb/22323#22323


body:
I have an Arduino Uno R3, Wireless Proto Shield and a XBee XB24-AWI-001 all hooked together. I'm using X-CTU software to access the XBee and change the properties of it. I did a little research and found out that if I want to access the XBee, I have to connect the GND to the RST pin (on the Proto Shield) or hold the RESET button on the board. This method works and when I do that, I can find the XBee on X-CTU.

The question is - why do I have to do that? I'm probably wrong, but as far as I understand, if I have my Arduino connected to the computer, I'm accessing the ATmega microprocessor and that's the reason I can't access the XBee, but when I do the reset, I'm constantly resetting the microcontroller and that's the reason why I can access the XBee? Hopefully someone can explain this...

The link where I found the information about resetting (or removing) the ATmega microproccesor, [Using Arduino to Connect Xbee Serial to Computer][1].

  [1]: http://forum.arduino.cc/index.php?topic=213239.0

title: Issues with connecting XBee to Arduino Uno R3

Answers: 1

body:
I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino *only*. The fact that you can actually talk to the XBee from the PC using X_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a *feature* of the shield1.

Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.

See the thread on the Digi forums, [xbee s1 xctu arduino][1]:

> The shield is not design for writing and reading firmware to and from
> the XBee module. It is only designed for basic two way communications.
> If you want to read or write firmware to the module, you need to use a
> board that is designed for it such as the XBIB boards from Digi.

See also [Can an XBee be programmed with an XBee Shield][2].

However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

----

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to *either* the Arduino *or* the USB, but *not both* at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.

So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, [UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal][3] which hints at the same thing. Two comments of note from that thread are:

> It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

> Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the **USB-to-TTL IC**'s DTR line, or equivalent (?), is [logically] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.

Note: The **USB-to-TTL IC** could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.

### Addendum

I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of [USB-TTL interface devices on OS X](https://gr33nonline.wordpress.com/2015/12/13/usb-ttl-devices/). That explorer,  [XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino][4], is good value for money and compatible with WinTel, LinTel and OS X machines:

[![XBee explorer][5]][5]

  [1]: http://www.digi.com/support/forum/49165/xbee-s1-xctu-arduino
  [2]: https://electronics.stackexchange.com/questions/8882/can-an-xbee-be-programmed-with-an-xbee-shield
  [3]: http://forum.arduino.cc/index.php?topic=187950.0
  [4]: http://www.ebay.co.uk/itm/161894812598
  [5]: https://i.stack.imgur.com/ELlYY.jpg


body:
In Arduino Eclipse (v3, nightly build) I have not been able to load 'foreign' libraries, those written by me or someone else, so they are not among the available choices in the include-library dialogs.

I've tried adding them to a project as well as adding them as an available library resource using the built-in dialogs for doing so, but I don't see a way to select a library that isn't already included in those dialogs.

My ideal case would be a way for the Arduino Eclipse plugin to use the same boards and libraries as I use in my Arduino IDE installation, so that:

 - An upgrade to the Arduino IDE would simultaneously upgrade the core libraries in Eclipse;
 - An optional library would need installing in only one place;
 - Modifying an optional library would only need to be done once, in one place.

The goal, as in an earlier question of mine, is to seamlessly permit using either IDE to advance a project. However, I'd be grateful to be able to add to my Eclipse installation any library of my choosing.

title: Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?

Answers: 2

body:
I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
*UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.*

**Lets start with the Libraries**
What you do is:
In arduino eclipse ide remove all libraries from the library manager.

In windows->preferences->arduino->"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.

**Then the boards**
The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content.
If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
**Step 1:** Keep as little boards as possible installed. **You have to keep at least 1** or the plugin will reinstall the AVR boards of Arduino when started.
**Step 2:** In windows->preferences->arduino->"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
**Step 3:** Recreate the project in eclipse as described in your other question.
**Step 4:** If the build fails modify the [eclipse installation]/arduinoPlugin/post and pre processing files to try to get it to work.
**Step 5:** in project properties->Arduino select apply and OK (this will take your changes in step 4 into account)
**Step 6:** Goto Step 4

Good luck
Jantje

body:
Making Blynk libraries, v0.3.6 and (presumably) later, Eclipse compatible.
------------------------------------------------------------------------

With much help from Jantje (thank you!), I found 4 easy steps that make the Blynk v0.3.6 libraries Eclipse-compatible:

1.    Create `.../libraries/Blynk/Blynk.h` (may be empty) and #include it before including any Blynk libraries.
2.    Likewise, create and #include `.../libraries/BlynkESP8266_Lib/BlynkESP8266_Lib.h`
3.    Delete the entire folder `.../libraries/Blynk/linux` (unless you're running Linux! In which case, some more discovery needs doing.)
4.    In Blynk projects previously imported to Eclipse Arduino, delete the (possibly hidden) file `.ino.cpp` and do a clean build.

This recipe works for me under MacOS 10.11.5, the Eclipse Arduino IDE nightly build, and ArduinoIDE version 1.6.9. It should be reproducible by anyone wishing to compile Blynk programs in Eclipse. Under OSes other than Mac, especially linux, step 3 may need to be modified. I deleted the `linux` folder to prevent Eclipse from compiling `main.cpp` and `BlynkDebug.cpp` from there which was resulting in multiple definition errors at link time.

The above is an excerpt from a how-to I [posted to the Blynk community][1] but I think this has all of the relevant information.

  [1]: http://community.blynk.cc/t/making-the-blynk-libraries-compatible-with-eclipse/5608


body:
I am making a game where four different colored LEDs are flashing randomly, and when the green LED lights up, the user presses a button. If the user pushes the button when the LED is green, I want my 16x2 LCD screen to record points. And when the user presses the button on the wrong LED, i want the LCD screen to start over at "0 points."

Can you give me some place to start on a code that will feed "data" from  each time the button is pushed to the LCD screen?

title: LED and LCD game

Answers: 1

body:
You need an example that shows you how to right to a screen and an example that shows you how to detect a button press, also you need to be able to light LEDs.  These are all examples supplied with the Arduino IDE, are you using that?  Look at each example in turn, setup the circuit get to understand them, then disect them and understand how they work and can get them to do what you want.

Button presses can be trouble some, you may need to investigate denouncing, either software or hardware.

Hope that gives you a starting point.


body:
I'm trying to experiment with a "return" function. Yet each time I try to run my program, there happens to be an error, like "expected declaration before '}' token."

Can someone explain the basics of a return function, and look at my code below to possibly see what the problem could be?

    {
    int index;

    pinMode(10, INPUT); //button input

    int checkInput();

    if (digitalRead(10) == 0) {

    return 1;
    else{

    return 0;
     }
    }

title: "Return" Code Not Working

Answers: 2

body:
It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.

       {
    int index;

    pinMode(10, INPUT); //button input

    int checkInput();

    if (digitalRead(10) == 0) {

    return 1;}
    else{

    return 0;
     }
    }

body:
That piece of "code" is, I am afraid to say, complete gibberish.

Passed through Artistic Style to reformat it ends up with:

    {
     int index;

     pinMode(10, INPUT); //button input

     int checkInput();

     if (digitalRead(10) == 0) {
      return 1;
      else {
       return 0;
      }
     }

Starting from the top of the program the errors are:

1. You have a bracket hanging at the front of the snippet for some reason
2. `int checkInput();` is a function prototype (forward declaration) and doesn't do anything other than tell the compiler that you will define this function somewhere else in your sketch.
3. You are lacking the balancing bracket for the first portion of your `if` statement, so your `else { return 0; }` never runs.
4. There is no balancing bracket for the strange one by itself at the start of the snippet.

In short, I have a feeling you need to learn the basics of C syntax.


body:
I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/
and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .

I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect  to the COM port at all to monitor the traffic, and others let me connect, but send a message of <NUL>. I'm expecting an introduction message from the firmware that is supposed to be built in.

Thanks for the help.

title: How to Determine Fuse Settings

Answers: 1

body:
Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of

lowfuse=0xff

highfuse=0xde

extendedfuse=0x05

Serial should work fine.


body:
I have created an arduino prototype using the exact instructions found on this page:

https://www.arduino.cc/en/Main/Standalone

However, when I plug in the micro USB power supply and try to upload a program, here's the error I get:

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe0

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

I have tried the following solutions, to no avail:
1) press the restart button (in a variety of ways and lengths of time)
2) Enable verbose output
3) trying the different board types in the Arduino IDE
4) Checking the COM port

I have no idea what to do I've basically tried everything I could find, on this website and others.

I hope you guys can help! Thanks very much :)

title: Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding"

Answers: 2

body:
Remove the pins connected to Tx and Rx while uploading the code , it worrked for me.
also include all the libraries currently used in your program.
Good luck!!

body:
Check for Baudrate, the Arduino Serial Terminal, and serial port terminal should exactly match.

Or either check your Rx and Tx pins for respective voltages
Either there may be problem related to power supply.
It is better you also mention the code


body:
I see some old library code that initializes SPI this way:

        SPI.begin();
        SPI.setClockDivider(2);

It does not use `beginTransaction`/`endTransaction` blocks, and `setClockDivider` is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.

What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?

title: What is the equivalent of this old SPI code using the current SPI library?

Answers: 2

body:
The default is:

* Mode 0
* MSBFIRST

Not sure on the default speed. But:

`setClockDivider()` sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.

`setClockDivider(2)` would be the same as using F_CPU/2 as a speed.

body:
I have example code [here](http://www.gammon.com.au/forum/?id=10892&reply=9#reply9).

The code is:

<!-- language-all: lang-C++ -->

    #if SPI_HAS_TRANSACTION
      SPI.usingInterrupt (0);  // I am using external interrupt 0
      SPI.usingInterrupt (1);  // I am also using external interrupt 1
      SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock
    #else
      SPI.setClockDivider(SPI_CLOCK_DIV8);
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
    #endif // SPI_HAS_TRANSACTION

    digitalWrite (SS, LOW);        // assert Slave Select
    byte foo = SPI.transfer (42);  // do a transfer
    digitalWrite (SS, HIGH);       // de-assert Slave Select

    #if SPI_HAS_TRANSACTION
      SPI.endTransaction ();   // allow external interrupts to fire now
    #endif // SPI_HAS_TRANSACTION

The default setting for SPI is to use the system clock speed divided by four.


body:
I have a potentiometer with switch, that seems to be working a little wonky (Keep in mind I have tried this with a few different pots and they all behave the same way which leads me to believe I am wiring them wrong).

I can easily hookup the potentiometer and it's three terminals on the side, 1 being ground, 2 being output, 3 being input power. I can monitor it's value on a serial port with Arduino.  However when I try and test the switch, which are two terminals on the bottom of the pot.  I get an on signal when the pot is on, but when it is clicked off I get a random on/off signal.  As in it reads that it is sort of on but never truly reads off.

Right now I am simply giving it 5v from the Arduino to both the switch and the third terminal.  Should I be giving the switch power via a capacitor? Not sure, have not tried that yet but that may smooth out my readings.

Any suggestions?

title: Potentiometer with switch wiring question. Not reading correctly

Answers: 1

body:
From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.

As noted in comments and answers to  “[Why all unset pins of my Arduino Uno are outputting 2 volts?](https://arduino.stackexchange.com/q/21082)”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

> ... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
>
> When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the [voltage] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with `INPUT_PULLUP` pinmode instead of just `INPUT`.


body:
Are there any MQTT libraries that do not block while connecting?

I'm currently using PubSubClient, and the connection part contains this code:
https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.cpp
<!-- language-all: lang-cpp -->

            while (!_client->available()) {
                unsigned long t = millis();
                if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
                    _state = MQTT_CONNECTION_TIMEOUT;
                    _client->stop();
                    return false;
                }
            }

I'd like my main loop to continue, or a callback to be called, while the MQTT connection is established, rather than waiting for ages if the MQTT server is unavailable.

**Update:**

I wrote a modification to take a callback function, and called it in an else clause added to that if statement, and discovered that the blocking delay is not this while loop. I think it's in the _client->connect at the start of the method.

title: Non-blocking MQTT library

Answers: 1

body:
I had the same question and found an mqtt library that is completely non-blocking.

 - https://github.com/marvinroger/async-mqtt-client

You need to manually install it and the docs give instructions:
 - https://github.com/marvinroger/async-mqtt-client/blob/develop/docs/1.-Getting-started.md

It requires one additional library:
 - for esp8266: https://github.com/me-no-dev/ESPAsyncTCP
 - for esp32:   https://github.com/me-no-dev/AsyncTCP

I also liked the example's use of the Ticker library as a general tool for non-blocking code.


body:
I recently found that standard servos only rotate 90deg total rotation for a pulse width range of 1-2 usec.  To rotate 180deg total rotation they need a .5-2.5 usec pulse range.  The arduino is programmed to only output the 1-2 usec range for 0-180 deg rotation.  Is there a way to make the arduino output the .5-2.5 usec pulse range to get full 180deg rotation?

Thanks

title: Can the servo pulse width range be changed?

Answers: 1

body:
The [Servo Attach](https://www.arduino.cc/en/Reference/ServoAttach) method has two forms,

    servo.attach(pin)
    servo.attach(pin, min, max)

In the latter form, you can specify values for the min and max microseconds that `servo.write()` will use to represent 0° and 180° respectively.

Note, default values are 544 μs and 2400 μs, which is not so different than the range you say you want, so perhaps some other problem is afflicting your setup.

Also, as explained in [my answer](https://arduino.stackexchange.com/a/20814/3917) to question  “[Change Servo Speed With RedBearLabs BLE Shield](https://arduino.stackexchange.com/q/20810)”, you can issue `servo.write(value)` calls with value in microseconds instead of in degrees, which may allow more precise control.


body:
I'm trying to understand if the following bit of code is subject to memory fragmentation.

Let's say I incrementally build a string within a function and I don't know how large the string should be.

    String f() {
        String s = String("");
        s += "a"; // ...
        s += "bc"; // ...
        return s;
    }

The `String` object does dynamic memory allocation internally, but `s` is on the stack, so once the function returns, the `s` object presumably deallocates and dynamically allocated memory is freed.

Before this happens, the `String` object to be returned must be copied from `s`. Since `String` objects hold internal data in dynamically allocated buffers, this means that the `s` internal buffer is allocated, then the return object internal buffer is allocated, then the `s` internal buffer is deallocated.

The return object internal buffer allocation is sandwiched between the `s` object alloc and dealloc.

To me, this implies that this will cause memory fragmentation. Am I reading this properly, or is this not the case? If so, does this also imply that functions like `Serial.readString` are also subject to memory fragmentation?

title: Is this function subject to memory fragmentation?

Answers: 3

body:
Pretty much every use of the String object can lead to memory fragmentation. Especially concatenating and copying objects.

I cover it here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

You are much better off never using the String class and instead sticking to basic C strings (char arrays).

body:
Memory fragmentation is hard to predict, as it depends on how your
different allocation patters interact. This single pattern, _per se_,
looks safe. By safe I mean that _if_

1. your heap is not fragmented when you enter this function, and
2. you do no dynamic allocation inside the function other than growing the
string,

then the string will be allocated to the top of the heap and grow from
there without moving or making holes. You can check this is the case by
looking at the address of the string's internal buffer, which is given
by the `c_str()` method. It should not change inside the function:

<!-- language: lang-c++ -->

    String f() {
        String s = String("");
        const char * p = s.c_str();
        s += "a"; // ...
        s += "bc"; // ...
        if (p != s.c_str())
            Serial.println(F("Warning: memory fragmentation."));
        return s;
    }

------------------------------------------------------------------------
**Edit**: I wrote this small test program to show the behaviour of the
heap when you use string concatenation this way:

<!-- language: lang-c++ -->

    extern uintptr_t __brkval;

    String f() {
        String s("");
        const char * p = s.c_str();
        Serial.print(F("  f(): string buffer @ 0x"));
        Serial.println((uintptr_t) p, 16);
        for (int i = 0; i < random(8) + 1; i++)
            s += random(2) ? "a": "bc";
        if (p != s.c_str())
            Serial.println(F("Warning: memory fragmentation."));
        Serial.print(F("        top of heap at 0x"));
        Serial.println(__brkval, 16);
        return s;
    }

    void setup() {
        Serial.begin(9600);
        Serial.print(F("***     heap starts at 0x"));
        Serial.println((uintptr_t) __malloc_heap_start, 16);
    }

    void loop() {
        Serial.print(F("loop(): top of heap at 0x"));
        Serial.println(__brkval, 16);
        String s = f();
        Serial.print(F("  f() returned "));
        Serial.println(s);
        Serial.print(F("        with buffer at 0x"));
        Serial.println((uintptr_t) s.c_str(), 16);
        delay(1000);
    }

The output of the program is:

<!-- language: lang-none -->

    ***     heap starts at 0x1D7
    loop(): top of heap at 0x0
      f(): string buffer @ 0x1D9
            top of heap at 0x1DF
      f() returned abcbc
            with buffer at 0x1D9
    loop(): top of heap at 0x1D7
      f(): string buffer @ 0x1D9
            top of heap at 0x1DF
      f() returned abcbc
            with buffer at 0x1D9
    loop(): top of heap at 0x1D7
      f(): string buffer @ 0x1D9
            top of heap at 0x1DC
      f() returned aa
            with buffer at 0x1D9
    loop(): top of heap at 0x1D7
      f(): string buffer @ 0x1D9
            top of heap at 0x1E2
      f() returned aabcabca
            with buffer at 0x1D9
    [...]

The very first “top of heap at” is bogus because at this point the
malloc library has not been initialized. Besides that, you can see here
that:

* the heap is always empty (top = bottom) at the beginning of `loop()`
* the string is always allocated at the same place
* the heap size inside `f()` varies depending on the string's length
* the string is not copied when returned to the caller, as the internal
  buffer is still at the same address.

However, if the statement `String s = f();` is replaced by
`String s; s = f();`, then the string is copied when returned to the
caller, which doubles the amount of RAM required to handle it. This is
presumably because only the first form allows [copy elision
optimization](https://stackoverflow.com/questions/12953127). (This
paragraph was added after reading Nick Gammon's answer, which made me
realize the copy elision issue).

Keep in mind that this works so nicely only because there is nothing
else doing dynamic allocation in this small program. This usage pattern
is safe, but once you start doing dynamic allocation in different parts
of the program, it becomes difficult to ensure that the
allocation/deallocation pattern is still safe vs. memory fragmentation.

body:
The worst line in your example is this:

    s += "a"; // ...

Any sort of loop that adds one byte to a String is potentially going to fragment memory. First the String class allocates zero bytes for the string, then when you add a byte, it has to allocate one byte, then when you add another byte it has to deallocate (free) that byte and allocate two bytes, and so on.

The allocator *tries* to be efficient, so eventually when you get up to three bytes you will, with luck, actually get the memory previously allocated to the one-byte string followed by the two-byte string.

But if other allocations have occurred (eg. another use of String elsewhere in the program) this might not be possible. Eventually you have lots of small gaps of maybe one or two bytes, with other stuff inbetween. Unless they are adjacent they cannot be recombined into a bigger block. This is your "fragmentation".

---

> When you += "a", it does not free the previously allocated space: it calls realloc() to grow the buffer, and realloc() tries to grow it in place.  This works fine, without fragmentation, as long as your buffer is at the top of the heap.

Good point, however if you have multiple String instances, this may not work.

Edgar Bonet is right, however there is certainly the potential, with multiple String instances, for each of them to prevent the others from growing their buffer size neatly. In the example in the question, you will probably find that when `f()` returns, it returns a *copy* of the String allocated on the stack, thus we now have 2 x String instances.

---

While Edgar was writing some test code, so was I. :)

    #include <memdebug.h>

    String foo;

    String f() {
      String s = String("");
      s += "a"; // ...
      s += "bc"; // ...
      return s;
    }  // end of f

    void showMemoryUsage ()
    {
      Serial.println (F("---------------"));
      Serial.print (F("Largest block in freelist: "));
      Serial.println (getLargestBlockInFreeList ());
      Serial.print (F("Largest available memory: "));
      Serial.println (getLargestAvailableMemoryBlock ());
      Serial.print (F("Free memory: "));
      Serial.println (getFreeMemory ());
      Serial.print (F("address of foo data = "));
      Serial.println ((int) foo.c_str ());
    } // end of showMemoryUsage

    void setup()
    {
      Serial.begin (115200);
      Serial.println ();
      showMemoryUsage ();
      Serial.println (F("Calling f() ..."));
      foo = f ();
      showMemoryUsage ();
      Serial.println (F("Calling f() ..."));
      foo = f ();
      showMemoryUsage ();
      Serial.print (F("foo = "));
      Serial.println (foo);
    }  // end of setup

    void loop ()
    {
    }  // end of loop

Memory debug library from <http://andybrown.me.uk/wk/2011/01/01/debugging-avr-dynamic-memory-allocation/>

Output:

    ---------------
    Largest block in freelist: 0
    Largest available memory: 1675
    Free memory: 1677
    address of foo data = 478
    Calling f() ...
    ---------------
    Largest block in freelist: 2
    Largest available memory: 1669
    Free memory: 1675
    address of foo data = 482
    Calling f() ...
    ---------------
    Largest block in freelist: 2
    Largest available memory: 1669
    Free memory: 1675
    address of foo data = 482
    foo = abc

The address of the data in `foo` has changed from 478 to 482, so my prediction above was right. The function `f()` made a String, but a second *copy* was returned, hence we have now "lost" 4 bytes in the heap. Well, not lost, but there is a gap.

Calling `f()` a second time did not make the fragmentation worse.

---

BTW, this is unnecessary:

      String s = String("");

Just write:

      String s;

You are invoking a second String just to provide something to copy into the first String. Strings start off empty so this is just wasted time.


body:
I came across the problem to handle two DHT22 devices.

I use the [Adafruit DHT Sensor library][1].

Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.

I checked the source and found, that the DHT object only gets constructed **before** `setup()` as a constant in the examples, because the library is written that way.

I did a quick [hack][2], which works, but seems ugly to me:

**DHT.cpp**

    DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
    -  _pin = pin;
    -  _type = type;
    -  #ifdef __AVR
    -    _bit = digitalPinToBitMask(pin);
    -    _port = digitalPinToPort(pin);
    -  #endif
    +  //_pin = pin;
    +  //_type = type;
    +  //#ifdef __AVR
    +  //  _bit = digitalPinToBitMask(pin);
    +  //  _port = digitalPinToPort(pin);
    +  //#endif

    ...

    -void DHT::begin(void) {
    +void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
    +  _pin = pin;
    +  _type = type;
    +  #ifdef __AVR
    +    _bit = digitalPinToBitMask(pin);
    +    _port = digitalPinToPort(pin);
    +  #endif

**DHT.h***

    -   void begin(void);
    +   void begin(uint8_t pin, uint8_t type, uint8_t count=6);

Basically, I moved a few lines from the constructor to the `begin()` method. The whole thing works. I can even rewire & change the data-pin dynamically while the Arduino runs.

Here are my questions:

 - Is the hacked away behavior a bug or feature?
 - Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.

  [1]: https://github.com/adafruit/DHT-sensor-library
  [2]: https://github.com/SteffenKockel/DHT-sensor-library/commit/c0dff8755a94e587eac674cfc0e4f555f5a2b30e#diff-e3bd93bd1d2964ed65bbaf66e517e5a7

title: Why does DHT-library (and others) only allow one object instance?

Answers: 2

body:
There is nothing wrong with the library. It does not allow just one object instance.

What is wrong is your way of using it.

It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.

But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete.

    DHT *myDHT = NULL;

    myDHT = new DHT(4,5);
    // do something
    // change pins
    delete myDHT;
    myDHT = new DHT(6,7);

body:
Changing the pins sounds like a reasonable requirement, and you shouldn't have to delete/new to achieve it.

I would leave the library alone (for backwards compatibility) except to add a `changePins` function which you may choose whether or not to call, to assign new pins to the class structure. (Effectively it would be your rewritten `begin` function with a different name).


body:
I'm new to Arduino and I was wondering how to add an SD card to Arduino so it can store more code and also store files such as text files.

Is there such a shield, and if so, any suggestions?

title: How to add SD card to store data

Answers: 2

body:
Take a look at this:

[Sparkfun OpenLog][1]

  [1]: https://www.sparkfun.com/products/9530

body:
Here's a good tutorial:

https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/intro

This is from adafruit and is for the micro sd card.