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.

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);
  }
}

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

Download the two files of the new version of the library 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.

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];
}


Why does a delay make my stepper stop? And why does the break command raise an error? I am using a stepper motor for a project that I want it to stop. I tried for loops, while, and an if statement. All of these were placed inside the void loop, because it raised an error.

My code with the if loop:

//This program does about 1 rotation or 4100 steps. The program should be able to stop the stepper motor after it does one rotation.
int Pin1 = 8;
int Pin2 = 9;
int Pin3 = 10;
int Pin4 = 11;
int _step = 0;
int _on = 4100;
int _switches = 0;
boolean direct = false;
void setup() {
  pinMode (Pin1, OUTPUT);
  pinMode (Pin2, OUTPUT);
  pinMode (Pin3, OUTPUT);
  pinMode (Pin4, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (_on > 0) {
    switch(_step)
    {
      case 0:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 1:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, HIGH);
      break;
      case 2:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 3:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, HIGH);
        digitalWrite (Pin4, LOW);
      break;
      case 4:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 5:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, HIGH);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 6:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
      case 7:
        digitalWrite (Pin1, HIGH);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, HIGH);
      break;
      case 8:
        digitalWrite (Pin1, LOW);
        digitalWrite (Pin2, LOW);
        digitalWrite (Pin3, LOW);
        digitalWrite (Pin4, LOW);
      break;
    }

    if(direct == false) {
      _step++;
      _switches++;
      direct = false;
    }else{
      _step--;
      _switches--;
      direct = true;
    }

    Serial.println(_switches);

    if(_step>7) {
      _step=0;
    }

    if(_step<0) {
      _step=7;
    }
    _on--;
    delay(1); // This solves it.
  }
  break; //This raises an error when used with for loop.
}

Can anyone help on why the delay makes it stop? And why the break command raises and error?

Arduino UNO. 5 wire stepper.

... why the break command raises and error?

Because you are using it wrong! break will end a loop, and is used in the switch...case statements. Read the documentation for break if you need to know more

  I have fixed it, the delay at the end fixes it for some reason. I don’t know why though.

You haven't really fixed it if you don't know why. It seems that you are trying to directly control a 5 wire stepper, i assume your pins must drive a transistor or something as the arduino pins themselves will not work.

The reason it works is because the stepper takes time to energize and move, if you don't wait long enough it won't work, your serial.print must be long enough, as the delay(1) should produce a 1ms delay which is too short.

You are driving your stepper wrong, you have the code setup for a half-step control, but you have 9 states, state 8 in not needed.

you are duplicating effort you don't need with both _steps and _switches, they always have the same value.

you can do better on your code as well:

int dir = 1
int c = 0

// in loop
c += dir

if (c > max)
{
  dir *= -1
  c = max
}

if (c < min)
{
  dir *= -1
  c = min
}

With this you don't have to check the direction to modify your variables.


nRF24L01 pipe question I am looking through the example code found here. I know there are 6 pipes that the nRF24L01 module can use but I've been searching the internet for the address designations and have been able to find nothing. More specifically on line 37, is there a reference for where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?

Thanks.

As most of the people have posted, the values for the pipe are arbitrary, but must follow the rules per the API:

  Pipes 1-5 should share the first 32 bits. Only the least significant
  byte should be unique, e.g.

Before I answer your question, I think an explanation on Hex and Decimal values are needed.

The 40 bit hexadecimal is a number representation of base 16. A decimal is of base 10. So you can convert a Hex Value to Decimal. As this is out of scope for the question, you can google on how to convert from one to another. There are some online converters:

Hex to Decimal Converter

You will see when you convert the Hex value to decimal, that its just a number representation. When you convert, you drop the 0x and LL. As stated the 0x indicates the value is a hex value and LL means type Long Long.

So to answer your question, use the a converter to find a hex number like:

F0F0F0F0A1
F0F0F0F0A2
F0F0F0F0B4
F0F0F0F0E9

Just change the last 2 digits (least significant bit):

Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.
   openReadingPipe(1,0xF0F0F0F0AA);
   openReadingPipe(2,0xF0F0F0F066);

Add the 0x and LL

0xF0F0F0F0A1LL
0xF0F0F0F0A2LL
0xF0F0F0F0B4LL
0xF0F0F0F0E9LL

All should work.

I am no expert on hex, as I am learning, so if I am incorrect, then please someone correct me.

Finally, the nRF24L01 datasheet makes the following point that the choice of address is not completely arbitrary:

  Note: Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate.


Need a component to connect a 9v water pump I have a 9v water pump that i want to turn on\off from the arduino,
What module should i use to turn it on and off?

I am using now a mosfet for my 5v pump, can a mosfet be used for 9v as well? Or is there some better solution?

Yes, a MOSFET should work just fine. As others have said in the comments, you just need to make sure that it's rated for your desired voltage and current, and that it's threshold voltage is low enough (around 2.5V) that the Arduino is able to drive it to saturation with a logic level 1 (5V).

I've used this one (rated at 60V and 30A) in various projects:

https://www.sparkfun.com/products/10213


Only 2 decimal places in printed float There was a similar thread before but it didn't solve my problem. I had an issue with sending GPS data, which is float, and I couldn't receive the float with the same amount of significant figures as I was sending. I always received a number with 2 digits after a decimal point. So I started debugging and wrote this simple code just to check if floats work as intended:

#include <SoftwareSerial.h>
void setup() {
Serial.begin(9600);
}
void loop() {
float number1;
number1=1.45436;
Serial.print(number1);
delay(200);
}

And the serial monitor showed 1.45 as an output. How can increase the precision of the float I am saving in memory?

By default, the Serial print function shows only 2 decimals, however I'm sure the float has the full (unrounded) value, even if it does not show it.

You can read about it in the official documentation here

With the following code you can use more decimals (fragment from the official documentation):

-Serial.println(1.23456, 0) gives "1"
-Serial.println(1.23456, 2) gives "1.23"
-Serial.println(1.23456, 4) gives "1.2346"

Also, probably the next link (PrintFloat) will help:

PrintFloat

It works roughly by iterating through the digits and printing them.


Expand Arduino storage without an SD card I'd like to have my Arduino write some files and store them somewhere. They won't be big files, but the 1Mb available on the device won't be enough.
I know an SD card is the popular solution, but the smallest SD card here is a little expensive, and more than enough, I mean, I could get by with around 10mb (or even less than that), so it would be wasteful to add a 1gb SD card (or a 512mb, 256 or 128), and it would be expensive too. Is there an intermediate solution?
Some way cheap of adding just a bit more?

Thanks

This may be relevant if you can get your hand on some old 30 Pin SIMM RAM.

Its a library some clever chap wrote to interface with 30-pin simm ram using an atmega328p on Arduino

https://github.com/zrafa/30pin-simm-ram-arduino

Also his video here: here https://youtu.be/Yah3ViEggxA

It is apparently quite wasteful though as you only get to use 256Kb of the RAM!

The author also states that "using this kind of RAM will put your Arduino CPU to refresh the SIMM RAM data part of the time. It means that your sketches (programs) could run a little slower than before. Also, we need to use most of the Arduino pins to be soldered with SIMM RAM pins so there will be just few available extra pins for your project."


Are function pointer assignments atomic in Arduino? The following snippets are from TimerOne library source code:

// TimerOne.h:
void (*isrCallback)();

// TimerOne.cpp:
ISR(TIMER1_OVF_vect) // interrupt service routine that wraps a user defined function supplied by attachInterrupt
{
  Timer1.isrCallback();
}

// TimerOne.cpp:
void TimerOne::attachInterrupt(void (*isr)(), long microseconds)
{
  if(microseconds > 0) setPeriod(microseconds);
  isrCallback = isr; // register the user's callback with the real ISR
  TIMSK1 = _BV(TOIE1); // sets the timer overflow interrupt enable bit
  resume();
}

The question: if the timer is already running, and the main program calls attachInterrupt(), could the timer interrupt occur there during the function pointer assignment isrCallback = isr;? Then, with lucky timing, Timer1.isrCallback(); function pointer would consist partly of the old and partly of the new address, causing the ISR jump to a bogus location?

I suppose this might be the case, since function pointers are certainly wider than 1 byte, and accessing > 1 byte data isn't atomic. Possible workarounds could be:

Always call detachInterrupt() to make sure the timer isn't running, before calling attachInterrupt(), i.e. clarify Timer1 docs.
Or, modify Timer1, disabling timer overflow interrupts temporarily just before isrCallback = isr;

Does this make sense, or is there something in Timer1 sources or function pointer assignments that I've missed?

Have a look at the code for attachInterrupt() and detachInterrupt() in
/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino/WInterrupts.c (well, that's where they are on a Mac, anyway. Arduino file structure on other OSes' probably looks similar in the lower levels of the path).

It appears that attachInterrupt() assumes that the interrupt in question is not yet enabled because it writes the function pointer without taking any precautions. Note that detachInterrupts() disables the target interrupt before writing a NULL-pointer to its vector. So I'd at least use a detachInterrupt() / attachInterrupt() pair

I'd want to run any such code in a critical section, myself. It appears your first way (detach, then attach) would work, though I can't be sure it couldn't miss an unfortunately timed interrupt. The datasheet for your MCU might have more to say on that. But neither am I sure at this point, that a global cli()/sei() wouldn't miss it either. The ATMega2560 datasheet, section 6.8, does say "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example", seeming to imply that it can buffer an interrupt while the interrupts are off.


LCD display not working properly + inconsistent results I have soldered the pins to my 20x4 LCD display. The soldering is not very good, but this is the best i can do. I have measured the resistance between each of the pins of the LCD with my multimeter to check if the pins are isolated. And they are! So the bad soldering is not the problem...

Last night, the display showed weird results and non-existent characters, all over the 20x4 display.
This morning, it showed only full blocks. But now it is showing only 2 of the 4 rows.
I think this is weird because i did not touch it in my sleep...

I should see the text 'Welcome', but i only see blocks now.

I dont have a potentiometer any more, so i used a for-loop with a PWM signal to check the contrast i need. This did work the last time for me.

I use the arduino MEGA.
Below you see my code, and photo's of my little project.

#include <LiquidCrystal.h>
LiquidCrystal lcd(9, 10, 48, 46, 44, 42);

const int contrastPin = 8;

void setup() {
  // put your setup code here, to run once:
  lcd.begin(20,4);
  pinMode(contrastPin,OUTPUT);
}

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

  lcd.setCursor(0,0);
  lcd.print("Welcome");

  //LOOP TO CHECK TE CONTRAST
  for(int i = 0; i <= 255; i++){
    analogWrite(contrastPin,i);
    delay(30);
  }
}

I re-soldered the pins. Also, I used a small resistor between my PWM signal and the VO port. Now it works perfectly.


Problems returning char array from function, value gets messed up I use the Base64 library for Arduino (but I don't think the problem is related to the library) and have the following function definition:

char* decodeImage(char inputString[], unsigned int inputStringLength) {
  int decodedLength = Base64.decodedLength(inputString, inputStringLength);
  char decodedString[decodedLength];
  Base64.decode(decodedString, inputString, inputStringLength);
  Serial.printf("%s",decodedString); // prints "Base64DecodeExample"
  return decodedString;
}

Later on, I use the following snippet to access the function:

  char inputString[] = "QmFzZTY0RGVjb2RlRXhhbXBsZQA=";
  char* output = decodeImage(inputString, sizeof(inputString));
  Serial.printf("%s",output); // prints garbage

The problem is, that the result of the decoding INSIDE the function seems to be correct, but when I return the value to the calling code, the value get garbled somehow.

I suppose this has something to do with pointer magic or "decaying" of references. Has someone a suggestion?

Your variable decodedString[] is created inside the function, used inside the function - and destroyed inside the function before it returns.

See how your function decodeImage() returns a char *? That's a pointer to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.

This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
You can make decodedString a permanent part of the function by making it static:

static char decodedString[64];

  Note that the above two solutions have the same two problems:
  a. There is only one array. That means that if the same function is called again, it will overwrite the results from last time - use it before you lose it!
  b. You can't calculate the length and then use it - it has to be created at the maximum possible size.

You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function malloc and pass in the number of bytes that you want. It returns a pointer to that lump of memory:

char *decodedString = (char *)malloc(decodedLength);

Note that malloc doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the (char *) before the call to malloc does.

But if you use malloc, at some stage you must give the memory back with a call to free:

free(returnedString);

The function that did the malloc doesn't have to be the function that frees it - any function can, as long as some function does! Otherwise you'll run out of heap.

Another thing that you must NOT do is call free on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.

EDIT

There's a C++ version of malloc / free called new / delete. You use them similarly:

char *decodedString = new char[decodedLength];
...
// And later...
delete [] returnedString;

It looks and behaves similarly to malloc and free, without the ugly (char *) type-cast. Note that since an array was allocated with the new, you need to call the array version of delete by adding the [] as shown.


How to use AT+CFTRANTX command in SIM7100 I am working on a project using pro mini 8MHz/3.3v and SIM7100, I want to know how can I used AT+CFTRANTX command. I am try to read file from EFS and write to SD card via Serial port. I have get some data in SD but is junk.

My board is Arduino Pro Mini (ATMega 328) 8MHz/3.3 V datasheet (DEV-11114) and Modem is home-made board with SIM7100 module, already test board and module work with all functions without any problem. I’ve added a schematic of the board to the question.

Here is SIM7100 Schematic

Here is SD Module, Pro Mini and SIM7100 pin layout

c:\data2.txt is: A1 to F0

A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6B7B8B9B0C1C2C3C4C5C6C7C8C9C0D1D2D3D4D5D6D7D8D9D0E1E2E3E4E5E6E7E8E9E0F1F2F3F4F5F6F7F8F9F0

Any help would be appropriated.

The code that I am using, I tried it with every possible baud rate:

#include <SPI.h>
#include <SD.h>
#include <SoftwareSerial.h>
SoftwareSerial simSerial(7, 6);
File myFile;

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

  simSerial.begin(9600);
  Serial.print("\nInitializing SD card...");

  if (!SD.begin(10)) {
    Serial.println("\nInitialization failed!");
    while (1);
  }
  Serial.println("\nInitialization done.");
  delay(8000); //For booting SIM7100
  if (SD.exists("1.TXT")) SD.remove("1.TXT");

  myFile = SD.open("1.txt", FILE_WRITE);
  if (myFile) {
    simSerial.println("AT+CFTRANTX=\"c:/data.txt\"");
    while (simSerial.available() > 0) {
      byte voc = simSerial.read();
      myFile.write(voc);
    }
    myFile.close();
    // Serial.println("\nClose done.");
  } else {
    // Serial.println("Error opening 1.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("1.txt");
  if (myFile) {
    Serial.println("1.txt:");
    while (myFile.available()) {
      Serial.print(myFile.read());
    }
    myFile.close();
    Serial.println("\nReading SD Card done.");
  } else {
    Serial.println("Error opening 1.txt");
  }

}

void loop() {

}

Here is test sketch for software & hardware serial.

SoftwareSerial mySerial(7,6); // RX, TX

void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Hardware Serial port!");
  mySerial.begin(9600);
  mySerial.println("AT+CFTRANTX=\"c:/data.txt\"");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

When having trouble in getting started with a modem, it's usually best to connect to the modem in "interactive mode", to verify that you're sending the right commands and getting the right responses.

Have you made sure that your modem/module's UART is at the right logic level to interface directly with your Pro Mini? How about the supply voltage? (Post a link to the product). If you're done with all that, then connect only the modem to the Pro Mini:

5V/3.3V -> Vcc (depending on the module's supply voltage)
D6 -> Modem TX
D7 -> Modem RX
Gnd -> Gnd

Then, upload the following to your Pro Mini:

#include <SoftwareSerial.h>

SoftwareSerial fserial(6, 7);

void setup(void)
{
    Serial.begin(57600);
    // I assume this is the default for your modem
    fserial.begin(115200);
    Serial.println("Starting.");
}

void loop(void)
{
    while (fserial.available())
        Serial.write(fserial.read());
    while (Serial.available())
        fserial.write(Serial.read());
}

This should basically transfer everything you send from your Serial Monitor to the modem, and in the reverse, transfer everything the modem sends to your Serial Monitor.

After uploading the sketch, in the Serial Monitor, set the Line Ending at the bottom to Carriage Return. Then you can first send the simple AT and should receive OK from the modem, to confirm that your setup works. Then to test your file reading code, send your command AT+CFTRANTX="c:/data.txt" and see what you get.

If you can confirm this works, writing code to do this automatically should then be much clearer. Or at the very least, you'll have ruled out a whole bunch of possible problems.

(Note: the Arduino may not work reliably with 115200 baud on Software Serial. So you may want to change the modem's baud rate quickly with AT+IPREX=9600. And then modify your sketch accordingly and re-upload.)


Trying to power multiple servos at once using a Arduino Mega Recently I have been trying to do a project for my end of year project, it involved making a humanoid arm.

I am still a newbie at these things, I usually have my friend do the wiring, but since he is away for the moment can anyone help me with it?

I am currently using 6X MG996R Servos for each finger and 1 for the wrist. I am also using a Arduino Mega with a Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface.

I have already searched through the web for the best way to power it but I only found people trying to power it with a 5v adaptor, my problem is I'm trying to make the hand mobile so I need to use a battery. I have tried 2x UltraFire 18650 3000mAh 3.7V rechargeable battery in series (still doesn't work only 1 servo moved), also using a 9v battery (Only moved 2 servos).

So i have been wondering if I could utilise the Adafruit 16-Channel 12-bit PWM/Servo Shield - I2C interface..

Here is a spec-sheet for the MG996R servos. Notice at the top of the 2d page, they require a supply of 4.8 - 7.2 volts, and can draw .5 - .9 Amps running and 2.5 Amps when stalled.

You'll need a supply of 6 volts (+/-) that can handle that current, times however many servos you need to operate simultaneously. The 3.7 volt batteries don't even meet the minimum voltage for the servos (unless you have two of them in series, but then they're slightly over the maximum).

You need to figure out your power budget first, then how your are going to meet it. You might be able to use a lighter supply than the worst case (6 stalled motors) would require or even than 6 motors at full operating torque (0.9 Amp each), if you monitor the current on each motor and shut down the or sequence the one(s) with the highest draw. You might even try monitoring just the battery-pack voltage, which won't tell you which motor(s) are stressing, but will let you know that you're unable to supply the total requirement for that present move.

If it were me, I'd use battery voltage sensing first (easier, simpler) to see if I have a problem that I can't solve by sequencing the motors. I might find I don't need to measure each motor's current.

Update:

  So its either i use 3.7 bat or 9v. Or.can you suggest any other power
  source?

A single 3.7v battery won't work well) for a motor that needs 4.8v minimum. Two of them in series will be slightly over the max voltage spec (7.4v vs. 7.2v). Will that slight overage damage or overheat the motor? Will be OK for intermittent use? Maybe, if you're careful to shut down a stalled motor quickly. The alternative is to build a voltage regulator that will drop the 7.4 to around 6v, but the regulator must also be able to meet your power budget, too.

A 9v supply is definitely too high and will need to regulated to within the motors' spec. (I assume you're not considering the four or five cm high ones with snap-on connectors, usually used in smoke-detectors? They have very little capability to deliver current and will be totally unsuitable for your application.)

My first try would be to experiment with 1 motor at 7.4v with a typical (for your project) mechanical forces on it, and see if it overheats and how soon, with how much load. You'd be taking a bit of a risk with that motor but the potential advantage is you might save yourself having to build a high-current voltage regulator.

Update2:

  NiMH AA cells are 1.2V

Good call. Just know that Nickle-based batteries have the twin disadvantages of long charge cycles (or degradation of capacity with faster charging) and higher self-discharge rate of about 1%/day. Their advantage to you is that it's easier to make a battery pack whose voltage falls within the motor spec. If this is a one-time project, this may well be more important to you than their disadvantages.


Function, struct or class? I am trying to learn more about arduino programming, and recently i've written functions for randomizing and then modifying a single array. Now i'd like to do the same for four individual arrays. This is where i'm getting stuck. My questions:

Am i right to assume that it's not possible calling a function for multiple individual arrays?

Perhaps a separate question, but if a class or struct would be more suitable for multiple instances, what are the major differences worth considering to choose the right approach?

Are you trying to use the same function for different arrays at different times, or are you trying to use a function that handles four different arrays at the same time?

If the former, you'd write something like

void myfunc( T *arr, size_t size ) // where T is the type of the array
{
  for ( size_t i = 0; i < size; i++ )
    arr[i] = some_new_value();
}

then call it for each array:

T arr1[N];  // where T is int, float, double, whatever
T arr2[M];
T arr3[O];
T arr4[P];

myFunc( arr1, N );
myFunc( arr2, M );
myFunc( arr3, O );
myFunc( arr4, P );

This assumes all the arrays have the same base type (e.g., they're all arrays of int).

If you want a function to work on four arrays simultaneously, you'd write it as

void myFunc( T *a1, size_t a1_size,
             T *a2, size_t a2_size,
             T *a3, size_t a3_size,
             T *a4, size_t a4_size )
{
  // code for handling each array
}

While I wrote it such that all the arrays have the same type, it doesn't have to be this way.  Each array can be a different type (a1 can be int, a2 can be double, etc.).


Sharing serial output from one to many arduinos (plus a computer) via USB hub I am trying to send rotary encoder output from an UNO to seven Trinket M0s and a computer via a (powered) USB hub.

Currently the UNO → Laptop bit works great, serial monitoring works via the hub for everyone and I'm able to get a master/slave connection going between the UNO and a Trinket via Arduino's Wire library. But Wire uses pins, and I haven't had any luck finding a similar solution for USB. Thus far, the best leads seem to be around using something like stty in a bash script to listen for what each port is up to but I'm so far in over my head at this point that that might just be wishful thinking.

I'm not looking for a solution here, just some suggestions as to where to head next. Specifically:

Is the Wire library useful for USB communication?  Is there something similar (master/slave-wise) that would be helpful?
Assuming the serial/listen thing works, are there good ways to re-route data to different ports? Currently my best guess is something like $ echo $encoderVal > /dev/cu.usbmodem????? to each one individually ... but that might be a completely noobish notion.)
i2c keeps on coming up in searches, but looks like overkill. Is that a direction to head?
Is this all completely nuts?

Anyways, thanks to everyone in advance.

Update

Ok! Thanks to the advice of @Gerben and @chrisl I ended up routing everything around with PySerial, and (for the extremely limited purposes of this little project) it works well! Here's what is currently working:

import serial
from time import sleep
import os

# Connect to each Arduino individually
serialUno = serial.Serial("/dev/cu.usbmodem141101", 9600, timeout=0)
serialTrinket1 = serial.Serial("/dev/cu.usbmodem1414401", 9600, timeout=0)
# (+ 6 more. serialTrinket2, serialTrinket3, etc)

# Open a text file to save the encoder value in
f = open("encoderVal.txt", "w")

while True:
  # Read encoderVal from the UNO
  data = serialUno.read(9999)
  if len(data) > 0:

    # Send data to each trinket
    serialTrinket1.write(data)

    # Save val to text file to Unity
    with open('encoderVal.txt', 'r+') as f:

      # Wipe the file so it's only the most recent value
      f.truncate()
      dataStripped = data.strip()

      # Return the last int in the data stream
      dataSplit = dataStripped.split('\n')
      f.write(dataSplit[-1])

  sleep(0.05)

# Close serial connections & file on interrupt
serialUno.close()
serialTrinket1.close()
f.close()

As for the laptop end of the equation, I abandoned the serial library that I had been using in favor of this Unity-to-Python tool, which works perfectly.

The only issue thus far is that PySerial loses the occasional few bytes here and there, which outputs a wonky number ever 30 or so. That'll be tomorrow's project.  Thanks everyone for your help!

First, read a bit about USB, it is an entire protocol, not just a hardware/pin based interface. It is actually quite involved. Then it will be clearer to you why a USB (from the Nano) solution will be... difficult.

Based on my understanding, I would use your #2 idea and what has been suggested, and do the following...

Setup the Uno as a USB slave, not a master.
Using the PC, connect to the Uno and the Trinkets.
When the PC gets data from the Uno have the PC "repeat" it to the Trinkets.

I think this will be the easiest and quickest solution.


Distance Readings Getting Manipulated When Calling Unrelated Function I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.

To describe exactly what I mean, this is my function:

int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
Serial.println(distanceConverted); // Print the distance

and it gives me an output of this (which is correct):

780 cm
787 cm
790 cm
794 cm
782 cm
787 cm
790 cm
786 cm
790 cm
780 cm
788 cm
784 cm

I'm using these distances to control LED lights and a speaker, and call this function to do so:

void lights(int distanceConverted)
{
    if (distanceConverted < 1000 && distanceConverted > 500)
    {
      digitalWrite(yellowLEDPin, HIGH);
      delay(20);
      tone(8, 35000, 250);
    }

    else if (distanceConverted <= 500)
    {
      digitalWrite(redLEDPin, HIGH);
      delay(20);
      tone(8, 40000, 250);
    }
}

However, when this is called (and I call the function after I print the distance values), these are the results I get:

268 cm
267 cm
266 cm
267 cm
269 cm
267 cm
265 cm
267 cm
266 cm
266 cm
267 cm
264 cm
269 cm

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:

int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

New Values:
2640 cm
2673 cm
2634 cm
2649 cm
2592 cm
2619 cm
2631 cm
2628 cm
2631 cm
2673 cm
2634 cm

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.

Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.

761 cm <- first value from sensor, correct
312 cm
308 cm
308 cm
309 cm
308 cm
307 cm
307 cm
309 cm
308 cm
308 cm

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?

The tone function uses timer interrupts to toggle a GPIO pin to make noise. That's quite intense from a CPU point of view and is most likely skewing the timing of the pulseIn function.

I would suggest not using tone if you can help it. Maybe change the frequency of a PWM output to something suitable and use analowWrite to create a 50% duty square wave.

Also learning how to use the Input Capture peripheral of the MCU (read the datasheet) will enable you to perform asynchronous sampling of your pulses and obtain much more accurate results.


Are DAC pins useful for anything besides working with audio? Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?

They are incredibly useful.  They are essentially how you deal with the analog world.

For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna...  The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!

So, yes, they are very useful. :)


Trying to explain strange behavior when attempting to do a digitalWrite to A7 on a pro mini? I found out the hard way today that pins A6 and A7 can't be used as digital outputs, but what actually happens when you try to read/write them?

Some backstory: I soldered some headers onto a pro mini and I wanted to test all the pins to make sure they worked.  I wrote a test program that looped through all the digital pins once a second and toggled their state by doing digitalWrite(pin, !digitalRead(pin);.  I then added a second loop that went through pins A0 through A7 and toggled them using the same method.  After adding this loop the built in LED on pin 13 no longer toggled on and off every second.  Instead, it would just flicker on very briefly.  At first I assumed there was something wrong with my loops (like an off by one) that was causing the strange issue, so I completely rewrote things to use a single loop that iterated over all the pins.  The resulting code should have been effectively equivalent to the original code, but now pin 13's LED was toggling properly again.

After much experimenting, I was able to whittle it down to the following test program to demonstrate the strangeness:

#define WORKS_CORRECTLY 1

int pins[] = {13, A7};
#define SIZE (sizeof(pins) / sizeof(int))

void setup()
{
#if WORKS_CORRECTLY
    for(int i = 0; i < SIZE; i++)
        pinMode(pins[i], OUTPUT);
#else
        pinMode(pins[0], OUTPUT);
        pinMode(pins[1], OUTPUT);
#endif
}

void loop()
{
    for(int i = 0; i < SIZE; i++)
    {
        int pin = pins[i];
        int pinVal = digitalRead(pin);
        digitalWrite(pin, !pinVal);
    }

    delay(1000);
}

With WORKS_CORRECTLY defined as 1 the LED on pin 13 toggles state every second like one would expect.  With it defined as 0, however, it just flickers on very briefly every second.  This is very perplexing.

Ultimately the answer is to not try to do a digitalWrite to A7 (or A6), but I'd like to understand why the behavior changes based on seemingly irrelevant differences.

You are calling digitalWrite and digitalRead with argument A7.

According to the file pins_arduino.h, A7 is defined as 21.

Now, the two functions are defined in file wiring_digital.c, and the most important part is that both of them use this code to understand which register and bit to use:

uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);

Those two are not functions, but macros defined in the Arduino.h file:

#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This means that the positions are stored into two arrays, and each pin data is an offset from the beginning of the array itself. This means that the pin 0 is located on register digital_pin_to_port_PGM[0] (i.e. port D) and is in position digital_pin_to_bit_mask_PGM[0] (so bit 0).

Now, what about pin A7? It is in index 21. But look at the file pins_arduino.h:

const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PD,
    PB, /* 8 */
    PB,
    PB,
    PB,
    PB,
    PB,
    PC, /* 14 */
    PC,
    PC,
    PC,
    PC,
    PC,
};

The array has only 20 entries! This means that A6 and A7 are NOT mapped. When you call the function with A7, you are going beyond the array limits.

This means that this leads to an unexpected behavior. In THIS particular case you are getting

PORT: _BV(1) = 2 which is equal to PB in Arduino.h
BIT: NOT_ON_TIMER = 0

So when you read from bit A7 you will check for

*portInputRegister(port) & bit
*portInputRegister(PB) & 0 => 0 for every value

so it always reads a LOW.

When you write any value to it, you will apply this code:

if (val == LOW) {
    *out &= ~bit;
} else {
    *out |= bit;
}

bit is always 0, so if you write a LOW value you will write a HIGH on ALL bits connected to port B, otherwise you will write a LOW on all of them.

Different is the access to A6: the port will be mapped to 0, which is translated to NOT_A_PORT when detecting the register. This will try to read and write from/to register #0, which I admit I do not know what means. According to the ATMEGA328P register map it is reserved, so better not to use it.

Short answer: never try to use values which are not supposed to be used, otherwise you will incur in strange behaviors


Use Android on Arduino TFT I don't know whether this is possible or not but is there any way that I can run something similar to Android on a normal TFT. I want to make complex graphics but can't program those complex programs using the Adafruit TFT library.
Arduino Mega 2560 with Elegoo TFT 2.8"

No. Not even remotely. Android runs on a powerful computer not a tiny embedded microcontroller.


Two Identical Potentiometers, two different results quick question.  I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected.  However now that I have epoxied one of them into my project and wired it up, I don't get any resistance.  I get a max reading all the time regardless of where the dial is set.  So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.

What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?

Everything falls within recommended specs of the pot and neither has been really used at all.

Trimmers have a really low current rating, so if you hadn't protect it enough, maybe you have broken it. Always remember a pull up resistor of 10k or more.


Fetching txt file's contents from a webhost using esp8266 I am trying to access a txt file in my website and fetch its contents that is hosted by 000webhost. I used this code:

void sendGET() //client function to send/receive GET request data.
{
 WiFiClient client;
 if (client.connect(host, httpPort)) {  //starts client connection, checks for connection
 Serial.println("connected");
 client.println("GET /status.txt HTTP/1.1"); //download text
 client.println("Host: *****.000webhostapp.com");
 client.println("Connection: close");  //close 1.1 persistent connection
 client.println(); //end of get request
}
else {
 Serial.println("connection failed"); //error message if no client connect
 Serial.println();
}
bool rn = false;
while (client.connected() && !client.available()) delay(1); //waits for data
while (client.connected() || client.available()) { //connected or data available
char c = client.read(); //gets byte from ethernet buffer
Serial.print(c); //prints byte to serial monitor
//    responsed = c;
if (rn == true) {
  if (c == '1') {
    Open();
  }
  else if (c == '0') {

  }
}
if (c == '!') {
  rn = true;
 }
}

Serial.println();
Serial.println("disconnecting.");
Serial.println();
client.stop(); //stop client
rn = false;
}

but in my serial monitor, it echoed

connected
HTTP/1.1 200 OK
Date: Tue, 20 Nov 2018 06:26:41 GMT
Content-Type: text/plain; charset=UTF-8
Content-Length: 1
Last-Modified: Mon, 19 Nov 2018 10:01:12 GMT
Accept-Ranges: bytes
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 4575720f977969af975e822bc1e15eea
Age: 10203
X-Cache: HIT from localhost
X-Cache-Lookup: HIT from localhost:3128
Via: 1.1 localhost (squid/3.5.27)
Connection: close

1
disconnecting.

why isn't it reading the content? i am new to this platform, thank you.

edit, the file contains only two characters. i used ! to indicate that the next number will be the one to store, and the next is either 0 or 1 based on the api i made. in short it is used to transfer my api's response to be read by arduino using esp8266

Your connection to the web server is through a Squid caching proxy.  It is delivering a cached version of the file:

X-Cache: HIT from localhost
X-Cache-Lookup: HIT from localhost:3128

The Age header shows you how long the page has been in the cache:

Age: 10203

That's been cached for about 2.8 hours.

You need to tell the cache not to get a cached version, but instead to always go to the server to get the latest copy.  To do that you should be able to include a "no-cache" header in your request:

Cache-Control: no-cache

That should tell squid "Don't cache this page - get the real one".

You can also add the HTTP/1.0 version of the same thing:

Pragma: no-cache

That way if one doesn't work on that version of squid the other one should.


Which external programmers work reliably with Arduino Mega? When looking for alternate external programmers (ISPs), I am noticing that many are not Arduino Mega 2560 compatible (e.g. Pocket AVR Programmer, USBtinyISP).

I am looking for a reliable external programmer for the Arduino Mega that is compatible with the Arduino IDE. What are my options? Currently I have been struggling with the retired ArduinoISP programmer, which doesn't look like its going to work. Does anyone have proven experience with a given programmer and a Mega?

The suggested AVR-mkII doesn't seem to be available anymore either.

I have successfully used Arduino as ISP (not to be confused with Arduino ISP) on a Mega clone that has a funky FTDI-clone onboard, and would not let me upload bootloader through serial. This worked fine, and is cheap.


Serial.print() not fully printing println() function is being used to send AT commands to GSM module.
sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);

But problem is the output -
AT+CLTS=1

OK
AT+COP

The command AT+COP did not print fully? Why?
Minimal Reproducable Example -
#include <SoftwareSerial.h>    //Library required for serial communication
char MYDATA[18];
SoftwareSerial sim800l(3, 2); // RX,TX for Arduino and for the module it's TXD RXD, they should be inverted
void setup() {
  Serial.begin(9600); //Start the serial interface on 9600
  sim800l.begin(9600);
  delay(100);
  // AT command to set sim800l to SMS mode
  sim800l.println("AT+CMGF=1");
  //Serialcom();
  delay(100);
  // Set module to send SMS data to serial out upon receipt
  sim800l.println("AT+CNMI=2,2,0,0,0");
  delay(100);
  sim800l.println("AT+CLTS=1");
  delay(3000);
  sim800l.println("AT+COPS=2");
  delay(3000);
  sim800l.println("AT+COPS=0,0");
  delay(3000);
   sim800l.println("AT+CCLK?");
  Serial.find("+CCLK: \"");
  Serial.readBytesUntil('\+', MYDATA, 17);

}

void loop() {
 Serial.print(MYDATA);
}

You're overflowing the serial receive buffer. There's only a limited amount of space (64 bytes normally, maybe less in SoftwareSerial) for receiving data before you must read it or lose data. Since you are just blindly throwing commands at the SIM800 and not doing anything with its responses until right at the end all that incoming data fills the receive buffer to overflowing.
Your methodology is flawed (not your fault, the examples on the internet are all rubbish and teach you the wrong way of doing things). What you should be doing is issuing a command then receiving the response back and parsing it to see if the command was successful or not, and retrieve any information that the response may include that you would want to know.


Connect SDRAM to STM32 Well, first of all hello to everything and thanks for reading my question. I am designing a board with STM32F730R8T6 MCU, and I want to connect MT48LC16M16A2P-6A to it which is 4MB SDRAM chip. The connections are pretty basic from what I saw, the thing is, how can I access that memory from my MCU? I mean there is a library or something to use it? and, if someone can send me an example schematic, to connect the memory I would appreciate it. Greetings.

As far as I know, you have to choose variant with FMC module (Flexible Memory Controller) with SDRAM support - that means you have to use 144pin version STM32F730Z8. The 100pin version does have FMC but doesn't support SDRAM.
After resolving this issue, it should be about configuring FMC module for using SDRAM (in STM32CubeMX for example) and the RAM will be available at some memory location according to the MCUs memory layout.


Spiffs vs Eeprom on esp8266 In my project, i have some data to save permanently. After some research i got many examples and informations to do that with eeprom. I used it effectively.
After all i decide to deep dive to esp8266 and i got some information about spiffs.
Now i know what spiffs is and what its purpose. But i am wondering what is difference between eeprom vs spiffs?
I know both of them using flash memory as same and we can write and store data with them but why spiffs? Why eeprom ? What are their pros and cons or etc.?

On the ESP8266 there's very little to choose from between the two. It all really boils down to what you want to store and how you best want to access it.

EEPROM emulation is ideal for small bits of data - configuration values and that sort of thing. Where you just want to store a few of values that would seldom change.

SPIFFS though is better at dealing with large amounts of data. Since it's a filesystem it can store actual files, and that makes it ideal for serving images and static data for web pages, for example.

A SPIFFS filesystem can be built on your PC from files of your choice and then uploaded over serial using mkspiffs and esptool.py or the SPIFFS tool that can be installed into the Arduino IDE. That means the files are very easy to update.

SPIFFS is not so great when it comes to writing data though - experiments have shown that it gets quite slow when writing often.  EEPROM doesn't suffer from such a problem, but then you can't write as much data to EEPROM as you can to SPIFFS.

So that's really all there is to it. Neither is "better" than the other, but each is better suited to different ways of working or to different styles of data.


Do some arduino pins give signals when the controller starts? For example, on the ESP32 board there are several contacts that can issue pulses when the controller starts, which is connected with the operation of the chip itself. It is not recommended to connect devices that respond to input signals from the ESP to these contacts.

Tell me, are there any contacts on the Arduino UNO (Atmega328P) that give out any impulses at startup?

In particular, it is important for me to know about the following contacts:

PB1 (9 pin)
PD4 (4 pin)
PD5 (5 pin)

Thank you!

Most Arduino boards come with a bootloader of some form.  This bootloader may do things with IO pins. However apart from that, no, nothing else happens to any IO pins.

The bootloader may:

Flash pin 13 (built in LED)
Configure and communicate on pins 0/1 (UART)

With no bootloader then absolutely nothing happens on any IO pins.


Can now() roll over just like millis()? I'm using now() and millis() to trigger events after a certain time has passed.
I am aware, and it's also easily found on the web, that millis() rolls over after a certain time has passed and for code that has to run indefinitely you have to handle this.

However I am not aware of if now() can do the same at some point. I mean it does count the seconds from the 1.1.1970 so just regarding this fact, it should not roll over. However, just like millis() this has to be counted somewhere no? How does it work?

now() is a function that is specific to Intel Curie based boards.

It returns an unsigned long (which on a 32-bit system is the same as an unsigned int) and so can provide the number of seconds since 1/1/1970 up until the year 2106, at which point it will roll over.

If you plan on having your system run continuously for more than the next 88 years you will have to deal with that rollover correctly, including:

Using subtraction to "wrap around" your calculations
Not trying to calculate any periods longer than 136 years


Arduino creating delay function I am trying to make my own delay function. Briefly mydelay function is calling toggled function every secs seconds. The code is not well written, i know (this is the first version). But i am just trying to get it work properly. Then i will refactor it. But i have some unexpected bugs. First time the loop in x function is working properly. It is printing "I am in while" for 1 second and then it prints "Im ending mydelay" which is the behaviour i want. But after finishing the loop in x. The second time when it loops. It enters the mydelay function (that is ok). But then it is not printing "I am in while" at all. It just prints "Im ending mydelay" which is not good.

Here is the code:

#include <Arduino.h>
int led = 7;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  x();
  Serial.println("Im ending main loop");
}

void x() {
  for (int i = 0; i <= 10; i++) {
    mydelay(led, 0, 1);
    mydelay(led, 1, 1);
  }
}

void mydelay(int pin, int hol, int secs) {
  int starttime = millis();
  while ((millis() - starttime) <= (secs * 1000)) Serial.println("I am in while");
  toggled(pin, hol);
  Serial.println("Im ending mydelay");
}

void toggled(int pin, int hol) {
  digitalWrite(led, hol);
}

You can try something along these lines:

void verboseDelay(unsigned long ms)
{
    unsigned long now = millis();
    Serial.print(F("delaying"));
    unsigned long start = now, lastPrintTime = now;
    do {
        now = millis();
        if (now - lastPrintTime >= 20) {
            Serial.write('.');
            lastPrintTime += 20;
        }
    } while (now - start < ms);
    Serial.println();
}

The trick is to used unsigned long for all the time-related variables,
and also to avoid printing too fast.


How do I set up a multi-file project in the Arduino IDE? Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.

module1.cpp
module1.h
module2.cpp
module2.h
...
main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.

module1.cpp
module1.h
module1.ino # test program
module2.cpp
module2.h
module2.ino # test program
...
main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.

How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

You have two options with ArduinoIDE.

First Each module in a module directory

So the structure looks like

  main_routine
     main_routine.ino
  --module1
      module1.ino  #test routine
      module1.cpp
      module1.h
 --module2
  .....

included in main_routine.ino

   #include "module1/module1.h"
   #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)

The second (more hacky way) is to have everything in one dir and for development testing working with include guards in the main_routine.ino

 // for production comment all MODULEX_TEST and uncomment PRODUCTION
 //#define PRODUCTION
 #define MODULE1_TEST
 //#define MODULE2_TEST
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   #include "module1/module1.h"
#endif

#if defined (PRODUCTION) || defined (MODULE1_TEST )
   uint8_t myModule1Var = 0;
#endif

setup(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   myModule1setup someInit(1,2,3);
#endif
.....
 }

loop(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   void mymodule1Func(){....};
#endif
#ifdef MODULE1_TEST
   void mymodule1Test(){....};
#endif

Pros and cons

+This approach gives you the possibility to test two modules together.
-Its harder to read, but
+easier to document with tools like doxygen
~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)


How can I handle the millis() rollover? I need to read a sensor every five minutes, but since my sketch also has
other tasks to do, I cannot just delay() between the readings. There
is the Blink without
delay tutorial
suggesting I code along these lines:

void loop()
{
    unsigned long currentMillis = millis();

    // Read the sensor when needed.
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        readSensor();
    }

    // Do other stuff...
}

The problem is that millis() is going to roll over back to zero after
roughly 49.7 days. Since my sketch is intended to run for longer
than that, I need to make sure the rollover does not make my sketch
fail. I can easily detect the rollover condition
(currentMillis < previousMillis), but I am not sure what to do then.

Thus my question: what would be the proper/simplest way to handle the
millis() rollover?

Short answer: do not try to “handle” the millis rollover, write
rollover-safe code instead. Your example code from the tutorial is fine.
If you try to detect the rollover in order to implement corrective
measures, chances are you are doing something wrong. Most Arduino
programs only have to manage events that span relatively short
durations, like debouncing a button for 50 ms, or turning a heater
on for 12 hours... Then, and even if the program is meant to run
for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the
rollover problem is to think of the unsigned long number returned by
millis() in terms of modular
arithmetics. For the
mathematically inclined, some familiarity with this concept is very
useful when programming. You can see the math in action in Nick Gammon's
article millis() overflow ... a bad
thing?. For the problem at hand,
what's important to know is that in modular arithmetics the numbers
“wrap around” when reaching a certain value – the modulus – so that
1 − modulus is not a negative number but 1 (think of a
12 hour clock where the modulus is 12: 1 − 12 = 1).

For those who do not want to
go through the computational details, I offer here an alternative
(hopefully simpler) way of thinking about it. It is based on the simple
distinction between instants and durations. As long as your tests
only involve comparing durations, you should be fine.

Note on micros(): Everything said here about millis() applies
equally to micros(), except for the fact that micros() rolls over
every 71.6 minutes, and the setMillis() function provided below
does not affect micros().

Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least
two different concepts: instants and durations. An instant is a
point on the time axis. A duration is the length of a time interval,
i.e. the distance in time between the instants that define the start and
the end of the interval. The distinction between these concepts is not
always very sharp in everyday language. For example, if I say “I will
be back in five minutes”, then “five minutes” is the estimated
duration of my absence, whereas “in five minutes” is the instant
of my predicted coming back. Keeping the distinction in mind is
important, because it is the simplest way to entirely avoid the rollover
problem.

The return value of millis() could be interpreted as a duration: the
time elapsed from the start of the program until now. This
interpretation, however, breaks down as soon as millis overflows. It is
generally far more useful to think of millis() as returning a
timestamp, i.e. a “label” identifying a particular instant. It could
be argued that this interpretation suffers from these labels being
ambiguous, as they are reused every 49.7 days. This is, however,
seldom a problem: in most embedded applications, anything that happened
49.7 days ago is ancient history we do not care about. Thus,
recycling the old labels should not be an issue.

Do not compare timestamps

Trying to find out which among two timestamps is greater than the other
does not make sense. Example:

unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

Naively, one would expect the condition of the if () to be always
true. But it will actually be false if millis overflows during
delay(3000). Thinking of t1 and t2 as recyclable labels is the
simplest way to avoid the error: the label t1 has clearly been assigned
to an instant prior to t2, but in 49.7 days it will be reassigned
to a future instant. Thus, t1 happens both before and after t2. This
should make clear that the expression t2 > t1 makes no sense.

But, if these are mere labels, the obvious question is: how can we do
any useful time calculations with them? The answer is: by restricting
ourselves to the only two calculations that make sense for timestamps:

later_timestamp - earlier_timestamp yields a duration, namely the
amount of time elapsed between the earlier instant and the later
instant. This is the most useful arithmetic operation involving
timestamps.
timestamp ± duration yields a timestamp which is some time after
(if using +) or before (if −) the initial timestamp. Not as useful as
it sounds, since the resulting timestamp can be used in only two
kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine
across the millis rollover, at least as long as the delays involved are
shorter than 49.7 days.

Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time
interval. As long as we do not need to handle durations longer than
49.7 days, any operation that physically makes sense should also
make sense computationally. We can, for example, multiply a duration by
a frequency to get a number of periods. Or we can compare two durations
to know which one is longer. For example, here are two alternative
implementations of delay(). First, the buggy one:

void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

And here is the correct one:

void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

Most C programmers would write the above loops in a terser form, like

while (millis() < start + ms) ;  // BUGGY version

and

while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration
distinction should make clear which one is buggy and which one is
correct.

What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still
hope if it is known that the respective instants are close enough:
closer than 24.85 days. Yes, our maximum manageable delay of
49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into
a duration comparison problem. Say we need to know whether instant t1 is
before or after t2. We choose some reference instant in their common
past, and compare the durations from this reference until both t1 and
t2. The reference instant is obtained by subtracting a long enough
duration from either t1 or t2:

unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

This can be simplified as:

if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

It is tempting to simplify further into if (t1 - t2 < 0). Obviously,
this does not work, because t1 - t2, being computed as an unsigned
number, cannot be negative. This, however, although not portable, does
work:

if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

The keyword signed above is redundant (a plain long is always
signed), but it helps make the intent clear. Converting to a signed long
is equivalent to setting LONG_ENOUGH_DURATION equal to
24.85 days. The trick is not portable because, according to the C
standard, the result is implementation defined. But since the gcc
compiler promises to do the right
thing,
it works reliably on Arduino. If we wish to avoid implementation defined
behavior, the above signed comparison is mathematically equivalent to
this:

#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

with the only problem that the comparison looks backwards. It is also
equivalent, as long as longs are 32-bits, to this single-bit test:

if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

The last three tests are actually compiled by gcc into the exact same
machine code.

How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you
nevertheless want to test, add this function to your sketch:

#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

and you can now time-travel your program by calling
setMillis(destination). If you want it to go through the millis
overflow over and over again, like Phil Connors reliving Groundhog Day,
you can put this inside loop():

// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the
compiler to an unsigned long corresponding to 3000 milliseconds before
the rollover (it is converted to 4294964296).

What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then
you really need to track the millis overflows. There are many ways to do
so. The most straightforward solution may be to simply extend millis()
to 64 bits:

uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This is essentially counting the rollover events, and using this count
as the 32 most significant bits of a 64 bit millisecond count.
For this counting to work properly, the function needs to be called at
least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check (new_low32 < low32) fails and the code misses a count of high32. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the
Arduino. It may be worth to reduce the time resolution in order to stay
at 32 bits.


I2C between 2 or more Arduino boards HELLO I have already connected with I2C 2 Arduino's all is working with comunication on Bus I2C. My Setup is :
MASTER with LCD I2C , RTC1037
SLAVE some sensor not I2C

I allready put 2 pullup resistor 10Kohm on SDA and SCL

I need to switch off the slave arduino but when i switch off the Slave board the Master Arduino stop working.Why? It's possible to continue working with master board and the slave board switch off? Thank's for help

You need to isolate the slave device from the I2C bus since it is causing interference with the signals.

Adafruit have published a good application note about level shifting in I2C busses using MOSFETs, and it also contains a bit about bus isolation:

  2.3.4 Isolation of the powered-down “Lower voltage” section.

  An additional feature of the level shifter circuit in figure 2 is the isolation of the “Lower voltage” section when
  VDD1 is switched off. In that case VDD1 is about 0 Volt and the MOS-FET’s [sic] are switched off because VGS is
  below the threshold voltage. The “Higher voltage” section is not hindered and stays operational. To assure a
  noise margin, the MOS-FET’s should have a minimum threshold voltage VGS(th) of e.g. 0.4V and VDD1 must
  stay below this value. The isolation feature can also be applied if no level shifting is required, VDD1 and VDD2
  may have the same value, e.g. both 3.3V or both 5V.


Controlling 2 DC Motors with L293D and 6 V battery pack? Sorry if my question looks newbie, but I'm just starting to delve into robotics and electronics, and my first project was building a small arduino collision-avoidance robot with a ultrasonic range finder, one servo and two dc motors. Right now I'm using a 6V battery pack to power both DC motors, another 6V just for the servo, and a 9V battery for the arduino.
But I'm in doubt if the power supply for the DC motors is enough. I'm using an L293D IC to control both motors, but the robot can barely move under load (and the total weight of the robot is not that much. I already reduced all the weight I could). So, how much power, typically, I should supply for the L293D to control those motors?

The L293D can handle two motors at a time and as per the data sheet the maximum voltage that you can give to the motor as a supply (on pin 8) is 36 volts.


Using a template inside a class I'm trying to use a template function, but I get an error
home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: sketch/emptyCode.ino.cpp.o: in function `startIOTservices()':
/home/guy/Documents/git/Arduino/HomePi/emptyCode/emptyCode.ino:37: undefined reference to `void myTest::funcOne<bool>(bool)'
/home/guy/.arduino15/packages/esp8266/tools/xtensa-lx106-elf-gcc/2.5.0-4-b40a506/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld: sketch/emptyCode.ino.cpp.o: in function `setup':
/home/guy/Documents/git/Arduino/HomePi/emptyCode/emptyCode.ino:70: undefined reference to `void myTest::funcOne<bool>(bool)'
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

inside .cpp file:
myTest::myTest()
{
        Serial.println("start");
}

template <class T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

inside .h file:
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

and calling it from .ino file:
testA.funcOne(true);
What am I doing wrong ?
EDIT 1:
complete .h .cpp files - which originaly belongs to myJSON library which are deleted in this snip
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define DOC_SIZE 1000

class myJSON
{
};

class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

#endif

.cpp file
#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

#define LOG_LENGTH 4

myJSON::myJSON(char *filename, bool useserial)
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

myTest::myTest()
{
        Serial.println("start");
}

// template <typename T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

move the template method definiton to .h or define it in class. it is not a real function, only a prescription for functions. Like this:
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg);
};

template <class T1>
void myTest::funcOne(T1 arg)
{
        Serial.println(arg);
}

or this
class myTest
{
public:
    myTest();
    template <class T1>
    void funcOne(T1 arg)
    {
            Serial.println(arg);
    }
};


Arduino not running code without connection to PC via USB I have an Arduino UNO and esp8266 connected to it. Both devices has separate power lines. Each connected via USB cable, for Arduino USB used as power line and standard firmware uppload line, for esp8266 only as power suppli line. If I connect all to computer's USB ports, everything working fine. But, if I connect Arduino to separate charger that has USB port, then Arduino not running code. I can see it by Serial interface work, because code using it intensively, and when I'm turning Arduino on the RX and TX lines are down all the time, that I think indicates, that code is not running, and Arduino in boot mode, somehow.

I've made a search through same issues and nothing helped from theirs suggestions. I tried to pull RX line to GND through resistor, to make sure that there are no noise on the line, added capacitors for power supply line, to make exclude pulsations on the line. But nothing helped.

Arduino not running code independently from esp8266. I tried to run Arduino separately, without any other connections, but it not helped. Still not running.

Have you made sure that the ground of both the arduino as well as esp8266 are connected together? Also since you are using esp8266 you must have connected it to rx and tx pins. Make sure you remove it while uploading the code and connect it afterwards.


How do I get a nonzero output from my HX711 and load cell? I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).

Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

Here is the calibration sketch I am using (from the HX711 hookup guide):

#include <HX711.h>

#define DOUT 9
#define CLK 8

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

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

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

Observations:

Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.


Arduino motor shield I'm making a soccer car with arduino. And I have this undocumented motor control shield. So I don't know how to program it. I've tried to code it as if it be an H bridge, but is not working. Someone know which are the pins that I have to use?
The plate is from DK Electronics, and says motor control shield for arduino.

Don't know why but the image can't be upload from my phone.

As I can't show more this way I have published on my Twitter account the image, if you can I'll be grateful.
Link: https://twitter.com/ricardovaras_99/status/789249497322889216

This is the code I used guided by some internet articles about the Arduino's original motors control shield.

 pinMode(8,OUTPUT);       //Channel A Brake Pin Initialize
 pinMode(9,OUTPUT);       //Channel B Brake Pin Initialize
 pinMode(12,OUTPUT);      //Channel A Direction Pin Initialize
 pinMode(13,OUTPUT);      //Channel B Direction Pin Initialize

Judging by the fact that you agree it looks like this, a search reveals it is a knock-off of the Adafruit V1 motor shield.

Their page shows how to connect to it, and has example code and a library.

I don't really want to post a link-only answer, but the alternative would be to parrot the Adafruit page, which isn't really fair to them because this board wasn't even purchased from them.


Arduino running at 8MHz with external crystal I want to use my Atmega328P in 8MHz, but I noticed that the internal clock is not as accurate and cause problems in my application. To add an external crystal 8MHz I do like the image below or 22pF capacitors are only necessary when I use a 16MHz crystal?

Yes, you require the capacitors, and the capacitors have to be the right value for your crystal.

The datasheet will specify a load capacitance which you use in the following formula:

C1 = C2 = 2(CL - C_STRAY)

That is, the load capacitance of the crystal, minus the stray capacitance from your circuit (as long as your traces are short that is negligible and can be largely ignored unless you have very very tight timing requirements) multiplied by 2.

So for 22pF capacitors it is safe to assume that the crystal that is with them has a load capacitance of 11pF.

So check the datasheet for the load capacitance (it should be very prominent) and select the correct capacitors accordingly.

If you want to do away with the capacitors and your timing requirements aren't that precise you may get away with a ceramic resonator which doesn't require capacitors.

Another option is to use a MEMS® clock chip which generates a stable clock signal at a pre-set frequency. While this doesn't require capacitors for the clock signal it does still require a decoupling capacitor on the power supply for it, but of course that doesn't affect the timing of the clock signal, so precise selection of a specific value isn't needed.