# Question
Title: 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);
  }
}

```

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

```
> 2 votes

# Answer
Use a scope to check levels on the TX of the BT module. Some HC-xx modules come with 3.3V levels which can make problems.

I would suggest using the same speed for the serial port and for the bt dongle. You have a glitch here, which may make problems:

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

```

Eventually, the Bluetooth module sends you data at a high bit rate. You get the first letter, then send it out to the PC at a lower bit rate. Sending it out to the PC takes as long time as the BT dongle sends four more characters.

Although there are serial buffers in the Arduino, this problem will easily cause a loss of data, as @Avamander has pointed out.

Based on your comment telling that you were able to get an endless mess from Putty, this can escalate to losing the sync on the RX from the BT module, and then further bits will start a new byte, giving you a total mess. However, OK must work, so you likely have also level problems.
> 1 votes

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

SoftwareSerial mySerial(10,11,true);

maybe someone else can explain why some protocols are inverse
> 0 votes

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


# Question
Title: Python Arduino Serial Communication Speed
Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.

I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.

Here my arduino code,

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

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int x,temp;

int sudutT0(long int p)
{
  int u = 3600+((405*p)/180);
  return u;
}

void setup() {
  Serial.begin(250000);
  Serial.println("Joint 2 Test!");
  pwm.begin();
  pwm.setPWMFreq(50);

  Wire.setClock(1000);
  for (uint8_t pin=0; pin<16; pin++)
  {
  pwm.setPWM(pin, sudutT0(90),4095);
  }
  pwm.setPWM(3, sudutT0(150), 4095);
}

void loop() {
    if(Serial.available() == 8){
      if(Serial.read() == 0xF5)
      {
        //Joint 1
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(0,x,4095);
      // Joint 2 Servo
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(1,x,4095);
      x = sudutT0(180-temp); //810 - theta
      pwm.setPWM(2,x,4095);
      //Joint 3 - 6, Gripper
      for(uint8_t u = 3; u<8; u++)
      {
        temp = Serial.read();
        x = sudutT0(temp);
        pwm.setPWM(u,x,4095);
      }
      //delay(100);
      }
    }
}

```

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?

# Answer
All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data. I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms
> 0 votes

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


# Question
Title: NRF24l01 with Atmega 32u4 and internal clock
Will the nrf24l01 work with the Atmega 32u4 if I am using the 32u4's internal clock, or must I have an external clock source?

# Answer
> 1 votes
You ask a yes/no question, to which the answer is yes, nRF24L01 as a serial peripheral device will work as well as if you had used an Arduino UNO or any other microcontroller, provided the SPI bus is correctly initialized.

Generally you want the following in the `setup()` part of your sketch/program:

```
  pinMode(CE_pin, OUTPUT);//chip enable set as output
  pinMode(CSN_pin, OUTPUT);//chip select pin as output
  pinMode(MOSI_pin, OUTPUT);//SPI data out
  pinMode(MISO_pin, INPUT); //SPI data in
  pinMode(SCK_pin, OUTPUT);//SPI clock out

  digitalWrite(CSN_pin, HIGH);//SPI idle
  digitalWrite(CE_pin, LOW);

  SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
  SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
  SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
  SPI.begin();//start up SPI library

```

---
Tags: nrf24l01+, atmega32u4, oscillator-clock
---


title: Read write with half duplex SPI

text:
# Question
Title: Read write with half duplex SPI
I'm currently struggling interfacing an SPI device using just 3 pins (CLK, DATA, NSS).

Wiring up? Connecting MOSI/MISO together?

How do i read since it's half duplex?

In ESP32 there are flags which can be set (SPI\_TRANS\_USE\_RXDATA, SPI\_TRANS\_USE\_TXDATA). How can i accomplish this in the Arduino environment? i didn't see a such option and the API seems a little bit limited.

Thanks for any advice.

# Answer
> 4 votes
All you need is a single resistor.

simulate this circuit – Schematic created using CircuitLab

When DATA is an input the data from MOSI passes through the resistor to both DATA and MISO. When DATA is an output the data from DATA goes to MISO and voltage is dropped safely across R1 to the sink or source of MOSI depending on what state it is in.

In other words, when DATA is input it receives from MOSI. When DATA is output MOSI is ignored.

Code wise, it's no different to any other transfer. You just never have any valid data to transfer while receiving. So just transfer anything (0xFF is a common choice).

For example, if you need to send 0x38 first then receive two bytes, you would:

```
SPI.transfer(0x38);
uint8_t byte1 = SPI.transfer(0xFF);
uint8_t byte2 = SPI.transfer(0xFF);

```

---
Tags: spi
---


# Question
Title: Problems when attaching a second ultrasound sensor (HC SR04)
I am working on an obstacle avoiding robot. It uses an ultrasound sensor to avoid obstacles, but currently has trouble avoiding objects that are diagonal to it. Thus, i want to add a second ultrasound sensor, and alternate their readings. I am testing the code, which should look right and then leftn and return the distances. The code worked for just one ultrasound. and it is a follows:

```
#include <NewPing.h>
#include <Servo.h>

#define trig_pin1 A1 //analog input 1
#define echo_pin1 A2 //analog input 2
#define trig_pin2 A3 //analog input 1
#define echo_pin2 A4 //analog input 2
int distance1 = 100;
int distance2 = 100;

#define maximum_distance 200 //sensor function
Servo servo1; //our servo name
Servo servo2;
NewPing sonar1(trig_pin1, echo_pin1, maximum_distance);
NewPing sonar2(trig_pin2, echo_pin2, maximum_distance);
void setup() {
  // put your setup code here, to run once:
  servo1.attach(11); //our servo pin
  servo1.write(90);
  servo2.attach(6); //our servo pin
  servo2.write(90);

  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
  distance1 = readPing1();
  distance2 = readPing2();
  delay(100);
}

void loop() {
    int distanceRight = 0;
  int distanceLeft = 0;

        distanceRight = lookRight();
    delay(300);
    distanceLeft = lookLeft();
    delay(300);
  }
}

int readPing1(){
  delay(10);
  int cm = sonar1.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
}

int lookRight(){
  servo1.write(50);
  delay(500);
  int distance1 = readPing1();
  delay(100);
  servo1.write(115);
  return distance1;
}

int readPing2(){
  delay(10);
  int cm = sonar2.ping_cm();
  if (cm==0){
    cm=250;
  }
  return cm;
  }
int lookLeft(){
  servo2.write(170);
  delay(500);
  int distance2 = readPing2();
  delay(100);
  servo2.write(115);
  return distance2;
  delay(100);
}

I get the following error:
'readPing1' was not declared in this scope

```

and I get the same error for the readPing2 function. Why could this be?

# Answer
> 1 votes
It turns out I had an extra "}" after the void loop function. The code worked as expected after removing it

---
Tags: arduino-uno, servo, hc-sr04
---


# Question
Title: How can i stop DC motor when button on remote is released?
I am trying to control a motor using a remote with Arduino Mega. The motor turns on when I press the button on the remote but when I release the button, it continues to move. Does anyone know how to stop the motor spinning when I release the button on the remote?

# Answer
For an infra-red remote control you generally can't. Those don't normally have the concept of button release.

Normally there are two kinds of buttons on a remote:

* Burst code
* Repeat code

The first sends a short burst of the same code. This allows for a function to be run once per button press. The second sends the same code over and over again constantly until you release it.

For the repeat code buttons you can use that to your advantage. You program your Arduino to run the motor for a short period. That period needs to be slightly longer than the time between each code reception. Then it can appear that it's responding to the release of the button.

For example, if your remote sends codes 5 times per second then whenever you receive a code you start the motor. If you haven't received a code for more than say 300ms then stop the motor.
> 2 votes

---
Tags: motor, remote-control, atmega2560
---


# Question
Title: How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?
I also want to know how can we make it without functions like digitalwrite

# Answer
> 1 votes
Yes, that's easy enough to do. I wrote a library to do that, as described here.

Basically you could make a class like this:

```
class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

```

Then implement the two functions like this:

```
void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

```

And now call it:

```
TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

```

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.

# Answer
> 0 votes
I made a 13 note piano-like (well, more organ-like) tones instrument here

https://forum.arduino.cc/index.php?topic=179761.0

Youtube clip of it in action

https://www.youtube.com/watch?v=4c8idXN4Pg0

Only 8 notes in the clip, that was all the buttons I had at the time.

I used a '1284P processor instead of '328P so it could have 13 inputs & 13 outputs, without jumping up to a 2560.

There is nothing wrong with using Direct Port Manipulation in the Arduino IDE environment. Arduino is just C++ with some things made easier for the user with functions, macros, etc.

Here's the code.

```
/* Crossroads, 26 July 2013
 test for creating multiple simultaneous notes using micros()
 press a key, get a note. Use external analog mixer (summing op amp) for sound mixdown to single output to a speaker
 need a higher pin count device - this code is for '1284P - with specific pin mappings, not written for uC portability
 play 13 notes for now, C4 up to C5
 note info from http://www.sengpielaudio.com/calculator-notenames.htm
 Input keys: pin2=C4, 3=C#4, 30=D4, 8=D#4, 9=E5, 31=F5, 4=F5#, 5=G5, 6=G5#, 7=A5, 10=A5#, 11=B5, 12=C5
 Output notes: pin 16=C4, 17=C#4, 18=D4, 19=D#4, 20=E5, 21=F5, 22=F5#, 23=G5, 24=G5#, 25=A5, 26=A5#, 27=B5, 28=C5
 Ordering is funny due to Bobuino mapping, and having PortA output bits follow portD input bits, portC output bits follow portB input bits
 0,1 reserved for serial
 13,14,15,29, unused, maybe make 1 of 9 octave select? Piano has 7 full C to B octaves, 2 partials
 */
// array of 1/2 period of the notes in microseconds
// so a C8 note would be 119uS High, 119uS low for example
unsigned long noteArray[] = {
  119, // C8, highest note - note 0
  127,134,142,150,159,169,179,190,201,213,225,239, // B7, A#7,A7, G#7, G7, F#7, F7, E7, D#7, D7, C#7, C7 - notes 1-12
  253,268,284,301,318,338,356,379,402,426,451,478, //  B6 down to C6 - notes 13-24
  506,536,568,602,638,676,716,758,804,851,902,965, // B5 down to C5 - notes 25-36
  1012,1073,1136,1204,1276,1351,1432,1517,1607,1703,1804,1911, // B4 down to C4 - notes 37-48
  2025,2145,2272,2408,2551,2703,2863,3034,3214,3405,3607,3822, // B3 down to C3 - notes 49-60
  4050,4290,4545,4816,5102,5405,5727,6067,6428,6810,7215,7645,  // B2 down to C2 - notes 61-72
  8099,8581,9091,9631,10204,10811,11454,12135,12856,13621,14431,15289,  //  B1 down to C1 - notes -73-84
  16198,17161,18182, // B0, A#0, A0 - 85-86-87
};  // really need to flip this whole thing over so that 0 is lowest note & 87 is  highest
byte keyArray[]={
  2,3,30,8,9,31,4,5,6,7,10,11,12,13,}; //Ports D2,D3,D4,D5,D6,D7,B0,B1,B2,B3,B4,B5,B6, added b7 - notes 48, 47,46,45,44,43,42,41,40,39,38,37,36
byte outputArray[] = {
  14,15,16,17,18,19,22,23,24,25,26,27,28, 21,22,29}; // Ports A0,A1,A2,A3,A4,A5,C0,C1,C2,C3,C4,C5,C6, added a6, a7, c7
// ports selected for consistency for bits used from input to output from D in to A out, and B in to C out
byte keyActive[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // 1 indicates key is pressed
//byte octaveSelect[] = {
// 13,21,22,29}; // b7,a6,a7,c7 -  0 to 9 - future use
// ATMEL ATMEGA1284P on Bobuino
//
//                       +---\/---+
//           (D 4) PB0 1 |        | 40 PA0 (D 21) AI 7
//           (D 5) PB1 2 |        | 39 PA1 (D 20) AI 6
//      INT2 (D 6) PB2 3 |        | 38 PA2 (D 19) AI 5
//       PWM (D 7) PB3 4 |        | 37 PA3 (D 18) AI 4
//   PWM/SS (D 10) PB4 5 |        | 36 PA4 (D 17) AI 3
//     MOSI (D 11) PB5 6 |        | 35 PA5 (D 16) AI 2
// PWM/MISO (D 12) PB6 7 |        | 34 PA6 (D 15) AI 1
//  PWM/SCK (D 13) PB7 8 |        | 33 PA7 (D 14) AI 0
//                 RST 9 |        | 32 AREF
//                VCC 10 |        | 31 GND
//                GND 11 |        | 30 AVCC
//              XTAL2 12 |        | 29 PC7 (D 29)
//              XTAL1 13 |        | 28 PC6 (D 28)
//      RX0 (D 0) PD0 14 |        | 27 PC5 (D 27) TDI
//      TX0 (D 1) PD1 15 |        | 26 PC4 (D 26) TDO
// INT0 RX1 (D 2) PD2 16 |        | 25 PC3 (D 25) TMS
// INT1 TX1 (D 3) PD3 17 |        | 24 PC2 (D 24) TCK
//     PWM (D 30) PD4 18 |        | 23 PC1 (D 23) SDA
//      PWM (D 8) PD5 19 |        | 22 PC0 (D 22) SCL
//      PWM (D 9) PD6 20 |        | 21 PD7 (D 31) PWM
//                       +--------+
//
byte x;
byte portDkeys;
byte portBkeys;
byte portAnotes;
byte portCnotes;
unsigned long currentTime;
unsigned long changeTime[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // track when to flip output
unsigned long duration;
/* consistency check
 INDEX, NOTE, port In, port Out
 0, C4,       D2, A2           read 04 write 04 FB 1111 1011 Middle C
 1, C#4,      D3, A3           read 08 write 08 F7 1111 0111
 2, D4,       D4, A4           read 10 write 10 EF 1110 1111
 3, D#4,      D5, A5           read 20 write 20 DF 1101 1111
 4, E4,       D6, A6           read 40 write 40 BF 1011 1111
 5, F4,       D7, A7           read 80 write 80 7F 0111 1111
 6, F#4,      B0, C0           read 01 write 01 FE 1111 1110
 7, G4,       B1, C1           read 02 write 02 FD 1111 1101
 8, G#4,      B2, C2           read 04 write 04 FB 1111 1011
 9, A4,       B3, C3           read 08 write 08 F7 1111 0111  Concert A
 10, A#4,     B4, C4           read 10 write 10 EF 1110 1111
 11, B4,      B5, C5           read 20 write 20 DF 1101 1111
 12, C5,      B6, C6           read 40 write 40 BF 1011 1111
 */
/*************/
void setup(){
  //Serial.begin (115200); // for debug testing
  for (x=0; x<14; x=x+1){ // input pins with pullup
    pinMode(keyArray[x], INPUT);
    digitalWrite (keyArray[x], HIGH);
  }
  for (x=0; x<17; x=x+1){
    pinMode(outputArray[x], OUTPUT); // output pins
  }
  //  for (x=0; x<4; x=x+1){ // future use maybe
  //    pinMode(octaveSelect[x], INPUT); // input pins with pullups
  //    digitalWrite (octaveSelect[x], HIGH);
  //  }
} // end setup

/***********/
void loop(){
  //Serial.print (" ");
  // if key is pressed, determine time for next transition
  // if key is not pressed, no transition, use AC coupling into summing op-amp for no output
  // idea is to allow multiple notes to be created simultaneoulsy. Can the reading & if's all be done fast enough?
  portDkeys = PIND; // Read the input keys - using direct port manipulation for speed
  portBkeys = PINB;
  currentTime = micros();

  // Didn't make this part of a larger loop/array lookup because that adds 12-15uS for each pass thru the loop

  /* Check if key for note C4 is pressed, key0  */

  if ((portDkeys & 0x04) == 0){ // key is pressed D2 -> A2
     if (keyActive[0]==0){
       keyActive[0] = 1;
       changeTime[0] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[0])>=noteArray[48]){ // time for a period toggle?
      changeTime[0] = changeTime[0] + noteArray[48];    // setup time for the next toggle
      PINA=0x04;  // write a 1 to PINx toggles an output bit - NickGammon to the rescue again!
    }
  }
  else{keyActive[0] = 0;}

  /* Check if key for note C#4 is pressed, key1  */

  if ((portDkeys & 0x08) == 0){ // key is pressed D3 -> A3
       if (keyActive[1]==0){
       keyActive[1] = 1;
       changeTime[1] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[1])>=noteArray[47]){
      changeTime[1] = changeTime[1] + noteArray[47];
      PINA = 0x08;
    }
  }
  else{keyActive[1] = 0;}

  /* Check if key for note D4 is pressed, key2  */

  if ((portDkeys & 0x10) == 0){ // key is pressed D4 -> A4
       if (keyActive[2]==0){
       keyActive[2] = 1;
       changeTime[2] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[2])>=noteArray[46]){
      changeTime[2] = changeTime[2] + noteArray[46];
      PINA = 0x10;
    }
  }
  else{keyActive[2] = 0;}

  /* Check if key for note D#4 is pressed, key3  */

  if ((portDkeys & 0x20) == 0){ // key is pressed D5 -> A5
       if (keyActive[3]==0){
       keyActive[3] = 1;
       changeTime[3] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[3])>=noteArray[45]){
      changeTime[3] = changeTime[3] + noteArray[45];
      PINA = 0x20;
    }
  }
  else{keyActive[3] = 0;}

  /* Check if key for note E4 is pressed, key4  */

  if ((portDkeys & 0x40) == 0){ // key is pressed D6 -> A6
       if (keyActive[4]==0){
       keyActive[4] = 1;
       changeTime[4] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[4])>=noteArray[44]){
      changeTime[4] = changeTime[4] + noteArray[44];
      PINA = 0x40;
    }
  }
  else{keyActive[4] = 0;}

  /* Check if key for note F4 is pressed, key5  */

  if ((portDkeys & 0x80) == 0){ // key is pressed D7 -> A7
       if (keyActive[5]==0){
       keyActive[5] = 1;
       changeTime[5] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[5])>=noteArray[43]){
      changeTime[5] = changeTime[5] + noteArray[43];
      PINA = 0x80;
    }
  }
  else{keyActive[5] = 0;}

  /*  Now Port B & Port C */
  /* Check if key for note F#4 is pressed, key6  */

  if ((portBkeys & 0x01) == 0){ // key is pressed B0 -> C0
       if (keyActive[6]==0){
       keyActive[6] = 1;
       changeTime[6] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[6])>=noteArray[42]){
      changeTime[6] = changeTime[6] + noteArray[42];
      PINC = 0x01;
    }
  }
  else{keyActive[6] = 0;}

  /* Check if key for note G4 is pressed, key7  */

  if ((portBkeys & 0x02) == 0){ // key is pressed B1 -> C1
       if (keyActive[7]==0){
       keyActive[7] = 1;
       changeTime[7] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[7])>=noteArray[41]){
      changeTime[7] = changeTime[7] + noteArray[41];
      PINC = 0x02;
    }
  }
  else{keyActive[7] = 0;}

  /* Check if key for note G#4 is pressed, key8  */

  if ((portBkeys & 0x04) == 0){ // key is pressed B2 -> C2
       if (keyActive[8]==0){
       keyActive[8] = 1;
       changeTime[8] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[8])>=noteArray[40]){
      changeTime[8] = changeTime[8] + noteArray[40];
      PINC = 0x04;
    }
  }
  else{keyActive[8] = 0;}

  /* Check if key for note A4 is pressed, key9  */

  if ((portBkeys & 0x08) == 0){ // key is pressed B3 -> C3
       if (keyActive[9]==0){
       keyActive[9] = 1;
       changeTime[9] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[9])>=noteArray[39]){
      changeTime[9] = changeTime[9] + noteArray[39];
      PINC = 0x08;
    }
  }
  else{keyActive[9] = 0;}

  /* Check if key for note A#4 is pressed, key10  */

  if ((portBkeys & 0x10) == 0){ // key is pressed B4 -> C4
       if (keyActive[10]==0){
       keyActive[10] = 1;
       changeTime[10] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[10])>=noteArray[38]){
      changeTime[10] = changeTime[10] + noteArray[38];
      PINC = 0x10;
    }
  }
  else{keyActive[10] = 0;}

  /* Check if key for note B4 is pressed, key11  */

  if ((portBkeys & 0x20) == 0){ // key is pressed B5 -> C5
       if (keyActive[11]==0){
       keyActive[11] = 1;
       changeTime[11] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[11])>=noteArray[37]){
      changeTime[11] = changeTime[11] + noteArray[37];
      PINC = 0x20;
    }
  }
  else{keyActive[11] = 0;}

  /* Check if key for note C5 is pressed, key12  */

  if ((portBkeys & 0x40) == 0){ // key is pressed B6 -> C6
       if (keyActive[12]==0){
       keyActive[12] = 1;
       changeTime[12] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[12])>=noteArray[36]){
      changeTime[12] = changeTime[12] + noteArray[36];
      PINC = 0x40;
    }
  }
  else{keyActive[12] = 0;}

} // end loop

```

---
Tags: arduino-uno
---


title: ESP8266 TCP connection WiFiClient issue

text:
# Question
Title: ESP8266 TCP connection WiFiClient issue
I am using ESP8266 01 board to send some data via TCP to server on local network. My code is:

```
#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pas";

const char* host = "192.168.1.103";

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

  // Wifi connection

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  while(Serial.available() == 0)
  {
    //wait for arduino serial data
  }

   while(Serial.available())
  {
    // send data to server
    client.print(Serial.read());
  }
}

```

After chacking code in Arduino IDE I am getting error message:

```
In function 'void loop()':
espwifitcp1:57: error: 'client' was not declared in this scope
     client.print(Serial.read());
     ^
exit status 1
'client' was not declared in this scope

```

It appears that if I declare `WiFiClient client;` inside `setup()` function it can't be accessed outside it. Do I correctly understand the problem? I have tried to declare object outside `setup()` and `loop()` functions but it got even more errors. Any suggestions?

# Answer
You have declared `WiFiClient client;` in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of `void setup()`
> 3 votes

# Answer
in the header include WifiClient.h
> -1 votes

---
Tags: esp8266, wifi, tcpip
---


# Question
Title: Error compiling for board Arduino/Genuino Uno
I am getting the following error message when compiling a program on my Arduino IDE. This does not happen when compiling the given example programs in the IDE.

The error message is as follows :

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

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware
C:\Program Files\Arduino\hardware -tools
C:\Program Files\Arduino\tools-builder -tools
C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries
C:\Program Files\Arduino\libraries -libraries
C:\Users\mahim\OneDrive\Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path
C:\Users\mahim\AppData\Local\Temp\arduino_build_361527 -warnings=none -build-cache
C:\Users\mahim\AppData\Local\Temp\arduino_cache_227236 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=
C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=
C:\Program Files\Arduino\hardware\tools\avr -verbose
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino
readlink
C:\Users\mahim\OneDrive\Documents\Arduino\3potpass\3potpass.ino: The system cannot find the file specified.

Error compiling for board Arduino/Genuino Uno.

```

# Answer
> 2 votes
This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

# Answer
> 0 votes
Following on from duskwuff's answer, the issue with OneDrive folders has been resolved as of version 1.8.6.

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

> ARDUINO 1.8.6 2018.08.23
>
> \[ide\]
>
> * Updated arduino-builder to 1.4.0:
>     + parallel build (improve compile speed)
>     + better reuse of already compiled files
>     + **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.

---
Tags: arduino-uno
---


title: Increasing speed of Vl6180x Sensors

text:
# Question
Title: Increasing speed of Vl6180x Sensors
I have 5x vl6180x pololu ToF sensors. I have managed to hook up all of the sensors to the arduino via I2C by making each sensor startup at different times and when they do, changing their addresses, but while I can quite easily read them, they take a very long time, 50ms - 300ms. I'm using the Pololu VL6180x library and when I've investigated the library, I couldn't find any delays in the code. I have also tried to change the clock rate of I2C to 400kHz, but that didn't seem to affect the speed. The datasheet of the sensors says that a sensor might take ~63ms to respond, but is there any way to make it faster? If not, can I read the sensors with the AtTiny13A and send the data from each chip to arduino? Which protocol should i use to communicate with them, if i want to read their measured distance?

Ps. I'm making a robot which needs to move fast and react quickly to each sensor. (11 of sensors in total, none, except ToF are I2C)

# Answer
> 0 votes
You can use `startRangeContinuous` and `readRangeContinuous` to have the sensor continuously measuring the distance, negating the need to wait for the sensor to do a measurement.

Using `readRangeSingle` will start a single measurement, and this function will just sit there waiting for the measurement to be done, after which it will return the result.

---
Tags: sensors, i2c, communication, attiny
---


title: Cannot load anything from library

text:
# Question
Title: Cannot load anything from library
So I installed libraries through the Arduino interface (`Sketch` \> `Include Library` \> `Manage Library`). Then I check: `C:\Users\username\OneDrive\Documents\Arduino\Libraries`, and I confirm the new libraries are there.

However, when I compile I always get the error that Arduino cannot find the library, no matter which one I try to import.

I'm on Arduino 1.8.5, Windows. What am I missing?

# Answer
This was a problem with using your OneDrive folder.

duskwuff wrote:

> This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

The issue with OneDrive folders has been resolved as of version 1.8.6.

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

> ARDUINO 1.8.6 2018.08.23
>
> \[ide\]
>
> * Updated arduino-builder to 1.4.0:
>     + parallel build (improve compile speed)
>     + better reuse of already compiled files
>     + **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.
> 2 votes

---
Tags: library, compile
---


# Question
Title: Process Sensor Data from Arduino Yun with Python
I'm currently working on a small project with my Arduino Yún. I want to process the sensor data in python and send them in a message queue. I need to use Python3.

I cannot find a way to get the sensor data in my Python code. I already tried to start the python process in my sketch and use the `println` method of the process object but this doesn't work.

I also tried to use the `BridgeClient` class from the Arduino Github but it won't work either.

Summarized: I can't find a way to send my measurements from my Arduino sketch to the my Python3 program on the Linux side of the Arudino Yún.

I don't think this is an extraordinary problem and I don't understand why there aren't any tutorials for this specific use-case.

The section below contains my Arduino sketch, which does the measurements.

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

HTU21D myHumidity;

int trigPin = 11;
int echoPin = 12;

void setup() {
  // put your setup code here, to run once:
  pinMode(A1, INPUT);
  Serial.begin(9600);

  myHumidity.begin();

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

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

  //Perform 5 SoilMoisture-measurements and get mean
  float soil = meanSoilMoisture(A0, 5);
  float humd = myHumidity.readHumidity();
  float temp = myHumidity.readTemperature();

  float distance = getDistance();

  String dataString;
  dataString += String(soil) + ", " + String(humd) + ", " + String(temp) + ", " + String(distance);
  Serial.println(dataString);

  delay(4000);
}

long getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  long duration = pulseIn(echoPin, HIGH);

  // Convert the time into a distance
  return (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
}

float meanSoilMoisture(int analogPin, int nMeasurements) {
  float sum = 0;
  for(int i = 0; i < nMeasurements; i ++) {
    sum = sum + readVH400(analogPin);
    delay(50);
  }

  return sum / nMeasurements;
}

//Perform Measurement
float readVH400(int analogPin) {
  int sensor1DN = analogRead(analogPin);
  float sensorVoltage = sensor1DN*(3.0 / 1023.0);
  float VWC;

  // Calculate VWC
  if(sensorVoltage <= 1.1) {
    VWC = 10*sensorVoltage-1;
  } else if(sensorVoltage > 1.1 && sensorVoltage <= 1.3) {
    VWC = 25*sensorVoltage-17.5;
  } else if(sensorVoltage > 1.3 && sensorVoltage <= 1.82) {
    VWC = 48.08*sensorVoltage-47.5;
  } else if(sensorVoltage > 1.82) {
    VWC = 26.32*sensorVoltage-7.89;
  }
  return(VWC);

}

```

I'd like to have a way to send `dataString` to the linux side of the Arduino Yún and process it with Python3.

As explained earlier I've already tried out multiple solutions, e.g. start a new process and use the `println` method of the process.

```
{...}
Process proc;
void setup() {
    {...}
    proc.begin("python3 /mnt/sda1/test.py");
    p.runAsynchronously();
    {...}
}
{...}
    proc.println(dataString);
{...}

```

I've tried to read this `dataString` in Python3 in different ways, e.g. I've used the `input` method, because I read in a forum that I can handle such input like a keyboard input. It didn't work and I didn't get an error, neither in Python nor in my sketch.

I've read different examples using the `Bridge` library. So I set up the sketch:

```
{...}
bridge.put("data", dataString);
{...}

```

I'd like to try out the `BridgeClient`on the python side but this library was written in Python2. I don't want to migrate the library to Python3 and I need to use Python3, so I didn't find a way to write Python code here.

I would highly appreciate any help from you.

# Answer
> -1 votes
You might want to try the Process method, although, looking at your recent edits to the question, it seems like you already have.

Nevertheless, I was having difficulty getting my head around the problem when I first used my Yún, and I found the information below helped me understand how to get up and running. You do say that you've tried many solutions already, and maybe you've already seen this, but as you don't list which solutions you have already tried (apart from one), I thought it might be worth posting this link as an answer.

From this post to the thread on the Arduino forums, Yun Serial connection between Arduino and Linux

> Accepting HTTP connections, as shown in the Bridge tutorial, is but one facet of the Bridge library. (And probably the least useful and least efficient facet.) It is intended for accepting incoming connections from the greater network, not necessarily the local Linux processor.
>
> The Bridge library is a collection of different classes that perform a variety of operations, all over the serial link between the two processors, and all can be used at the same time. The Bridge uses a network port paradigm, not HTTP. Using ports gives it a little more overhead, but it allows multiple simultaneous "connections" between the sketch and Linux sides.
>
> I suggest you take a look at the Process tutorial. It does what you want, and 95% of the time it is the only part of the Bridge library that I use. The example defines Process objects that are local to a function, which run simple commands that do a little bit different f processing, return a result, and then exit.
>
> My projects typically define a global Process object which starts a Python script, and keeps the connection open. Once open, the sketch can write to the Process object at any time, and the Python script reads that data from STDIN. Python can write to STDOUT at any time, and the sketch can read it from the Process object. The Process class derives from the Stream class, just like Serial, so your sketch can use any of the read/write methods you would use for a serial port. On the Linux side, you are just reading/writing as you would to the console. By default, Pythons runs in a buffered mode: I've found that you need to add the -u option to the command line that runs your Python script, or add it to the hashbang at the beginning of your script.
>
> There are those who disable the Bridge library, and use the serial port manually on both sides. This can be done, but I've not had to resort to that yet. The Process class does everything that a direct serial connection can do, and more: you can have multiple simultaneous Process connections going, and you can still use all of the other Bridge library features. If you disable the Bridge library, you get just the one connection stream. It would be a bit more efficient, but unless you are dealing with high amounts of data, I'll bet you don't need to do that.
>
> My typical project has the sketch running as a rather dumb I/O processor, passing barely digested input data down though one or more Process objects to a Python script. The Linux side does all of the heavy processing and network communications, and then sends output data back up the sketch which outputs it to the pins.

---
Tags: arduino-yun, python
---


title: Spi based pin expander for Arduino

text:
# Question
Title: Spi based pin expander for Arduino
I don't have enough pins on my Esp32 board. I would like to use a pin expander. All the ones I could find online only use i2c. Are there ones available that use SPI?

I would like send pwm signals to the pin expander outputs. Is that possible?

# Answer
> 1 votes
Here you go https://www.microchip.com/wwwproducts/en/MCP23S17. Found it. I am gonna leave this here in case anyone needs it.

---
Tags: arduino-ide, pins
---


title: Include guards vs #pragma once

text:
# Question
Title: Include guards vs #pragma once
Is there any particular reason why `#pragma once` doesn't seem to be used in Arduino code? Is this just because it's not a well-known feature, or is there some overriding reason to use `#ifndef XXX_H`/`#define XXX_H`/`#endif`?

# Answer
`#pragma once` operates on the absolute filename of a file. Include guards work on the content of the file.

If you have multiple copies of the same library (maybe one library has some parts of another included in it - it happens...) `#pragma once` would have no hope of working right.

Add to that the fact that the Arduino IDE copies some files around the place when building and `'#pragma once` is pretty much screwed.

Include guards work regardless. So sensible people use include guards and shun `#pragma once`.
> 9 votes

---
Tags: programming, library
---


title: Problems with Serial.read()

text:
# Question
Title: Problems with Serial.read()
```
void loop()
{
  if (sensor.begin() == true)
  {
    Serial.print("Current Conversion Mode: ");
    Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

```

I'm currently using the SparkFun red board to run this code on. I have been trying to get this to read from the serial monitor to take an input to send to the library I wrote to change the value of the conversion mode register of a temperature sensor. When I run the code, I can only have it run once correctly, then it jumps directly to the else statement for the inputs, saying that 0-3 was not an input. I tried the other methods that people have suggested from this website and the Arduino forums but none of them have worked for me yet. I'm not sure if adding more delays would help - that was one of the most common suggestion I found for this specific issue and it wasn't that consistent. Please help! Thanks.

# Answer
Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

> Current Conversion Mode: Enter your mode of Conversion (number 0 - 3): Number recieved: 2
>
> Current Conversion Mode: Enter your mode of Conversion (number 0 - 3): Number recieved:
>
> Conversion mode unsuccessfully set - Please enter a number 0 - 3 Current Conversion Mode: Enter your mode of Conversion (number 0 - 3): Number recieved:
>
> Conversion mode unsuccessfully set - Please enter a number 0 - 3 Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change `mode` to an `int` then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?

Here is a test sketch:

```
char mode;

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

void loop()
{
  if (true)
  {
    Serial.print("Current Conversion Mode: ");
    //Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      //sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

```
> 0 votes

---
Tags: arduino-uno, programming, arduino-ide, c++, c
---


title: About ATmega32 event system

text:
# Question
Title: About ATmega32 event system
From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?

# Answer
The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.

ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.

The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...

To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.

It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.

On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.

After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.

a simple Arduino SAMD lib for a Triac/ZC module (in development):

```
#ifndef _TRIAC_LIB_
#define _TRIAC_LIB_

namespace Triac {

const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
const int TIMER_PRESCALER = 8;
const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

Tcc* TCC;

void syncTCC() {
  while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
}

void zeroCrossing() {
}

void setup(byte zcPin, byte triacPin) {

  // setup the external interrupt
  attachInterrupt(zcPin, zeroCrossing, RISING);
  uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
  EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

  const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
  TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
  uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

  // setup the pin as TCC wave out pin
  PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
  PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

  // setup the timer

  REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
  while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

  TCC->CTRLA.bit.SWRST = 1; // reset timer
  syncTCC();
  TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
  syncTCC();
  TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
  syncTCC();

  TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
  syncTCC();
  TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
  syncTCC();

  TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
  syncTCC();
  TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
  syncTCC();

  // event system
  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
  while (GCLK->STATUS.bit.SYNCBUSY);

  EVSYS->CTRL.bit.SWRST = 1; // reset
  while(EVSYS->CTRL.bit.SWRST);

  EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
      EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
  while (!EVSYS->CHSTATUS.bit.USRRDY0);
}

/*
 * r is from interval <0.0, 1.0>
 */
void setPeriod(float r) {
  unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
  TCC->PER.reg = period + PULSE_PERIOD;
  syncTCC();
}

}
#endif

```

other SAMD example
> 2 votes

# Answer
The ATmega32 has a coupe of peripheral-to-peripheral communication features that are in some way similar to the Event System:

* You can use the analog comparator to trigger an input capture on Timer 1.
* You can use the analog comparator, external interrupt 0, Timer 0, or Timer 1 to trigger a conversion on the ADC.

These are the only ones I know about. As you can see, it's a very limited functionality. From what I read, the Event System looks like a generalization of this idea. You have many peripherals that can trigger events (event emitters), many that can be triggered by such events (event receivers), and you can connect any event emitter to any event receiver. You thus have much more flexibility than the very limited peripheral-to-peripheral communication facilities provided by the ATmega32.

The configuration of the event system (emitter to receiver connections) is performed by your software. However, once the connection is established, the peripheral-to-peripheral communication is entirely hardware, and does not depend on the CPU.
> 0 votes

---
Tags: avr, events
---


# Question
Title: Can I solder wall cord directly to servo?
I have a servo which requires 7.4v and a wall power cord which says the output is 7.4v but the connector does not fit that of the servo. Is it safe to snip off the end of the wall cord and solder the internal wires directly to the servo?

# Answer
> 1 votes
First choice: Attach compatible, polarized connectors to both pigtails.

Alternatively, you can solder it up but the result is certainly less convenient to use. I like heat-shrink tubing for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires **before** I solder the joints. :)

---
Tags: power, servo, voltage-level
---


# Question
Title: My webswerver works fine when there is only 1 servo used/defined in my code
I am trying to make a webserver which controls my 3 servos for a robotic arm. When I define and use 1 servo it is nice and quick, but whereas if I use more than 1 the webserver is very slow and barely loads. Someone please help.

I will post the code below. With this code the webserver is very slow:

```
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip []={10,1,1,121};// check back of your shield
   // when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
 Ethernet.begin(mac, ip);
server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

robotservo1.attach(9);
robotservo2.attach(10);

robotservo1.write(45);
robotservo2.write(45);

}

void loop() {
  // put your main code here, to run repeatedly:
EthernetClient client = server.available();
if (client) {
if (client.connected()){
  if (client.available()) {
  char c = client.read();
  if (readString.length() < 100) {
          readString += c;
        }
  if (c == '\n') {
          Serial.println(readString);
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<hmtl>");
          client.println("<head>");
client.println("<title>Ethernet shield, hopefully works</title>");
client.println("</head>");
client.println("<title>");
client.println("Control the robotic arm using the buttons below");
client.println("</title>");
client.println("<body bgcolor = black>");
client.println("<font color = antiquewhite>");
client.println("<meta http-equiv=\"refresh\" content=\"4\">");
client.println("<b>");
client.println("Control the robotic arm by pressing the buttons below!!!");
client.println("</b>");
client.println("<body>");
client.println("<p>");
client.println("Servo 1 or Base");
client.println("<br>");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>");
client.println("</FORM>");
client.println("</p>");

client.println("<p>");
client.println("Servo 2 or Elbow");
client.println("<br>");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>");
client.println("</FORM>");
client.println("</p>");

client.println("<p>");
client.println("Servo 3 or Shoulder");
client.println("<br>");
client.println("<FORM>");
client.println("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>");
client.println("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>");
client.println("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>");
client.println("</FORM>");
client.println("</p>");

client.println("</font>");
client.println("</body>");
client.println("</html>");

 delay(1);

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo1.write(0);
            }

          else{
            if(readString.indexOf("?baseserv45") >0)
            {
              robotservo1.write(45);
            }

          else{
            if(readString.indexOf("?baseserv90") >0)
            {
              robotservo1.write(90);
            }

  }

}

  if(readString.indexOf("?baseserv0") >0)
            {
              robotservo2.write(0);
            }

          else{
            if(readString.indexOf("?elbowserv45") >0)
            {
              robotservo2.write(45);
            }

          else{
            if(readString.indexOf("?elbowserv90") >0)
            {
              robotservo2.write(90);
            }

  }

}

  readString="";
          client.stop();
  }}}}}

```

# Answer
> 1 votes
I have no Ethernet board so I couldn't test the timings, but when I compiled your code for an Uno, I got a low free-memory warning; that 83% of memory was used and stability problems could occur. That's the compiler telling you that your code might not run right. It may very well be the reason your server was slow. The largest user of data-memory (SRAM) is the text in your client.print() statements.

I put that text into program-memory (Flash, of which there is over 10x as much!) which got the SRAM use down to 29%! Try running that and see if it won't behave a little bit better:

```
#include <Ethernet.h>
#include <SPI.h>
#include <Servo.h>
String readString;
Servo robotservo1;
Servo robotservo2;

byte mac[] = { 0x2C, 0xF7, 0xF1, 0x08, 0x29, 0xAF };
byte ip [] = {10, 1, 1, 121}; // check back of your shield
// when the shield connected the serioal monitor will display the ip address
EthernetServer server(80);

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Ethernet.begin(mac, ip);
   server.begin();
   Serial.print("server is at ");
   Serial.println(Ethernet.localIP());// prints my IP address, so you can copy paste in browsr

   robotservo1.attach(9);
   robotservo2.attach(10);

   robotservo1.write(45);
   robotservo2.write(45);

}

void loop() {
   // put your main code here, to run repeatedly:
   EthernetClient client = server.available();
   if (client) {
      if (client.connected()) {
         if (client.available()) {
            char c = client.read();
            if (readString.length() < 100) {
               readString += c;
            }
            if (c == '\n') {
               Serial.println(readString);
               client.println(F("HTTP/1.1 200 OK"));
               client.println(F("Content-Type: text/html"));
               client.println();
               client.println(F("<hmtl>"));
               client.println(F("<head>"));
               client.println(F("<title>Ethernet shield, hopefully works</title>"));
               client.println(F("</head>"));
               client.println(F("<title>"));
               client.println(F("Control the robotic arm using the buttons below"));
               client.println(F("</title>"));
               client.println(F("<body bgcolor = black>"));
               client.println(F("<font color = antiquewhite>"));
               client.println(F("<meta http-equiv=\")refresh\" content=\"4\">"));
               client.println(F("<b>"));
               client.println(F("Control the robotic arm by pressing the buttons below!!!"));
               client.println(F("</b>"));
               client.println(F("<body>"));
               client.println(F("<p>"));
               client.println(F("Servo 1 or Base"));
               client.println(F("<br>"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?baseserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?baseserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?baseserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("</p>"));

               client.println(F("<p>"));
               client.println(F("Servo 2 or Elbow"));
               client.println(F("<br>"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?elbowserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?elbowserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?elbowserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("</p>"));

               client.println(F("<p>"));
               client.println(F("Servo 3 or Shoulder"));
               client.println(F("<br>"));
               client.println(F("<FORM>"));
               client.println(F("<INPUT type=button value=Servo-0 onClick=window.location='/?shoulderserv0\'>"));
               client.println(F("<INPUT type=button value=Servo-45 onClick=window.location='/?shoulderserv45\'>"));
               client.println(F("<INPUT type=button value=Servo-90 onClick=window.location='/?shoulderserv90\'>"));
               client.println(F("</FORM>"));
               client.println(F("</p>"));

               client.println(F("</font>"));
               client.println(F("</body>"));
               client.println(F("</html>"));

               delay(1);

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo1.write(0);
               }

               else {
                  if (readString.indexOf("?baseserv45") > 0)
                  {
                     robotservo1.write(45);
                  }

                  else {
                     if (readString.indexOf("?baseserv90") > 0)
                     {
                        robotservo1.write(90);
                     }

                  }

               }

               if (readString.indexOf("?baseserv0") > 0)
               {
                  robotservo2.write(0);
               }

               else {
                  if (readString.indexOf("?elbowserv45") > 0)
                  {
                     robotservo2.write(45);
                  }

                  else {
                     if (readString.indexOf("?elbowserv90") > 0)
                     {
                        robotservo2.write(90);
                     }

                  }

               }

               readString = "";
               client.stop();
            }
         }
      }
   }
}

```

---
Tags: arduino-uno, ethernet
---


# Question
Title: How to rotate a servo motor on a specific angle?
I am trying to rotate a top on a specific angle after every 1 second. For example: 1 degree/second. I have two question:

1. Can I achieve this with servo motors?
2. If not, what motor should I use?

I know this question has very little description. I am mainly a programming guy. I don't much about arduino stuff. It's actually a hobby project for me.

Thanks in advance.

# Answer
The kind people who have written the Arduino libraries include software drivers for servo control. These drivers abstract the hardware from the programmer of the sketch software (the sketch is application software you write in C or C++). It is unnecessary to understand the driver in detail. However the servo driver software (likely written in C++) can been examined here.

To move a normal servo to a particular position, make a call to the Arduino Servo Driver using the function write(angle) passing an angle value from 0 to 180. The value is an approximation of degrees and the value type is of type integer.

In the above links you will find this example of sweeping the servo motor across its range:

```
/* Sweep
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

Proceed to that page for more details including a schmatic (diagram) of how the servo is connected to an Arduino Uno board.
> 1 votes

# Answer
You can rotate the servo motor per degree, but it has it's limitations, it only has 0-180 degrees of movement. If you need to rotate beyond that, I would recommend using Stepper motors, they can be very precise, but they don't have a potentiometer, like a servo does, so, after resetting the system, the motor won't comeback to the starting position.
> 0 votes

---
Tags: motor, servo
---


# Question
Title: Is there an alternative to soldering to connect boards?
I know that shields are usually soldered to headers so they can be attached to the board with the Arduino. I have a tremor, which makes soldering impossible. **Are there ways of connecting PCBs without soldering?**

If a concrete example would be helpful, I would like to connect the Adafruit WINC1500 WiFi Shield to a SparkFun RedBoard.

# Answer
Sparkfun has a lot of sensor boards that use their Qwiic Connect System. Those you can just plug in, and even chain together, with their cables with JST connectors.

Adafruit has their Flora like of products. Mostly tailored to wearables, but with their large connector pads, you can easily connect the board to the sensors wit alligator clips.
> 1 votes

# Answer
Yes, there are ways. There is a system called "Press Fit" where the pins have a bulge in one end of them. This grips the inside of the holes in place of soldering.

A number of companies make them, such as TE Connectivity and Positronic.

Of course, these depend on the holes being just the right size, and finding the right connectors could be tricky... so... your mileage may vary.

But nothing is better than getting someone to solder the pins for you. You could teach one of your younger relatives to solder, for example...
> 5 votes

# Answer
Boards with headers can be connected using jumper wires or hookup wire. If there are no headers then I don't think you will be able to get a reliable connection without soldering.

The RedBoard you linked to uses headers, so you should be able to use jumpers with it, but I suspect you are out of luck with the WiFi shield. You'll probably either need to find a version that is built using headers or ask/hire somebody to solder headers onto it for you.

As for the center portion of the shield you should probably just skip that part and use a breadboard, which uses jumpers or hook-up wires.
> 1 votes

---
Tags: pins, shields, hardware
---


title: Arduino DUE- flash space for user

text:
# Question
Title: Arduino DUE- flash space for user
I need for my project to save only 32bit in non-volatile storage. What is the easiest/cheapest way to do that in Arduino DUE?

ArduinoDUE is Atmel SAM3X8E so according to the attached table (from Atmel DS)

In the chip I have 4KB of NFC SRAM. NFC = Nand Flash Controller, so I have 4KB of internal flash in the internal SRAM?

Thanks,

# Answer
> 1 votes
It looks like there's at least one library out there to emulate EEPROM functionality in the DUE using Flash.

https://github.com/sebnil/DueFlashStorage

---
Tags: flash
---


# Question
Title: Arduino wrap or subclass print() to work with multiple Serial
I am writing an Arduino program that uses Bluetooth on `Serial1` to print text to a Bluetooth terninal on an Android phone and also normal `Serial` to print text to the serial monitor on a laptop. I would like to wrap the `Serial.print()` and `Serial.println()` functions so that they work with either or both `Serial` and `Serial1`. For example the code below works fine depending on the values of the global variables. But this only works for single chars, but `print()` and `println()` can take a very wide variety of datatypes. If I also define overloading functions for int and String types it works fine, but that is a very verbose and maybe fragile solution, it also ignores the optional inputs to the underlying functions. What is the proper way to do this ?

```
void print(char x) {
  if (g_use_Serial)
    Serial.print(x);
  if (g_use_Serial1)
    Serial1.print(x);
}

void println(char x) {
  if (g_use_Serial)
    Serial.println(x);
  if (g_use_Serial1)
    Serial1.println(x);
}

```

---

I have implemented the solution suggested and it works nearly perfectly. There seems to be a problem with the new line characters on the bluetooth (`Serial1`) connection.

The code is:

```
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

void setup()  {
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(1000);
}

void loop() {

  out.use_Serial = true;
  out.print("Printed to USB only.\n");
  out.use_Serial1 = true;
  out.print("Printed to both USB and BT.\n");
  out.use_Serial = false;
  out.print("Printed to BT only.\n");
  out.use_Serial1 = false;

  delay(3000);
}

```

The output on the USB Serial monitor is as expected:

```
Printed to USB only.
Printed to both USB and BT.
Printed to USB only.
Printed to both USB and BT.

```

The output on the Bluetooth terminal is not as expected, the new lines are not in the right position:

```
Printed to both USB and BT.Pri
nted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.
Printed to both USB and BT.Pr
inted to BT only.

```

Any suggestions on how to fix this. Are there other function members that need to be re-implemented to make this work properly?

Many thanks for high quality answers so far.

# Answer
You can create a class derived from `Print` that forwards its output to either or both `Serial` and `Serial1`. The only method you need to implement for this to work is `write(uint8_t)`:

```
class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

```

You would use it like this:

```
out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

```

Note that with this approach, unlike yours, printing number will format them as text only once, and the underlying `Serial` and `Serial1` will only handle the resulting characters.

---

**Edit**: To answer the question in OP's comment, the construct

```
class ClassName
{
    ...definition...
} classInstace;

```

is a shotcut for

```
class ClassName
{
    ...definition...
};
ClassName classInstace;

```

A very similar construct exists in plain C:

```
struct struct_name {
    ...the struct fields...
} struct_instance;

```
> 6 votes

---
Tags: arduino-uno, serial, c++, c
---


title: SPI communication Problem Arduino

text:
# Question
Title: SPI communication Problem Arduino
I'm trying to set up SPI communication between two Arduinos (UNO and Mega), I want to read the status of the slave output pin from the master.

I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct. I used another code I found online.

MASTER code

```
#include <SPI.h>
const byte btn =8;

void setup(void) {

Serial.begin (9600);
pinMode (btn, INPUT_PULLUP);
digitalWrite (SS, HIGH);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV8);

}

void loop(void) {

byte Mvalsent,Mvalreceived;
digitalWrite (SS, LOW);
for (int jj=0; jj<255; jj++)
  {
      Mvalsent =jj;
      Mvalreceived =SPI.transfer (Mvalsent);
      Serial.print ("Retou d'etat ");
      Serial.print (Mvalsent);
      Serial.print ("\t ,l'etat de la diode est ");
      Serial.println (Mvalreceived);
      delay (400);
  }

  digitalWrite (SS,HIGH);

}

```

SLAVE Code

```
#include <SPI.h>
byte state;
const byte led =9;
volatile boolean process_it;
volatile byte Svalreceived, Svalsent;
int jj=0;
void setup (void)
{
  Serial.begin (9600);
pinMode (led,OUTPUT);
//set MISO pin as output
pinMode (MISO, OUTPUT);
//turn on SPI in slave mode
SPCR |= _BV (SPE);
//get ready for an interrupt
process_it = false;
//now turn on interrupts
SPI.attachInterrupt ();
}
ISR (SPI_STC_vect)
{
  Svalreceived = SPDR;
  process_it =true;
}
void loop (void)
{
 if (process_it)
 {

   digitalWrite (led, LOW);
   state =digitalRead(led);
   SPDR = state;
   Serial.print("l'etat de la diode est: ");
    Serial.println (state);
    delay (400);

    process_it =false;
  }
}

```

# Answer
Why not use I2C slave-master between arduinos? You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).

And you still keep the SPI for a microsd card adapter, for example.

Follow this official tutorial:

MASTER ARDUINO 1

```
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

```

SLAVE ARDUINO 2

```
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

```

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).
> 1 votes

---
Tags: arduino-uno, arduino-mega, spi
---


# Question
Title: LED not blinking when using a transistor
I want to control an led using a transistor. The led gets it‘s power from an external 5v dc power supply.

For the transistor I use an 1kΩ base resistor. The transistor is a BC547C (npn). The datashet is available here. The led is red (3mm), draws 20mA of current and needs 2V.

I‘ve got a very simple Arduino sketch and wiring setup:

**Code:**

```
#define ledPin 6

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(1000);
}

```

**Wiring diagram:**

**Problem:**

1. The led is not blinking but shining at full power constantly.
2. Disconnecting `ledPin 6` from the Arduino (to mimic `digitalWrite(ledPin, LOW)`) still lets the led shine, just not as bright. The LED should be off in that case, not just dimmed to 50% brightness.

**What I tried so far:**

1. I tried using different base resistors. I tried 2kΩ, 3kΩ, 2.5kΩ, 470Ω, 1.5kΩ. The behavior did not change.
2. I tried using different leds. Same behavior. LEDs are shining constantly, not blinking, and are dimmed when disconnecting `pin 6`.
3. I used another BC547C to see if the first one was broken. It wasn’t. I still got the same behavior.
4. Connecting the led directly to the Arduino without the transistor and external power supply let’s the led blink exactly how it was defined in code.

Any ideas? I several-times-checked the wiring in my setup. It should not be the problem.

# Answer
Without a common reference (ground) between the Arduino power supply and the external power-supply, again, you have a floating base, as you can't know what the Arduino's 5v output (or local ground) looks like to the external circuit.

Connect the two grounds. That should correct the LED brightness with respect to the Arduino output pin level. Then, if you need the external circuit to behave in a specific way when the base is disconnected from the Arduino, add a 10K resistor from the transistor base to the external +5 if you want the LED to be on, or to ground, if you want it to be off. Again, I'm guessing at both the pullup/pulldown value (but 10K should be in the ballpark) and the switching sense ('On' or 'Off' for base at +5), but from the expectation state in your point (2.), I think I have it right.

Update: But see @EdgarBonet's comment to me about BJT's. I'd still avoid leaving an input floating as a matter of practice, but it seems not relevant in your circuit.
> 8 votes

---
Tags: arduino-uno, led, transistor
---


# Question
Title: How can I rewrite Arduino Code using SPI library into C++?
The issue is that I have code using an Arduino library and need to convert it into C++ so I can use it with a raspberry pi on ROS (Robot operating system). Does anyone know the best way to change it over or know of good resources?

I know that Arduino is essentially C++ but I am uncertain about how to make Arduino libraries into C++.

# Answer
> 0 votes
The sometimes-called "Arduino Language" is C++, but with some upfront work - primarily supplying file inclusions - done for you if you don't.

The Arduino compiler is a GNU C++ compiler. If you write or supply standard C++ to the Arduino IDE, it will compile it.

# Answer
> 0 votes
The Arduino compiler is a GNU C++ compiler HOWEVER there is no c runtime library (which is not part of the compiler).

Probably more significant to the question is that the Arduino compiler supplies support for the ATMEL hardware. This is incompatible with the Raspberry Pi.

The Arduino is a real time microcontroller and has unrestricted access to its hardware, the Pi usually runs a multi-tasking OS, the hardware is not directly accessible from user space, so many tasks need to be written differently; often this means relying on a OS supplied kernel driver.

Any practicable Arduino program would require extensive changes to work on the Raspberry Pi. The effort involved is likely to be more than writing a Raspberry Pi program from scratch.

---
Tags: arduino-ide, c++, spi
---