# Question
Title: how to use an object of a class within that same class?
I want to write a tree data structure made up of Nodes, but I'm having a problem with my Node.h class as each Node need to have a reference Variable to other Nodes,it's children. which ends up giving me the following error

> "field 'child' has incomplete type"

so I thought to myself if I was to `#include "Node.h"` within my Node.h class which gave another error

> "#include nested too deeply

how can I have reference to my child Nodes within my node class

# Answer
> 0 votes
You will need to forward declare the class and add a pointer to it from within the class. i.e.

```
class CElement;  // Forward declaration

class CElement
{
public:
    CElement();
    ... // Other functions
private:
    CElement *m_NextElement;
};

```

Just to be clear you can't have your class as a member variable, it has to be a pointer or a reference. This is because:

1. You can't use a type that hasn't been fully defined.
2. You would end up with your class consuming an infinite amount of memory, because every node would contain a node, which contains a node, etc...

# Answer
> 0 votes
### If you have a class like this:

```
class Node {

public: // Methods

    inline Node() :
           left(nullptr),   // No children yet!
           right(nullptr) {
    } // Node()

public: // Variables (normally this should be private, but for this example...)

    Node *left;
    Node *right;

}; // Node

Node root; // The root of the tree

```

You now have a `class` that has two members, both pointers to `Node`s. Obviously there's going to be more data in there - `string`s or whatever - but let's ignore that for now.

I've also created the `root` of the tree - note that I didn't use `new`! It's a file variable that is always accessible, and there's not an `*` in sight (except inside `root`...).

What are `left` and `right`? Pointers to the children. They are ***not*** the children: just pointers to them. As soon as any `Node` is created (after the constructor has finished), the `Node` has no children - both pointers are `nullptr`.

So (ignoring any attempt to sort the children into place) you *could* now do the following:

```
void AddChildren() {
    Node sister;           // Create a sister
    Node brother;          // Create a brother
    root.left = &sister;   // Point to sister
    root.right = &brother; // Point to brother
} // AddChildren()

```

Note you couldn't do `node.left = sister;` \- you're not trying to put `sister` *inside* `root`, you're only trying to *point* to `sister` *with* one of `root`'s children. So you take `sister`'s address with the `&` operator.

Only... as soon as `AddChildren()` exits, both `sister` and `brother` are destroyed (they're local to the function, so get destroyed as the function leaves) - but `root` is still pointing to where they used to be! It doesn't know that they are dead!

That is why you call `new`. It creates the object on the heap rather than the stack, and the object stays around until explicitly destroyed with `delete`. Only, `new` returns a pointer to the object, not the object itself. So:

```
void AddChildren() {
    Node *sister = new Node();  // Point to new object on the heap
    Node *brother = new Node(); // Point to new object on the heap
    root.left = sister;         // Already a pointer! Just copy it
    root.right = brother;       // Already a pointer! Just copy it
} // AddChildren()

```

Or, perhaps easier:

```
void AddChildren() {
    root.left = new Node();  // Point to new object on the heap
    root.right = new Node(); // Point to new object on the heap
} // AddChildren()

```

Now, how do you access the different fields inside `Node`? It depends on whether you're accessing them through an object or through a pointer:

* Through an object?
With `.`, like `root.left` above
* Through a pointer?
Using `->`, such as `ptr->left`

So finally, how can you use it for real?

```
// TraverseTree is going to call a function that looks like this:
typedef void TraverseFn(const Node &node);

// Traverse a (sub)tree, calling the passed-in fn() on each Node.
void TraverseTree(Node *node, TraverseFn *fn) {
    if (node == nullptr) { // Nothing to traverse!
        return;
    } // if
    TraverseTree(node->left, fn);  // Trees love recursion!
    fn(*node);                     // Call the passed-in fn with node
    TraverseTree(node->right, fn); // More recursion!
} // TraverseTree(Node)

```

And you can call the above with:

```
// A function to print the contents of Node
void PrintNode(const Node &node);

// Traverse the whole Tree, from root, calling PrintNode at each Node
TraverseTree(&root, &PrintNode);

```

---

## Beware! Do not pass! Here be dragons!

(or at least pointers to member functions...)

Personally, I would have put `TraverseTree()` inside `Node`:

```
class Node {

public: // Methods to call with Traverse()

    // Print this Node
    void Print();

public: // Traverse

    // This is the type of the function that Traverse will call
    typedef void TraverseFn();

    // Note we're passing in a pointer-to-member-function!
    void Traverse(TraverseFn Node::*fn) {
        if (left != nullptr) {
            left->Traverse(fn);
        } // if
        (this->*)fn();
        if (right != nullptr) {
            right->Traverse(fn);
        } // if
    } // Traverse(fn)

}; // Node

```

If you do that, you'd print out the tree like this:

```
root.Traverse(&Node::Print);

```

---
Tags: programming, data-type
---


# Question
Title: bitClear doesn't work on most significant bit
I'm currently working on a project where I read a 32 bit sequence. The digitalPin is always HIGH when no sequence is received and starts oscilating with about 1kHz when the sequence starts (RC5).

I am setting and clearing bits of an uint32\_t depending on which signal is on the digitalPin. It seems to work very well with every bit except of the MSB.

Here a short code snippet to show what I mean:

```
const short irPin = 8;
const short msgDelay = 250;

uint32_t data = 0xFFFFFFFF;
long msgArrived = 0;

void setup(){
  Serial.begin(115200);
  pinMode(irPin, INPUT);
}

void loop(){
  long now = millis();

  if( (!(PINB & 1)) && ((now - msgArrived)> msgDelay)){
    msgArrived = millis();
    bitClear(data, 31);

    Serial.println(data, BIN);
  }
}

```

This gives me an output of

```
11111111111111111111111111111111

```

I have already tried

```
bitClear(data, 32); -> 11111111111111111111111111111111
bitClear(data, 30); -> 10111111111111111111111111111111

```

So every output is right, but not the when I try to clear the msb.

Has anyone experienced a similar behaviour?

# Answer
```
uint32_t data = 0xFFFFFFFF;
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 30);
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 31);
Serial.println(data, BIN);

```

On my mega outputs:

```
11111111111111111111111111111111
10111111111111111111111111111111
1111111111111111111111111111111

```

Are you sure you aren't mistaking the fact that println doesn't print leading 0's for the number being nothing but 1's? Try printing as hex, then all the numbers will be the same width:

```
FFFFFFFF
BFFFFFFF
7FFFFFFF

```
> 5 votes

---
Tags: arduino-uno, ir
---


# Question
Title: I2C: What is the difference between A4&A5 and SCL&SDA pins?
On tutorials are most people using the A4&A5 pins with the Wire.h library. But i have an arduino with dedicated I²C pins. How can i use them?

# Answer
> 4 votes
They are the same pins. They are physically connected to each other on the UNO board. (So SDA is connected to A4. SCL is connected to A5)

---
Tags: i2c
---


# Question
Title: How would you send clock impulses to a camera with an Arduino Mega?
Hardware newbie here and I need to know how to connect my TSL 1401 line scan camera to an Arduino Mega so that I can send it the needed impulses. The Mega has a hundred different sockets and the Schema just scared me when I looked at it.

I just want to know which socket I can connect to the CLK and SI ports of my camera so that I can get and an analog output of pixels.

# Answer
> 1 votes
It depends on the camera that you're using but you send in impulse just sending digital write signal, waiting a little bit and then turning it off. You do this over and over again until you have all the pixels. Here is an example where I send 128 impulses:

```
  for(int i = 0; i < 128; i++)
  {
    digitalWrite(CLK, HIGH);
    delay(1);
    digitalWrite(CLK, LOW);
    delay(1);
  }

```

Depending on the hardware you are using you might have to send a SI (signal impulse) prior to the CLK impulses and the delay in between them will vary. The best thing to do is to read the documentation to find these figures.

---
Tags: arduino-mega
---


# Question
Title: Why can't I declare variables inside an if statement?
I have a void function that helps me set the time on my arduino clock. I need to use the same function twice - once for the alarm and once for the actual time. The variables I am defining need to equal either alarmHours and alarmMinutes, or hours and minutes. This was my solution:

```
void setting(int i){
 if(i==0){
  int mi=alarmMinutes;
  int ho=alarmHours;
 }else if(i==1){
  int mi=minutes;
  int ho=hours;
 }
//more code later
}

```

I got an error saying that ho and mi are undefined. I fixed this like this:

```
void setting(int i){

 int mi;
 int ho;

 if(i==0){
  mi=alarmMinutes;
  ho=alarmHours;
 }else if(i==1){
  mi=minutes;
  ho=hours;
 }
}

```

This solved the problem. Why couldn't I use the first option if I passed in a 0 or a 1 to the parameters of the function?

# Answer
Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible.
> 4 votes

# Answer
The problem with doing it how you originally did is that the variables you initialized inside the if statement do not go onto the else statement.

That is why your solution is correct. You need to declare your variables before going inside of a block in order to use them.

There are uses for declaring a variables inside of a block.. but this is not one of them as you realized and fixed.
> 2 votes

---
Tags: arduino-uno, time, variables
---


# Question
Title: How to Implement Simple, Quick HMAC on Arduino
Hi I am a research student working on securing the communications in Controlled Area Networks (CANs), and I am using Arduinos to simulate one of these CANs.

My goal is to use HMAC to implement message authentication of packets, and the algorithm **must** be *very fast* (I was originally thinking of using FNV1a). However, there are no Arduino libraries for this (I found one, but it uses SHA which will most likely be too slow for CAN). I don't have a *lot* of practice with cryptography and hash algorithms, only usage of them.

So basically, I need help writing a FNV or FNV1a function in C. The message for input will be a key (obviously) concatenated with a string (char array). Also, I need the hash to be between 128 and 256 bits for sufficient security.

Just as a side note: A CAN message/packet looks like **7df#02010d** and the actual data part, **010d** (two bytes) is the char array I will be using. For example, as integers, the array for **010d** would be {1, 13}.

--

I also know this message applies more to cryptography than Arduino, but I figured someone from this community might have more experience with my particular task, or even have/know of a library I can use that I hadn't found.

-Thanks

---

*EDIT:* I found this FNV1a implementation in C/C++ that might work. But I have not tested it yet.

# Answer
I ended finding a Arduino library called **Spritz** which can be found here:
https://github.com/abderraouf-adjal/ArduinoSpritzCipher

Also, for anyone else who comes across this task, here is a *very simple* Hashed Message Authentication Code (HMAC) example I scrapped together:
https://github.com/zach-king/ArduinoStash/blob/master/src/Spritz\_HMAC/Spritz\_HMAC.ino

This library supports encryption as well, which is nice, but not needed in my case.

--EDIT--
The SpritzCipher library was actually too slow (about a 50% reduction in network speed) so I must try a different approach. I have found a MD5 library for Arduino which I will try next:
https://github.com/tzikis/ArduinoMD5
> 2 votes

---
Tags: arduino-uno, programming, c, can-bus
---


# Question
Title: How can you count the number of interrupts that have taken place?
I'm trying to program a Timer Interrupt that will go off every 33 ms. I am doing this on the ATtiny85 which has a 20MHz clock. The maximum prescaler I can set is 32 so the longest possible time a single interrupt can be is 408 microseconds.

My plan to reach 33 milliseconds is to just run the interrupt 81 times and that will get me the desired 33 milliseconds. However, I have no clue as to how you can actually count how many time an interrupt has taken place. Anyone on here know how to do that or have any idea as to what would work?

# Answer
> 2 votes
Yes, just add a check inside your ISR statement.

```
ISR(TIMER0_OVF_vect)
{
  static uint8_t postscale = 0;
  if (++postscale == 81)
  {
    postscale = 0;
    do_stuff();
  }
  else
  {
    go_to_sleep();
  }
}

```

You always have to enter the ISR method once you're done with the interrupt so just add that if statement and use a static variable (so that it keeps its value) to check if you have made the correct number of loops.

---
Tags: interrupt, attiny
---


# Question
Title: How can you check how long a timer interrupt really is?
I'm trying to set a 33 ms interrupt on my Arduino Mega and I'm not sure if I a in fact getting that kind of delay time. Is there a way to check?

I've calculated that that I need 515.6 ticks to achive this kind of delay with a prescaler of 1024 and I've coded it up like so:

```
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS12) | _BV(CS10); // prescale by 1024
  interrupts();
}

```

I followed the information on the Arduino Playground page and if my math is correct this interrupt should be going off every 33 milliseconds. I tried to test that using the `millis();` method but it only returns the time that program was on.

# Answer
> 2 votes
It doesn't fire every 33 milliseconds. First, you missed setting the CSn1 bit necessary for a 1024 prescaler; second, It looks like you want CTC mode (where the timer resets at OCRnA) but you didn't set the WGM21 bit necessary for that mode. After that your problem is that timer2 is an 8 bit timer and so OCR2A cannot store 515, but you math is correct.

You can get the period you want on a 16-bit timer; on the arduino mega thats timers 1,3,4, and 5.

Anyway here is a simple sketch for finding the average interval between interrupts. It just keeps track of the total time elapsed and the number of times the interrupt fired; the ratio of these two is the average time per interrupt.

In this case, with a prescaler of 1024, OCRA = 0xFF, and CTC mode, it runs at an interrupt every 16.384 ms.

```
volatile uint16_t interruptCount;
volatile uint32_t start;

ISR(TIMER2_COMPA_vect){
    interruptCount++;
}

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

    noInterrupts();
    TCCR2A = _BV(WGM21);
    TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20); // prescale by 1024
    OCR2A = 0xFF;
    TIMSK2 = _BV(OCIE2A);
    // start the timer
    interruptCount = 0;
    start = micros();
    interrupts();
}

void loop(){
    // read interrupt count into a local variable atomically
    noInterrupts();
    uint16_t localCount = interruptCount;
    interrupts();
    uint32_t time = micros() - start;

    // time elapsed
    Serial.print(time);
    Serial.print(" ");

    // number of times the interrupt handler fired
    Serial.print(localCount);
    Serial.print(" ");

    // average number of microseconds per interrupt
    Serial.print(time / localCount);
    Serial.println();

    delay(30);
}

```

---
Tags: arduino-mega, interrupt
---


title: expected class-name before '{' token

text:
# Question
Title: expected class-name before '{' token
I am getting the following error when attempting to compile my sketch:

> In file included from sketch.ino:24:0: SerialRenderer.h:7: error: expected class-name before '{' token

**SerialRenderer.h**

```
#ifndef SERIALRENDERER_H_
#define SERIALRENDERER_H_

#include <MenuSystem.h>

class SerialRenderer : public MenuComponentRenderer
{
public:
    SerialRenderer();
    virtual ~SerialRenderer();

public: // methods from MenuComponentRenderer
    virtual void render(Menu const& menu) const;
    virtual void render_menu_item(MenuItem const& menu_item) const;
    virtual void render_back_menu_item(BackMenuItem const& menu_item) const;
    virtual void render_numeric_menu_item(NumericMenuItem const& menu_item) const;
    virtual void render_menu(Menu const& menu) const;
};

#endif // SERIALRENDERER_H_

```

The contents of MenuSystem.h can be found at https://github.com/jonblack/arduino-menusystem/blob/master/MenuSystem.h.

It seems like the include of MenuSystem.h does not happen when SerialRenderer.h is included from my main sketch file. I get the same error if the include in SerialRenderer.h is removed.

Is there something simple I am missing for the compiler to be able to "see" MenuSystem.h?

**EDIT:**

Turns out I was looking at a newer version of the arduino-menusystem library than I had installed (version 2.1.1). That version did not have a class called MenuComponentRenderer.

I pulled the latest version from https://github.com/jonblack/arduino-menusystem/tree/master and it compiles fine.

# Answer
> 0 votes
It is most likely caused by the fact that a correct version of MenuSystem library is not properly installed. Check whether you can add the library to your sketch.

**EDIT**: added that also the version should be correct

---
Tags: c++
---


title: Not able to make my NrF24L01 work

text:
# Question
Title: Not able to make my NrF24L01 work
I have been trying to make my two Nrf24L01 wireless model work for few days now, to do so I follow the tutorial in the following link.

http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

I followed the link exactly, i changed nothing, expect i didn't add the bypass capacitor , as they said it will improve the performance and reduce heat, however mine is not working at all.

here is a pictures of my hardware setup ,

for the code i didnt change any this from the tutorial but i will past it to make it easy to follow Transmitting code

```
 /* YourDuinoStarter Example: nRF24L01 Transmit Joystick values
 - WHAT IT DOES: Reads Analog values on A0, A1 and transmits
 them over a nRF24L01 Radio Link to another transceiver.
 - SEE the comments after "//" on each line below
 - CONNECTIONS: nRF24L01 Modules See:
 http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
 1 - GND
 2 - VCC 3.3V !!! NOT 5V
 3 - CE to Arduino pin 9
 4 - CSN to Arduino pin 10
 5 - SCK to Arduino pin 13
 6 - MOSI to Arduino pin 11
 7 - MISO to Arduino pin 12
 8 - UNUSED
 -
 Analog Joystick or two 10K potentiometers:
 GND to Arduino GND
 VCC to Arduino +5V
 X Pot to Arduino A0
 Y Pot to Arduino A1

 - V1.00 11/26/13
 Based on examples at http://www.bajdi.com/
 Questions: terry@yourduino.com */

 /*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN   9
#define CSN_PIN 10
#define JOYSTICK_X A0
#define JOYSTICK_Y A1

// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
int joystick[2];  // 2 element array holding Joystick readings

void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(pipe);
 }//--(end setup )---

 void loop()   /****** LOOP: RUNS CONSTANTLY ******/
 {
  joystick[0] = analogRead(JOYSTICK_X);
  joystick[1] = analogRead(JOYSTICK_Y);

   radio.write( joystick, sizeof(joystick) );

   }//--(end main loop )---

  /*-----( Declare User-written Functions )-----*/

  //NONE
  //*********( THE END )***********

```

Receiving code :

```
/* YourDuinoStarter Example: nRF24L01 Receive Joystick values

 - WHAT IT DOES: Receives data from another transceiver with
   2 Analog values from a Joystick or 2 Potentiometers
   Displays received values on Serial Monitor
 - SEE the comments after "//" on each line below
 - CONNECTIONS: nRF24L01 Modules See:
 http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
   1 - GND
   2 - VCC 3.3V !!! NOT 5V
   3 - CE to Arduino pin 9
   4 - CSN to Arduino pin 10
   5 - SCK to Arduino pin 13
   6 - MOSI to Arduino pin 11
   7 - MISO to Arduino pin 12
   8 - UNUSED

 - V1.00 11/26/13
   Based on examples at http://www.bajdi.com/
   Questions: terry@yourduino.com */

/*-----( Import needed libraries )-----*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
/*-----( Declare Constants and Pin Numbers )-----*/
#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe

/*-----( Declare objects )-----*/
RF24 radio(CE_PIN, CSN_PIN); // Create a Radio
/*-----( Declare Variables )-----*/
int joystick[2];  // 2 element array holding Joystick readings

void setup()   /****** SETUP: RUNS ONCE ******/
{
  Serial.begin(9600);
  delay(1000);
  Serial.println("Nrf24L01 Receiver Starting");
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}//--(end setup )---

void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  if ( radio.available() )
  {
    // Read the data payload until we've received everything
    bool done = false;
    while (!done)
    {
      // Fetch the data payload
      done = radio.read( joystick, sizeof(joystick) );
      Serial.print("X = ");
      Serial.print(joystick[0]);
      Serial.print(" Y = ");
      Serial.println(joystick[1]);
    }
  }
  else
  {
      Serial.println("No radio available");
  }

}//--(end main loop )---

/*-----( Declare User-written Functions )-----*/

//NONE
//*********( THE END )***********

```

The output result on the serial is No radio available

dose anyone know where i can go from here ? or how i can debuge such a problem ? i dont even know if the problem is with the sender or receiver or both of them

# Answer
> 4 votes
Just added a 47uf capacitor to the pin 1 and 2 in NF24L01 ,then every thing worked fine

this is the new setup .

# Answer
> 2 votes
If adding a 47uF capacitor between the 3.3V and GND is not enough to solve your problem, try to:

* power the NRF24 through a 3.3V voltage regulator (like a LM1117T-3.3) and power the voltage regulator (NOT the NRF24) through the Arduino's 5V pin. Indeed, the Arduino 3.3V pin is limited to 150mA output, while the the 5V pin can provide you about 400mA.
* don't use a breadboard: the NRF24 chip is very sensitive, so try to connect it directly to the board through jumpers or PCB / perf-board.
* Add to your code the line:

```
radio.setPALevel(RF24_PA_MIN);

```

and check if it works in that way; if it does, the issue is probably about the chip's current consumption.

Hope this helped

---
Tags: nrf24l01+
---


title: Atmega2560 + weather station freezing

text:
# Question
Title: Atmega2560 + weather station freezing
i made a weather station which is build on a ATmega2560 mini pro, Esp8266 module which communicate with atmega on serial1 which sends values to thingspeak, an TSL2561, 2.4 tft lcd, BMP180, DHT22 and a dust sensor module PMS5003 which is set on serial3 on mega2560. I made the wiring, program etc. the weather station is working fine for some days when it freezes. The problem is that thingspeak reports that it receive some data every 6 mins like i set it but the data received is blank. Not 0, or any other value, just blank data. I'm thinking it could be a problem with SRAM since it loses the values it reads. But why the loop is still working since it sends blank data to thingspeak ?

Atmega reads all values from sensors, then communicates with esp8266 by serial and using AT commands it sends the values read to thingspeak. So in my opinion it reads the values, but it won't stores them, then it sending blank data to thingspeak. If i reset the arduino it works fine for some days when suddenly it decides to stop working.

After compiling the program the arduino ide is reporting this:

Sketch uses 28,890 bytes (11%) of program storage space. Maximum is 253,952 bytes. Global variables use 1,800 bytes (21%) of dynamic memory, leaving 6,392 bytes for local variables. Maximum is 8,192 bytes.

So, my program it's not filling the SRAM. I'm a beginner in C++ so i tried to do my best with programming.

Link to thingspeak weather station: https://thingspeak.com/channels/116912

The code:

```
#include <SFE_BMP180.h>
#include <Wire.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include "SWTFT.h" // Hardware-specific library

#define DHTPIN 25     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
#define ALTITUDE 320.0 // Altitude in Grasse

// Assign human-readable names to some common 16-bit color values:
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

SWTFT tft;

DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino
SFE_BMP180 pressure;

Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);

//double bmptemp; //temp bmp rectificata cu 1.9 grade -
float hum;  //Stores humidity value
float temp; //Stores temperature value
float lux; //Stores lux luminosity
char status; //used by bmp180
double T,P,p0; //p0 - sea-level compensated pressure in mb, T - temperature, P = absolute pressure in mb

#define IP "184.106.153.149" // thingspeak.com IP address; see their website for more detail
String GET = "GET /update?key=NWHWO6SLWNJP3HGQ"; // you channel will have unique code
int concentration=0;

//cod dust sensor
#define LENG 31   //0x42 + 31 bytes equal to 32 bytes
unsigned char buf[LENG];

int PM01Value=0;          //define PM1.0 value of the air detector module
int PM2_5Value=0;         //define PM2.5 value of the air detector module
int PM10Value=0;         //define PM10 value of the air detector module

void setup() {

  pinMode(17, OUTPUT); //pin pt esp - on /off
  pinMode(16, OUTPUT); //pin buzzer
  pinMode(31, OUTPUT); //pin on/off dust sensor

  Serial.begin(9600); // this is to start serial monitoring with your Arduino IDE Serial monitor.
  Serial1.begin(9600); // this is to start serial communication with the ESP via Software Serial.
  Serial3.begin(9600); //serial dust sensor

  Serial.println("Begin");
  tft.reset();
  uint16_t identifier = tft.readID();
  tft.begin(identifier);

  dht.begin();

  if (!pressure.begin()) {
    Serial.println("BMP180 init fail"); // Oops, something went wrong, this is usually a connection problem,
    while(1); // Pause forever.
    }

  if(!tsl.begin()) {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }
  //tsl.setGain(TSL2561_GAIN_1X);      /* No gain ... use in bright light to avoid sensor saturation */
  //tsl.setGain(TSL2561_GAIN_16X);     /* 16x gain ... use in low light to boost sensitivity */
  tsl.enableAutoRange(true);            /* Auto-gain ... switches automatically between 1x and 16x */
  tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS);  /* 16-bit data but slowest conversions */

}

void loop() {
  digitalWrite(31, LOW);
  digitalWrite(17, LOW);
  Serial.println("-----------------------");
  dht22 ();
  bmp120 ();
  tsl2561();
  dust();
  Serial.println("-----------------------");

  tft.fillScreen(BLACK);
  tft.setRotation(1);
  tft.setCursor(0, 0);

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("DHT22");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(temp);
  tft.println(" C");
  tft.print("Humidite = ");
  tft.print(hum);
  tft.println(" %");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("BMP180");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Temperature = ");
  tft.print(T);
  tft.println(" C");
  tft.print("Pression = ");
  tft.print(p0);
  tft.println(" mb");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("TSL2561");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  tft.print("Luminosite = ");
  tft.print(lux);
  tft.println(" Lux");
  tft.println();

  tft.setTextColor(GREEN);
  tft.setTextSize(2);
  tft.println("Pollution aux particules");
  tft.setTextColor(WHITE);
  tft.setTextSize(2);
  //tft.println("Concentration - ug/m3");
  tft.print("PM1.0: ");
  tft.print(PM01Value);
  tft.println(" ug/m3");
  tft.print("PM2.5: ");
  tft.print(PM2_5Value);
  tft.println(" ug/m3");
  tft.print("PM10: ");
  tft.print(PM10Value);
  tft.println(" ug/m3");
  //tft.println("Pcs/0.01cf");

  String tempdht22 = String(temp);// turn integer to string
  String humdht22 = String(hum);
  String tempbmp180 = String(T);
  String pressbmp180 = String(p0);
  String lum = String(lux);
  String pol01 = String(PM01Value);
  String pol25 = String(PM2_5Value);
  String pol10 = String(PM10Value);
  esp8266(tempdht22, humdht22, tempbmp180, pressbmp180, lum, pol01, pol25, pol10);
  Serial.println("Waiting..");
  delay(300000);

}

void dht22 () {
//Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.println(" % ");
    Serial.print("Temp: ");
    Serial.print(temp);
    Serial.println(" C");
}

//cod pt dust sensor
void dust () {
  digitalWrite(31, HIGH);
  Serial.println("High Pms5003");
  delay(5000);
  for (int i=0; i <= 60; i++){
  if(Serial3.find(0x42)){    //start to read when detect 0x42
    Serial3.readBytes(buf,LENG);

    if(buf[0] == 0x4d){
      if(checkValue(buf,LENG)){
        PM01Value=transmitPM01(buf); //count PM1.0 value of the air detector module
        PM2_5Value=transmitPM2_5(buf);//count PM2.5 value of the air detector module
        PM10Value=transmitPM10(buf); //count PM10 value of the air detector module
      }
    }
  }

  Serial.print("PM1.0: ");
  Serial.print(PM01Value);
  Serial.println("  ug/m3");

  Serial.print("PM2.5: ");
  Serial.print(PM2_5Value);
  Serial.println("  ug/m3");

  Serial.print("PM10: ");
  Serial.print(PM10Value);
  Serial.println("  ug/m3");
  Serial.println();
  delay(1000);
  }
  delay(1000);
  Serial.println("Low Pms5003");
  digitalWrite(31, LOW);
}

char checkValue(unsigned char *thebuf, char leng)
{
  char receiveflag=0;
  int receiveSum=0;

  for(int i=0; i<(leng-2); i++){
  receiveSum=receiveSum+thebuf[i];
  }
  receiveSum=receiveSum + 0x42;

  if(receiveSum == ((thebuf[leng-2]<<8)+thebuf[leng-1]))  //check the serial data
  {
    receiveSum = 0;
    receiveflag = 1;
  }
  return receiveflag;
}

int transmitPM01(unsigned char *thebuf)
{
  int PM01Val;
  PM01Val=((thebuf[3]<<8) + thebuf[4]); //count PM1.0 value of the air detector module
  return PM01Val;
}

//transmit PM Value to PC
int transmitPM2_5(unsigned char *thebuf)
{
  int PM2_5Val;
  PM2_5Val=((thebuf[5]<<8) + thebuf[6]);//count PM2.5 value of the air detector module
  return PM2_5Val;
  }

//transmit PM Value to PC
int transmitPM10(unsigned char *thebuf)
{
  int PM10Val;
  PM10Val=((thebuf[7]<<8) + thebuf[8]); //count PM10 value of the air detector module
  return PM10Val;
} //cod dust sensor

void bmp120 () {
  status = pressure.startTemperature();
  if (status != 0)
  {
    // Wait for the measurement to complete:
    delay(status);

    // Retrieve the completed temperature measurement:
    // Note that the measurement is stored in the variable T.
    // Function returns 1 if successful, 0 if failure.

    status = pressure.getTemperature(T);
    if (status != 0)
    {
      // Print out the measurement:
      Serial.print("Temp2: ");
      Serial.print(T);
      Serial.println(" C ");

      // Start a pressure measurement:
      // The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).
      // If request is successful, the number of ms to wait is returned.
      // If request is unsuccessful, 0 is returned.

      status = pressure.startPressure(3);
      if (status != 0)
      {
        // Wait for the measurement to complete:
        delay(status);

        // Retrieve the completed pressure measurement:
        // Note that the measurement is stored in the variable P.
        // Note also that the function requires the previous temperature measurement (T).
        // (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)
        // Function returns 1 if successful, 0 if failure.

        status = pressure.getPressure(P,T);
        if (status != 0)
        {

          // The pressure sensor returns abolute pressure, which varies with altitude.
          // To remove the effects of altitude, use the sealevel function and your current altitude.
          // This number is commonly used in weather reports.
          // Parameters: P = absolute pressure in mb, ALTITUDE = current altitude in m.
          // Result: p0 = sea-level compensated pressure in mb

          p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO)
          Serial.print("Pressure: ");
          Serial.print(p0);
          Serial.println(" mb");
        }
        else Serial.println("error retrieving pressure measurement\n");
      }
      else Serial.println("error starting pressure measurement\n");
    }
    else Serial.println("error retrieving temperature measurement\n");
  }
  else Serial.println("error starting temperature measurement\n");
}

void tsl2561 () {
  /* Get a new sensor event */
  sensors_event_t event;
  tsl.getEvent(&event);

  /* Display the results (light is measured in lux) */
  if (event.light)
  {
    Serial.print(event.light); Serial.println(" lux"); lux = event.light;
  }
  else
  {
    /* If event.light = 0 lux the sensor is probably saturated
       and no reliable data could be generated! */
    Serial.println("0 lux");
  }
}

void esp8266( String temp1, String humm, String temp2, String pression, String luminosite, String pol001, String pol025, String pol010) {
  //update value on thingspeak
  digitalWrite(17, HIGH);
  Serial.println("High ESP8266");
  delay(4000);
  Serial1.println("AT+RST"); // this resets the ESP8266.
  Serial.println("AT+RST"); // this is just echoing the command to your serial monitor so you can follow what is going on
  delay(2000);
  Serial1.println("AT");
  Serial.println("AT");
  delay(5000);
  if(Serial1.find("OK")){
      Serial.println("OK");
      Serial.println("Connected");
  }

  Serial.println("in the update loop");
  //ESP8266.println("AT+RST"); // it seems that mine works better if I reset it everytime before I do CIPSTART
  //Serial.println("AT+RST");
  //delay(5000);
  String cmd = "AT+CIPSTART=\"TCP\",\""; //standard code. see https://github.com/espressif/esp8266_at/wiki //
  cmd += IP; // += is concatenating the previous cmd string with the content of IP
  cmd += "\",80"; // same thing here it just keep adding stuff to the cmd string content
  Serial1.println(cmd);//type in the string in cmd into the ESP8266
  Serial.println(cmd);
  delay(1000);

  if(Serial1.find("Error")){
    Serial.println("AT+CIPSTART Error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
    return;
  }
  cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";
  Serial1.print("AT+CIPSEND=");
  Serial1.println(cmd.length());
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  delay(1000);
  if(Serial1.find(">")){ // if ESP8266 return the > prompt back from the CIPSEND command, you are set, if not something is wrong
    Serial1.print(cmd); //type in the GET command string and done
    Serial.print(">");
    Serial.println(cmd);
    Serial.println("OK Sent");
  }
  else
  {
   Serial.println("AT+CIPSEND error");
    digitalWrite(16, HIGH);
    delay(250);
    digitalWrite(16, LOW);
  }
  delay(1000);
  digitalWrite(17, LOW);
  Serial.println("Low ESP8266");
}

```

Here i uploaded the data file from thingspeak. You can see that until 2016-06-17 14:58:00 UTC it was working fine then thingspeak started receiving blank data. It received something but only blank data. The weather station is in another location so i don't have acces all time to reset it. http://www.filedropper.com/feeds8

\[Shown below are some lines from the front, the transition point, and the end of the feeds (8).csv file at Andrei's filedropper link. – jw\]

```
created_at,entry_id,field1,field2,field3,field4,field5,field6,field7,field8
2016-06-16 05:50:45 UTC,1,19.10,92.70,20.80,1003.02,1512.00,8,15,15
2016-06-16 05:55:07 UTC,2,19.00,94.00,20.91,1003.09,1659.00,41,54,61
2016-06-16 06:01:32 UTC,3,19.10,92.70,20.98,1003.11,2233.00,6,7,12
2016-06-16 06:07:57 UTC,4,19.00,92.90,21.16,1003.11,2620.00,6,7,11
2016-06-16 06:14:22 UTC,5,19.10,92.70,21.19,1002.97,2701.00,6,6,12
2016-06-16 06:20:48 UTC,6,19.10,92.20,21.44,1002.97,2973.00,220,291,327
2016-06-16 06:27:13 UTC,7,19.30,92.20,21.47,1002.99,3197.00,5,6,7
...
2016-06-17 14:19:30 UTC,305,22.70,50.50,23.43,1013.88,1956.00,1,1,1
2016-06-17 14:25:55 UTC,306,22.60,51.20,23.27,1013.88,1979.00,1,1,1
2016-06-17 14:32:20 UTC,307,22.70,50.10,23.18,1014.00,1962.00,1,1,1
2016-06-17 14:38:45 UTC,308,22.70,49.50,23.17,1014.03,1967.00,1,1,1
2016-06-17 14:45:10 UTC,309,22.50,50.90,23.55,1014.01,1856.00,2,2,2
2016-06-17 14:51:35 UTC,310,22.60,51.80,23.62,1013.99,1870.00,1,1,1
2016-06-17 14:58:00 UTC,311,22.60,50.80,23.21,1013.94,1987.00,1,2,2
2016-06-17 15:04:26 UTC,312,"",,,,,,,
2016-06-17 15:10:51 UTC,313,"",,,,,,,
2016-06-17 15:17:16 UTC,314,"",,,,,,,
2016-06-17 15:23:41 UTC,315,"",,,,,,,
2016-06-17 15:30:06 UTC,316,"",,,,,,,
2016-06-17 15:36:31 UTC,317,"",,,,,,,
2016-06-17 15:42:56 UTC,318,"",,,,,,,
...
2016-06-17 22:59:18 UTC,386,"",,,,,,,
2016-06-17 23:05:43 UTC,387,"",,,,,,,
2016-06-17 23:12:08 UTC,388,"",,,,,,,
2016-06-17 23:18:33 UTC,389,"",,,,,,,
2016-06-17 23:24:58 UTC,390,"",,,,,,,
2016-06-17 23:31:23 UTC,391,"",,,,,,,
2016-06-17 23:37:48 UTC,392,"",,,,,,,
2016-06-17 23:44:13 UTC,393,"",,,,,,,

```

I went and saw the station, it's more like an electrical problem imo because if i reset arduino nothing happens. The data readed by arduino on dht22 is nan and the rest of the sensors is working fine. The only way i could make dht22 reading again is to unplug the power and plug it back. So that's why i think it's more an electrical problem but can't figure why dht22 stops responding and need to switch off all power to bring it back to life. I will try putting an capacitor on wires to dht22 to see if it's better.

# Answer
> 1 votes
You may have a power problem, but with all those libraries, I would also suspect memory issues with `String`. The percentages reported by the IDE do not show actual `String` memory usage, just the declared variables and double-quoted string constants, like `"BMP180 init fail"`.

I think those humidity sensors have a heating cycle, so maybe they're causing a power sag, or maybe the sketch has run amok and is constantly requesting conversions.

Regardless, instead of building a `String` to be printed all at once, just print the pieces. That is, instead of this:

```
String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial1.println(cmd);

```

...do this:

```
Serial1.println( F("AT+CIPSTART=\"TCP\",\"") );
Serial1.print( IP );
Serial1.print( F("\",80") );

```

This saves copying bytes into buffers, reallocating `String`s, copying them to the output buffer... yuck.

The `F("x bytes")` macro also saves x bytes of RAM each time you use it on a double-quoted string constant!

And this:

```
cmd = GET + "&field1=" + temp1 + "&field2=" + humm + "&field3=" + temp2 + "&field4=" + pression + "&field5=" + luminosite + "&field6=" + pol001 + "&field7=" + pol025 + "&field8=" + pol010 + "\r\n\r\n";

```

OMG. Use separate `Serial1.print` statements and `F()` macros. However, because you have to send the command length first to the ESP8266, don't pass them in as `String`s, pass them as ints or floats, and add up the individual string lengths.

There are several ways to do this, depending on the old RAM-vs-speed tradeoff. Here's a minimal RAM approach:

```
  //  Pass in values, not Strings
  esp8266( temp, hum, T, p0, lux, PM01Value, PM2_5Value, PM10Value );
}
    ...

void esp8266( float temp1, float humm, float temp2, float pression, float luminosite, int pol001, int pol025, int pol010 )
{
    ...

  //  Start with the fixed-length string constants:
  //     GET + 8 * "&field#" + line termination
  size_t cmdLength = strlen(GET) + 8 * 8 + 4;

  //  Convert each value to a char array to see how big each one is...
  char buf[16]; // to hold temporary "char strings"

  unsigned char decimalPlaces = 2;
  dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);

  dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
  cmdLength += strlen(buf);
     ...
  itoa( pol10, buf, 10 );  // value, char *, base
  cmdLength += strlen(buf);

  //  Now we know the total length
  Serial1.print("AT+CIPSEND=");
  Serial1.println( cmdLength ); //  <-- calculated!
  delay(1000);

  if (Serial1.find(">")) {

    // send all the same pieces of the GET command
    Serial1.print( GET );

    Serial1.print( F("&field1=") );
    dtostrf( temp1, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field2=") );
    dtostrf( humm, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );

    Serial1.print( F("&field3=") );
    dtostrf( temp2, (decimalPlaces + 2), decimalPlaces, buf);
    Serial1.print( buf );
        ...
    itoa( pol010, buf, 10 );  // value, char *, base
    Serial1.print( buf );

    Serial1.print( F("\r\n\r\n") );

```

**NOTE:** It is important that you use the *same* technique to calculate the length of one piece *and* to print that piece. Here, the same `dtostrf` call with the same `decimalPlaces` is used for each piece. Ditto for `itoa`.

The speed penalty is that you convert each parameter twice, but this is probably still quicker than all the alloc/realloc/delete/copy that `String` was doing.

The RAM advantage is that you are using only 16 bytes for `buf` instead of hundreds of bytes on the heap (that's where `String` actually stores its characters).

The program space advantage is about 1600 bytes for *not* using the `String` library.

I hope you now see that the apparent "convenience" of using the `String` class has real costs in speed, RAM and program size. `String` also affects the long-term stability of your program: you get weird crashes, hangs or string values.

---
Tags: arduino-mega, programming, sram
---


title: Renaming pins in sketch

text:
# Question
Title: Renaming pins in sketch
I'm trying to rename pins so that they post as some kind of alpha-numeric combination in a database. For example, if I define the following....

```
#define APLHA 0
#define BRAVO 2
#define CHARLIE 5
#define DELTA 6

```

...I would like to rename the output of the pins, as recorded in the db, as something other than 0, 2, 5, and 6 (or whatever pin is used). Let's say A, B,C, and D for the purposes of this exercise.

Is this just as simple as creating if() function that is called upon prior to posting to the db (ex. if 0 then A, if 2, then B, etc)? I feel like there must be a better, dare I say more elegant(?), way of doing this?

Current output:
PIN | VALUE
0 | 1
2 | 1
5 | 0
6 | 0

Desired:
PIN | VALUE
A | 1
B | 1
C | 0
D | 0

# Answer
If I understood your question correctly, you're looking for something like this:

```
static const byte PIN_NUMBER[4] = { 0, 2, 5, 6 };
static const char *PIN_NAME[4] = { "A", "B", "C", "D" };

// and use them like this:

void Log(byte index)
{
  byte val = digitalRead(PIN_NUMBER[index]);
  Serial.print(PIN_NAME[index]);
  Serial.print('|');
  Serial.println(val);
}

void setup()
{
  for (byte i = 0; i < 4; ++i) pinMode(PIN_NUMBER[i], INPUT);
}

void loop()
{
  Serial.println("PIN|VALUE");
  for (byte i = 0; i < 4; ++i) Log(i);
  delay(1000);
}

```

Also, in the special case of "A", "B", "C", "D" as pin names, you don't really need the `PIN_NAME` array, instead of

```
Serial.print(PIN_NAME[index]);

```

you can use:

```
Serial.print('A' + index);

```
> 1 votes

---
Tags: pins, datalogging
---


# Question
Title: What is the maximum prescaler you can set for an ATtiny85 Timer Interrupt?
I'm having trouble understanding the datasheets for the ATtiny and I need to know what is the largest prescaler that can be set for an ATtiny Timer Interupt? I'm new to hardware so can someone tell me if this is correct:

```
void setupInterupt()
{
  noInterrupts();
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = PERIOD - 1;
  TIMSK2 = _BV(OCIE2A);
  TCCR2B |= _BV(CS13) | _BV(CS12) | _BV(CS12) | _BV(CS10);
  interrupts();
}

```

Will this set a prescaler of 16384? Am I understanding the chart on page 89 correctly and is my syntax okay? This is my first Arduino Project.

# Answer
> 1 votes
I don't know the objectives of your project, or its constraints and requirements. Thus, portions of the following might not apply.

If I were using an ATtiny85 in an application that needed to “maximize the amount of power saved” and also needed to wake up about every 33 ms, I'd use the factory-calibrated 8 MHz clock (rather than attaching a 20 MHz external crystal), and use system clock prescaling \[see §6.3, System Clock Prescaler, on page 31 of the ATtiny85 specs, and Table 6-15. Clock Prescaler Select, p. 33\] to scale that 8 MHz down to 250 KHz. As implied by Table 21-1, DC Characteristics, page 162 of specs, this will drop CPU current draw down to under 0.1 mA if powered by 2 V, or under 0.35 mA if powered by 3 V.

With the system clock running at 250 KHz, you can use timer 0 prescaled by a factor of 1024 \[see §11.3.1, Internal Clock Source with Prescaler, p. 166 of specs\] to get an interrupt every 33 ms or so.

If 250 KHz is too slow to get done with whatever computation needs to be done every 33 ms, upon waking I would change the system clock prescale factor per §6.3.1, Switching Time, to 8 MHz or 4 MHz or whatever it needs to be to get the computation done at lowest power cost. That might or might not be the same as getting the computation done most quickly.

Then, after the periodic computation is done, I'd revert the system clock to 250 KHz, and go to sleep in Idle mode (Ref §7.1.1, Idle Mode) with almost everything except timer 0 shut down via the PRR. (Ref §7.3, Power Reduction Register.)

---
Tags: interrupt, attiny
---


title: What's up with my code?

text:
# Question
Title: What's up with my code?
Sorry if my code isn't well written or anything because I'm new to Arduino and coding in C, but what is wrong with my code?

```
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val = 0)
  {
    pinMode(LED, HIGH);
  }
  else(val > 0)
  {
    pinMode(LED, LOW);
  }
}

```

# Answer
> 2 votes
Your IF statement, you're using: `(val = 0)`, and I believe you meant `(val == 0)`.

Also, you're using `else(val > 0)` and `else` doesn't need any argument. So the fixed code should look like:

```
int sidepin = 2;
int LED = 5;
int val;
void setup() {
  pinMode(sidepin, INPUT);
  pinMode(LED, OUTPUT);
}

void loop() {
  val = digitalRead(sidepin);
  if(val == LOW)
  {
    pinMode(LED, HIGH);
  }
  else
  {
    pinMode(LED, LOW);
  }
}

```

---
Tags: arduino-uno, code-review
---


title: Arduino as switch for external circuit

text:
# Question
Title: Arduino as switch for external circuit
I am trying to use the Arduino as a switch for an external circuit.

I first thought about using a shift register, but this wont allow me to switch the external circuit. Here is a little sketch of what I want to do :

So basically I got this external circuit with a 3 position switch. And I want to replace this manual switch with an Arduino so it can be controlled by a PC, without influencing the other circuits Voltage or Amps...

Any suggestions ?

# Answer
> 0 votes
Three-position makes it a little more tricky than normal.

The simplest option, though depending on what the circuit is, maybe not the safest option, is to use three relays.

Switch only one relay on and it is the same as having the three-position switch in that same state. Switch that relay off and switch another on and you have changed the switch position.

The danger is that this arrangement can have two or even three relays on at once, something that can't happen with a switch. Also how you do the switching could be critical. Switch one relay off, then add a delay before switching the next one on, so that the previous one has a chance to switch off properly first. That way you avoid having two on at once. Of course, depending on what it is you're switching, that may or may not be an issue.

The safest option, though the hardest to create, would be to physically move the existing switch with, say, a servo motor. Without knowing a little more about the mechanics of your switch I can't really advise more on this option.

---
Tags: arduino-uno, switch, arduino-setup
---


# Question
Title: I/O expander with i2c interface vs Multiplexer
I am wondering where are the difference in between using something like: CD4067, which selects which pins to read/write from by "selecting" an address with 4 pins by writing to it. Versus the MCP23017 which uses the i2c interface.

I am trying to learn and build a simple application with lots of digital inputs and outputs, and need something that is fast at switching the pins and reading/writing to it.

# Answer
> 2 votes
The MCP23017 gives you 16 extra real IO pins. Each one has facilities such as pull-up resistors, change notification interrupts, etc - the kind of things that you expect from real IO pins. You can read and write to all of the pins.

A multiplexer though just feeds signals through to the existing pins. They're pretty dumb. Only the signal that is currently fed through can have anything done to it. So only one signal can have a value written on it or read from, and pullup resistors and interrupts are non-existent.

However the CD4067 can be used with signals other than digital - as such they are good at being a multiplexer to the analog inputs, something an IO expander can never do. You could, though, use an I2C ADC chip for that.

For high speed IO control you really want to be using the MCP23S17 instead of the MCP23017. It uses SPI instead of I2C and thus is much faster to control.

---
Tags: i2c, multiplexer
---


title: Water measuring

text:
# Question
Title: Water measuring
After recent flooding of my apartment (pipe burst) I got an idea of automatic water flow watch. I would like to measure or just watch if water flows on main water intake. Arduino will know at what time of day (during nights and when nobody is home) the water flow is a problem and will send me an sms or whatever alarm. Measurement will be better to enable you to go to the bathroom, so the alarm will be raised only after certain amount of water.

The main problem is how to measure the water, are there any water-meter that can communicate with arduino?

# Answer
> 2 votes
I have an electronic water flow meter which uses a turbine wheel inside the pipe. Ostensibly there is a magnet on one or two or all four of the blades, which is read by a hall-effect sensor inside the meter. The specifications require 3 gallons per minute, which may be lower than you wish. http://catalog.gpi.net/item/chemical-and-water-meters/01-series-electronic-digital-meters/01n31gm-nylon-water-meter?plpver=1001

If the flow rate is acceptable, you could add your own hall-effect sensor outside the pipe and connect an appropriately programmed Arduino to perform the tasks you require.

Alternatively, one could create via 3d modeling software an equivalent design to be printed by an online service or a friend with a printer. For balance purposes, a magnet in each vane would be advised.

Years ago, I had a speedometer for a kayak, about the size of one's thumb. It used the same technology, although the sensor was about two inches away on the upper side of the hull, while the tiny propeller was on the bottom. Apparently small magnets spinning create sufficient disturbances in the force to be read by mass produced sensors, even more than a decade ago.

# Answer
> 1 votes
The utility company probably already placed a meter at your apartment.

Mine has a spinning dial, that's half metal, half plastic. I've had a photo-reflective sensor attached to it that so I could detect the change in amount of light being reflected (metal vs plastic). Every peak meant one liter.

Mine also has a rotating magnet, but I wasn't able to read that using a hal-effect sensor, or the magnetometer on my phone.

---
Tags: home-automation
---


title: Clearing arduino serial buffer

text:
# Question
Title: Clearing arduino serial buffer
How to clear the serial buffer of arduino uno? This is my code to on and off the LED using sms from mobile using gsm module

```
#include <SoftwareSerial.h>
int Led=7;

SoftwareSerial mySerial(9, 10);

void setup()
{
  pinMode(Led,OUTPUT);
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (mySerial.available()>0)
  {

  }
   switch(mySerial.read())
  {
    case 'a':
           digitalWrite(Led,HIGH);
           delay(10000);
           digitalWrite(Led,LOW);
           delay(100);
           break;

    case 'b' :
           digitalWrite(Led,LOW);
           break;

  }}

```

problem is whenever i on the module or the connection is restablished it automatically gets even without an sms.I need it to be fully in my control so i need to clear the serial buffer.

# Answer
If you are receiving unsolicited message (reading junk) then you could extend the bit pattern you are expecting so that there is almost no possibility of you accidentally receiving it.

Rather than 'a' and 'b' as triggers user LED="0" and LED="1". Doing this makes reading the data much harder, because what you are looking for may start on character 4 of the string you read. This is what I think you will need to do.

1. Read each character in turn and store them in a buffer until you have 7.
2. Is the first character an L.
3. If it isn't then delete the first character, shuffle the buffer left one place and load in the next character before returning to step 1.
4. If it was, check the next character matches the expected.
5. If it doesn't match delete all character to the left and this one and return to step one.
6. If you have a matching token then parse it (get the 1 or 0) and do the action.
> 1 votes

# Answer
You can simply clear it by reading it until its empty.

```
while(Serial.available()){
    Serial.read();
}

```

There also used to be a

```
Serial.flush();

```

to clear the serial. However they changed it to some other functionality. For further details you can look at the arduino reference page on Serial.
> 0 votes

---
Tags: gsm
---


title: Inheritance not working as expected

text:
# Question
Title: Inheritance not working as expected
**Short version**: This is a lighting control project. Some of the clases are Pin and Channel. Channel contains a Pin. Pin is a base class for DigitalOutPin and will be the base class for AnalogOutPin, and I want Channel to be able to use any child of Pin.

Pin has an abstract method setPinValue(), but when I create a DigitalOutPin object and call setPinValue(), Pin.setPinValue() gets called, not DigitalOutPin.setPinValue() and my program doesn't work because Pin.setPinValue() is empty as it's supposed to be overwritten.

**Long version**: If I leave out the definition of Pin.setPinValue(), I get that most idiotic of error gcc messages, "undefined reference to \`vtable for Pin'". If I make it pure virtual I get several errors in the form of

```
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:21:20: error: cannot declare parameter 'pin' to be of abstract type 'Pin'
     void begin(Pin pin, int channelNumber);
                ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   because the following virtual functions are pure within 'Pin':
 class Pin
   ^
/devel/arduino/libraries/LightBrightLib/Pin.h:33:18: note:  virtual void Pin::setPinValue(int)
     virtual void setPinValue(int value)=0;
              ^
In file included from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:9:0:
/devel/arduino/libraries/LightBrightLib/Channel.h:23:9: error: invalid abstract return type for member function 'Pin Channel::getPin()'
 Pin getPin();
     ^
In file included from /devel/arduino/libraries/LightBrightLib/DigitalOutPin.h:10:0,
             from /devel/arduino/lightbright/LightBrightMain/LightBrightMain.ino:8:
/devel/arduino/libraries/LightBrightLib/Pin.h:16:7: note:   since type 'Pin' has pure virtual functions
 class Pin
   ^

```

Full code is at GitHub but here are the relevant parts: Pin is declared like this right now as pure virtual, but I've tried with and without =0

```
class Pin
{
  public:
   ...
  protected:
   ...
  // This method is child-specific. It's empty in this base class
  virtual void setPinValue(int value)=0;
};

```

DigitalOutPin is declared as

```
class DigitalOutPin : public Pin
{
  public:
    void on();
    void off();
  protected:
    void setPinValue(int value);
};

```

and defined as

```
void DigitalOutPin::setPinValue(int value) {
....
}

```

**Disclaimer**: I'm primarily a Java developer so C++ OO is very different for me, but as far as I can tell this should work as designed.

Thanks for any advice you can offer.

# Answer
> 0 votes
I have taken your code from above and compiled it for a PC in Visual Studio. When I create an object of type DigitalOutPin and call setPinValue() it calls the function I expect. So this means either you have managed to find a bug in the gcc compiler, or there is something else in your code that is coming into play. Can you try writing a VERY simple minimal test program that defines the Pin class and DigitalOutPin class (with just the setPinValue functions that print a string) and the setup and loop functions. Just to see if you have found a gcc bug.

Even if this fixes the inheritance problem, you have other issues with you code because C++ is weird. In Channel.h your Pin variables will need to be pointers, this will allow them to call the functions in the derived classes, not the base class functions.

I think you may get a performance improvement by using "const int& foo" for you parameters. The const means the function can't change it, this allows the compiler to treat it differently and the "&" means use a reference to the variable rather than make a new copy of it.

Functions that don't change member variables within the code should also be declared constant. "int FooBar(const int& value) const;" It makes it clearer to the reader and the compiler probably does some funky stuff to improve performance. (You might want to investigate "inline" if you are writing one line functions.)

Finally I'd recommend using constructors and destructors. In release builds variables are not assigned a value. If these variables are class members this means you don't know what they are to start with. Also derived classes should initialise the base class, so:

```
// Class constructor for DigitalOutPin
DigitalOutPin::DigitalOutPin(const int& pinNumber)
  : Pin(pinNumber)  // Initialise the base class
  , m_State(false)  // Initialise all the class members (in order declared in .h file)
{
  // Lots of lovely code
}
// Class destructor for DigitalOutPin (Declared as virtual)
DigitalOutPin::~DigitalOutPin()
{}

```

---
Tags: programming, class, gcc
---


# Question
Title: Arduino Uno - External Power not working properly
I am a newbie to Arduino and created my first project. The project is using a Sharp short range sensor and a 7 seg LED board (http://embedded-lab.com/blog/new-version-of-max7219-based-4-digit-serial-seven-segment-led-display/) to count objects.

Everything works fine when on USB power to my computer or if I use a 5v 1A wall adapter with a USB cable. The problem is when I use an external power adapter or use a DC power supply to the Vin. The board powers up and I measured the output voltage on the 5v pin and is measuring around 4.8v.

The Sharp sensor is connected to the A0 Analog in and I see the voltage fluctuate when an object passes, but the LED is not displaying a value when on the external power. The display is connected to GRD, 5v where DIN, CLK, and LOAD pins of the display are connected to pins 7, 6, and 5 as the instructions stated.

I tried two different Arduino boards and several different AC to DC power adapters ranging from 9v to 12v plus used a DC power supply to the Vin and same results.

The code is below and pretty simple (although I am sure there is a lot better way of doing it but this is my first project in C so go easy on me and the function for digits is from a website and not written by me).

If a picture of the project would help I can upload one.

Any ideas or thoughts? Thanks, Steve

```
#include "LedControl.h"
#include <stdio.h>
#include <math.h>

// Arduino Pin 7 to DIN, 6 to Clk, 5 to LOAD, no.of devices is 1
LedControl lc = LedControl(7, 6, 5, 1);
int sensorpin = 0;      // analog pin used to connect the sharp sensor
int val = 0;            // variable to store the values from sensor(initially zero)
int cnt = 1;

void setup()
{
    // Initialize the MAX7219 device
    lc.shutdown(0, false);   // Enable display
    lc.setIntensity(0, 10);  // Set brightness level (0 is min, 15 is max)
    lc.clearDisplay(0);     // Clear display register

}
void loop()
{

    val = analogRead(sensorpin);       // reads the value of the sharp sensor
    if (val >= 650)
    {

    //write values to LED
    if (cnt<=9)
    {
        lc.setDigit(0, 0, cnt, false); // Display 4 to Digit 1-9, " "
    }
    if (cnt >= 10 && cnt <= 99)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt,0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
    }

    if (cnt >=100)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt, 0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
        lc.setDigit(0, 2, getDigitFromNum(cnt, 2), false); // Display 2 to Digit 1-9, " "
    }

    delay(400);
    cnt++;

}
}

// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum(int num, int digit) {
    num /= pow(10, digit);
    return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec(double dec, int digit) {
    dec *= pow(10, digit);
    return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals(double dec) {
    return dec - (int)dec;
}

```

# Answer
> 2 votes
The only difference between powering from USB and powering through the barrel jack is the voltage is reduced to 5V through a Low Dropout (LDO) voltage regulator. These are typically a clone of the popular LM1113-50 and vary in current handling capacity from around 500mA up to 1A.

I notice your board is not a genuine Arduino - therefore the components used may be at the cheaper end. So we'll assume a low-grade LDO that only handles 500mA before going into thermal shutdown with good heatsinking. Since there isn't on these boards we shall therefore assume a maximum of 400mA before it gets too hot. Probably somewhat conservative.

So if your entire circuit is drawing more than about 400mA you can expect the regulator to shut down, or at least to reduce the current and/or voltage available.

The fact you're seeing 4.8V rather than 5V could be an indication that there is *voltage droop* occurring - i.e., the regulator is not able to supply enough current so the voltage drops. This would be accompanied by the regulator getting very hot.

The regulator is the device with 3 pins on the right side and a single tab on the left directly above the barrel jack socket. See how hot that is getting.

As a rule of thumb if you can hold your finger on it without crying for 10 seconds it's not too hot.

---

Another thing you can do is to reduce your circuit to the bare minimum. Unplug absolutely everything and upload the Blink example sketch. Power that from the external DC and see if the LED blinks for you. If it does then the power supply is working OK. You can then add your peripherals one at a time to see when it fails.

If it doesn't blink then there must be something inherently wrong with the supply.

One possibility is that the LDO is *oscillating* due to insufficient or incorrect input and output capacitors. This basically means the "5V" voltage it gives out is actually wildly swinging between say 4.5V and 5V or 4.75V and 5.25V, which really confuses the microcontroller. Cheap LDOs are often more sensitive to the capacitors they are paired with and can suffer from this kind of problem.

To diagnose that kind of thing you would really need access to an oscilloscope to analyse the voltage.

If it is oscillating a 10µF ceramic capacitor connected between the lower two pins of the LDO (as orientated in your picture - that is Vout and GND) may cure it. A 1206 surface mount capacitor fits nicely across those pins and is reasonably easy to hand solder. You could also try a through-hole capacitor (ceramic again) between 5V and GND on the power header, but you really want it as close to the LDO as you can get it, so soldered direct to the LDO's pins is best.

---
Tags: arduino-uno
---


# Question
Title: Connecting 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino
I am trying to make an obstacle avoiding robot with robotic arm. First, I am from software programming field with no experience in electronics, circuits and Arduino. Using online tutorials so far I am able to blink an led, bluetooth communication between PC and Arduino and sonar range measurement.

After doing a lot of research on internet I have made the following diagram to connect 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino using "fritzing" software. I have the sketches for running servos and motors but I am not sure the circuit is correct due to the lack of knowledge in electronics. My doubts are,

1) Is 6V supply enough for 4 servos and 2 dc to work?

2) Is the connection between L293D and 2 DC motors correct?

The final robot will look like (I hope!) a "mearm" like robot arm attached on top of an obstacle avoiding robot.

UPDATED:

# Answer
> 1 votes
> 1) Is 6V supply enough for 4 servos and 2 dc to work?

If the motors are 6V motors then 6V is not only enough, it is what you *need*. What you should be asking is "Can my power source provide enough **current**.

> 2) Is the connection between L293D and 2 DC motors correct?

Not quite. You have only got half your grounds connected up. Also 3,4EN should be connected to Vcc1 not Vcc2.

1A/2A and 3A/4A are the direction/break pins (one high and one low for a direction, both low for break). The EN pins can be (if you wish) used to control the speed with PWM (if you have any spare) - if not then they should be tied to the logic supply voltage, Vcc1, not the power supply voltage, Vcc2, since that can be up to 36V and is way too high for logic inputs like EN.

---
Tags: arduino-uno, motor, servo
---


title: Audio Input into A0?

text:
# Question
Title: Audio Input into A0?
I saw a YouTube Video of someone who used an aux cord input into pin A0 on their Arduino to control a strip of LEDs. I have a strip of Adafruit's RGB NeoPixel LEDs, but I'm not sure how to input my audio into pin A0. If there is a way to do this without a separate shield or board, that'd be great because I'm on a tight budget, but if not possible it'll have to do. Also, would it be possible to send this audio to another Arduino via wifi or bluetooth using a different shield? Thanks.

# Answer
> 3 votes
Depending on how loud your audio signal is, you may be able to do it with just one capacitor and two resistors:

If your signal is quite quiet, though, you may need to amplify it using an op-amp. For instance:

That arrangement would double the volume of the audio. It also has the effect of inverting it, so you will need to invert your readings in software.

Also note that both of these methods will give you an AC waveform centred around 2.5V, so silence will be a reading of around 512, and it will go up and down from there. You can sample that audio waveform and do some basic (though quite slow on an Arduino) analysis of it, such as FFT to get the frequency content of the audio - great for visual effects...

---
Tags: led, bluetooth, audio, rgb-led, neopixel
---


# Question
Title: Relationship between avrdude's "programmer" and bootloaders
I'm trying to understand the "programmer-id" concept, as specified in `-c` `avrdude`'s option.

`avrdude` asks me to choose a "programmer-id" among many it knows of. Let's say (just as an example) I have a Arduino 2560 to which I connect via USB, and I want to program it using the bootloader. Then, in this scenario, is one programmer-id and just one supposed to work?

More in general, one has

1) some particular board (MCU, `-p` in `avrdude`)

2) some particular programming method/connection (JTAG, ISP, development board, USB/serial, etc)

3) (if using bootloader) some particular bootloader code in Flash.

How are these things related with the programmer selection? I guess that some (most?) programmers-ids are specific to some programmer connection/method (AND probably with some hardware family?), and they have nothing to do with the bootloader. What is the programmer to use for a standard Arduino with bootloader, connected via USB? What more can be said?

Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't). Why this distinction? Isn't a programmer always used? What does the IDE do, under the hood (does it call avrdude?) when choosing "Upload" ?

# Answer
If you are using the bootloader, you are *not* using a programmer. The programmer, when used, is connected to the ICSP pins on the Arduino. The bootloader however expects a well-defined sequence of data from the Arduino *through the serial port* immediately after reset. The bootloader recognizes that (if received) and reprograms the flash.

If you turn on verbose mode for uploading you will see the programmer type:

```
-carduino

```

That is, the Arduino is using the bootloader programming method.

See my post here: What happens when code is uploaded using the bootloader?

---

> Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't).

Yes, with "Upload Using Programmer" you need a programmer, such as the AVRISP which you would plug into your USB port, and then select that as the type of programmer to use. In this case, your Arduino does not need to be plugged into the USB as the serial port is not used for programming.

Note that some programmers supply Vcc (ie. +5V) to the Arduino and some don't. The AVRISP doesn't.

---

> Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino.

As far as I know, recent Arduino Unos (and probably others) ship with Optiboot. Its main advantage is that it is smaller (only 512 bytes).

> More in general, do avrdude need to know the particular bootloader?

I think the smaller boards use STK500 protocol (see links below) and the larger ones (eg. the Mega) use STK500 Version 2. That is because they have a larger address space. So yes, it needs to know the protocol.

When I switched my board type to Mega2560 the "-c" option changed to:

```
-cwiring

```

I am guessing from that, the "arduino" is code for "STK500" and "wiring" is code for "STK500 V2".

## Protocols
> 4 votes

---
Tags: uploading, avrdude, programmer
---


# Question
Title: Significant drop in speed between Arduino IDE and Visual Studio?
So, I'm not sure what is causing this, but maybe I'm overlooking something simple. I have a simple program designed to read the analog input at 640 Hz, it looks like this:

```
int Ch0 = 0;
int count = 0;
unsigned long startTime;
unsigned long currentTime;
bool startedReading = false;

void setup() {
  //set up pin(s)
   pinMode(Ch0, INPUT);

  //begin serial at 115200bps
  Serial.begin(115200);
}

...

//if the current time exceeds the start time by one second, set the start time equal to current time, print the count, set count equal to zero
if (currentTime - startTime >= 1000) {
  startTime = currentTime;
  Serial.println("time");
  count = 0;
}

//read input, delay some microseconds as a means of controlling sampling rate, bring count up by one
//should read somewhere along the lines of 640-ish Hz
analogRead(Ch0);
delayMicroseconds(1230);
Serial.println(count);
count++;

```

And this all works fine and dandy in the Arduino IDE, I pull up the Serial Monitor, and it prints every number 1-640 and then says time, with good consistency. Yet, when I open up a Visual Studio program and call the command:

EDIT: Added entire data received event method

```
private: System::Void serialPort1_DataReceived(System::Object^  sender, System::IO::Ports::SerialDataReceivedEventArgs^  e) {
    if (!this->reading) return;
    else
    {
         try
         {
            //get incoming port and read
            SerialPort^ sp = (SerialPort^)sender;
            String^ sInData = sp->ReadLine();
            //parse read data
            double inData = double::Parse(sInData);

            //write data to debugger for testing
            Debug::WriteLine(inData);

            //start populating the "in" array
            AppendIn(inData);
          }
          catch (Exception^ e)
          {
            Debug::WriteLine(e->Message);
          }
    }
}

```

Aside from the obvious error that occurs when I try to parse the string "time" to indicate when 1 second has elapsed, everything works fine. Except for the fact that the numbers feed into the debugger *very* slowly. As in, it'll take roughly 4-5 seconds to read through all 640 reads of the count integer and then it throws the time at me. Thus, this leads me to conclude that Arduino is indeed calculating that 1 second has elapsed and then sending that over, but the output is essentially the same, the only difference being that the message takes exactly 1 second to read on the Arduino IDE and over 4 seconds to read in real time in Visual Studio.

Maybe it has something to do with the way I'm reading the data in VS? I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial. No data at all is being lost, it's just very slow...and only in VS. Thanks in advance for any help you can give, but I'm at a bit of a loss.

# Answer
> 0 votes
> I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial.

I suspect that is the issue. Waiting for an incoming "serial data available" event and then processing it, is likely to be slow. I would rework how you get serial data. You haven't shown that bit but maybe you can use a larger buffer.

---
Tags: arduino-mega, c++, arduino-ide, visualstudio
---


title: Arduino Button interference

text:
# Question
Title: Arduino Button interference
With a push button on an Arduino (or Raspberry Pi), instead of wiring a high voltage (5v) through a button and to a pin to read the input, you often want your input pin set to HIGH (high impedance) and wired through a switch to ground to avoid interference like EM waves. My question is what exactly does setting the input pin to HIGH do (besides making it high impedance)? Does it make the circuit less sensitive to EM interference? I like to understand more of the physics behind circuit design.

# Answer
In Arduino, just setting the pin as input already makes it high impedance.
Writing HIGH on an input pin actually enables its internal pull-up resistor.
This way, the voltage at the pin is always defined (instead of floating when the switch is open).
Just search for "pull-up resistor" if you need more information.
Note that this code:

```
pinMode(n, INPUT); // set as input, high-impedance
digitalWrite(n, HIGH); // activate the internal pull-up resistor

```

is equivalent to this (in recent Arduino IDEs):

```
pinMode(n, INPUT_PULLUP)

```
> 2 votes

---
Tags: arduino-uno, pins
---


title: Arduino LCD Screen

text:
# Question
Title: Arduino LCD Screen
I am newer to arduinos, and could use some help. I have a LCD screen hooked up to an arduino uno. I can get it to display whatever I type in, which is great. But, what i want it to display is a value from an excel spreadsheet. So, it will change depending on what is in that field. Or even better yet, from access. Is this possible? is there code to have the arduino pull information from an existing table? (assuming it is connected via USB, or, eventually, wifi). thanks!

# Answer
> 1 votes
Assuming your Excel spreadsheet or Access table is stored on your PC, you can write a PC program to read the file and send the data serially over the USB connection to the connected Arduino, which can display it on the LCD.

If the file is stored on an SD card instead, and you want the Arduino to access the file directly by reading said SD card (through an Ethernet shield perhaps), you need to make the file format a lot simpler than XLS to ease parsing; CSV is quite simple and suitable for a lot of tasks. The built-in `SD` library can be employed to read the data from the card, the Arduino parses the data and displays it on the LCD.

In general, I suggest you do more research.

# Answer
> 1 votes
It is not the easiest thing to do especially if you are newer to arduinos but Roberto Valgolio has made an Arduino Excel interface: http://www.robertovalgolio.com/sistemi-programmi/arduino-excel

I have not worked with it yet but it's worth looking into it.

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


title: Detect movements of a person?

text:
# Question
Title: Detect movements of a person?
I'm working on a Virtual Reality game. I want to detect the position or movement of most of the bones in the human body(e.g. Knees, elbows, shoulders, hands and legs). This person may wear special equipment. How should I detect this?? I also want to get the distances between a certain position(e.g. The Arduino board) and each bone. Any ideas?

# Answer
> 2 votes
What you're looking for is called motion capture. If you google it, you'll find a Wikipedia article that can give you a starting point for deciding which of the many available techniques will suit your project. Youtube also has several videos explaining motion capture, and different technologies.

---
Tags: sensors
---


# Question
Title: How to connect an Arduino with SIM300 and a seperate GPS module?
I am trying to connect an Arduino with SIM300 and GPS module to upload data directly into a database on my localhost using GPRS of the SIM inserted. I am not able to interface the separate GPS and GSM modules. Kindly help in this regard.

# Answer
I know I should write this in comment section , but as comment have word limitation and I'm going to give you a idea why this should not be a question and how should you go for your problem, I'm writing it in answer section.Please don't down voted me :p

You miss the point of my comment. This is a forum where you ask about your problem and people try to help you to solve it. It's not a tutorial providing forum. But from you'r question as far as I understand , you want more or less a full tutorial about your circuit. That's why you are getting down vote.

First you should run your module individually . Here is two YouTube tutorial link for your GPS and GSM modules.

GSM module tutorial

GPS module tutorial

You can look for more tutorials in YouTube and build a besic idea. Then make GSM and GPS module working individually. When individually they work, then add there code and components and run the whole system. This way , it will be easy for you to detect where the problem is. If you'r device fail and you can't find or solve the problem, then ask here.

There is some rules how to ask questions here, follow them. Give total idea about your problem and how far you can debug.If possible, add your code and circuit diagram. Hope we can help you then.
> 2 votes

---
Tags: gps
---


title: Starter Kit for Arduino Cookbook

text:
# Question
Title: Starter Kit for Arduino Cookbook
I have this book here about Arduino. What kind of Kit should I purchase to get started? Would this work?

---

I'm not yet sure about what I'd like to do with Arduino, so I may prefer a pretty ***Universal Kit*** in order to cover a pretty wide range of projects.

Except this, I won't need any advanced stuff, at the moment, as a beginner I may want to understand the fundamentals, so will surely need **LEDs**, maybe **screens**, and other **basic** stuff like that.

Later on I may try to go for Wireless modules, but not at the moment as a beginner.

Any ideas? Hope to have clarified more or less what projects I'm aiming to, yeah the range is wide, but restricted to basic beginner projects.

# Answer
The advantage to a kit is it includes a lot of stuff. You'll have a big selection of sensors and parts to choose from.

The disadvantage to a kit is it includes a lot of stuff. You'll have bought and paid for a big selection of sensors and parts, some of which you may never use.

Since you linked to Amazon, I assume you are someplace where shopping on line is convenient. In that case I'd start with a small handful parts and let your developing skills and interests guide your future purchases.

A bag of LEDs with resistors included is really basic - start there. I make up a dozen or so of them with a resistor permanently soldered to the cathode (ground) side of the LED (it doesn't matter which side you choose, just be consistent for your own sanity later on!) These are quicker to wire up on a breadboard than using separate LEDs and resistors, and they make a quick and dirty logic-probe ("Is there 5v on this board?", "Is this pin HIGH or LOW?") or output device.

A handful of push-buttons, often called "Tact switches", a few analog thermo sensors (LM34 or LM35 f/ex), and a light sensor, would start you off inexpensively while providing you opportunities to learn how connect these devices, some basic electronic theory, and some programming skills.

By then, you'll have a much better idea what kinds of projects you want to pursue and the parts necessary to build them.
> 0 votes

# Answer
The Stack Exchange format is not well suited for opinions. That said, people are apparently giving the kit good reviews. And I see hardware that appears to allow for several projects (LED arrays?, motors?, ultrasonic-distance-measurement?, IR-remote-control?, Alpha-numeric-LCD?, 7-segmet-LED-display?, ect). Which is more than you need for basic Arduino projects.

In general, it would make the most sense to find a kit with a book rather than obtain a book and a kit separately. This is because slight differences between the written material and independently obtained hardware will cause confusion. This is generally not a problem for experienced embedded developers.

Keep in mind that embedded processor projects are half hardware and half software. Since the hardware has already been collected, the majority of activity will be in software. If this paradigm agrees with you, good luck & have fun.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Does IDLE Mode not power down an ATtiny85?
So I'm trying to power down my ATtiny85 to save power, but for some reason the ATtiny doesn't power down when I'm using the default `IDLE` mode, but when I start using the `SLEEP_MODE_PWR_DOWN` the ATtiny appears to go to sleep.

I'm testing it by calling a `checkPower()` method that blinks an LED after the `sleepNow()` method. In other words, if the ATtiny goes to sleep then the `checkPower()` method should not be reached and the LED should not blink. Here is the code:

```
void loop()
{
  doStuff();
  sleepNow();
  checkPower();
}

void sleepNow()
{
    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_IDLE);
    // Set sleep enable (SE) bit:
    sleep_enable();
    // Put the device to sleep:
    sleep_mode();
    // Upon waking up, sketch continues from this point.
    sleep_disable();
}

void checkArrays()
{
  for(i = 0; i < 15; i++)
  {
     digitalWrite(1, HIGH);
     delay(1000);
     digitalWrite(1, LOW);
     delay(1000);
  }
}

```

Any idea why my LED would continue to blink when using the `IDLE` mode but no the `PWR_DOWN` mode?

# Answer
> 1 votes
In IDLE mode the timers still run. Arduino uses timer0 for millis. So when timer0 overflows the ATTiny will wake up and call the ISR.

So the ATTiny will go to 'sleep' but wake up a number of microseconds later.

---
Tags: attiny, sleep
---


# Question
Title: Sending values to an Arduino Yun across different networks
I have quite a lot of experience with Arduino but have recently been faced with a challenge that has stumped me. The project is to create a robot that can be controlled from a separate network than it is on. I had the idea of using the Yun board to receive the values. Does anyone know a way I could have a computer send data to a Yun on a different network? (Maybe through a website?)

# Answer
I have accomplished this, first by reading this article on controlling a Yun through a web-browser *on the same network*. From there it was a matter of allowing my Yun to be accessed *externally* (setting up port-forwarding on my router) and changing a few lines of code to reflect the new location reference.

All the necessary files and code are included under the heading "Project Files" in the above link and no modification is needed to get it working within the same network. That said, I had to convert the two `.jpg` files to `.png` (and change the filenames in `index.html`) - I don't know why they wouldn't show up in my browser.

## In brief:

The Yun hosts a webpage (index.html) which contains some indicators and control inputs. These objects are linked to the 32u4 using Bridge and the REST API - nothing special. The bulk of the html code is for visual purposes, and the actual REST calls are nice and simple.

What is good is that the webpage can be accessed from anywhere with the right jiggery-pokery, and with a little more determination can be *hosted* from anywhere.

## External Access

Once you have that working, you need to do the following to allow access externally. I tested this using my smartphone - disconnected from my home WiFi of course - to ensure the link was over the Internet, not intranet.

1) Set up port forwarding and a static IP for the Yun. This is the fundamental step if you simply want to control your Yun over the Internet. However, I can't actually tell you how to do this because I don't know what equipment you have! Information is all over Google for setting up both DHCP static IP and port forwarding.

2) Get a static IP from your ISP for your home/work, or set up a Dynamic DNS service (these people offer it free, but I've never actually needed to use an external service). Most commercial ISPs tend to dish out static IPs, but that's no guarantee that yours will.

3) Access your Yun with a browser via: `http://YOUR.IP.ADD.RES:PORT/arduino/<SketchName>`.

## External Hosting

If you want to host the webpage on something other than the Yun, you can! You will of course need a server to host this, either your work's central server or an external hosting service. You'll need to change some more lines in the code:

1) ~~In the Yun sketch change `server.ListenOnLocalhost();` to `server.noListenOnLocalhost();` \- the subtle difference is the 'no', and is essential for external control.~~ *Sorry, that's incorrect without a little more explanation than is required at the moment to answer your original question.*

2) In the `.html` file, you need to change each instance of:

```
server = "/arduino/<SOMETHING>";

```

to

```
server = "YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

```

If you have the REST password set to ON then you have to incorporate the username/password in there too:

```
server = "username:password@YOUR.IP.ADD.RES:PORT/arduino/<SOMETHING>";

```

There are *three* occurences in the original file, so be sure to catch them all.

3) When making changes to the `.html` file, make sure you re-upload it to the external host, not the Yun - that mistake took me hours to figure out.

## A little more...

While searching for the URL of the article in the opening paragraph I found this atricle on a similar theme. It looks to have plenty of information although I haven't read it yet fully yet; I've been busy writing an answer on Stack Exchange. External Access should be no different, and if you want the 'External Hosting' version you just need to find any line that references the 'server' as `"/arduino/..."` and change it to `"YOUR.IP.ADD.RES:PORT/arduino..."`.
> 1 votes

# Answer
You havent mentioned what exactly your robot does, for now I am going to assume it is something as simple as switching on a light etc and not something like a rover.

The easiest way would be to make the YUN read from a db (like mysql, etc.) and depending on the value perform a task.

For example, you could have a row called **light**, if the value of it is **1** then turn on the light else turn off the light

The problem you are going to face is the power consumption as you will constantly be polling from the database. You could also look into push notifications ( I am not sure if it is applicable here)

You could also look into creating a private VPN and connecting the YUN and your other devices to it and then control it.
> 0 votes

# Answer
Basically your yun is a linux box with a arduino connected to it on port /dev/ttyATH0.
If you know linux that should answer all your questions about what is possible. I have setup my own bridge and communicate via html to my robot using cgi script and lua.
I have demoed this on a web contest and you can see it in action on this video from 15:25 onwards https://www.youtube.com/watch?v=q0CnB7Yzpfg&index=3&list=PLCSjf7QmP3TCOLIw0lMPbwHtKrO-nwfKG
> 0 votes

---
Tags: wifi, arduino-yun, remote-control
---


title: Issue with IF statement condition

text:
# Question
Title: Issue with IF statement condition
I am using 2 accelerometers connected to an arduino. The code below does not work.

```
> if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <=40)) //If acc1 is between 20 and 40 AND if acc2 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

```

But, the following code does:

```
> if((acc1 >= 20 && acc1 <= 40)) //If acc1 is between 20 and 40
>     {
>         digitalWrite(13, HIGH);
>     }

```

Can anyone tell me why please? Edit with full code:

```
const int acc1_xPin = 0; //X Pin on acc1
const int acc1_yPin = 1; //Y Pin on acc1
const int acc2_xPin = 2; //X Pin on acc2
const int acc2_yPin = 3; //Y Pin on acc2

int xAcc1_maxVal = 409; //Maximum value for X-axis Acc1
int xAcc1_minVal = 269; //Minimum value for X-axis Acc1
int yAcc1_maxVal = 410; //Maximum value for Y-axis Acc1
int yAcc1_minVal = 270; //Minimum value for Y-axis Acc1

int xAcc2_maxVal = 411; //Maximum value for X-axis Acc2
int xAcc2_minVal = 268; //Minimum value for X-axis Acc2
int yAcc2_maxVal = 402; //Maximum value for Y-axis Acc2
int yAcc2_minVal = 263; //Minimum value for Y-axis Acc2

//Hold Calculated Values
double acc1; //acc1 angle
double acc2; //acc2 angle

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

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

  int acc1_xRead = analogRead(acc1_xPin); //acc1 X-axis
  int acc1_yRead = analogRead(acc1_yPin); //acc1 Y-axis
  int acc2_xRead = analogRead(acc2_xPin); //acc2 X-axis
  int acc2_yRead = analogRead(acc2_yPin); //acc2 Y-axis

  //convert read values to degrees -90 to 90 - Needed for atan2
  int acc1_xAng = map(acc1_xRead, xAcc1_minVal, xAcc1_maxVal, -90, 90);
  int acc1_yAng = map(acc1_yRead, yAcc1_minVal, yAcc1_maxVal, -90, 90);
  int acc2_xAng = map(acc2_xRead, xAcc2_minVal, xAcc2_maxVal, -90, 90);
  int acc2_yAng = map(acc2_yRead, yAcc2_minVal, yAcc2_maxVal, -90, 90);

  //Caculate 360deg values like so: atan2(-yAng, -zAng)
  //atan2 outputs the value of -π to π (radians)
  //We are then converting the radians to degrees
  acc1 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
  acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

  if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <= 40))
  {
    digitalWrite(13, HIGH);
    Serial.println("HIGH");
  }
  else if ((acc1 >= 41 && acc1 <= 60) && (acc2 >= 41 && acc2 <= 60))
  {
    digitalWrite(13, LOW);
    Serial.println("LOW");
  }

  Serial.print("Acc1: ");
  Serial.print(acc1);
  Serial.print(" Acc2: ");
  Serial.print(acc2);
  delay(1000);

}

```

I'd really appreciate any input as to way the if statements are not working when I have 2 conditions in them but will work when I have 1 condition.

Edit: I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.

# Answer
I think this is your problem (from the full code snapshot)

```
(acc2 >= 20 && acc2 >= 40))

```

I believe it should be (like your first snapshot)

```
(acc2 >= 20 && acc2 <= 40))

```

Note that the first is greater than or equal to 40 rather than less than or equal to. Also note you've done this when determining whether or not acc2 is between 41 and 60 in the else if part of that same if statement.

I have no idea why the code differs between your first and third snapshot. Potentially you have spotted this already and failed to update the full code being run?
> 2 votes

# Answer
Your code has the following lines:

```
acc2 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees

```

If I'm going to believe the comments, the *first* line should start:

```
acc1 = ...

```
> 1 votes

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