body:
I also got the same problem, and after a few researches, I found that it was related with a [bug][1] inside the library SoftwareSerial. Here is how to fix it :

- Download the two files of the [new version of the library][2] on github
- Rename them into ```mySoftwareSerial.cpp``` and ```mySoftwareSerial.h``` and put them in the working folder
- Replace in the working file **and in the file ```mySoftwareSerial.h```** the line ```#include <SoftwareSerial.h>``` into

     ```#include "mySoftwareSerial.h"```

- Compile and send it to the arduino. It should work ! (Tested in AT mode at a baud rate of 38400, and in classical mode (+AT mode) with a baud rate of 57600 on a arduino nano)

You can find the file I used at the and of the post.

By the way, I also mention another problem I got which is not related but could help : in some models of HC-05 you have a pin ```EN``` instead of ```KEY```. Here, instead of connecting the VCC to the ```KEY``` pin, you need to press the button on the top of the HC-05 board before starting the HC-05 module : this button will connect VCC to the pin 34 for you. But note that if you don't keep this button down, **you will be able to do only a subset of the commands** (for example, ```AT+NAME?``` won't work, while ```AT+NAME=...``` and ```AT``` will). You can find lot's of additional information [here][3].

## The files I used

This file is the "project file" used to forward the classical serial connection (Ctrl+Shift+M on arduino software) to the bluetooth device. Type ```AT``` commands here.

    #include "mySoftwareSerial.h"
    SoftwareSerial BTserial(7, 8); // RX | TX
    // Connect the HC-05 TX to Arduino pin 2 RX.
    // Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
    //

    char c = ' ';

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Arduino is ready");
        Serial.println("Remember to select Both NL & CR in the serial monitor");

        // HC-05 default serial speed for AT mode is 38400
        BTserial.begin(38400);
    }

    void loop()
    {

        // Keep reading from HC-05 and send to Arduino Serial Monitor
        if (BTserial.available())
        {
            c = BTserial.read();
            Serial.write(c);
        }

        // Keep reading from Arduino Serial Monitor and send to HC-05
        if (Serial.available())
        {
            c =  Serial.read();
            BTserial.write(c);
        }

    }

The file ```mySoftwareSerial.h```, taken from the github page :

    /*
    SoftwareSerial.h (formerly NewSoftSerial.h) -
    Multi-instance software serial library for Arduino/Wiring
    -- Interrupt-driven receive and other improvements by ladyada
       (http://ladyada.net)
    -- Tuning, circular buffer, derivation from class Print/Stream,
       multi-instance support, porting to 8MHz processors,
       various optimizations, PROGMEM delay tables, inverse logic and
       direct port writing by Mikal Hart (http://www.arduiniana.org)
    -- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
    -- 20MHz processor support by Garrett Mace (http://www.macetech.com)
    -- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    The latest version of this library can always be found at
    http://arduiniana.org.
    */

    #ifndef SoftwareSerial_h
    #define SoftwareSerial_h

    #include <inttypes.h>
    #include <Stream.h>

    /******************************************************************************
    * Definitions
    ******************************************************************************/

    #ifndef _SS_MAX_RX_BUFF
    #define _SS_MAX_RX_BUFF 64 // RX buffer size
    #endif

    #ifndef GCC_VERSION
    #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
    #endif

    class SoftwareSerial : public Stream
    {
    private:
      // per object data
      uint8_t _receivePin;
      uint8_t _receiveBitMask;
      volatile uint8_t *_receivePortRegister;
      uint8_t _transmitBitMask;
      volatile uint8_t *_transmitPortRegister;
      volatile uint8_t *_pcint_maskreg;
      uint8_t _pcint_maskvalue;

      // Expressed as 4-cycle delays (must never be 0!)
      uint16_t _rx_delay_centering;
      uint16_t _rx_delay_intrabit;
      uint16_t _rx_delay_stopbit;
      uint16_t _tx_delay;

      uint16_t _buffer_overflow:1;
      uint16_t _inverse_logic:1;

      // static data
      static uint8_t _receive_buffer[_SS_MAX_RX_BUFF];
      static volatile uint8_t _receive_buffer_tail;
      static volatile uint8_t _receive_buffer_head;
      static SoftwareSerial *active_object;

      // private methods
      inline void recv() __attribute__((__always_inline__));
      uint8_t rx_pin_read();
      void setTX(uint8_t transmitPin);
      void setRX(uint8_t receivePin);
      inline void setRxIntMsk(bool enable) __attribute__((__always_inline__));

      // Return num - sub, or 1 if the result would be < 1
      static uint16_t subtract_cap(uint16_t num, uint16_t sub);

      // private static method for timing
      static inline void tunedDelay(uint16_t delay);

    public:
      // public methods
      SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);
      ~SoftwareSerial();
      void begin(long speed);
      bool listen();
      void end();
      bool isListening() { return this == active_object; }
      bool stopListening();
      bool overflow() { bool ret = _buffer_overflow; if (ret) _buffer_overflow = false; return ret; }
      int peek();

      virtual size_t write(uint8_t byte);
      virtual int read();
      virtual int available();
      virtual void flush();
      operator bool() { return true; }

      using Print::write;

      // public only for easy access by interrupt handlers
      static inline void handle_interrupt() __attribute__((__always_inline__));
    };

    // Arduino 0012 workaround
    #undef int
    #undef char
    #undef long
    #undef byte
    #undef float
    #undef abs
    #undef round

    #endif

The file ```mySoftwareSerial.cpp```, also taken from the github page:

    /*
    SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
    Multi-instance software serial library for Arduino/Wiring
    -- Interrupt-driven receive and other improvements by ladyada
       (http://ladyada.net)
    -- Tuning, circular buffer, derivation from class Print/Stream,
       multi-instance support, porting to 8MHz processors,
       various optimizations, PROGMEM delay tables, inverse logic and
       direct port writing by Mikal Hart (http://www.arduiniana.org)
    -- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
    -- 20MHz processor support by Garrett Mace (http://www.macetech.com)
    -- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    The latest version of this library can always be found at
    http://arduiniana.org.
    */

    // When set, _DEBUG co-opts pins 11 and 13 for debugging with an
    // oscilloscope or logic analyzer.  Beware: it also slightly modifies
    // the bit times, so don't rely on it too much at high baud rates
    #define _DEBUG 0
    #define _DEBUG_PIN1 11
    #define _DEBUG_PIN2 13
    //
    // Includes
    //
    #include <avr/interrupt.h>
    #include <avr/pgmspace.h>
    #include <Arduino.h>
    #include "mySoftwareSerial.h"
    #include <util/delay_basic.h>

    //
    // Statics
    //
    SoftwareSerial *SoftwareSerial::active_object = 0;
    uint8_t SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF];
    volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
    volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;

    //
    // Debugging
    //
    // This function generates a brief pulse
    // for debugging or measuring on an oscilloscope.
    #if _DEBUG
    inline void DebugPulse(uint8_t pin, uint8_t count)
    {
      volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));

      uint8_t val = *pport;
      while (count--)
      {
        *pport = val | digitalPinToBitMask(pin);
        *pport = val;
      }
    }
    #else
    inline void DebugPulse(uint8_t, uint8_t) {}
    #endif

    //
    // Private methods
    //

    /* static */
    inline void SoftwareSerial::tunedDelay(uint16_t delay) {
      _delay_loop_2(delay);
    }

    // This function sets the current object as the "listening"
    // one and returns true if it replaces another
    bool SoftwareSerial::listen()
    {
      if (!_rx_delay_stopbit)
        return false;

      if (active_object != this)
      {
        if (active_object)
          active_object->stopListening();

        _buffer_overflow = false;
        _receive_buffer_head = _receive_buffer_tail = 0;
        active_object = this;

        setRxIntMsk(true);
        return true;
      }

      return false;
    }

    // Stop listening. Returns true if we were actually listening.
    bool SoftwareSerial::stopListening()
    {
      if (active_object == this)
      {
        setRxIntMsk(false);
        active_object = NULL;
        return true;
      }
      return false;
    }

    //
    // The receive routine called by the interrupt handler
    //
    void SoftwareSerial::recv()
    {

    #if GCC_VERSION < 40302
    // Work-around for avr-gcc 4.3.0 OSX version bug
    // Preserve the registers that the compiler misses
    // (courtesy of Arduino forum user *etracer*)
      asm volatile(
        "push r18 \n\t"
        "push r19 \n\t"
        "push r20 \n\t"
        "push r21 \n\t"
        "push r22 \n\t"
        "push r23 \n\t"
        "push r26 \n\t"
        "push r27 \n\t"
        ::);
    #endif

      uint8_t d = 0;

      // If RX line is high, then we don't see any start bit
      // so interrupt is probably not for us
      if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
      {
        // Disable further interrupts during reception, this prevents
        // triggering another interrupt directly after we return, which can
        // cause problems at higher baudrates.
        setRxIntMsk(false);

        // Wait approximately 1/2 of a bit width to "center" the sample
        tunedDelay(_rx_delay_centering);
        DebugPulse(_DEBUG_PIN2, 1);

        // Read each of the 8 bits
        for (uint8_t i=8; i > 0; --i)
        {
          tunedDelay(_rx_delay_intrabit);
          d >>= 1;
          DebugPulse(_DEBUG_PIN2, 1);
          if (rx_pin_read())
            d |= 0x80;
        }

        if (_inverse_logic)
          d = ~d;

        // if buffer full, set the overflow flag and return
        uint8_t next = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
        if (next != _receive_buffer_head)
        {
          // save new data in buffer: tail points to where byte goes
          _receive_buffer[_receive_buffer_tail] = d; // save new byte
          _receive_buffer_tail = next;
        }
        else
        {
          DebugPulse(_DEBUG_PIN1, 1);
          _buffer_overflow = true;
        }

        // skip the stop bit
        tunedDelay(_rx_delay_stopbit);
        DebugPulse(_DEBUG_PIN1, 1);

        // Re-enable interrupts when we're sure to be inside the stop bit
        setRxIntMsk(true);

      }

    #if GCC_VERSION < 40302
    // Work-around for avr-gcc 4.3.0 OSX version bug
    // Restore the registers that the compiler misses
      asm volatile(
        "pop r27 \n\t"
        "pop r26 \n\t"
        "pop r23 \n\t"
        "pop r22 \n\t"
        "pop r21 \n\t"
        "pop r20 \n\t"
        "pop r19 \n\t"
        "pop r18 \n\t"
        ::);
    #endif
    }

    uint8_t SoftwareSerial::rx_pin_read()
    {
      return *_receivePortRegister & _receiveBitMask;
    }

    //
    // Interrupt handling
    //

    /* static */
    inline void SoftwareSerial::handle_interrupt()
    {
      if (active_object)
      {
        active_object->recv();
      }
    }

    #if defined(PCINT0_vect)
    ISR(PCINT0_vect)
    {
      SoftwareSerial::handle_interrupt();
    }
    #endif

    #if defined(PCINT1_vect)
    ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
    #endif

    #if defined(PCINT2_vect)
    ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect));
    #endif

    #if defined(PCINT3_vect)
    ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect));
    #endif

    //
    // Constructor
    //
    SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
      _rx_delay_centering(0),
      _rx_delay_intrabit(0),
      _rx_delay_stopbit(0),
      _tx_delay(0),
      _buffer_overflow(false),
      _inverse_logic(inverse_logic)
    {
      setTX(transmitPin);
      setRX(receivePin);
    }

    //
    // Destructor
    //
    SoftwareSerial::~SoftwareSerial()
    {
      end();
    }

    void SoftwareSerial::setTX(uint8_t tx)
    {
      // First write, then set output. If we do this the other way around,
      // the pin would be output low for a short while before switching to
      // output high. Now, it is input with pullup for a short while, which
      // is fine. With inverse logic, either order is fine.
      digitalWrite(tx, _inverse_logic ? LOW : HIGH);
      pinMode(tx, OUTPUT);
      _transmitBitMask = digitalPinToBitMask(tx);
      uint8_t port = digitalPinToPort(tx);
      _transmitPortRegister = portOutputRegister(port);
    }

    void SoftwareSerial::setRX(uint8_t rx)
    {
      pinMode(rx, INPUT);
      if (!_inverse_logic)
        digitalWrite(rx, HIGH);  // pullup for normal logic!
      _receivePin = rx;
      _receiveBitMask = digitalPinToBitMask(rx);
      uint8_t port = digitalPinToPort(rx);
      _receivePortRegister = portInputRegister(port);
    }

    uint16_t SoftwareSerial::subtract_cap(uint16_t num, uint16_t sub) {
      if (num > sub)
        return num - sub;
      else
        return 1;
    }

    //
    // Public methods
    //

    void SoftwareSerial::begin(long speed)
    {
      _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;

      // Precalculate the various delays, in number of 4-cycle delays
      uint16_t bit_delay = (F_CPU / speed) / 4;

      // 12 (gcc 4.8.2) or 13 (gcc 4.3.2) cycles from start bit to first bit,
      // 15 (gcc 4.8.2) or 16 (gcc 4.3.2) cycles between bits,
      // 12 (gcc 4.8.2) or 14 (gcc 4.3.2) cycles from last bit to stop bit
      // These are all close enough to just use 15 cycles, since the inter-bit
      // timings are the most critical (deviations stack 8 times)
      _tx_delay = subtract_cap(bit_delay, 15 / 4);

      // Only setup rx when we have a valid PCINT for this pin
      if (digitalPinToPCICR(_receivePin)) {
        #if GCC_VERSION > 40800
        // Timings counted from gcc 4.8.2 output. This works up to 115200 on
        // 16Mhz and 57600 on 8Mhz.
        //
        // When the start bit occurs, there are 3 or 4 cycles before the
        // interrupt flag is set, 4 cycles before the PC is set to the right
        // interrupt vector address and the old PC is pushed on the stack,
        // and then 75 cycles of instructions (including the RJMP in the
        // ISR vector table) until the first delay. After the delay, there
        // are 17 more cycles until the pin value is read (excluding the
        // delay in the loop).
        // We want to have a total delay of 1.5 bit time. Inside the loop,
        // we already wait for 1 bit time - 23 cycles, so here we wait for
        // 0.5 bit time - (71 + 18 - 22) cycles.
        _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 75 + 17 - 23) / 4);

        // There are 23 cycles in each loop iteration (excluding the delay)
        _rx_delay_intrabit = subtract_cap(bit_delay, 23 / 4);

        // There are 37 cycles from the last bit read to the start of
        // stopbit delay and 11 cycles from the delay until the interrupt
        // mask is enabled again (which _must_ happen during the stopbit).
        // This delay aims at 3/4 of a bit time, meaning the end of the
        // delay will be at 1/4th of the stopbit. This allows some extra
        // time for ISR cleanup, which makes 115200 baud at 16Mhz work more
        // reliably
        _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (37 + 11) / 4);
        #else // Timings counted from gcc 4.3.2 output
        // Note that this code is a _lot_ slower, mostly due to bad register
        // allocation choices of gcc. This works up to 57600 on 16Mhz and
        // 38400 on 8Mhz.
        _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 97 + 29 - 11) / 4);
        _rx_delay_intrabit = subtract_cap(bit_delay, 11 / 4);
        _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (44 + 17) / 4);
        #endif

        // Enable the PCINT for the entire port here, but never disable it
        // (others might also need it, so we disable the interrupt by using
        // the per-pin PCMSK register).
        *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
        // Precalculate the pcint mask register and value, so setRxIntMask
        // can be used inside the ISR without costing too much time.
        _pcint_maskreg = digitalPinToPCMSK(_receivePin);
        _pcint_maskvalue = _BV(digitalPinToPCMSKbit(_receivePin));

        tunedDelay(_tx_delay); // if we were low this establishes the end
      }

    #if _DEBUG
      pinMode(_DEBUG_PIN1, OUTPUT);
      pinMode(_DEBUG_PIN2, OUTPUT);
    #endif

      listen();
    }

    void SoftwareSerial::setRxIntMsk(bool enable)
    {
        if (enable)
          *_pcint_maskreg |= _pcint_maskvalue;
        else
          *_pcint_maskreg &= ~_pcint_maskvalue;
    }

    void SoftwareSerial::end()
    {
      stopListening();
    }

    // Read data from buffer
    int SoftwareSerial::read()
    {
      if (!isListening())
        return -1;

      // Empty buffer?
      if (_receive_buffer_head == _receive_buffer_tail)
        return -1;

      // Read from "head"
      uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
      _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
      return d;
    }

    int SoftwareSerial::available()
    {
      if (!isListening())
        return 0;

      return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
    }

    size_t SoftwareSerial::write(uint8_t b)
    {
      if (_tx_delay == 0) {
        setWriteError();
        return 0;
      }

      // By declaring these as local variables, the compiler will put them
      // in registers _before_ disabling interrupts and entering the
      // critical timing sections below, which makes it a lot easier to
      // verify the cycle timings
      volatile uint8_t *reg = _transmitPortRegister;
      uint8_t reg_mask = _transmitBitMask;
      uint8_t inv_mask = ~_transmitBitMask;
      uint8_t oldSREG = SREG;
      bool inv = _inverse_logic;
      uint16_t delay = _tx_delay;

      if (inv)
        b = ~b;

      cli();  // turn off interrupts for a clean txmit

      // Write the start bit
      if (inv)
        *reg |= reg_mask;
      else
        *reg &= inv_mask;

      tunedDelay(delay);

      // Write each of the 8 bits
      for (uint8_t i = 8; i > 0; --i)
      {
        if (b & 1) // choose bit
          *reg |= reg_mask; // send 1
        else
          *reg &= inv_mask; // send 0

        tunedDelay(delay);
        b >>= 1;
      }

      // restore pin to natural state
      if (inv)
        *reg &= inv_mask;
      else
        *reg |= reg_mask;

      SREG = oldSREG; // turn interrupts back on
      tunedDelay(_tx_delay);

      return 1;
    }

    void SoftwareSerial::flush()
    {
      // There is no tx buffering, simply return
    }

    int SoftwareSerial::peek()
    {
      if (!isListening())
        return -1;

      // Empty buffer?
      if (_receive_buffer_head == _receive_buffer_tail)
        return -1;

      // Read from "head"
      return _receive_buffer[_receive_buffer_head];
    }

  [1]: https://github.com/arduino/Arduino/issues/2019
  [2]: https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/libraries/SoftwareSerial/src
  [3]: http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/


sender: user

message:
Bluetooth HC-05 module returns encoded data

I have searched online, and haven't found anyone hitting this issue. Strangely my Bluetooth HC-05 is returning encoded data. I have tried using different boards - Induing, Uno, Freeduino and I have the same problem with them all.

The Bluetooth module I am using is a [HC-05 Bluetooth Module][1].

When I pass 'AT' command, I expect the return to be 'OK'. I get data as

    CF  A7  86  85

This is 8-bit data, and if I drop the MSB I would be:

    4F  27  06  05

Instead I should have received:

    4F  4B  0D  0A

I looked at the binary pattern to understand if this is something like 7 bit encoding used in GSM.

    Actual Data
    CF       A7       86       85
    11001111 10100111 10000110 10000101

    Expected Data
    4F  4B  0D  0A
    01001111 01001011 00001101 00001010

I have tried other AT commands and everything appears to be encoded.

The code I have written is pretty standard, module is blinking at 2 sec pulse (in command mode). I get encoded output for all AT commands. I even tried ORGL, INIT and other commands as suggested on various discussion threads.

    #include <SoftwareSerial.h>

    SoftwareSerial BtDongle = SoftwareSerial(10, 11);

    void setup() {
      digitalWrite(9, LOW);
      delay(100);
      digitalWrite(9, HIGH);
      delay(100);
      Serial.begin(9600);
      Serial.write("AT Command: \n\n");
      BtDongle.begin(38400);
    }

    void loop() {
      while(BtDongle.available()) {
        unsigned char data = BtDongle.read();
        Serial.println(data, HEX);
      }

      while(Serial.available()) {
        char data = Serial.read();
        Serial.print(data);
        BtDongle.print(data);
      }
    }

  [1]: https://www.fabtolab.com/radio/bluetooth/HC-05-bluetooth-module-6-pin

sender: assistant

body:
I once had problems comunicating a GPS serial cable with an arduino.
Conecting the gps to the PC serial port COM1 everything was ok.
but the arduino was receiving strange characters.
The solution was seting inverse_logic to true, the 3rd argument of SoftwareSerial.

SoftwareSerial mySerial(10,11,true);

maybe someone else can explain why some protocols are inverse


message:
Improvement security in a domotic project

I recently started with a domotic project, I began creating a lock opening with a RFID
currently I'm trying improving the code (I took from http://forum.arduino.cc/index.php?topic=256260)

but I have some question about the security of this system (or any in the domotic way).

First, I know any system is 100% secure. starting from there, I was thinking, what happens if someone known that the system is built in the arduino platform and has some knowlege about it, that person can create a sketch, upload to the board and make "opening" all the pings?, they will have access to that room or thing I'm protecting (or trying). This is just a excercise, I don't want to go in depth about the external security that the board/system must have.

So, searching topics about it, I didn't find anything to help in the solution of this theoretical problem. I read some articles about the bootloader and I think, the solution can be there, I know Arduino is a openSource solution, but I think it doesn't mean insecure, so I think some kind of system who check a key before to load a sketch can help. It can have a default key, who can be used to the developing process, and other key (any) who must be verified, in the current sketch.

I'll try to explain it a little better:

**Developing Mode**
Bootloader [No Key] -----> can upload any sketch

**Production Mode**
Bootloader[check mode] -----> [Sketch with the secure key]
[Upload New sketch] -----> Bootloader[check the key in the new sketch with the key in the current sketch] (allow or block access, according as appropriate)

I don't have deep knowledge in criptography or bootloading, so I don't know if it's corret solution. I saw there are some way to "download" the code of the board (in a bin), I don't know if with this way the key will be exposed.

can someone tell me if this basic security would be helpful?
if it's, can be possible to implement? how?
Will the key be exposed in the bin (in case of download)?

body:
A major factor in digital security is physical security. If you want a secure system you have to keep the bad guys from being able to connect wires and such.

If you have your Arduino inside a secure box inside your locked house, and it is not connected to the internet, the only way an intruder will be able to access it is to get into your house. Once inside the house you should require a second, higher level of security to unlock the Arduino's enclosure and muck with it.

If the Arduino is inside your house and an intruder doesn't have physical access to it, they can't install new apps on it or do ANYTHING with bootloaders.

If you don't use encryption of some sort you will not have very good security.

You can build an RFID or NFC system that uses a challenge-response scheme with encryption.

Something like this: When the house detects a unique RFID identifier, it generates a random number and encrypts it with that key's public encryption key. It sends the encrypted number to the key, which decrypts it using it's private key, then re-encrypts it with the house's public key and sends it back. The house decrypts the number, verifies that it is the correct number, and only then unlocks the door. The house is programmed to time out pretty quickly if it doesn't receive the correct key, to avoid brute force cracking of the encryption.

You also want a system where after a modest number of wrong responses, the system locks out for a couple of minutes.

With crypto, it doesn't matter if an intruder captures the RFID/NFC communication between the house and the key. What's sent is a one-time, encrypted code. Without the encryption keys, the intruder can't do anything with that data. It just looks like noise.

Even better is to add second factor authentication like a numeric code the user has to type, some sort of biometric scan, etc.

The above requires a fair amount of smarts in the key. There are RFID chips out there that have built-in crypto support. I don't know how good they are however. You either need hardware crypto support or a pretty high powered chip (ARM or better) to do crypto in a pocket sized device.


body:
First of all, a quick rule that you should follow... It is called [Kerckhoffs's principle][1]. Wikipedia states it as this:

> A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.

So, you're never going to reach "full security."

If the attacker can physically access your Arduino, all bets are off. They can upload new code, replace the Arduino, or just simply rewire your circuit so the door opens.

Also, they may be able to remove the RFID module and replace it with another Arduino board that sends random data in the right format hundreds or thousands of times a second. If they find the key code, they can make a new RFID tag with that ID. Thus, it is essential to keep that ID private.

So here's what you should do (in this scenario, password = RFID key's ID):

 - **Make sure they can touch or access as little as possible.** If you can, embed the RFID receiver inside a wall so they don't know where the receiver is and would have to break the wall to access it. If they break the wall, they could break the door, so this isn't necessarily a major security flaw. Of course, remember the sensitivity of your receiver.
 - **Obfuscate your code:** If you do something where you combine only certain bits/bytes of a few different strings to get a passcode to be compared to the sensor value. Of course, the compiler will remove most of this in an attempt to optimize your code. Note that this isn't actual security, just making the intruder having to do more work. A lot of people discourage this since it gives you a false sense of security, but I encourage it because it will take a little bit longer to hack into your application if they get your code. Remember that at any time they can use `Serial.println(finalPasswordHere);`.
 - **If you're really worried, hash it.** AVR chips probably don't have enough power to do advanced hashes like SHA-512. There seems to be a few MD5 hash algorithms for Arduino. MD5 isn't really secure with only a few digits, but if you have a 30 character hash that would take a long time to brute-force it. Add a salt with a ton of random characters (ex: `lsjJK399!$%^&flk2`) that aren't normally found in lookup tables. You'd combine the salt and the ID for the tag into one hash and put that in the code. Then, you'd hard code that hash into the main code. When you want to check if the ID being scanned is correct, you'd hash it with the salt and then compare that to the known hash. If you have more than one ID in the system, it's a good idea to have a different salt for each.

  [1]: http://en.wikipedia.org/wiki/Kerckhoffs's_principle


message:
Arduino + CO2 + humidity + noise + temperature sensors on one board

I'm looking for an Arduino board that include this sensors out of the box:

- CO2
- Humidity
- Noise
- Temperature

I've found here https://arduino.stackexchange.com/questions/269/using-the-waspmote-sensor-board something that could be enough, but I'm searching for more options.

I did a lot of searches on the Internet without good results.

Any suggestions?

body:
For humidity and temperature you can plug the DHT11 or DHT22 to your arduino. DHT11 is cheaper but you'll get a more precise value with DHT22.

For noise you have ready made PCB like these : [here][1]
You'll only have to plug it to GND, 5V and analog input.

For CO2 this is more complicate. There is a cheap but very unprecise option, using a MQ135 sensor, here is a tutorial: [here][2]
Otherwise there are better sensors like the [K30][3] but they are much more expensive.

  [1]: http://www.ebay.com/sch/items/?_nkw=arduino sound sensor&_sacat=&_ex_kw=&_mPrRngCbx=1&_udlo=&_udhi=&_sop=12&_fpos=&_fspt=1&_sadis=&LH_CAds=&rmvSB=true
  [2]: https://hackaday.io/project/3475-sniffing-trinket/log/12363-mq135-arduino-library
  [3]: http://www.co2meter.com/products/k-30-co2-sensor-module


message:
Arduino IDE #ifdef

I use my Arduino IDE to either upload my sketch to a Arduino or ATTiny or ATmega328. As you know each device can have a different pinout. Does the Arduino compiler support `ifdef`, depending on the board I am connected to?

For example

    #ifdef Attiny85
           a=0; b=1; c=2;
    #else
           // arduino
           a=9; b=10; c=11;
    #endif

body:
Yes. Here is the syntax:

    #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
        //Code here
    #endif

You can also do something like this for the Mega:

    #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
        //Code here
    #endif

Assuming the implementation for the ATtiny is correct, your code should be like this:

    #if defined (__AVR_ATtiny85__)
           a=0; b=1; c=2;
    #else
           //Arduino
           a=9; b=10; c=11
    #endif


message:
What is the best way to get started?

I am interested in learning about arduino.  What is the quickest and cheapest way to find out if this is something I can and want to do?

body:
By an [Arduino starter kit][1] and do all the projects. There are components and instructions for 15 different circuits. This is not cheap, but I think it will give you a good taste for electronics.

![enter image description here][2]

  [1]: http://arduino.cc/en/Main/ArduinoStarterKit
  [2]: https://i.stack.imgur.com/p7x7q.jpg


body:
The starter kit would get you everything you need to do a whole set of projects. Alternatively there is a PDF on the Arduino site with a whole set of projects in it. You could go through it, put together an inventory of the parts you need, and order those parts from an electronics supplier like Mouser, DigiKey, Jameco, etc, and save some money.

The starter kit is probably worth the extra money, though, because it has everything you need, plus an organized set of lessons that teach you the various skills you'll need.


message:
Serial data to arduino problem

![enter image description here][1]

  [1]: https://i.stack.imgur.com/2LYkt.jpg

I cant understand what is going on here , I was trying to find way to send through Serial a number for example 12 and then extract from it number 1 and 2 and store them in two different variables , but suddenly i was unable to make a simple division !!

body:
Do you want to eventually do `12 / 10` or `1 / 10` and `2 / 10`? If the second one, you'll have to read all the serial values into an array and convert those characters to their plain integer values (subtracting 48 from each value). After that, you'll have to add them together with the correct placeholders (`A * 100 + B * 10 + C`).

Basically, the `read()` function returns **one character in the ASCII format**. ACII basically representing characters on your screen with numbers. 48 displays a 0 on your screen, 49 a 1, and so on.

You're also facing a problem where your numbers are getting truncated. This means it cuts off the decimal. For when you send `100`, it is `48 / 10 = 4.8`, however `4.8` becomes just `4`. The same thing happens for 49.

To fix this, you need to use a `float` data type. This allows decimal values. You also want to make sure that the conversion from float to string works correctly for the `Serial.print()` so you don't end up with `4` again.

Final code:

    while(Serial.available()) {
      float number = (float)(Serial.read() - 48) / 10;
      Serial.println(number, 4);
    }


body:
Anonymous Penguin's code works for me on an Uno after fixing a couple of typos.  It is often best to make sure that both the numerator and the denominator are floats to ensure that the result is also treated as a float.  So please try the following where the 10 is replaced with a 10.0:

    while(Serial.available())
    {
      float number = (float)(Serial.read() - 48) / 10.0;
      Serial.println(number, 4);
    }

If you want to deal with each digit separately an array might be best but that will depend on your end goal.

    const int MAX_LENGTH = 10;
    char buffer[MAX_LENGTH];
    char lineFeed = 10;

    int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
    int i = 0;
    while( i < length )
    {
      //do what ever needs to be done to each character here, I'll just convert them to an int and print them as an example
      Serial.println( buffer[i]-48 );
      i++;
    }


message:
Using Arduino to control a 12v car light system?

I am new, but I am wondering what options I may have to control a 12v line that connects to a light with Arduino i/o.

Given the voltage limitations of an arduino, I am thinking using some kind of 5v relay to switch a 12v line on/off ( if it exists )

Though I was also hoping to be able to utilize the PWM pins in conjunction with a 12v line to 'reduce' it to 6v without using a resistor.  (though I would have no idea how to go about this, or if it is even possible).

Any help appreciated.

body:
Yes, you can use a relay. However, you'll almost certainly need to drive the relay with a transistor because the current requirements of the relay will be too high for an Arduino pin.

Better to use a logic MOSFET N-channel transistor as an electronic switch. You connect the Arduino's output pin to the gate of the transistor. You connect the + terminal of your 12 volt source to one end of the light, and connect the other wire from the light to the drain on the MOSFET. You then connect the source pin on the MOSFET to ground, and tie the ground of your Arduino to the 12 volt negative terminal.

In this setup, the MOSFET acts as a switch. When you switch the output pin of your Arduino to HIGH, the MOSFET turns on, providing a very low resistance path to ground. Current flows from the +12 volt supply, through the light, through the MOSFET, and to ground.

When the Arduino's output pin is low, the MOSFET acts as an open switch. There's no path to ground so the light is not lit.

You can't use PWM to lower 12 volts to 6 volts without some additional circuitry. PWM rapidly pulses the output from all the way on to all the way off. If you feed a PWM pin into a transistor, it can be used to create a higher voltage and/or current pulsed signal. However, pulsed DC is not the same thing as a lower DC voltage. You'd need to feed the pulsed 12 volts through a reservoir capacitor, perhaps 2 capacitors (and possibly a choke)  in order to average out the pulses into a lower DC voltage. That simple approach would work ok for powering a 6 volt incandescent light, but would not be good enough to power a solid state component because the output would not be even enough. It would have a fair amount of ripple and high frequency noise in it.


message:
How does Arduino IDE for mac deal with functions in other files

I'm a longtime C programmer. I've also done a little C++, a little Java, and a LOT of Objective-C, but am fairly new to the Arduino platform and it's IDE.

So far all my sketches have had a single source file.

I see how you copy libraries into the libraries sub-folder of your Arduino source folder, either from the Mac finder or from the IDE.

I'm trying to understand somebody else's project (The "Camera Axe" device for high speed photography.) in that project there is a folder for the entire sketch, "cameraAxe". In that folder there's a file called "cameraAxe.ino", which follows the usual convention that the sketch's main source file needs to be inside a folder with the same name.

However, for this project there are 17 other source ".ino" files. Looking at the main "cameraAxe.ino" file, it only #includes 2 files, "EEPROM.h" and "DogmCA.h", both using the convention of enclosing the filename in angle brackets so the compiler knows to look in it's libraries directory. That makes perfect sense to me, and works like any other C compiler I've ever seen.

What I **DON'T** understand is how the compiler knows where to find the code for the many functions that are defined in other files in the same folder. There a function projectileMenu() which handles the menu for configuring a projectile sensor. That function is defined in the file menu01_projectile.ino, but it doesn't have a header, and there's no #include anywhere.

Does the compiler treat all the ".ino" files in your sketch folder as part of your source and compile them all together and as if they are one large file? I see tabs in the IDE for each of the files, which suggests that it does.

What if there are dependencies among the files? What defines the order in which they are compiled? Or is it a 2 pass compiler where the order of function definitions doesn't matter?

::wanders off, muttering in confusion::

body:
arduino has its own little .ino preprocessor that generates forward declarations (like in a header file) for all function in the project's .ino files. Most of the time this just makes things less confusing for new users.

I'm not familiar with the entire process, but the effect is that any function in any .ino is known to all other .ino code.

Anything with .h or .cpp in a library or in the project file is treated as normal c++ code and not subject to arduino's manipulations. It will need "#include"s.

If you are interested, there is a hack to make arduino not mess with a function in a .ino file: add an empty "throw()" like this:

    void foo() throw() {
    }


message:
Attiny84A and IR Sensor

I have a [GP2Y0A21YK0F Sharp IR Analog Distance Sensor 10-80cm + Cable, Arduino Compatible][1] and its is connected to my Arduino. All works well and I can read the analog data with the following code:

    #include <SoftwareSerial.h>
    #define RX 2 // receive
    #define TX 3 // transmit
    #define SEN1 4
    SoftwareSerial mySerial =  SoftwareSerial(RX, TX);

    void setup()
    {

      mySerial.begin(4800);
      mySerial.println("Hello, world?");
    }

    void loop() // run over and over
    {

       int reading = analogRead(SEN1);
       mySerial.println(reading);
       delay(500);
    }

![GP2Y0A21YK0F][2]

When the code runs on the Attiny with the `GP2Y0A21YK0F` IR Sensor connected, the Attiny84 resets over and over. The Attiny84 and `GP2Y0A21YK0F` are part of the same circuit e.g. Attiny and `GP2Y0A21YK0F` share the power and ground rail.

When I disconnect the `GP2Y0A21YK0F`, the program runs and stops resetting. I was able to reproduce this on an Attiny85 and ATMega328.

The strange thing is, it works fine on the Arduino. Any help is greatly appreciated.

  [1]: http://www.amazon.com/gp/product/B00IMOSEJA/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
  [2]: https://i.stack.imgur.com/NWzZQ.jpg

body:
It sounds like the microcontroller is browning out.

IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.

Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.

Hope this helps!

(**edit**: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage_droop)


message:
Servo library unable to control more than 11 servos

I am working on assembling the ROFI robot from Project Biped (http://www.projectbiped.com/prototypes/rofi) and I have not been able to run any arduino program as they will not function correctly.

To be more specific, when I attempt to run 12 servos on a single Arduino Mega, the servos twitch uncontrollably and do not move to the positions which are set in the program.  At the same time the power light on the arduino mega blinks and does not turn solid (as opposed to if I use less than 11 servos when the pwr light is solid).  I predict it might be the power source but after checking the batteries with the multimeter they check out to be fine (7.6 V).  The circuit is pretty simple, I am using a servo shield connected to a 6V regulator connected in parallel to two 7.2 V 1350 mah LiPo batteries.  The arduino is connected through the dc power jack to the same circuit in parallel.

Here is the code...

       #include <Servo.h>

    // 0 Right Ankle (roll)
    // 1 Right Lower Leg
    // 2 Right Knee
    // 3 Right Middle Leg
    // 4 Right Upper Leg
    // 5 Right Hip (roll)
    //LEFT LEG JOINTS
    // 6 Left Ankle (roll)
    // 7 Left Lower Leg
    // 8 Left Knee
    // 9 Left Middle Leg
    // 10 Left Upper Leg
    // 11 Left Hip (roll)

    int c=0;

    Servo rightAnkle;
    Servo lowerLeg;
    Servo rightKnee;
    Servo rightMiddleLeg;
    Servo rightUpperLeg;
    Servo rightHip;
    Servo leftAnkle;
    Servo leftLowerLeg;
    Servo leftKnee;
    Servo leftMiddleLeg;
    Servo leftUpperLeg;
    Servo leftHip;

    void setup(){
      rightAnkle.attach(0);
      lowerLeg.attach(1);
      rightKnee.attach(2);
      rightMiddleLeg.attach(3);
      rightUpperLeg.attach(4);
      rightHip.attach(5);
      leftAnkle.attach(6);
      leftLowerLeg.attach(7);
      //leftKnee.attach(8);
      //leftMiddleLeg.attach(9);
      leftUpperLeg.attach(10);
      leftHip.attach(11);
    }

    void loop(){
      rightAnkle.write(90);
      lowerLeg.write(90);
      rightKnee.write(90);
      rightMiddleLeg.write(90);
      rightUpperLeg.write(90);
      rightHip.write(100);
      leftAnkle.write(90);
      leftLowerLeg.write(90);
      leftKnee.write(90);
      leftMiddleLeg.write(90);
      leftUpperLeg.write(90);
      leftHip.write(90);
    }

body: It sounds to me like you're exceeding the current limits of your power supply. Add up the current drawn by your servos (and their controller(s), and also the current drawn by your Arduino and any other circuits you have. I bet you'll find that at 12 servos, you go over the current limit of your regulator. You might need a higher current regulator or a second one.


body:
> Servo library unable to control more than 11 servos

because the library isn't written to control more.

this approach (https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/) can drive arbitrary number of servos over multiple ports / pins.

it is written for a pic but it has links to AVR implementation as well.


message:
How to serial connect arduino galileo to alarm system

i'm a little new in this.
I have an alarm system panel which has TX,RX wires with 12V output/input.

how can i  read the output with arduino and control it with serial communication?

body:
First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.

After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.

You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.


message:
Blank Serial Print AdaFruit BTLE

I working on a prototype with an Arduino UNO and an [AdaFruit Low Energy Blue tooth][1]

I have an array of uint32_t that I am trying to send via blue tooth to a given device.  I don't think i can send the array so I was trying to send it as a comma separated string.

I can print out each individual index of that array just fine, but its completely blank when i try to make a comma separated String..  See code and comments below.

**Ay Array:**

    uint32_t items[]= {0,3513728,7925384,0,0,0};

**In My Loop:**

    String output = "";

    for(int i = 0; i<6;  i++){

      BTLEserial.print(items[i]); // Prints as expected
      output += getStringForUI32_T(items[i]);
      output+=",";

     }
     BTLEserial.print(output); // prints BLANK

I imagine this has something to do with memory but I am at a complete loss.. Please help!

  [1]: https://www.adafruit.com/products/1697

body:
I'd probably do it directly like:

    for(int i = 0; i<6;  i++) {
      BTLEserial.print(items[i]);
      BTLEserial.print(',');
    }
    BTLEserial.println();

But with the string I think it would be something like:

    String output = "";

    for(int i = 0; i<6;  i++) {
      output += getStringForUI32_T(items[i]);
      output+=",";
    }
    BTLEserial.println(output[0]);

But as someone else got it working using String on your adafruit thread maybe this is just barking up the wrong tree.


message:
USB MIDI HID with the ATmega32u4?

There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as [MocoLUFA](http://morecatlab.akiba.coocan.jp/morecat_lab/MocoLUFA.html). Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.

Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?

Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?

body:
The teensy series from pjrc.com allows USB MIDI natively (full USB speed!).  It works well and does not require any firmware tomfoolery.  It can also do HID keyboard/mouse/joystick natively as well.

There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory.  If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.


message:
Power supply voltage confusion

I just ran into this article: [Arduino: What adapter?][1].

It says that the external power supply should be 9-12V. That really surprises me, since my Arduino Uno can also be powered via USB, which is 5V.

Later he talks about a 9V pin. But I can only see a 5V and 3.3V pin on mine. Is he talking about a different version of Arduino?

Judging from the picture, his Arduino looks slightly different from my Arduino Uno R3, but I can't tell which version is on the picture.

  [1]: http://playground.arduino.cc/Learning/WhatAdapter

body:
The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.

Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a [dropout voltage][1].

Looking at the [schematic of the Uno][2] we see it uses a [NCP1117][3], which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.

The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).

  [1]: http://en.wikipedia.org/wiki/Dropout_voltage
  [2]: http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
  [3]: http://www.onsemi.com/pub_link/Collateral/NCP1117-D.PDF


body:
And the third part of your question: It is possible to bypass the voltage regulator and feed REGULATED 5 volts directly to the 5V pin.

That's how the Arduino is powered using USB. The USB power is already regulated 5V, and is fed directly to the 5V pin.

Beware of doing this yourself however. You better be certain the 5V you're feeding in is a clean, filtered and regulated 5V. If it's not you run the risk of destroying your Arduino (and possibly anything connected to it's 5V lines.)


message:
Arduino Uno R3 not working after shorting 5V to GND

While wiring up my new Arduino Uno R3 on a proto-board, I accidentally shorted the 5V pin directly to Ground. The LED's immediately turned off and connection was lost. It was powered by USB connection. After 3-5 seconds I removed the short. The LED's have remained out, and I haven't been able to reestablish connection with my computer since. I've unplugged and re-plugged the USB cable and tried the re-set button plenty of times. This short shouldn't have fried the board...  what happened? How can I get my Arduino working again??

body:
Have you tried restarting the computer? The computer will shut down the USB port to protect it from a malfunction like this (over-current).

You can also try the ports on the other side of the computer (or front/back) as they're usually on different controllers.


body:
The genuine Arduino boards feature a digital (temperature based) fuse.

When shorting an Arduino, it will heat up the fuse on the Arduino. When the fuse gets to a certain temperature, it will automatically cut off the power from the USB connection to the Arduino board.

When the fuse cools down, it will conduct again.

The motherboards of most computers these days also work with these digital fuses, so you might have heated up both. It wouldn't hurt to reboot the PC and disconnect the Arduino and give it a minute to cool down.

If it still doesn't work, you might have fried the Arduino or the specific USB port.
Try a USB port that is likely not connected to the same USB controller in the PC. Meaning, don't just try the first USB port next to the one you used, but try a USB port on the other side of the PC / laptop, they are likely to be connected to different USB controllers.


message:
Receiver xbee receiving data even if the Transmitter is not sending?

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

TX code:

    #include <SoftwareSerial.h>

    const int MAX_LENGTH = 2;
    char buffer[MAX_LENGTH];
    char lineFeed = 2;

    SoftwareSerial   Xbee(10, 11);

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

    void loop() {
      int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
      int i = 0;
      while( i < length )
      {
        Serial.print(buffer[i]-48);
        Xbee.print(buffer[i]-48);
        i++;
      }
    }

RX code:

    const int MAX_LENGTH = 2;
    char buffer[MAX_LENGTH];
    char lineFeed = 2;

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

    void loop() {
      int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
      int i = 0;

      while( i < length )
      {
        Serial.print(buffer[i]-48);
        i++;
      }
    }

NOTE :

1- The Rx xbee is receiving data even if am not sending and even if the TX xbee is powered off

2- When i send data from the TX xbee id didn't get revived by the RX xbee

I need to solve both problems.

*** What i need exactly is to send serial data from my pc to arduino and send it wireless through xbee and then receive to the other arduino connected to my circuit

  [1]: https://i.stack.imgur.com/qIFWb.png
  [2]: https://i.stack.imgur.com/bZxmF.png

body:
The reason that it is printing characters with no input is that the readBytesUntil function has a timeout. If no new characters are received for a certain amount of time, "Serail.setTimeout()" seconds, it will just continue with the code. the default timeout is 1 second.

The reason you are not receiving what you transmit (or at least a reason) is that the RX code does not read from an xbee, but reads from regular "serial".

I recommend you try something simple first to test the xbee's configuration, like having TX run this:

    void loop(){
        xbee.println("Hello");
        delay(1000);
    }

and RX run something to echo serial like this:

     void loop(){
         if(xbee.available()){
             Serial.print((char)xbee.read());
         }
    }

And make sure you set up an xbee object an the receiving side first.


message:
how to push data from an Arduino pin to Bluetooth module

I'm writing a software that can receive data from Arduino via Bluetooth. My software is pretty fine now, at least it can pair with my hardware but when I try to test whether it can receive data via Bluetooth, I'm stuck. My Arduino receives temperature readings from a sensor at Analog pin 0. My Bluetooth module HC-05 connects with Arduino at Digital 0 and 1 (RX and TX pin respectively, as default). I don't know how to push data from Analog pin 0 to the Bluetooth module. Thanks in advance for any suggestion.

body:
The HC-05 looks like like any other terminal to the Arduino so any serial operations that you would use for a wired terminal can be used with the HC-05. See the HC-05's manual for how to set it up initially. Note that HC-05s don't forget their settings and they have no reset command to put them into a known state, so write down your settings for your future reference.

    - Read the analog pin value;
    - Convert the value into whatever physical units you require;
    - Print the result with Serial.print() or Serial.println()

Edit:  You wrote that your HC-05 is connected to Digital 0 and 1, but you created your SoftwareSerial, `mySerial`, to transmit on Digital 11. In that case your HC-05's receive pin must be connected to Digital 11.


body:
It's my code. Can anyone suggest anything wrong with it if my idea is to push data from Analog pin 0 to Digital pin 11, which is the Tx pin on Arduino connecting to Rx pin on HC-05?

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);
    int tempPin=0;

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

    void loop()
    {
     float reading = analogRead(tempPin); // reading on tempPin
     float voltage = reading*5.0/1024.0; // the resolution of a pin is 10 bit,
     float tempC = voltage/0.01; // 10mV = 1 Celcius
     mySerial.write(tempC);

     delay(3000);
    }


message:
What are the current limits on an Arduino Micro?

Just to make sure I don't set my board on fire, is there any information out there about the maximum current per pin/pin group on an Arduino Micro?

[This page][1] states I can get 40mA per pin, but are there limits on group of pins?

As stated [here][2], there are pin groups which should not exceed 100mA. But could not find anything about that in the ATmega32u4 datasheet, or any other Arduino Micro related websites.

  [1]: http://arduino.cc/en/pmwiki.php?n=Main/arduinoBoardMicro
  [2]: http://forum.arduino.cc/index.php/topic,148734.0.html

body:
It's in the notes in section 29.2:

> 3. Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
conditions (non-transient), the following must be observed:
ATmega16U4/ATmega32U4:
1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
than the listed test condition.
4. Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
state conditions (non-transient), the following must be observed:
ATmega16U4/ATmega32U4:
1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not *fail* if these are exceeded, but the rest of the numbers in the table may no longer apply.


message:
Arduino and visual basic Serial data

I am trying to send command serially through Vb.through serial monitor working fine . But Through VB it not detecting port
**My arduino code:**

    int ledPin = 2; // the number of the LED pin

    void setup() {
    Serial.begin(9600); // set serial speed
    pinMode(ledPin, OUTPUT); // set LED as output
    digitalWrite(ledPin, LOW); //turn off LED
    }

    void loop(){
    while (Serial.available() == 0); // do nothing if nothing sent
    int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

    if (val == 1) { // test for command 1 then turn on LED
    Serial.println("LED on");
    digitalWrite(ledPin, HIGH); // turn on LED
    }
    else if (val == 0) // test for command 0 then turn off LED
    {
    Serial.println("LED OFF");
    digitalWrite(ledPin, LOW); // turn off LED
    }
    else // if not one of above command, do nothing
    {
    //val = val;
    Serial.println("Wrong command");
    }
    Serial.println(val);
    Serial.flush(); // clear serial port
    }

VB Code

    Imports System.IO
    Imports System.IO.Ports
    Imports System.Threading

    Public Class Form1
        Shared _continue As Boolean

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

            SerialPort1.Open()
            SerialPort1.PortName = "COM3"

            SerialPort1.BaudRate = 9600
            SerialPort1.DataBits = 8
            SerialPort1.Parity = IO.Ports.Parity.None
            SerialPort1.StopBits = IO.Ports.StopBits.One
            SerialPort1.Handshake = IO.Ports.Handshake.None
            SerialPort1.Encoding = System.Text.Encoding.Default 'very important!

        End Sub

        Private Sub Button1_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1_Click.Click
            SerialPort1.Open()
            SerialPort1.Write("1")
            SerialPort1.Close()
        End Sub

        Private Sub Button2_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2_Click.Click
            SerialPort1.Open()
            SerialPort1.Write("0")
            SerialPort1.Close()
        End Sub

    End Class

Error I am getting .Arduino port is 3. and configured to port 3 . i dont know why it giving error.

    The port 'com10' does not exist.

This Line added as you said

    Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            SerialPort1.Open()
            Dim str As String
            str = SerialPort1.ReadExisting
            Current_Read.Text = str
            SerialPort1.Close()
        End Sub

This is working But data not being updating

    Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Current_Read.Text =SerialPort1.ReadLine
        End Sub

body: You've opened the port before you've configured it.


message:
Receiver xbee receiving data while the Transmitter is powered off?

My receiver xbee is receiving data even if the transmitter is disconnected , so if i am sending the string hello world , the receiver will repeat this string .

    void loop() {
        Serial.println("Hello");
        delay(1000);
    }

    void loop() {
         if(Serial.available()>0){
             Serial.print((char)Serial.read());
         }
    }

body:
As @Garben mentioned, we do not know what is your question, problem or whatever...
Provide some more information about wiring. I looked at your question 5 mins and still can't get what is wrong...

What are you doing here??? Sending from Arduino+XBEE to another Arduino+XBEE???

    void loop() {
        Serial.println("Hello");
        delay(1000);
    }

Here you are resending what you got

    void loop() {
         if(Serial.available()>0){
             Serial.print((char)Serial.read());
         }
    }

So what is your problem? Or is this all your code???
Arduino has to have

    void setup(){
    //Set up your Arduino here
    }
    void loop(){
    //Code here will run over and over and over...
    }


message:
Communication Protocol Best Practices and Patterns

Every time I design a serial protocol to be used between two arduinos, I feel a bit like I'm reinventing a wheel. I wonder if there are any best practices or patterns people follow. This question is less about the actual code, but more about the format of the messages.

For example, if I wanted to tell an arduino to flash it's first LED 3 times I might send:

    ^L1,F3\n

* '^': starts a new command
* 'L': Defines the command, (L: target this command to an LED)
* '1': Target the first LED
* ',': Command line separator, new value in this message to follow
* 'F': Flash sub-command
* '3': 3 times (Flash the LED three times)
* '\n': End the command

Thoughts? How do you usually approach writing a new serial protocol? What about if I wanted to send a query from arduino 1 to arduino 2 and then receive a response?

body:
I do not have any formal expertise on serial protocols, but I've used them quite a few times, and more or less settled on this scheme:

(Packet header)(ID byte)(data)(fletcher16 checksum)(Packet Footer)

I usually make the header 2 bytes and the Footer 1 byte. My parser will dump everything when it sees a new packet header, and attempt to parse the message if it sees a footer. If the checksum fails, it will not ditch the message, but continue adding until the footer character is found and a checksum succeeds. That way the footer only needs to be one byte since collisions don't disrupt the message.

The ID is arbitrary, sometimes with the length of the data section being the bottom nibble (4 bits). A second length bit could be used but I normally don't bother since the length does not need to be known to parse correctly, so seeing the right length come through for a given ID is just more confirmation that the message was correct.

The fletcher16 checksum is a 2 byte checksum with nearly the same quality as CRC but is much easier to implement. some details [here][1]. The code can be as simple as this:

    for(int i=0; i < bufSize; i++ ){
       sum1 = (sum1 + buffer[i]) % 255;
       sum2 = (sum2 + sum1) % 255;
    }
    uint16_t checksum = (((uint16_t)sum1)<<8) | sum2;

I've also used a call and respone system for critical messages, Where the PC will send a message every 500ms or so until it gets an OK message with a checksum of the whole original message as data (including the original checksum).

This scheme is, of course, not well suited for being typed into a terminal like your example would be.  Your protocol seems pretty good for being limited to ASCII and I'm sure is easier for a quick project that you want to be able to directly read and send messages. For larger projects it is nice to have the density of a binary protocol and the security of a checksum.

  [1]: https://en.wikipedia.org/wiki/Fletcher's_checksum


body:
There are a lot of ways to write a serial protocol depending on what functionality you might want and how much error checking you need.

Some of the common things you see in point to point protocols are:

**End of message**

The simplest ASCII protocols just have an end of message character sequence, often `\r` or `\n` as this is what gets printed when the enter key is hit. Binary protocols might use `0x03` or some other common byte.

**Start of message**

The problem with just having end of message is that you don't know what other bytes have already been received when you send your message. These bytes would then be prefixed to the message and cause it to be interpreted wrongly. For example, if the Arduino just woke from sleep there might be some garbage in the serial buffer. To get around this you have a start of message sequence. In your example, `^`,  in binary protocols often `0x02`

**Error Checking**

If the message can be corrupted we need some error checking. This could be a checksum or a CRC error or something else.

**Escape Characters**

It could be that the checksum adds to a control character, such as the 'start of message' or 'end of message' byte, or the message contains a value equal to a control character. The solution is to introduce an escape character. The escape character is placed before a *modified* control character so that the actual control character is not present. E.g. if a start character is 0x02, using the escape character 0x10 we can send the *value* 0x02 in the message as the byte pair 0x10 0x12 (byte XOR control character)

**Packet number**

If a message is corrupted we could request a resend with a nack or retry message, but if multiple messages have been sent then only the latest message can be resent. Instead the packet can be given a number that rolls over after a certain number of messages. For example, if this number is 16, the transmitting device can store the last 16 messages send and if any were corrupted the receiving device can request a resend using the packet number.

**Length**

Often in binary protocols you see a length byte which tells the receiving device how many characters are in the message. This adds another level of error checking as if the correct number of bytes were not received then there was an error.

***Arduino specific***

When coming up with a protocol for Arduino the first consideration is how reliable is the communications channel. If you are sending over most wireless mediums, XBee, WiFi, etc, there is already built in error checking and retries and thus no point in putting these in your protocol. If you are sending over RS422 for a couple of kilometres then it will be necessary. The things I would include are the start of message and end of message characters, as you have. My typical implementation looks something like:

`>messageType,data1,data2,…,dataN\n`

Delimiting the data parts with a comma allows for easy parsing, and the message is sent using ASCII. ASCII protocols are great because you can type messages into the serial monitor.

If you want a binary protocol, maybe to shorten the message sizes, you will have to implement escaping if a data byte can be the same as a control byte. Binary control characters are better for systems where the full spectrum of error checking and retries is desired. The payload can still be ASCII if desired.


body:
If you're into standards, then you may take a look at ASN.1 / BER TLV encoding. ASN.1 is a language used to describe data structures, made specifically for communication. BER is a TLV method of encoding the data structured using ASN.1. Problem is that ASN.1 encoding may be tricky at best. Creating a full fledged ASN.1 compiler is a project in itself (and a particularly tricky one at that, think *months*).

---

It's probably better to keep just the TLV structure. TLV basically consists of three elements: a tag, a length and a value field. The tag defines the type of the data (text string, octet string, integer etc.) and the length the length *of the value*.

In BER the T also denotes if the value is a set of TLV structures itself (a constructed node) or directly a value (a primitive node). That way you can create a tree in binary, much like XML (but without the XML overhead).

Example:

    TT LL VV
    02 01 FF

is an integer (tag `02`) with a length of the value of 1 (length `01`) and value -1 (value `FF`). In ASN.1 / BER the integers are sign big endian numbers, but you can of course use your own format.

    TT LL (TT LL VV, TT LL VV VV)
    30 07  02 01 FF  02 02 00 FF

is a sequence (a list) with length 7 containing *two* integers, one with value -1 and one with value 255. The two integer encodings together make up the value of the sequence.

You can simply [toss this into an online decoder too](), aint that nice?

---

You can also use indefinite length in BER which will allow you to stream data. In that case you do need to parse your tree correctly though. I'd consider it an advanced topic, you need to know about breadth first and depth first parsing, for one.

---

Using a TLV scheme basically allows you to think of any kind of data structure and encode it. ASN.1 goes a lot further than that, giving you unique identifiers (OID's), choices (a lot like C-unions), includes of other ASN.1 structures etc. etc. but that may be overkill for your project. Probably the best well known ASN.1-defined structures today are the certificates used by your browser.


body:
If not, you've got the basics covered. Your commands can be created and read by both humans and machines which is a big plus. You might add a checksum to detect a mal-formed command or one damaged in transit, especially if your channel includes long cable or a radio link.

If you need industrial strength (your device mustn't cause or allow someone to get hurt or die; you need high data rates, fault recovery, missing packet detection etc.) then look to some of the standard protocols and design practices.


message:
4-digit 7 Segment LED displaying numbers in the wrong order

I am a novice Arduino programmer and am currently having trouble with a SH5461AS 4-digit/7-segment LED when using it with an Arduino Uno. I have struggled to find an accurate datasheet/tutorial of any kind for this particular model (It is the LED without the colons in between digits 2 and 3) but I believe I have it figured out.

I currently have it going through a HC595 shift register but when I removed the register and connected the LED directly to the board the problem remained. My code below is with the shift register; I am displaying it this way because it is simpler to view and I thought it would make it easier to debug.

I can display a single digit at a time correctly. However, when I try to display 2+ digits at one time, they are in the incorrect order.
For example, I can count 1-9 on the first digit, then 1-9 on the 2nd digit, and so on and everything displays correctly (other digits are off). But as soon as I try to display multiple digits they are in the wrong order. So if I try to display 12__ with the last 2 digits off, 21__ is displayed with the last two digits off. If I try to display _23_, _32_ is displayed. If I try to display 1234, 4123 is displayed.

I am at a loss because the code seems like it should be simple.

    const int DATA = 0;
    const int LATCH = 1;
    const int CLOCK = 2;

    const int DIGIT_ONE = 3;
    const int DIGIT_TWO = 4;
    const int DIGIT_THREE = 5;
    const int DIGIT_FOUR = 6;

    //digits[0-9] corresponds to the patterns for numbers 0 -> 9.
    //Add 1 to the digits[X] to turn on the dot.
    byte digits[] = {B11111100, B00011000, B01101110, B00111110, B10011010, B10110110, B11110010, B00011100, B11111110, B10111110};

    void setup() {
      pinMode(DATA, OUTPUT);
      pinMode(CLOCK, OUTPUT);
      pinMode(LATCH, OUTPUT);

      pinMode(DIGIT_ONE, OUTPUT);
      pinMode(DIGIT_TWO, OUTPUT);
      pinMode(DIGIT_THREE, OUTPUT);
      pinMode(DIGIT_FOUR, OUTPUT);

      digitalWrite(DIGIT_ONE, HIGH);
      digitalWrite(DIGIT_TWO, HIGH);
      digitalWrite(DIGIT_THREE, HIGH);
      digitalWrite(DIGIT_FOUR, HIGH);
    }

    void loop() {
      writeDigit(DIGIT_TWO, 2);
      writeDigit(DIGIT_THREE, 3);
    }

    /*
     * Write a digit to the 4-digit 7-segment LED
     * - digitPin corresponding to the pin on the LED to light up the correct digit.
     * - number 0-9 to display on the LED
     */
    void writeDigit(int digitPin, int number) {
      digitalWrite(digitPin, LOW);

      digitalWrite(LATCH, LOW);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
      digitalWrite(LATCH, HIGH);

      digitalWrite(digitPin, HIGH);
    }

So in this instance, I am expecting _23_ but _32_ is displaying instead.

I am also having trouble with some bleeding (I don't know what the correct term is) where some segments are very faintly glowing even though I am not doing it intentionally. This is a much smaller issue, however, than digits randomly in the wrong order.

If it would help, I can try to post the circuit diagram as well.

body:
I found the data sheet here:

https://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AK2B-35.pdf.

It's a horrible bit of writing. Not at all clear.

It looks like it's multiplexed. You use pins 14, 16, 13, 3, 5, 11, 15, and 7 as the cathodes for the segments on a digit (ground the pins for the segments you want to light.) Pin 7 appears to be the decimal place for a given digit.

One of the pins 1, 2, 6, or 8 should be fed a +5V to light a particular digit.

The other pins control the colons and other dots on the display. Let's ignore those.

To light the display here's what I THINK you would do (I'm tired, and didn't study the data sheet that closely, so I may may be wrong here)

For pins 14, 16, 13, 3, 5, 11, 15, and 7: These are the cathodes for the segments in the current digit you are driving. Set the pins you want to light as digital outputs, LOW. Set the others as inputs, which will make them essentially open circuits. The selected pins will be grounded, and the ones set as inputs will not be connected to anything.

Pull pin 1 HIGH to light the selected segments in digit 1. Put it back low, set the segment pins, then pull pin 2 HIGH to light that digit. Repeat, pulling pins 6 and 8 high to light the selected segments in digits 3 and 4.

You'd have to cycle rapidly through the digits, lighting 1 at a time, in order to make them appear all lit at once.

Get that working first without using shift registers. (It will take 11 I/O lines to drive all 4 digits and their decimal places - 1 less if you don't care about the decimal place.)

I think that if your drive all the pins using a shift register then some of the unlit segments will be fed reverse voltage. (When set as an output, sending a LOW connects the output pin to ground, and setting it high drives it to 5V. With all the control pins driven from outputs of a shift register, the off segments will have 5 volts on them, and the off digit select pins will have ground on them.)


body:
Here is a datasheet I found that seems a better macth for your display model (that's the datasheet for a display that I use):

http://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom/upload/File-1356269320.pdf

This is the datasheet I directly got from my local supplier.

According to what you say, the problem does not seem to be a wiring problem.

It looks more like a **timing** issue:

    void writeDigit(int digitPin, int number) {
      digitalWrite(digitPin, LOW);

      digitalWrite(LATCH, LOW);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
      digitalWrite(LATCH, HIGH);

      digitalWrite(digitPin, HIGH);
    }

The first issue when you call `writeDigit()` is that it forces the cathod low **BEFORE** having set the shift register, so the digit will first show the current register value, i.e. the one from the previous call to `writeDigit()`.

Then it pushes the new value for the segments on the shift register, that will be fast but not as fast as two consecutive calls to `loop()`.

If we try to roll and expand the `loop()` call in your example that will be:

    // First call: writeDigit(DIGIT_TWO, 2)
      digitalWrite(DIGIT_TWO, LOW);
      digitalWrite(LATCH, LOW);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
      digitalWrite(LATCH, HIGH);
      digitalWrite(DIGIT_TWO, HIGH);

    // Second call: writeDigit(DIGIT_THREE, 3)
      digitalWrite(DIGIT_THREE, LOW);
      digitalWrite(LATCH, LOW);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);
      digitalWrite(LATCH, HIGH);
      digitalWrite(DIGIT_THREE, HIGH);

The calls to `loop()` and `writeDigit()` are negligible in terms of timing here.

In the sequence above, most of the time is spent in:

      shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);

So that means your function will:

1. show the previous value on the new digit for `t1 us`
2. show the new value of the new digit for `t2 us`

with `t1 >> t2`, hence your eyes will see the opposite of your intent!

To fix that issue you definitely need to introduce some delay to reverse what your eyes will see:

    void writeDigit(int digitPin, int number) {
      digitalWrite(LATCH, LOW);
      shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
      digitalWrite(LATCH, HIGH);
      digitalWrite(digitPin, LOW);
      delayMicroseconds(100);
      digitalWrite(digitPin, HIGH);
    }

In the code above:

- no digit shows while the shift register is set
- the requested digit shows immediately after the shift registry has been written and lacthed, and for a duration of 100us, which will be much longer than the rest of the time.

That code should also get rid of the "bleeding" you observed.


body:
I don't have enough reputation to add a comment, but the datasheet link in @jfpoilpret is dead. [This link][1] has the datasheet from the same website.

Thanks.

  [1]: https://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom/upload/File-1356269320.pdf


message:
Distance and Serial or SPI

I'm setting up a grid of 200+ slave modules which will be about 12 inches apart and the master will be anywhere from 5 to 10 meters away from the closest module. Each slave module will have a ATtiny85 to manage the sensor reading, LEDs and the network protocol.

The communication packets will be small and will probably be at 115200 baud if using ATTiny85's TTL serial or 1MHz if using SPI. In either case, the modules will be connected in a daisy chain to each other.

Each module will have a resistive touch sensor and be driving about 12 - 16 RGB LEDs (I'm making a step responsive disco dance floor). There will be 12v+ running to each module to drive the LEDs and regulated down to 5V for the ATtiny.

Which brings me to my question. With these constraints, do you think the ATtiny85's built-in serial or SPI would still work well over the 5 to 10 meters from the closest module to the master.

I know some people push towards RS422 or RS485 transceivers for distance applications, but I'd like to keep the total part count down, if possible.

body:
I have a few years working with DMX, SPI (and other serial) & LEDs. I have worked with DMX and a video dance floor for 10+ years previously. I would offer that "some people" are correct. You will get a reliable system with differential pair signalling (such as DMX).
I have found from experience that over 5m of unbalanced serial starts chancing it. Over 10m and you are likely to come up with at least reliability issues, but more likely garbage.

I have used the TI SN75176B driver a fair bit and is cheap and works.

Depends on your audience. You can afford to chance it for your bedroom, but not paid business.


body:
Sounds like a fascinating project.

It sounds like the majority of signals are driven by one ATTiny85 and received by a neighboring ATTiny85 about 12 inches away, with a good ground connection between them.
Those signals can be directly connected.

If I were you, I would go ahead and get differential transceivers for the 10 meter distance.
If you use daisy-chain SPI, then you need 3 differential line drivers at one end of the cable and 1 differential line driver at the other (and the corresponding line receivers to match); plus GND and +12VDC.
If you use a SN75176BP as a line driver and another one as a line receiver for each SPI signal, that's a total of less than $8 for those 8 interface chips.
(You need fewer line driver chips if you somehow daisy-chain TTL UART serial, since it uses fewer pins, but requires each chip to have more precise baud clock).

The software should not even be able to detect the difference between a simple wire from the output pin of one chip to the input pin of the next chip, vs. a line driver, some twisted pair cable, and a line receiver between those same two chips running the same software.

Many people use the rule of thumb that if a bit time is less than 10 times the time it takes for something traveling at the speed of light to make a round trip from the transmitter to the receiver and back, then you must use differential signaling with line termination.
At 1 MHz, that gives a (1-way) cable length of 15 meters before you must use differential signaling with line termination.

So using the differential line drivers is probably overkill, but I'd rather have the first prototype work rather than cut corners on 100 things that I'm 99% sure *probably* won't matter, and then spend a lot of time debugging trying to figure out which one or two of those 100 things turns out that it *does* matter.

In addition to distance, loading might also be an issue.
In particular, the "CLK" and "/CS" pins from the SPI master apparently need to drive every SPI slave.
You can't really expect a single MCU output pin or even a single RS485 line receiver to be able to drive 200+ other chips.
A line driver or other buffer every 10 or so chips is more than adequate.

Related:

["What if the SPI signal lines are very long?"][1]
(this experiment completely neglects the effects of interference from *other* noisy devices).

[AN10364 "Transmitting the I2C signals as differential signals using RS-485 hardware"][2]
(Like SPI, I2C signals were never intended to be transmitted long distances over wire cables.)

["Maximum Unterminated Network Speed Calculator"][3]

  [1]: http://jeelabs.org/2013/06/19/what-if-the-signal-lines-are-very-long/
  [2]: http://www.nxp.com/documents/application_note/AN10364.pdf
  [3]: http://www.baranidesign.com/rs485/rs485.html


message:
Enable free fall detection using Arduino

I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.

However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.

The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).

Thank you.

body:
Sitting an accelerometer flatly on a bench will produce a value of 1G in one of the 3 axes.

Free fall of an accelerometer (assuming you haven't reached terminal velocity) should read near zero on all 3 axes.

I am not aware of a mode you can set for this, but if you check the values of the 3 axes and all are close to zero, you are probably in a free fall condition.


body:
Take the root sum squared [sqrt(acc_x^2 + acc_y^2 + acc_z^2)] of your accelerometer readings.  This is your total acceleration vector.  Then write a function that triggers the free fall variable when that equation is less than or equal to a certain threshold near to zero (the value itself depends on your accelerometer).

Your gyro and magnetometer will not help as they relate to the attitude (facing direction) and rotational speed of your thing, not the linear motion.  Test and play with the threshold and you will get the most accurate result possible.


message:
Arduino IDE Unable to detect ZumoMotor.H ( PIXY PET )

recently i trying to make the pixy pet work for my project. (https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/playing-with-your-pet).

I used the given code for the arduino IDE, but i keep on getting this error Arduino: 1.5.7 (Windows 7), Board: "Arduino Leonardo"

sketch_sep17a.ino:27:24: fatal error: ZumoMotors.h: No such file or directory compilation terminated.

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

The Code, im using, was given by the official maker of the Pixy Pet. Please have a look. ( https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code)

Thank You.

body:
It looks like you need to install the ZumoMotors library.

There's one available at the following link, although I don't know for sure that it's the same one your Pixy Pet requires:

 * https://github.com/pololu/zumo-shield

That page includes instructions on how to install the libraries. If you get stuck, there's more help in the official Arduino documentation:

 * http://arduino.cc/en/Guide/Libraries


message:
Relay activation

I am posting my simple code here, I wanted to print the Output_Current Inspite when delay function called.Below is my code.

    #include <MsTimer2.h>

    int Analog_Pin=5;
    int newaverage;
    float Output_Current;
    #define RELAY1  7
    #define MAX_TRIP_COUNT  5
    float Current_Limit=0.6;
    static int Trip_Count=0;
    static int Tripped_Flag=1;
    int Serial_Status=0;

    void TakeReading()
    {
      newaverage = analogRead(A5);

    //  Serial.print("newaverage:");
      //Serial.println(newaverage);
      Output_Current = 0.0336666666667*newaverage - 17.17;
    }

    void Chk_Relay_Tripped()
    {
      if(Output_Current>=Current_Limit)
      {
        Trip_Count=Trip_Count+1;
        if((Trip_Count>=MAX_TRIP_COUNT) &&(Serial_Status==0))
        {

          Trip_Count=0;

      MsTimer2::set(30000, Relay_Activate); // 500ms period
      MsTimer2::start();
         // Relay_Activate();
        }
        else
          if(Serial_Status==1)
          {
            Serial.println("> MODE");
            Relay_Deactivate();
          }

      }
      else
      {
        Trip_Count=Trip_Count-1;
        if(Trip_Count<0)
        {
          Trip_Count=0;
        }

        if(Trip_Count<MAX_TRIP_COUNT && Serial_Status==1)
        {
          Relay_Deactivate();
          Serial_Status=0;
        }

      }

    }

    void Relay_Activate()
    {
       // MsTimer2::stop();

       for (unsigned long start = millis(); millis() - start < 10000;)
      {
        digitalWrite(RELAY1,HIGH);
        Serial_Status=1;
      }

        digitalWrite(RELAY1,HIGH);
        Serial_Status=1;

    }

    void  Relay_Deactivate()
    {
      digitalWrite(RELAY1,LOW);
     // Serial_Status=0;
    }

    void Relay_Intialize()
    {
      digitalWrite(RELAY1,LOW);
    }

    void setup() {
      Serial.begin(9600); // set serial speed
      pinMode(RELAY1, OUTPUT); // set LED as output
      //digitalWrite(RELAY1, LOW); //turn off LED

      pinMode(Analog_Pin,INPUT);
      Relay_Intialize();
    }

    void loop(){
      TakeReading();
      Chk_Relay_Tripped();
      Serial.println(Output_Current);
       //while (Serial.available() == 0); // do nothing if nothing sent
      int val = Serial.read() - '0';
      if (val == 1) { // test for command 1 then turn on LED
        Serial.println("RELAY on");
        digitalWrite(RELAY1, LOW); // turn on LED
        Serial_Status=1;

      }
      else if (val == 0) // test for command 0 then turn off LED
      {
        Serial.println("RELAY OFF");
        digitalWrite(RELAY1, HIGH); // turn off LED
        Serial_Status=0;
      }
      delay(500);
    }

In above code everything working fine. But as soon as this function called . It wait 30s. after that it will print data. But i wanted to print data on serial monitor even if this function called. Please let me know how can i do this. Main intenstion of code is when current >1A trip the relay , wait for 30S and connect back. I wanted to print output even in 30S

    void Relay_Activate()
    {

       for (unsigned long start = millis(); millis() - start < 30000;)
      {
        digitalWrite(RELAY1,HIGH);
        Serial_Status=1;
      }

    }

body:
I read you code as: check the output current every 500ms. If it exceeds the limit more than `MAX_TRIP_COUNT` times, set `Relay_Activate` to run after 30secs. In `Relay_Activate`, write `HIGH` to the `RELAY1` over and over for 30 seconds:

    void Relay_Activate()
    {
      for (unsigned long start = millis(); millis() - start < 30000;)
      {
        digitalWrite(RELAY1,HIGH);
        Serial_Status=1;
      }
    }

I don't think you really mean to do this, especially as after the 30 seconds you are not writing `LOW` to turn it off. Maybe you mean that after 30 seconds it should start checking the current again?

    void Relay_Activate()
    {
      digitalWrite(RELAY1,HIGH);
      Serial_Status=1;
    }

What you want is a state machine so that your delays don't hold up your loop. Here is some pseudo code:

    loop {

    * read current
    * print out current

    switch(current_state) {
      //Normal operation
      case 0:
        * check if tripped
          - if tripped change state to 1
      //Turn on relay
      case 1:
        * turn on relay
        * set state_timer = millis()
        * change state to 2
      //Turn of relay after 30 seconds
      case 2:
        * if millis() -state_timer > 30000 turn off relay
        * change state to 0
    }
    delay 500ms
    }


message:
Class TKPotentiometer has no member named 'read'

I am testing a set-up using the TinkerKit shield for Arduino Uno, and a few TinkerKit inputs and outputs. I have an issue with the code provided on the [TinkerKit website][1] for the potentiometer component:

    #include <TinkerKit.h>

    // creating the object 'pot' that belongs to the 'TKPotentiometer' class
    TKPotentiometer pot(I0);

    // creating the object 'led' that belongs to the 'TKLed' class
    TKLed led(O0);

    int brightnessVal = 0;  // value read from the pot

    void setup() {
      // initialize serial communications at 9600 bps
      Serial.begin(9600);
    }

    void loop() {
      // read the potentiometer's value:
      brightnessVal = pot.read();

      // set the led brightness
      led.brightness(brightnessVal);

      // print the results to the serial monitor:
      Serial.print("brightness = " );
      Serial.println(brightnessVal);

      // wait 10 milliseconds before the next loop
      delay(10);
    }

I get an error message when compiling:

    Class TKPotentiometer has no member named 'read'

According to [this webpage][2], though, `read` should be a member of the class. Why am I receiving this message?

  [1]: http://www.tinkerkit.com/linear-pot/
  [2]: http://www.tinkerkit.com/linear-pot/

body:
As soon as I finished writing the question, it came to my mind that perhaps I misspelled something, so I looked for a file in the Menu's sketchbook that I could load.

With my surprise, I found the same exact code as I posted, with a little difference:

`pot.read()` was substituted with `pot.get()`


message:
Cannot drive DC motor with Arduino PWM

I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.

But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.

How can I fix that??

body:
It's hard to know without an oscilloscope, but as a guess you might be seeing voltage spikes on Vcc at the reset pin due to inductive load dumps from the motor.  Per Atmel app note [AVR042][1], you might try a 5V zener diode from the reset pin to ground and/or a capacitor to snub the spikes.

  [1]: http://www.atmel.com/images/atmel-2521-avr-hardware-design-considerations_application-note_avr042.pdf


body:
I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a [MOSFET][2] like [this][1].

  [1]: http://bildr.org/2012/03/rfp30n06le-arduino/
  [2]: http://en.wikipedia.org/wiki/MOSFET


message:
Do we need another controller when using ArduPilot?

I'm a newbie on the all Arduino platform and I'm currently building a drone with Autopilot functionality. I've heard about ArduPilot and I'm wondering if that is all I need, in terms of controllers (I'm excluding the ESC, engines, and the rest). Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?

Cheers,
r

body:
There are a few key points worth making before answering your question:

 - **Ardupilot** has undergone a re-branding and is now known as **APM**; this change was made to reflect that the technology has grown beyond strictly using an Arduino environment. You can see this for yourself at [their website][1].
 - The term(s) Ardupilot/APM have been used somewhat interchangeably for both the hardware and software. This can be confusing so I'll refer to the hardware as an "APM Kit"

**Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?**

Yes, [3DRobotics][2] offers APM Kits that are plug-and-play hardware packages with preloaded firmware. They (optionally) supply all of the components needed to operate a small unmanned hobby aircraft including:

 - Power module
 - Transmitter and receiver for the APM-to-Ground-Station link
 - GPS module w/ compass

The user is generally expected to provide:

 - Airframe
 - Batteries
 - Servos
 - RC transmitter and receiver
 - An additional voltage-regulator/BEC if using high-torque servos
 - A computer (groundstation)

However, the unspoken question is:

**How easy is it to setup Ardupilot/APM to work safely and correctly?**

In truth, it takes considerable effort to put together a properly working system. The plug-and-play hardware saves you a great deal of trouble but tuning and operating an RC aircraft requires a different skillset. If you're experienced in RC, this *may* not be a problem.

From experience, you can expect to spend a number of weekends configuring and tuning APM (the software) even if you have a perfectly tuned RC aircraft.

  [1]: http://ardupilot.com/
  [2]: http://store.3drobotics.com/t/parts/autopilots


message:
Arduino Yun - not enough i2c & interrupt pins?

I'm trying to build a small personal weather station. The rain sensor, and wind speed sensor use interrupts. The barometric sensor uses i2c SDA and SCL.

[Reading the Arduino Yun manual][1], it says there are 5 interrupt pins, but 2 of them are SCL/SDA (pins D2 and D3), and 2 of them are serial comms between Linio and the 32U4 (pins 0 and 1).

This leaves me with 1 interrupt pin left (pin 7).

Is there a work around to get my 2 digital sensors AND SDA SCL pins connected?

If I do use pins 0 and 1 (Linux serial), what do I risk? I will need to use the Bridge to relay information to the internet.

  [1]: http://arduino.cc/en/pmwiki.php?n=Main/arduinoBoardYun

body: OR the interrupt lines together so that you only need 1 external interrupt. Then when an interrupt is triggered, poll the devices until you find the one that triggered the interrupt. If the interrupt outputs are open-drain then you can wired-OR them together, otherwise you will need something like the 74LVC32 to OR the push-pull outputs together.


body:
Any of the port B pins on the ATmega32u4 can interrupt on pin change. Unlike the external interrupts however, these pin change interrupts share the same interrupt vector. So in the interrupt routine you have to work out which one fired.

The port B pin change interrupt is not support by the Arduino core library so you have to download a third-party library. This one seems fairly recent:

https://code.google.com/p/arduino-pinchangeint/

Then you connect your two interrupt lines to spare Port B pins and monitor for pin changes.


message:
If I connect a battery to the vin pin on the arduino, will the 5V pin be activated?

My wording might be a bit confusing, if I plug an 8 volt battery into Vin, will the arduino be powered and will the 5V pins work?

body:
> - **VIN.** The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

source