# Question
Title: Read/write data from 2 Arduinos simultaneously with Python
So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.

If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like `pin.write(1)` to turn on or `pin.write(0)` to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.

The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.

At the moment I have custom code on My Arduino Mega and a `StandardFirmata` on the Arduino Uno, but I am open to other suggestions that could work.

Arduino Mega code:

```
/*
by Ben-Tommy Eriksen
https://github.com/BenTommyE/BenRotaryEncoder
*/

// Encoder connect to digital pin 2 and 3 on the Arduino.

int counter = 0;
//This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (4600);
  //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  Serial.println (counter);
}

void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
    counter--;
  } else {
    counter++;
  }
}

```

Python code:

```
import pyfirmata
import serial
import time

#Associate pyfirmata with python for my UNO board
port='COM5'
board= pyfirmata.Arduino(port)
#Use iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start()

#Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
outPin1 = 12 #passes the signal to the valve

s = serial.Serial('COM4',4600)
while time<60s #generalized:
    rotary = s.readline() #reads the counter of the rotary encoder form arduino

    #convert the rotary to an integer try/except is needed to work
    try:
        var = long(rotary)
        last_var = var
    except:
        var = last_var
        pass

    value1 = lickpin.read()

    # Here I move the cursor up and down depending on the rotation of the encoder
    # if the cursor moves above a certain value
    if y>-18:
        board.digital[12].write(1) #should open the valve

```

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

# Answer
> -1 votes
I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).

Here is the pinout:

```
ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

```

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :

```
/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}

```

---
Tags: serial, arduino-mega, python, rotary-encoder, firmata
---


title: Capturing avrdude command in IDE

text:
# Question
Title: Capturing avrdude command in IDE
With verbose upload selected the IDE provides the executed avrdude command at the top of the log.

I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.

Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?

# Answer
> 2 votes
If you run the IDE from a terminal you should get the output to STDOUT in your terminal to do with what you want.

---
Tags: arduino-ide, command-line
---


# Question
Title: LCD is not printing strings, only integers with Arduino
As mentioned in the title I'm facing a problem in printing strings in the LCD. It's printing actually weird characters.

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);

  lcd.print("hello, world!");
}
void loop() {

 lcd.setCursor(0, 1);
  lcd.print(millis()/500);
}

```

You can find the output of the LCD in the picture below:

# Answer
> 1 votes
Whenever I use an LCD display I make sure to use the I2C backpack. It takes actual effort to hook it up wrong if you use them. So if this were me, I would desolder all those pins and get one.

Here is a good description of how they work: https://learn.adafruit.com/i2c-spi-lcd-backpack/overview

---
Tags: arduino-uno, serial, programming, arduino-ide, lcd
---


# Question
Title: Why is my transistor always transmitting?
I want to use a transistor to turn on and of an electric magnet, I have hooked up a transistor like this:

simulate this circuit – Schematic created using CircuitLab

The blue wire goes to the magnet and the white wire goes to the ground:

Regardless of if the arduino is on or off(I can even unplug port 12 from the arduino, the magnet is still on, the circuit never closes. What do I need to do to make the transistor turn off?

# Answer
Darlington transistors are *very* sensitive; even putting your hand near it can be enough to turn it on. Either tie the base to ground with a large resistor or switch to a MOSFET with its gate tied to ground through same. In either case put a diode backwards across the coil to absorb the energy from the coil when it de-energizes so that the transistor is not damaged.
> 1 votes

---
Tags: power, transistor
---


# Question
Title: Having problems compiling this code for NRF24l01 on arduino uno and arduino micro
I have the library RF24 and everything in my arduino library but for some reason it's not compiling. I don't know why. I posted the code and also the error message that the arduin IDE keeps showing. Please help me figure out whats wrong!

```
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Uno"

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_register(unsigned char, unsigned char*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_register(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write_register(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::openReadingPipe(unsigned char, unsigned long long)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setAutoAck(bool)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setAutoAck(unsigned char, bool)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read_payload(void*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::flush_rx()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getDynamicPayloadSize()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::flush_tx()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::get_status()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::available(unsigned char*)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_status(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_observe_tx(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_byte_register(char const*, unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::print_address_register(char const*, unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::RF24(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setChannel(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setPayloadSize(unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getPayloadSize()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::stopListening()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::powerDown()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::powerUp()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::write(void const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::available()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::read(void*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::whatHappened(bool&, bool&, bool&)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::openWritingPipe(unsigned long long)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::startListening()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::toggle_features()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::enableDynamicPayloads()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::enableAckPayload()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::writeAckPayload(unsigned char, void const*, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::isAckPayloadAvailable()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::isPVariant()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::testCarrier()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::testRPD()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getPALevel()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setDataRate(rf24_datarate_e)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getDataRate()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setCRCLength(rf24_crclength_e)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::getCRCLength()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::printDetails()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::disableCRC()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::setRetries(unsigned char, unsigned char)'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\RF24-master\RF24.cpp.o (symbol from plugin): In function `RF24::csn(bool)':

(.text+0x0): multiple definition of `RF24::begin()'

libraries\RF24ArduinoCommunicator-master\RF24.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

Multiple libraries were found for "nRF24L01.h"
 Used: C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
 Not used: C:\Users\Owner\Documents\Arduino\libraries\RF24-master
exit status 1
Error compiling for board Arduino/Genuino Uno.

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

```

Example I tried to compile:

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

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

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

//
// Hardware configuration
//

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

RF24 radio(9,10);

//
// Topology
//

// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

//
// Role management
//
// Set up role.  This sketch uses the same software for all the nodes
// in this system.  Doing so greatly simplifies testing.
//

// The various roles supported by this sketch
typedef enum { role_ping_out = 1, role_pong_back } role_e;

// The debug-friendly names of those roles
const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};

// The role of the current running sketch
role_e role = role_pong_back;

void setup(void)
{
  //
  // Print preamble
  //

  Serial.begin(57600);
  printf_begin();
  printf("\n\rRF24/examples/GettingStarted/\n\r");
  printf("ROLE: %s\n\r",role_friendly_name[role]);
  printf("*** PRESS 'T' to begin transmitting to the other node\n\r");

  //
  // Setup and configure rf radio
  //

  radio.begin();

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

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

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

  // This simple sketch opens two pipes for these two nodes to communicate
  // back and forth.
  // Open 'our' pipe for writing
  // Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)

  if ( role == role_ping_out )
  {
    radio.openWritingPipe(pipes[0]);
    radio.openReadingPipe(1,pipes[1]);
  }
  else
  {
    radio.openWritingPipe(pipes[1]);
    radio.openReadingPipe(1,pipes[0]);
  }

  //
  // Start listening
  //

  radio.startListening();

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

  radio.printDetails();
}

void loop(void)
{
  //
  // Ping out role.  Repeatedly send the current time
  //

  if (role == role_ping_out)
  {
    // First, stop listening so we can talk.
    radio.stopListening();

    // Take the time, and send it.  This will block until complete
    unsigned long time = millis();
    printf("Now sending %lu...",time);
    bool ok = radio.write( &time, sizeof(unsigned long) );

    if (ok)
      printf("ok...");
    else
      printf("failed.\n\r");

    // Now, continue listening
    radio.startListening();

    // Wait here until we get a response, or timeout (250ms)
    unsigned long started_waiting_at = millis();
    bool timeout = false;
    while ( ! radio.available() && ! timeout )
      if (millis() - started_waiting_at > 200 )
        timeout = true;

    // Describe the results
    if ( timeout )
    {
      printf("Failed, response timed out.\n\r");
    }
    else
    {
      // Grab the response, compare, and send to debugging spew
      unsigned long got_time;
      radio.read( &got_time, sizeof(unsigned long) );

      // Spew it
      printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time);
    }

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

  //
  // Pong back role.  Receive each packet, dump it out, and send it back
  //

  if ( role == role_pong_back )
  {
    // if there is data ready
    if ( radio.available() )
    {
      // Dump the payloads until we've gotten everything
      unsigned long got_time;
      bool done = false;
      while (!done)
      {
        // Fetch the payload, and see if this was the last one.
        done = radio.read( &got_time, sizeof(unsigned long) );

        // Spew it
        printf("Got payload %lu...",got_time);

        // Delay just a little bit to let the other unit
        // make the transition to receiver
        delay(20);
      }

      // First, stop listening so we can talk
      radio.stopListening();

      // Send the final one back.
      radio.write( &got_time, sizeof(unsigned long) );
      printf("Sent response.\n\r");

      // Now, resume listening so we catch the next packets.
      radio.startListening();
    }
  }

  //
  // Change roles
  //

  if ( Serial.available() )
  {
    char c = toupper(Serial.read());
    if ( c == 'T' && role == role_pong_back )
    {
      printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");

      // Become the primary transmitter (ping out)
      role = role_ping_out;
      radio.openWritingPipe(pipes[0]);
      radio.openReadingPipe(1,pipes[1]);
    }
    else if ( c == 'R' && role == role_ping_out )
    {
      printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");

      // Become the primary receiver (pong back)
      role = role_pong_back;
      radio.openWritingPipe(pipes[1]);
      radio.openReadingPipe(1,pipes[0]);
    }
  }
}

```

# Answer
> 3 votes
You have multiple copies of the library.

Delete the folder located at:

```
C:\Users\Owner\Documents\Arduino\libraries\RF24ArduinoCommunicator-master

```

---
Tags: arduino-uno, nrf24l01+, arduino-micro
---


title: strtok problem while parsing String

text:
# Question
Title: strtok problem while parsing String
Here is my code. The incoming string is "\*CRB12344,Temp25,Humidity55,CC5#"

I am unable to get value of Temp which is 25 and Humidity which is 55 and CC which 5. It only display the value of CR i.e B12344 (in this case). May be issue with strtok function?

```
String inputString = "";
boolean stringComplete = false, StartCapturing = false;

char inData[50];
char inChar, IncomingWeight;
char IncomingString[50];
const int httpPort = 80;

char *i, *k,*p;
String CardID;
int Temprature, Humidity, TC, CC;
byte SendData = 0;

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

void loop()
{
  serialEvent();

  if (stringComplete)
  {
    inputString.toCharArray(IncomingString, 50);
    Serial.println();
    Serial.println(IncomingString);

    i = strstr(IncomingString, "CR");
    {
      if (i)
      {
        p = i+2;
        CardID = strtok(p, ",");

        Serial.print("Card Number :");
        Serial.print(CardID);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Temp");
    {
      if (i)
      {
        Temprature = strtoul(i + 4 , NULL, 10);
        Serial.print("Temprature :");
        Serial.print(Temprature);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "Humidity");
    {
      if (i)
      {
        Humidity = strtoul(i + 8 , NULL, 10);
        Serial.print("Humidity :");
        Serial.print(Humidity);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "TC");
    {
      if (i)
      {
        TC = strtoul(i + 2 , NULL, 10);
        Serial.print("Total Count :");
        Serial.print(TC);
        Serial.println();
      }
    }

    i = strstr(IncomingString, "CC");
    {
      if (i)
      {
        CC = strtoul(i + 2 , NULL, 10);
        Serial.print("Current Count :");
        Serial.print(CC);
        Serial.println();

      }
    }

    stringComplete = false;
    inputString = "";
    delay(10);
  }

```

# Answer
`strtok()` is a destructive function. It replaces the token with an end-of-string marker (`\0`). Thus once used the original string is irevocably lost.

Your first use of `strtok()` changes the string from:

```
*CRB12344,Temp25,Humidity55,CC5#\0

```

to:

```
*CRB12344\0Temp25,Humidity55,CC5#\0

```

Thus any future references to `InputString` only see up to the end-of-string marker:

```
*CRB12344\0

```

Instead you should use `strtok()` in a `while` loop to slice the string into tokens and examine what the token is:

```
char *tok = strtok(IncomingString, ",");
while (tok) {
    if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
        // ... whatever ...
    } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
        // ... whatever ...
    } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
        // ... whatever ...
    } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
        // ... whatever ...
    }
    tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}

```
> 3 votes

---
Tags: serial, programming, string
---


# Question
Title: Arduino Pro Mini RESET button suddenly stopped working
I am powering my Pro Mini(3.3V version) using an external battery (~6.5V 700mA) . I used to connect it to the RAW and GND pins on my pro mini and everything ran fine.

Today when I powered up my Arduino again, it didn't light up. A quick glance told me that I had connected the battery to the RST and GND pins mistakenly. Quickly pulled them out and put them into place, the Arduino worked perfectly until I discovered that the RESET button is no longer working. Without the RESET button I can't upload anything to my board.

Tried connecting the RST and GND Pins, didn't work.

The board is working fine though, I discovered a new procedure to upload as follows-
NOTE: I use the USB-to-TTL adapter by DSUN (picked up at a local electronics store).

1. Connect the RX, TX and GND Pins from the adapter to the Pro Mini.
(The green LED on the Pro Mini lights up dimly)
2. Upload the sketch from the IDE.
3. As soon as the IDE shows "Uploading", connect the +5V pin from the adapter to RAW pin on Pro Mini. Upload goes fine.

The above procedure is working just fine, and the board as well. But I'd like to have my RESET button back.
So what do I do?

# Answer
> 1 votes
What do you do? You replace the chip on the board.

By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.

It's dead, Jim.

Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).

---
Tags: arduino-ide, uploading, arduino-pro-mini, reset
---


# Question
Title: Speed of comunication by SI4463 under RH_RF24.h
As in this SO question, I use use a RH\_RF24.h to control an SI4463. In RH\_RF24, there is not anything about the speed of communication. I need the way to control the speed of communication. Because I want to take high speed of communication when Rssi is strong and slow speed when weak (for reliability).

How should I to do it ?

# Answer
> 1 votes
According to RH\_RF24.h `setModemRegisters` takes a `ModemConfig` struct. `prop_2003`, `prop_2004` and `prop2005` are part of that struct and it's the value of these 3 bytes that sets the datarate.

Datarate is a **24bit unsigned value** (hence the 3 bytes in the struct). `prop_2003` is the **MSB** and `prop_2005` the **LSB**.

* `prop_2003` default is `0x0F`
* `prop_2004` default is `0x42`
* `prop_2005` default is `0x40`

meaning the default data rate is `0x0F4240` ( = 1Mbps)

This application note on the API gives more details (around page 99).

---
Tags: library, communication, wireless, rf
---


# Question
Title: How to use different device address for MCP23017 so I can use multiple chips?
I want to use more than 3 MCP23017-E/SP DIP28 chips so I can use many digital pins. I use Adafruit-MCP23017-Arduino-Library. I tried this solution but only device address with 0x00 is working.

**The question is** what device address should I use for additional chip?

```
#include "Adafruit_MCP23017.h"
Adafruit_MCP23017 mcp1;
#define addr1 0 // tested 1,2,3,4,5, 0x01, 0x02, 0x20, 0x21 but only 0 and 0x00 is working.
void setup()
  {
    mcp1.begin(addr1);
    mcp1.pinMode(0, INPUT); //pin 21 on chip
    Serial.begin(9600);
  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
  }

```

# Answer
I share my solution with 7 MCP23017 chip , 7x14 pins=98 pins using adafruit library.

**Connections:**

```
addr 0 = A2 low , A1 low , A0 low  000
addr 1 = A2 low , A1 low , A0 high 001
addr 2 = A2 low , A1 high , A0 low  010
addr 3 = A2 low , A1 high , A0 high  011
addr 4 = A2 high , A1 low , A0 low  100
addr 5 = A2 high , A1 low , A0 high  101
addr 6 = A2 high , A1 high , A0 low  110
addr 7 = A2 high, A1 high, A0 high 111

Connect pin #12 of the expander to Analog 5 (i2c clock)
Connect pin #13 of the expander to Analog 4 (i2c data)
Connect pins #15, 16 and 17 of the expander to ground (address selection)
Connect pin #9 of the expander to 5V (power) // operation voltage is 1.8 to 5.5
Connect pin #10 of the expander to ground (common ground)
Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)

Input #0 is on pin 21 so connect a button or switch from there to ground

```

**Code:**

```
#include <Adafruit_MCP23017.h>

Adafruit_MCP23017 mcp1; // chip 1
Adafruit_MCP23017 mcp2; // chip 2

#define addr1 7 // 7 = A2 high, A1 high, A0 high
#define addr2 0 // 0 = A2 high, A1 high, A0 high
void setup()
  {
    Serial.begin(9600);
    mcp1.begin(addr1);
    mcp2.begin(addr2);

    mcp1.pinMode(0, INPUT); //pin 21 on chip
    mcp2.pinMode(0, INPUT); //pin 21 on chip

  }

  void loop()
  {
      if(mcp1.digitalRead(0)== HIGH )
      Serial.println("HIGH");
      delay(1000);

      if(mcp2.digitalRead(0)== HIGH )
      Serial.println("HIGH 2");
      delay(1000);
  }

```
> 0 votes

---
Tags: arduino-mega, programming, c++, library
---


title: Measure voltage of data output?

text:
# Question
Title: Measure voltage of data output?
I'm trying to control a few NeoPixels using a 3.3V Particle Photon.

I've got a 5V power source that I'm using to power the NeoPixels (as they require that voltage. That works fine.

Them I'm using a 74AHCT125 level shifter to increase the data signal from the Photon from 3.3 to 5.

But I'm seeing sporadic response from the NeoPixels and my hunch is there's something wrong with the power output from the 74AHCT125.

Is there a way I can measure the voltage from the data output of the 74AHCT125? I tried connecting the wire from the 74AHCT125 to my multimeter but I'm not getting any measurement from it.

# Answer
The reason your mulitmeter is not telling you much is probably because it reads some sort of averaged voltage, and your signal is flipping between low and high very rapidly.

If you had an oscilloscope you could easily have a look and see what the peak-to-peak voltage is, but since you don't you'll have to find another way.

If you have some basic electronic components at your disposal, you could knock up a simple peak voltage front-end for your multimeter - this looks like roughly the right thing. You'll need to calibrate it with a known 5v level (i.e. see what reading your meter tells you for a fixed 5v supply) because you'll drop some voltage across the diode.

Otherwise perhaps you could use an analogue input of a 5v Arduino: write a simple sketch to measure (very rapidly!) and tell you the maximum reading every second, say. I don't know off hand how fast the Uno will sample, or the clock rate of your Neopixels - you'll need the Arduino to sample at least as fast as your clock rate.

For the purpose of a quick hassle-free check, I'd probably plump for the first option.
> -1 votes

---
Tags: power, voltage-level, digital
---


# Question
Title: Arduino Web Server: Receiving response from web form
I am using an Arduino Mega and I have a basic webpage built using `EthernetServer` for the connection and `EthernetClient` to write the HTML to the client. I have a simple web form:

```
client.println("<form method=get>");
client.println("<input type=text name=data>");
client.println("<input type=submit value=Submit>");
client.println("</form>");

```

I'd like to receive any input from the form and check it against values in order to do stuff on the back end (e.g. reset certain data). How do I get the data from the web page?

# Answer
Your form method is set to `GET`. In this case, when `Submit` is clicked, the client/browser sends request with values in URI:

```
GET /index.html?data=user_value&default_name_of_button=Submit HTTP/1.1
...more lines to follow...

```

These HTTP header lines will be available on your `EthernetClient` instance, retrieve them line-by-line using connected(), available(), read() methods. Then parse the line, find the `user_value`.

Please note that browser retrieves your page (to display it) using `GET` method too, in that case URI will be like:

```
GET /index.html HTTP/1.1
...more lines to follow...

```

It is recommended to use `POST` method to submit form values. Example content section (before content, server must send HTTP header - check Arduino Web Server example)

```
<form method="POST" action="foo.php">

First Name: <input type="text" name="first_name" /> <br />
Last Name: <input type="text" name="last_name" /> <br />

<input type="submit" name="action" value="Submit" />

</form>

```

In this case the values are returned in content section:

```
POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43

first_name=John&last_name=Doe&action=Submit

```

Tutorial on HTTP headers:

https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039
> 2 votes

---
Tags: arduino-mega, ethernet, web-server
---


# Question
Title: How to make RGB LED blink rapidly one color using FOR or WHILE loop
I found a code that turns on different RGB colors but I would like it to blink rapidly one color once called. I dont want to use void loop function to make this possible. My RGB is a cathode. Any help?

```
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
    for (int j = 0; j <= 10; j++) //LED simply stays on. No blinking occuring
     {
      setColor(255, 0, 0);
      delay(100);
      setColor(0, 0, 0);
        }
}

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

```

# Answer
> 1 votes
Simply do this:

```
int redPin = 8;
int greenPin = 9;
int bluePin = 10;

//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE

void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
  blinkLed();
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

void blinkLed()
{
  setColor(255, 0, 0);  // red
  delay(1000);
  setColor(0, 0, 0);  // off
  delay(1000);
}

```

This snippet will blink your led in the red color. Put it in your void loop and you are ready to go.

NOTE: Erase the rest of the void loop before putting this in. Don't delete the function though.

**EDIT**

FULL CODE ADDED

---
Tags: rgb-led
---


title: 2d 3*3 LED matrix code error

text:
# Question
Title: 2d 3*3 LED matrix code error
I have written a trivial code in Arduino IDE but while verifying its returning a error displaying "i was not declared in scope 12'

```
  int pinMatrix[i][j]= {{2,3,4},{5,6,7},{7,8,9}};
void setup() {
for (i=0;i<3;i++){
  for(j=0;j<3;j++){
    pinMode(pinMatrix[i][j],OUTPUT);
  }
}

}

void loop() {
for(i=0;i<3;i++){
  for(j=0;j<3;j++){
      digitalWrite(pinMatrix[i][j],HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j],LOW);
  }

  }

}

```

# Answer
Variable `i` & `j` are not declared. They should be declared as 3. Try this:

```
const int x = 3;
const int y = 3;

int pinMatrix[x][y] = {{2, 3, 4}, {5, 6, 7}, {7, 8, 9}};

void setup() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      pinMode(pinMatrix[i][j], OUTPUT);
    }
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      digitalWrite(pinMatrix[i][j], HIGH);
      delay(1000);
      digitalWrite(pinMatrix[i][j], LOW);
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to create a smooth change in voltage?
We are given two voltages A and B between 0 and 5V. So how do I generate a smooth/continuous analog change in voltage from A to B in a predefined time? The current with that varying voltage is 1 ma or less. The output voltage value is described by a simple quadratic (a*X^2)+(b*x)+c, at time x seconds.

If that not possible using an Arduino - what is the nearest solution to it? It seems that it would require an RC circuit?

When I mean smooth/continous I mean it doesn't move in "digital steps" or to use an analogy with resistance instead of voltage - it would be like the way resistance changes when a potentiometer is turned between two places, in a given time, by hand.

A potential solution would be to make a circuit that generate arbitrary voltage between 0 and 5v, some how, at a point in time. For each subsequent small change in time, the change in time is constant, generate the desired voltage from a sketch. If the change of time is small and constant, will putting in a high pass RC filter work? Though I'm not sure of a circuit that can create an arbitrary voltage, or arbitrary voltage resolution or how good the RC filter approximates the quadratic smoothness. I don't know the answer.

# Answer
I'm not sure that there exists a perfect solution for what you want. Generating the correct output voltage for time is easy. Just keep track of time and use the formula you wrote to compute the correct voltage you should be at. Then you can use a PWM output. However, this isn't going to be perfect since it is made with pulses rather than a continuous output. On the Uno the pulses are at 490Hz or 980Hz depending on which pin you use. Use an RC filter and you can then make it continuous - when you tell it output 2.5V you get 2.5V rather than 0 then 5 then 0 then 5 in short bursts. But, you're still going to get discrete steps based on the resolution of the ADC - for an Arduino Uno, it's 255 steps I believe. You could get a separate DAC chip to increase this and can probably get enough steps that their small enough you won't notice. Some versions of the arduino like the due have 12bit analog output and higher frequency, which should help.
> 1 votes

---
Tags: arduino-uno, voltage
---


# Question
Title: How to use ESP8266-12E with PCF8574 as an I/O extender
I am using ESP8266-12E with a PCF8574 as an I/O Pins Extender. There are videos on youtube to use the PCF8574 with an ESP8266-01, but my problem is that I'm unable to analyze the pin connections with an ESP8266-12E. In the youtube tutorial it is said that the *GPIO0* AND *GPIO2* will go to the *SDA* and *SLC* pins of the PCF8574, but then, in the case of ESP8266-12E, the pins will go to the PCF8547.

Thanks in advance.

# Answer
> -1 votes
Found the answer . The data sheet of ESP8266-12E explains everything. The pin diagram has the given tags which shows which pins we can use.

---
Tags: arduino-uno, esp8266, wifi
---


title: PCF8547 Wire.write explanations

text:
# Question
Title: PCF8547 Wire.write explanations
I am using an ESP8266-12E with a PCF8547. I have managed to turn on and turn off LEDs using these two things. I am using these three commands to do it.

```
 Wire.begin(SDA_PIN,CLK_PIN);
 Wire.beginTransmission(0x20);
 Wire.write(~((uint8_t)1<<cnt));
 Wire.endTransmission();

```

The problem I am facing here is: I am using 4 LEDs and I am only able to turn on one LED at a time. When I turn on another, all the LEDs turn off - in short, the LEDs or the PCF8547 do not preserve the state.

I want to toggle on the LEDs without disturbing the other's state. How can I do it?
I think, I need more knowledge about the write function, don't I?

**Update:**

I have already connected A0, A1, A2 to ground. This is the function I use now to toggle the LEDs.

```
void enlight(int cnt)
{
  if (cnt == 1)
    value = value | 1<<cnt;
    if (cnt == 2)
      value = value | 2<<cnt;
    if (cnt == 3)
      value = value | 3<<cnt;
    if (cnt == 4)
      value = value | 4<<cnt;
    value = ~value;
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20); Wire.write(value);
    Wire.endTransmission();
  }

```

but when I turn off/on any other LEDs they also toggle, which I don't want.

# Answer
(I haven't used this library, but this looks like a general C(++) question...)

The important part of what you're doing is this:

```
Wire.write(~((uint8_t)1<<cnt));

```

Let's break it down.

It calculates a value by taking the number `1` and shifting it left `cnt` times. Then it takes the complement of that number - changes 0s to 1s and 1s to 0s. This number is sent to Wire.write() and lights up light number `cnt`.

Example: Let's say you start with `cnt==2`, to light LED 2. It will shift the number `1` left by two digits, giving you the binary number `00000100`. Then it will invert this, giving you `11111011`. This is given to Wire.write().

We can see from this that to light an LED, we need to put a '0' in the right place.

How can you make several numbers light up? We need to put several zeros in, at the right places.

Here's an example of how you might like to do this - which isn't the prettiest code but I hope it shows you what's going on.

```
// How we would like the LEDs to appear
boolean led0 = true;    // LED 0 ON
boolean led1 = false;   // LED 1 OFF
boolean led2 = true;    // LED 2 ON
boolean led3 = false;   // LED 3 OFF

// Start with all LEDs off
uint8_t value = 0;

// Put a 1 in place for each LED we want to be ON
// The | symbol means "logical OR" (Google it)
if (led0) value = value | 1<<0;
if (led1) value = value | 1<<0;
if (led2) value = value | 2<<0;
if (led3) value = value | 3<<0;

// Invert this value
value = ~value;

// Write it to Wire
Wire.begin(SDA_PIN,CLK_PIN);
Wire.beginTransmission(0x20);
Wire.write(value);
Wire.endTransmission();

```

Since it appears you have to send values for all the lights every time, you need to remember the value you sent last time, and modify only the bits you want to change. Here's a way you can do that:

```
void setLight(int lightNum, boolean lightOn) {
  // Remember the last state of the lights.
  // Start with all lights OFF.
  static uint8_t lightsOn = 0;

  // We only have four lights (0-3).  Only respond for lights
  // we we have.
  if (lightNum<4) {
    // Get a bitmask with a single 1 in the right
    // position for this light
    uint8_t position = 1<<lightNum;

    // Clear (to 0) that bit in the state
    lightsOn &= ~position;

    // Set (to 1) the bit if we want the light on
    if(lightOn) lightsOn |= position;

    // Write out the value of all lights
    Wire.begin(SDA_PIN,CLK_PIN);
    Wire.beginTransmission(0x20);
    Wire.write(~lightsOn);
    Wire.endTransmission();
  }
}

```

Call it with something like

```
setLight(0, true);    // Switch the first light ON
setLight(3, true);    // Switch the fourth light ON (first stays on)
setLight(0, false);   // Switch the first light OFF (fourth stays on)

```
> 1 votes

---
Tags: esp8266, pins, code-optimization
---


# Question
Title: Why is my class losing a field in the middle of a method
I have a class with a byte (stripLength) that seems to just disappear in the middle of the frameStep() method. I'm not especially skilled with C++ (or non-VM languages in general), but I believe it's only written or modified at the initialization of the class. What am I doing wrong?

BugFinding.ino

```
#define PIN 11
#define NUM_LEDS 100
#define WAIT 5
#define TAIL_LENGTH 40

#include "Libraries/Adafruit_NeoPixel.h"
#include "LightingStrip.h"

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_RGB + NEO_KHZ800);
LightingStrip lightStrip = LightingStrip(strip, NUM_LEDS, 20);

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    Serial.println("BugFinding");
    lightStrip.setColors();
}

void loop() {
    Serial.println("loop");
    lightStrip.frameStep();
    lightStrip.write();
    delay(WAIT);
}

```

LightingStrip.h

```
#ifndef LIGHTINGSTRIP_H_
#define LIGHTINGSTRIP_H_

#include "Libraries/Adafruit_NeoPixel.h"

class LightingStrip {
    public:
        LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t stripLength, uint8_t lengthOfTail);
        void frameStep();
        void write();
        void setColors();
    protected:
        Adafruit_NeoPixel strip;
        uint8_t mode;
        uint8_t frame;
        uint8_t colorFrame;
        uint8_t stripLength;
        uint8_t tailLength;
        uint32_t buf[];
        uint32_t colors[7];
        uint8_t currentColor[3];

        void cycleStep();
};

#endif /* LIGHTINGSTRIP_H_ */

```

LightingStrip.cpp

```
#include "LightingStrip.h"
#include "Libraries/Adafruit_NeoPixel.h"

LightingStrip::LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t length, uint8_t lengthOfTail) {
    strip = ledStrip;
    stripLength = length;
    tailLength = lengthOfTail;

    buf[stripLength] = {0};
    colorFrame = 0;

    cycleStep();
}

void LightingStrip::setColors(){
    //colors = uint8_t[8][3];
    colors[0] = strip.Color(255, 120,   0); // Orange
    Serial.println("Color 0: " + String(colors[0]));
    Serial.println("Color 0: " + String(strip.Color(255, 120,   0)));
    Serial.println("stripLength: " + String(this->stripLength));
    colors[1] = strip.Color(  0, 255,   0); // Green
    Serial.println("setColors");
    Serial.println("stripLength: " + String(stripLength));
}

void LightingStrip::cycleStep(){
    frame = 0;
    colorFrame++;
}

void LightingStrip::frameStep(){
    Serial.println("frameStep");
    Serial.println("Color 0: " + String(colors[0]));
    int16_t j;
    Serial.println("frame: " + String(frame));
    Serial.println("colorFrame: " + String(colorFrame));
    Serial.println("stripLength 1: " + String(stripLength));
    if(frame > stripLength + tailLength)
        cycleStep();
    Serial.println("stripLength 1.2: " + String(stripLength));

    for(j=0; j<stripLength; j++){
        buf[j] = strip.Color(255,255,255);
    }
    Serial.println("stripLength 2: " + String(stripLength));
    for(j=frame; j>0 && frame-j<=stripLength; j--){
        if(j>stripLength) continue;
        buf[j] = colors[colorFrame];
        Serial.print("j: " + String(j));
        Serial.print(" color: " + String(colors[colorFrame]));
        Serial.println();
    }
    Serial.println("stripLength 3: " + String(stripLength));
    Serial.println("stripLength 4: " + String(stripLength + tailLength));
    Serial.println("stripLength 5: " + String(stripLength));

    frame++;
}
void LightingStrip::write(){
    Serial.println("write");
    Serial.println("stripLength: " + String(stripLength));

    int16_t j;

    for(j=0; j<stripLength; j++){
        Serial.print(" j: " + String(j));
        strip.setPixelColor(j, buf[j]);
    }
    Serial.println();
    Serial.println(String(buf[0]));
    Serial.println(String(strip.getPixelColor(0)));
    strip.show();
}

```

Serial Output:

```
BugFinding
Color 0: 16742400
Color 0: 16742400
stripLength: 100
setColors
stripLength: 100
loop
frameStep
Color 0: 16742400
frame: 0
colorFrame: 1
stripLength 1: 100
stripLength 1.2: 100

```

# Answer
At first glance this looks like a sketch with typical memory (heap) issues. When using a lot of string literals, `String` variables and expressions heap memory becomes fragmented or simple exhausted.

Some programming rules to avoid this:

1. If possible use the macro `F()` with string literals. Typically `F()` should be used when printing a string.
2. If possible do not use `String` especially when there is limited amount of SRAM. Remember that ATmega328 based boards such as Arduino Uno, Nano, etc, have only 2 Kbyte SRAM.
3. Avoid `String` expressions especially in `Serial` print statements. Use several print statements instead.

Applying these programming rules to some of the statements in the code above:

```
Serial.println("frameStep");
Serial.println("Color 0: " + String(colors[0]));
Serial.println("frame: " + String(frame));

```

Becomes:

```
Serial.println(F("frameStep"));
Serial.print(F("Color 0: "));
Serial.println(colors[0]);
Serial.print(F("frame: "));
Serial.println(frame);

```

With no `String` expressions, and a lot less memory used.

Cheers!

PS: As @MarkSmith points out there is also a pure allocation error. The statement below in the `LightingStrip` constructor:

```
buf[stripLength] = {0};

```

Does not mean allocate and assign. It means element `stripLength` is assigned the value of the pointer to an array with the single value zero. Guess that the compiler is also warning about this. The value of `buf` is random as it is not initiated. Assigning an element in the `buf` will write to a random position.
> 0 votes

# Answer
I think what you mean by stripLength "disappearing" is that your `stripLength 2` trace does not appear. This is going to be because you never reach this point in the code.

Look at `buf`: it's defined as an array in the .h file, but you don't ever allocate any memory for it. `buf[stripLength] = {0}` doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to. You want something like

```
buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

```

Remember to free it again in the destructor.

(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as `uint32_t buf[]`. It's more common, and certainly legal, to use `uint32_t* buf`.)
> 0 votes

---
Tags: c++, class
---


# Question
Title: Getting an error while uploading a code to the Arduino when ethernet shield is attached
I bought ethernet Shield today and connected it to Arduino Uno, now when I try to upldoad I get the following error, however if I remove the shield from the UNO it works fine.

```
Sketch uses 10,486 bytes (32%) of program storage space. Maximum is 32,256 bytes.
Global variables use 661 bytes (32%) of dynamic memory, leaving 1,387 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

```

Is it something wrong with he ethernet shield ? Ethernet is not plugged in but even when i plug in the ethernet wire the indicators at Jack does not lit up

# Answer
I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.
> 0 votes

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


title: Read signal from co-ax cable with ADC

text:
# Question
Title: Read signal from co-ax cable with ADC
I have an Arduino Uno and I'd like to read a signal from a co-ax cable with it. The cable carries 12VDC (power for other components) along with a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? I'm new to this field so I don't know the full capabilities of the ADC. Also, the Uno can't handle \>5 VDC, so what should I do to make the signal readable?

# Answer
It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.

Also the 1GHz signal itself is of no interest to you. What is of interest is what is *modulated* on the 1GHz signal.

What is normally done is:

1. Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
2. Demodulate the signal using whatever modulation scheme was used to encode it.
3. Extract the encoded information from the demodulated signal.

To do that you'd need

1. the precise carrier frequency (1GHz is not the same as 1.029GHz)
2. the modulation scheme used (there's loads to choose from)
3. knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.

So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.
> 2 votes

---
Tags: rf, adc
---


# Question
Title: Debugging library - Error- expected unqualified id before '.' token
I'm writing a library for my project, which interfaces sensors used and structures them in different systems.

But I'm such a noob at C++. The compiler is throwing this error:

```
libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
_Sluz.Update();

```

This is the header of that class:

```
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    class _Sluz;
    class _SDHT;
};

```

This are the member functions affected:

```
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
    //Systems to initialize
    LDR _Sluz(luzpin);      //analogpin
    DHT11 _SDHT(dhtpin);    //buspin
}
void Habitaculo::Update(){
    _CurrentMillis = millis();
    if (_CurrentMillis-_PreviousMillis > _RefreshRate){
        _Sluz.Update();  //unqualified-id before '.' token
        _SDHT.Update();  //unqualified-id before '.' token
        temp = _SDHT.temp;  //expected primary-expression before '.'
        hum = _SDHT.hum;  //expected primary-expression before '.'
        luz = _Sluz.value;  //expected primary-expression before '.'
        _PreviousMillis = _CurrentMillis;
    }
}

```

The error is thrown in every step of the `Update` method. But I can copy that piece of code right in the `Habitaculo` constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.

Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

# Answer
From what I guess in your code, here is how you want your class declared:

```
class Habitaculo
{
    public:
    Habitaculo(int refrate, int luzpin, int dhtpin);
    //Values from Indoor Sensors
    int temp;
    int hum;
    int luz;
    //Update Methods
    void Update();      //Updates sensors value
    void UpdateReg();   //writes to SD or enabled output method
    private:
    //Clock Managing
    long _PreviousMillis;
    unsigned long _CurrentMillis;
    int _RefreshRate;
    //Sensor instances
    LDR _Sluz;
    DHT11 _SDHT;
};

```

Of course, in your header file, you will have to `#include` the proper header files for `DHT11` and `LDR` classes.

Then you will need to change your constructor as follows:

```
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_Sluz(luzpin), _SDHT(dhtpin)
{
    //Clock management
    _RefreshRate = refrate;
    _PreviousMillis = 0;
}

```

Note the `:_Sluz(luzpin), _SDHT(dhtpin)` line before the constructor body, in C++, this is how members of your class that are instances of another class must be instantiated.

Actually, you could even empty the whole cosntructor body by also initializing `_RefreshRate` and `_PreviousMillis` in the same manner:

```
Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
:_PreviousMillis(0), _RefreshRate(refrate), _Sluz(luzpin), _SDHT(dhtpin) {}

```

which is a bit more idiomatic C++.
> 0 votes

# Answer
```
class _Sluz;
class _SDHT;

```

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.

I think you are lacking a bit of basic syntax knowledge there. You may have meant:

```
Sluz _Sluz;
SDHT _SDHT;

```

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.
> 1 votes

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


title: Atmega32u4 external 8MHz clock

text:
# Question
Title: Atmega32u4 external 8MHz clock
Does anyone know how to configure the Atmega32u4 to run using an external 8MHz oscillator ?

I needs to still be responsive to the Arduino IDE

Thanks

# Answer
See §28.2 in Atmel-7766-8-bit-AVR-ATmega16U4-32U4\_Datasheet.pdf, which explains usage of various fuse bits.

Also see engbedded.com/fusecalc, which lets you easily figure out fuse settings. Fusecalc also tells you the strings to use as part of avrdude command strings.

Once you know the fuse settings, send them to your device via a command like

```
avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

```

or like

```
avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

```

where `$port` represents a port name like `/dev/ttyUSB0`.

Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to. You can read the fuses via a command like

```
avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i

```
> 1 votes

---
Tags: arduino-leonardo, atmega32u4
---


title: How to use setModemRegisters in RF24

text:
# Question
Title: How to use setModemRegisters in RF24
The below picture is the introduction of setModemRegisters .

* First: What is the mean of **ModemConfig\* config**? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this SO question.
* Second: What is the mean of data rate? It is the speed of SPI between the SI4463 and MCU or speed of two SI4463 ?
* Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .

>

# Answer
**ModemConfig * config** is a pointer to a `ModemConfig` struct.

You need to create a `ModemConfig` struct, populate it then pass a pointer to it in the call to the `setModemConfig()` function.

Something like this:

```
// create the struct
ModemConfig mc = ModemConfig();

... //populate the struct values

// then call the function
setModemConfig(&mc);

```

The **datarate** is the rate at which you are sending information over the radio channel (**not** between the MCU and the Si4463).

The **bandwidth** is the range of frequencies used in the radio transmission (e.g. in FSK if a *low/0* is 99.95MHz and a *high/1* is 100.05Mhz then the bandwidth would be 100Khz)
> 1 votes

---
Tags: library, wireless, rf, arduino-mini
---


# Question
Title: Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?
I want to transmit some values from arduino uno to my phone using bluetooth. Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice ! :)

# Answer
It's not a sensor, its a module. A quite popular module is the HC-05. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.
> 2 votes

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


# Question
Title: Is there a non-float alternative to pow()?
I've scoured the LANGUAGE REFERENCE in the Arduino web-site, and I can't find a non-Float equivalent to `pow()` I've got to be missing something big, but for the life of me, I'm stumped! I found `pow()` in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters, \[base\] and \[exponent\] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024

Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!

# Answer
For the general case, @dat\_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.

Multiplying a number by a power of two can be accomplished by the left shift operation (`<<`), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward. In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see this answer on Stack Overflow.

It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which have a max value of `2^15-1` on Arduino Uno.

Given those caveats, here's a function to calculate powers of two within these constraints. This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.

```
int pow2(int p){
    return 1 << p;
}

```
> 8 votes

# Answer
It works with `int`, `double`, `long` and `float`. `unsigned long` and `unsigned int` should also work. You are not required to use ONLY floats.

Hope it helped!
> 1 votes

---
Tags: variables, float, mathematics
---


# Question
Title: Read time digits from DS1307 and run code based on return
I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using

```
 Serial.print(now.hour(), DEC);
 Serial.print(now.minute(), DEC);
 Serial.print(now.second(), DEC);

```

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.

=======================UPDATE=======================

I am using this code to set any individual digit of the nixie tube to on.

```
       //Turn on 0
 sr.set(4, LOW);
 sr.set(5, LOW);
 sr.set(6, LOW);
 sr.set(7, LOW);

```

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.

# Answer
> 0 votes
You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of `now.hour()/12` and the bits for the low digit of `now.hour()%12`. For example:

```
const byte digiBits[] = { B0000, B0001,
// and so forth for all the digits ...
};

void send1Digit(byte digiVal, byte whichDigit) {
  // somehow use whichDigit to direct the bits someplace...

  // To send the bits:
  byte bits = digiBits[digiVal];
  for (byte i=4; i<8; ++i) {
    sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
    bits >>= 1; // shift out the used bit
  }
}

void send2Digits(byte numVal, byte whichDigit) {
  send1Digit(numVal/10, whichDigit);
  send1Digit(numVal%10, whichDigit+1);
}

void loop() {
  // other stuff, then:
  send2Digits(now.hour(), HourSpot);
  send2Digits(now.minute(), MinuteSpot);
  send2Digits(now.second(), SecondSpot);
  // other stuff ...
}

```

Note 1: If your `sr.set()` routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing `digiBits[digiVal]` with whatever number `sr.set()` might be building up to shift out.

Note 2: If the numerical value of `digiBits[digiVal]` is equal to `digiVal`, then don't bother defining `digiBits[]`, but instead in `send1Digit()` just say `byte bits = digiVal`, or use `digiVal` directly in place of `bits`.

---
Tags: code-optimization, shift-register, oscillator-clock
---


title: Atmega328P 8MHz External Clock

text:
# Question
Title: Atmega328P 8MHz External Clock
Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?

I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

# Answer
If you reduce the main clock speed by 50% then everything else is reduced by 50% as well.

The whole chip runs at half the speed. That includes things like the UART.

For example, the bootloader is set to run at 115200 baud on a 16MHz chip. If you run that same chip, with the same bootloader, at 8MHz then the bootloader will actually be running at half the baud rate, so 115200 / 2 = 57600 baud.

Unless you tell the IDE that your board is now running at 8MHz (by creating or using the correct board configuration information to set F\_CPU to 8000000) then time runs at half the speed in your sketches too. So a delay of one second will last two seconds. Every two milliseconds a single millisecond will pass. And again baud rates will be wrong. If you use:

```
Serial.begin(9600);

```

you will actually be running at half that speed (4800 baud) and so you would have to set your serial terminal program to that speed instead of the one you requested.

To to do things properly you will have to:

1. Replace the crystal
2. Edit, compile, and install a new version of the bootloader that runs at 8MHz
3. Create (or edit) a suitable board definition (in boards.txt) to compile sketches that expect to run at 8MHz.
> 3 votes

# Answer
The easiest way is to use the settings:

**Tools \> Board \> Arduino Pro or Pro Mini**

**Tools \> Processor \> ATmega328 (3.3V, 8MHz)**

The problem with that is the Pro Mini bootloader is 2kB and has a bug that causes an endless reset loop if you do a watchdog reset.

The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.

After selecting the correct configuration for your hardware from the **Tools** menu, do **Tools \> Burn Bootloader**, which will set the fuses on your ATmega328P and upload the correct bootloader.
> 3 votes

# Answer
Firstly, you can buy 8MHz Atmega328P Pro-Minis from China. They are cheap and run at 3.3V. Look at eBay.

If you want to reduce the power consumption of Arduino boards, you have three primary attack vectors:

* Removing the power LED
* Removing the voltage regulator
* A Low-Power library

All of these have different impacts on the power consumption of your respective board.

An extensive comparison can be found here in this blog-post.
> 2 votes

---
Tags: atmega328, oscillator-clock
---


# Question
Title: Powering an Arduino Mega with external USB Power Bank?
**I am making a robot with arduino mega r3. I want to power the arduino with a usb power bank. How should I do that?**

# Answer
I have a "USB power bank" with two USB ports, which I use to power some projects.

I have discovered that my bank (i.e. your mileage may vary!) shuts off unless my project draws at least 50mA. If your project does draw at least that at ALL times, you should just be able to plug a USB cable directly from the powerbank to the project.

For some other projects, I have bought a USB cable (USB A to USB A) which I cut in half, stripped the wires, then used a multimeter set to "Volts" to work out which wire was +5V and which was GND; I connect these straight to the 5V/GND on my project. To make sure at least 50mA was drawn at all times, I put a 100 Ohm resistor from +5V to GND (at LEAST 1/4 watt!!). This obviously wastes a lot of power (turning it into 1/4 watt of heat), but it keeps the power bank "awake". By using a USB A to USB A, I now have two cables.

My power bank also has a "torch" (led) integrated; if the torch is on, it also stays awake.
> 6 votes

# Answer
Powerbank is a term for those external batteries that output USB. Usually used to recharge a phone when you don't have access to wall outlet and USB charger.

Inside powerbank:
Battery (3.7v) --- Some Circuit --- USB female

How to:
You have a bank
You have USB cable
ugh! ...
Plug USB to Arduino and you are (pretty much) done.

For those who use ProMini and/or want to skip the USB port
Cut the USB cable and take the red (+) and black (-).

Put it directly to Vin and Gnd and you are good to go.

*

Unfortunately for us (fortunately for most) most Powerbank has auto-shutoff where it will shut off the power if there's no load (usually ~50mA, vary with every brand). Since Arduino may not draw that much, the battery thinks it is not connected to anything.. thus it will auto-shutoff after a while

I found this trick helps (a lot!! thank you!):
https://www.dorkbotpdx.org/blog/paul/battery\_pack\_load
> 1 votes

# Answer
Not clear what a usb power bank is. I assume you actually have a battery, perhaps with a regulator. The data sheet http://www.arduino.cc/en/Main/arduinoBoardMega at says: Microcontroller ATmega1280 Operating Voltage 5V Input Voltage (recommended) 7-12V Input Voltage (limits) 6-20V Digital I/O Pins 54 (of which 15 provide PWM output) Analog Input Pins 16 DC Current per I/O Pin 40 mA DC Current for 3.3V Pin 50 mA

also

The Arduino Mega can be powered via the USB connection or with an external power supply. The power source is selected automatically.

External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER connector.

The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

If you use the usb connector, use the correct pins an make sure you have it regulated to 5 volts.

I think this answers the question, if not please comment.
> 0 votes

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


title: Compiling sketch vi command line

text:
# Question
Title: Compiling sketch vi command line
Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder here. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

# Answer
In the Arduino IDE preferences, select external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.
> 1 votes

# Answer
I found a makefile created to compile ESP8266 sketches. You can use this makefile from command line:

```
cd /path/to/sketch
make -f /path/to/makefile/makeEspArduino.mk upload

```
> 0 votes

---
Tags: arduino-ide, esp8266, compile, build, command-line
---


title: Difficulties with raw string literals

text:
# Question
Title: Difficulties with raw string literals
I have an application where I would like to include an external multiline script as a const in my sketch. As far as I understand from C++11, this should work:

**raw\_string\_literal\_test.ino**

```
const char *script =
#include "script.txt"
;

void setup() {
  // put your setup code here, to run once:

}

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

}

```

**script.txt**

```
R"(Line 1
Line 2
Line 3
Line 4
Line 5
Line 6)"

```

script.txt is placed in the same folder as raw\_string\_literal\_test.ino

However, upon clicking Verify (selected board is Arduino/Genuino Uno, Arduino version is 1.6.12 on Mac OS 10.11.6) I get the following error:

```
/Users/owner/Desktop/raw_string/raw_string.ino:2:22: fatal error: script.txt: No such file or directory
 #include "script.txt"
                      ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

```

What am I doing incorrectly?

# Answer
> 2 votes
Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.

Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.

Because of that only files with certain extensions ever get placed in the build folder. Those include:

* `.pde` and `.ino` for sketch files
* `.c` and `.cpp` for C and C++ source
* `.h` for headers
* `.S` for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.

---
Tags: c++, string, constants
---


# Question
Title: How to switch on and off an HD44780 LCD Display?
I have an LCD Display HD44780 model and I was reading his datasheets

I saw the it has the functionality to be switched on/off as stated:

> Display on/off control: D = 0; Display off // C = 0; Cursor off // B = 0; Blinking off

and by continue reading it states:

Then he states again:

**Display On/Off Control**

> D: The display is on when D is 1 and off when D is 0. When off, the display data remains in DDRAM.

But I can't reaaly understand what I fisically need to do, can anyone help me out to better understand?

EDIT: For better clarify myfinal goal is to completely (power OFF) the LCD screen, I have some NPN transistors and if this would be the best solution, how about the wiring? do I have only to stop suppying VDO?

# Answer
At the end I manage to control the complete poweroff of the screen by connecting the pin 15 of the lcd to the Arduino and with a simple HIGH an LOW set of the arduino pin I was able to power it ON/OFF.
> 0 votes

# Answer
Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

* set RS to LOW first (meaning it is command, not data)
* set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
* make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)
> 1 votes

---
Tags: arduino-uno, lcd
---


# Question
Title: Arduino as analog to digital converter for temperature sensor
I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.

So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.

I think this is possible but I can't figure out how to do it because I can only set pins to high or low.

Can somebody help me? Thanks a lot

P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone

# Answer
Both the ESP8266 and the Arduino have UART serial interfaces. This is by far the simplest method of communicating between two boards.

Connect the TX of the Arduino, through a voltage divider to drop it to 3.3V, to the RX of the ESP8266. Connect the grounds together. That's all you need. Yes, you can connect the TX of the ESP8266 to the RX of the Arduino but if you are never going to send anything from the ESP8266 to the Arduino then there is little point.

Then, with both devices set to the same baud rate, you can `Serial.print` on the Arduino, and `Serial.read` on the ESP8266. Just follow one of the many many tutorials about communicating between Arduinos using UART.
> 4 votes

---
Tags: arduino-uno, esp8266, digital-analog-conversion
---


title: What can I do in this situation

text:
# Question
Title: What can I do in this situation
I only currently have 2 arduinos and I find that any project I build I feel bad because I have to rip it apart to get the arduino because I want to build something else. Is there a way to get arduinos for cheap? (I'm new to arduino)

# Answer
Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.

I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.
> 0 votes

---
Tags: arduino-uno
---


title: 7 Segment display dimming

text:
# Question
Title: 7 Segment display dimming
I've got project that needed to have some (4) digits display, and had plenty of 7 seg. displays lying around. I didn't have any multiplexers left but have instead wired it up as per this diagram:

I've the wired my duemilanove with the a-dp pins on the 13-6, and the transistors on 5-2.

Getting the right segments on has been a breeze, but I'm finding that if I have any kind of counting logic, the displays dim to about 20%. What I mean by this is that I can have my sketch run with all digits full brightness displaying 8s no problem, but if anywhere in the loop I have a variable that I increment up (say by incrementing up 1 per loop), and change nothing else, the display will go from 100% brightness, to 20% (at best).

Below is the demo code I'm using (there are tons of weird things in it at the moment as I've been desperately trying to track this dimming issue down), and all I have to change to see the effect take place is to uncomment the line at the end of the loop: "//count = count + 1;"

```
const int sub_delay = 1000;

const int middle_middle = 13;
const int middle_top = 11;
const int middle_bottom = 8;

const int top_left = 12;
const int top_right = 10;
const int bottom_left = 9;
const int bottom_right = 7;
//Build the digit quick table

int digits_all[] = {top_left, top_right, middle_top, middle_bottom, bottom_right, bottom_left, middle_middle};
int digits0[] = {top_left, middle_top, top_right, middle_bottom, bottom_right, bottom_left};
int digits1[] = {top_right, bottom_right};
int digits2[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_left};
int digits3[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_right};
int digits4[] = {};
int digits5[] = {};
int digit_selector0 = 2;
int digit_selector1 = 3;
int digit_selector2 = 4;
int digit_selector3 = 5;
int digit_selectors[] = {digit_selector0, digit_selector1, digit_selector2, digit_selector3};

int last = digits_all;
int last_size = sizeof(digits_all);
int last_selector = digit_selector0;

String test = "12, 13, 10, 8, 7, 9";

int count = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  //Initialize the digit segments
  for (int c = 0; c < sizeof(digits0); c++) {
    //digitalWrite(digits0[c], HIGH);
    pinMode(digits0[c], OUTPUT);
  }

//demo
  //digitalWrite(middle_middle, HIGH);
  //digitalWrite(top_left, HIGH);
  //digitalWrite(middle_top, HIGH);
  //digitalWrite(top_right, HIGH);
  //digitalWrite(bottom_left, HIGH);
  //digitalWrite(middle_bottom, HIGH);
  //digitalWrite(bottom_right, HIGH);

    Serial.begin(9600);

}

void turn_off_all (int digit, int digits[], int digits_size, int num) {

  last = digits;
  last_size = digits_size;

  digitalWrite(last_selector, LOW);
  last_selector = digit;

  digitalWrite(digit, HIGH);
int temp = 1;
  if (num == 0) {
    digitalWrite(top_left, HIGH);
    digitalWrite(top_right, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(bottom_left, HIGH);
    digitalWrite(middle_top, HIGH);

    digitalWrite(middle_middle, LOW);
  }

  if (num == 1) {
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_right, HIGH);

    digitalWrite(top_left, LOW);
    digitalWrite(middle_bottom, LOW);
    digitalWrite(bottom_left, LOW);
    digitalWrite(middle_top, LOW);
    digitalWrite(middle_middle, LOW);
  }

  if (num == 2) {
    digitalWrite(middle_top, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_left, HIGH);

    digitalWrite(top_left, LOW);
    digitalWrite(bottom_right, LOW);
  }

  if (num == 3) {
    digitalWrite(middle_top, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_right, HIGH);

    digitalWrite(top_left, LOW);
    digitalWrite(bottom_left, LOW);
  }

  if (num == 4) {
    digitalWrite(top_right, HIGH);
    digitalWrite(top_left, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(middle_middle, HIGH);

    digitalWrite(middle_bottom, LOW);
    digitalWrite(middle_top, LOW);
    digitalWrite(bottom_left, LOW);
  }

  if (num == 5) {
    digitalWrite(top_left, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_top, HIGH);

    digitalWrite(top_right, LOW);
    digitalWrite(bottom_left, LOW);
  }

  if (num == 6) {
    digitalWrite(top_left, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(bottom_left, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_top, HIGH);

    digitalWrite(top_right, LOW);
  }

  if (num == 7) {
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(middle_top, HIGH);

    digitalWrite(bottom_left, LOW);
    digitalWrite(middle_bottom, LOW);
    digitalWrite(middle_middle, LOW);
    digitalWrite(top_left, LOW);
  }

  if (num == 8) {
    digitalWrite(top_left, HIGH);
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(bottom_left, HIGH);
    digitalWrite(middle_bottom, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_top, HIGH);
  }

  if (num == 9) {
    digitalWrite(top_left, HIGH);
    digitalWrite(top_right, HIGH);
    digitalWrite(bottom_right, HIGH);
    digitalWrite(middle_middle, HIGH);
    digitalWrite(middle_top, HIGH);
    digitalWrite(middle_bottom, HIGH);

    digitalWrite(bottom_left, LOW);
  }

}

// the loop function runs over and over again forever
void loop() {

    turn_off_all(digit_selector0, digits0, sizeof(digits0), 1);
  delay(1000);

  //count = count + 1;

}

```

Any suggestions welcome!

Extra notes: I haven't yet tried another arduino board, but I've never had issues with this particular board before (Though I am hoping to switch to an ESP8622, but that is irrelevant to this issue).

# Answer
> 2 votes
You seem to be trying to do this from scratch. I haven't analysed the code, but you would be better off using one of the established libraries.

The code is unclear - I am not sure what much of it is trying to do (a few comments would help). There are obvious errors - in particular the incorrect use of `sizeof()` which is a common error.

I use the following http://playground.arduino.cc/Main/SevenSegmentLibrary

This just requires a single call to set the digits to be displayed and includes a Brightness call.

# Answer
> 1 votes
If, as comments suggest, the problem also occurs when you are using a library, it's possible the problem is hardware related. The 10KΩ base resistors are inordinately large, and are so large the transistors probably are limiting the total current per display to under 50 mA.

When you turn on one of d2 ... d5 (your digit-select drives), at most half a milliamp (5V/10KΩ) will enter the base. If transistor beta is 100, that will allow 50 mA to flow. (Not knowing the transistor type you used, I don't know its range of betas.)

Consider replacing the 10KΩ base resistors with 500-700 Ω resistors.

I see no place in the circuit where capacitors would make any positive difference.

---
Tags: transistor, arduino-duemilanove, 7-segment
---