message:
Building a Vector class in Arduino

I'm struggling with this issue that I can seem to get around of.
 When defining a vector class, I'm seeming to get some issues when deleting the allocated pointer.

 Oddly enough, this only happens after I "read" the memory. What I mean by this is that if I push back a series of values to the vector, they seem to stay there. But once I read the values, the data pointer seems to become invalid of some sort so I crash when trying to deallocate it.

Code:

    #ifndef VECTOR_H
    #define VECTOR_H

    #include <string.h>  /* memcpy */

    #define min(a,b) (a < b) ? a : b

    template <typename T>
    class vector {
    public:
     vector() : __capacity(0), __count(0), __data(0) {} //empty constructor
     vector(T obj, int count = 1) {

      if (this->__data) { // free data ptr if used
       delete this->__data;
      }

      this->__data = new T[count];
      this->__count = count;
      this->__capacity = count;

      for (int i = 0; i < count; i++) //populate array with given object
       this->__data[i] = obj;

     }

     ~vector() {

      if (this->__data) { // free data ptr if used
       delete [] this->__data;
      }

      this->__count = this->__capacity = 0;
     }

     T const & operator[] (unsigned int idx) const {
      if (idx < this->__count) {
       return this->__data[idx];
      }
      else {
       // throw exception or handle error to be implemented
      }
     }

     T& operator[] (unsigned int idx) {
      if (idx < this->__count) {
       return this->__data[idx];
      }
      else {
       // throw exception or handle error to be implemented
      }
     }

     void resize_to_fit() {
      resize(this->__count);
     }

     T& pop_back(){
      return this->__data[--this->__count];
     }

     void push_back(T obj) {

      if (this->__capacity == this->__count) {
       resize(this->__capacity + 1);
      }

      this->__data[this->__count++] = obj;
     }

     bool isempty() {
      return !this->__data ||
       !this->capacity ||
       !this->size;
     }

     void clear() {
      this->~vector();
     }

     T* data() {
      return this->__data;
     }

     int size() {
      return this->__count;
     }

     int capacity() {
      return this->__capacity;
     }
    private:
     void resize(int capacity) {
      if (this->__data == nullptr) {
       this->__data = new T[capacity];

       this->__count = 0;
       this->__capacity = capacity;
      }
      else if (capacity != this->__capacity) { //else do nothing

       T* data = new T[capacity];

       this->__count = min(this->__count, capacity);
       this->__capacity = capacity;

       memcpy(data, this->__data, sizeof(T) * this->__count);

       delete this->__data; //program crashes here, but the pointer is already broken...
       this->__data = data;
      }
     }
    protected:

         int __capacity;
         int __count;
         T* __data;

    };
    #endif//VECTOR_H

I was using this code in my Arduino, not sure if it helps

    void print_vec(vector<int> v){
      Serial.println("Printing new vec!");
      for( int i = 0; i < v.size(); i++){
        Serial.println(v[i]);
      }
    }

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

      Serial.begin(9600); // Open serial connection to report values to host

      while(!Serial); //Waiting for serial to open

      vector<int> i = vector<int>();

      i.push_back(10);
      i.push_back(2);
      print_vec(i); //prints 10 and 2, perfect so far
      i.push_back(3);

      while(true){
        print_vec(i);
        i.pop_back();
        delay(2000);
      }
    }

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

    }

This code outputs:
Printing new vec!
10
2
Printing new vec!
0
2
3
Printing new vec!
0
2
Printing new vec!
0
(...)

What could be causing this? I'm stonewalled for a while now, any insight on how to solve this is appreciated. Thanks!

body:
### In your second constructor you start with the following code:

    if (this->__data) { // free data ptr if used
        delete this->__data;
    } // if

This is deadly! You've not initialised `__data`, so it could hold _any_ value under the Sun. And there is _no way_ that it could _possibly_ be a valid pointer to existing data - it's a brand-new uninitialized object. Returning this garbage pointer to the heap is simply asking for trouble.

Remove those lines - or even better, use an initialiser list like you did with the first constructor:

    vector(T obj, int count = 1) :
           __data(new T[count]),
           __count(count),
           __capacity(count)
    {
        for (int i = 0; i < count; i++) //populate array with given object
            __data[i] = obj;
    } // vector(T, count)

### Another problem: In your `clear()` member you wrote:

    void clear() {
        this->~vector();
    }

You should never, _never_, **never** directly call a destructor like this. The compiler can put all sorts of other code in the destructor code, since it "knows" that it's the only one that will ever call it. For example, some compilers pre-push a flag to say whether to `delete` the object from the heap after doing the destruction. You haven't done that, so the above can corrupt all sorts of things.

Instead, move the code that is in the destructor into `clear()`, and then simply call `clear()` from the destructor.

### Another one, this one picked up by @Nick Gammon:

    bool isempty() {
        return !this->__data ||
               !this->capacity ||
               !this->size;
    }

This is testing whether the `__data` member is false, and whether the `capacity` and `size` functions have been defined. Don't worry: the latter two have been... you missed the prefix `__`...

> [Also, stop it with the `this->` everywhere. You've used a `__` before all your member variables (which is itself against convention); you don't need to hammer home the fact that they are member variables: the compiler already knows.]


sender: user

sender: assistant

body:
You had a lot of problems with your code so it's hard to know where to start. :)

I agree with what John Burger said.

I took your code onto my PC to save mucking around uploading it each time, and also so I could use valgrind on it. Certainly valgrind reported an error after you printed the vector. The reason for that is simple. You passed a **copy** of the class to `print_vec` which meant that the destructor got called when `print_vec` exited, thus deallocating the memory. You should have had a *copy constructor*. Without it the compiler makes a bitwise copy of the class, which means you now have two objects sharing the same allocated memory.

A quick and dirty fix is to call `print_vec` by reference:

    void print_vec(vector<int> & v){

However that leaves the bug lurking around for the future.

I implemented the copy constructor in my example below, however calling `print_vec` by reference saves the class having to be copied, reducing the number of `new/delete`s you are doing, thereby possibly reducing memory fragmentation.

---

As John Burger said: **do not call the destructor yourself!** You can't do that. If you want to do the same thing in the destructor and the `clear` function, just get the destructor to call `clear()`.

---

The use of leading double-underscores in variables is contrary to the C++ Standard. Don't do that. Use a trailing underscore if you want to indicate a member variable. Lose all the `this->` references. They just clutter things up.

---

Since you allocate an array you should use `delete []` - you did that in one place but not the other.

---

Why do this? It's an unnecessary assignment:

      vector<int> i = vector<int>();

Just do:

      vector<int> i;

If you are going to assign the class for some reason you should also implement an `operator=` or you will have the same problems as you had with the copy constructor. (See my example).

---

Here you are testing functions (capacity and size) without calling them:

    bool isempty() {
        return !this->__data ||
            !this->capacity ||
            !this->size;
    }

---

 You can't really do this:

      T const & operator[] (unsigned int idx) const {
            if (idx < this->__count) {
                return this->__data[idx];
            }
            else {
                // throw exception or handle error to be implemented
            }
        }

If you take the "else" path then the function is returning no value (you get a compiler warning if you turn warnings on).

---

My reworked example, with my suggestions in it. It compiles without warnings or errors and runs without crashing (on a PC):

    //      g++ -std=c++11 -g3 test.cpp -o test
    // OR:  clang -std=c++11 -g3 -Wall test.cpp -lstdc++ -o test
    //
    // valgrind --leak-check=yes ./test

    #include <stdio.h>      // printf
    #include <string.h>     /* memcpy */

    #define min(a,b) (a < b) ? a : b

    template <typename T>
    class vector {
    public:
        //empty constructor
        vector() : capacity_(0), count_(0), data_(nullptr) {}

        // copy constructor
        vector (const vector & rhs) : capacity_(0), count_(0), data_(nullptr)
          {
          data_ = new T [rhs.capacity_];
          capacity_ = rhs.capacity_;
          count_ = rhs.count_;
          memcpy (data_, rhs.data_, sizeof (T) * count_);
          }  // end of copy constructor

        // operator=
        vector & operator= (const vector & rhs)
          {
          // gracefully handle self-assignment (eg. a = a;)
          if (this == &rhs )
            return *this;

          data_ = new T [rhs.capacity_];
          capacity_ = rhs.capacity_;
          count_ = rhs.count_;
          memcpy (data_, rhs.data_, sizeof (T) * count_);
          return *this;
          }  // end of operator=

        // destructor
        ~vector()
          {
            clear ();
          }  // end of destructor

        T const & operator[] (unsigned int idx) const {
           return data_[idx];
        }

        T& operator[] (unsigned int idx) {
           return data_[idx];
        }

        void resize_to_fit() {
            resize(count_);
        }

        T& pop_back(){
            return data_[--count_];
        }

        void push_back(T obj)
            {
            if (capacity_ == count_) {
                resize(capacity_ + 1);
            }

            data_[count_++] = obj;
        }

        bool isempty() {
            return count_ == 0;
        }

        void clear() {
          delete [] data_;
          data_ = nullptr;
          count_ = capacity_ = 0;
        }

        T* data() {
            return data_;
        }

        int size() {
            return count_;
        }

        int capacity() {
            return capacity_;
        }
    private:
        void resize(int capacity) {
            if (data_ == nullptr) {
                data_ = new T[capacity];
                count_ = 0;
                capacity_ = capacity;
            }
            else if (capacity > capacity_) { //else do nothing

                // allocate new memory
                T* data = new T[capacity];
                // count can't be higher than capacity
                count_ = min(count_, capacity);
                capacity_ = capacity;
                // copy data across to new pointer
                memcpy(data, data_, sizeof(T) * count_);
                // delete old pointer
                delete [] data_;
                // now remember the new pointer
                data_ = data;
            }
        }
    protected:

            int capacity_;
            int count_;
            T* data_;
    };

    void print_vec(vector<int> v){
      printf("%s\n", "Printing new vec!");
      for( int i = 0; i < v.size(); i++){
        printf("%i\n", v[i]);
      }
    }

    int main() {

      vector<int> i;

      i.push_back(10);
      i.push_back(2);
      print_vec(i);
      i.push_back(3);

      vector<int> j;

      // test assignment
      j = i;
      print_vec(j);
      print_vec(i);

      while(i.size () > 0){
        print_vec(i);
        i.pop_back();
      }

    }


body:
There is something I would like to add.

Others have already pointed out numerous errors in the code. And I could point many more, but that is not the point.

IMO, the biggest mistake is - implementing a Vector class for the Arduino!

Even if it works, it is just a bad idea. Keep in mind, that the Arduino has VERY limited amount of memory. Dynamic memory allocation in such a constrained space just sounds like a bad idea - you are wasting memory, you're fragmenting the heap and you gain almost nothing, except some coding convenience.

I have yet to see a case where one really needs dynamic memory allocation in an Arduino project. And even if you do, there are many other tools you can use (like stack-allocated temp buffers, arena allocators, pool allocators and whatnot). But again, probably the code and memory cost of these "generic" solutions will be unfeasible on the Arduino.

Most of the time it's fine to use vectors, maps and whatever you like on platforms like PC (I work as a PC games programmer, so I often encounter situations where extras like these are big "no-no", but for most applications it's fine).

But, on a "tight" platform like the Arduino, I think you should stay "close to the metal" and be in total control of what is going on (memory and CPU cycles wise). Ideally, you should only afford "luxuries" like these when you know what is going on "underneath" and you know you can get away with it. Which is rarely the case on "tight" platforms like the Arduino.


message:
Servos Do Not Move to Specified Position

This code receives sine wave parameters from a serial connection, then formats and writes the sine wave positions to 8 servo motors.

The positions are successfully written to 6 of the 8 motors.

Of the two that don't work, I tried changing the motors to see if they were faulty; they are not. I changed the output pins to see if they were damaged; they are not.

I changed the order the equations are solved, and the positions are written to ensure there wasn't some bizarre timing issue. I saved a full cycle of the written positions and they output the correct numbers (i.e. the correct amplitude). You can see them here (format is "servo #" : "position"):

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

    0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

The entire code is below. The relevant section begins after `if (Afreq > 0)` near the bottom. The positions that do not write correctly are pos[6] and pos[7]:

    /*
    This is a program that recieves sine wave parameters from a serial connection in a single string.
    The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
    positions for each joint of the robot.
    */

    #include <Servo.h>

    Servo SB, SF, HB, HF, EB, EF, KB, KF;
    int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
    unsigned int t = 0;
    unsigned long previousMillis = 0;
    float fKnee_amp, fAfreq, fPhase, fGait;

    void setup(){
      //Start serial stream at 115200 baud
      Serial.begin(115200);

      //Connect servos to Arduino
      HB.attach(2);
      KF.attach(3);
      SB.attach(4);
      EB.attach(10);
      HF.attach(6);
      KB.attach(7);
      SF.attach(8);
      EF.attach(11);

      delay(3000);
    }

    void loop(){
      char c, buffer[10];
      String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
      unsigned int sine_time = 50;

      while (Serial.available() && readString.length() < 37){
        //delay to allow buffer to fill
        delayMicroseconds(100);
        if (Serial.available() > 0){
          //get one byte from serial buffer
          char c = Serial.read();
          //creates the string "readString"
          readString += c;
        }
      }

      if (readString.length() > 36){
        //see what was received
        Serial.println("The string is: " + readString);
        Serial.println(readString.length());

        //parse serial string into separate parameters
        amp = readString.substring(0, 3);
        knee_amp = readString.substring(3, 7);
        afreq = readString.substring(7, 11);
        phase = readString.substring(11, 15);
        gait = readString.substring(15, 20);
        f_offset = readString.substring(20, 24);
        b_offset = readString.substring(24, 28);
        fk_offset = readString.substring(28, 32);
        bk_offset = readString.substring(32, 36);

        //convert string values to numbers
        iAmp = amp.toInt();

        knee_amp.toCharArray(buffer, 10);
        fKnee_amp = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        afreq.toCharArray(buffer, 10);
        fAfreq = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        phase.toCharArray(buffer, 10);
        fPhase = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        gait.toCharArray(buffer, 10);
        fGait = atof(buffer);
        memset(buffer, 0, sizeof(buffer));

        iF_offset = f_offset.toInt();
        iB_offset = b_offset.toInt();
        iFk_offset = fk_offset.toInt();
        iBk_offset = bk_offset.toInt();

        //clear strings
        readString="";
        amp="";
        knee_amp="";
        afreq="";
        gait="";
        phase="";
        f_offset="";
        b_offset="";
        fk_offset="";
        bk_offset="";
      }

      //if the joints should be oscillating
      if (fAfreq > 0){
        //determine joint positions
        pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
        pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
        pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
        pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

        pos[4] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1500 + iFk_offset;
        pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1581 - iFk_offset;
        pos[6] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 + iBk_offset;
        pos[7] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1538 - iBk_offset;

        //get time in milliseconds
        unsigned long currentMillis = millis();

        //if the time threshold has been passed
        if(currentMillis - previousMillis >= sine_time){
          previousMillis = currentMillis;

          //write servo positions

          SB.writeMicroseconds(pos[0]);
          SF.writeMicroseconds(pos[1]);
          HB.writeMicroseconds(pos[2]);
          HF.writeMicroseconds(pos[3]);
          EB.writeMicroseconds(pos[4]);
          EF.writeMicroseconds(pos[5]);
          KF.writeMicroseconds(pos[6]);
          KB.writeMicroseconds(pos[7]);

          //increment time parameter
          t+=1;
        }
      }
    }

I don't know what to try next.

body:
Given that it's the last two that aren't working, perhaps you've got a timing problem. Now I don't know how good the compiler is about detecting common code, but you might want to make it easier for it, and perhaps speed things up by making some temporary variables:

    //determine joint positions
    int pos01 = iAmp * sin(fAfreq*t);
    pos[0] = pos01 + 1500 + iF_offset;
    pos[1] = pos01 + 1522 - iF_offset;

    int pos23 = iAmp * sin(fAfreq*t + fGait);
    pos[2] = pos23 + 1500 + iB_offset;
    pos[3] = pos23 + 1446 - iB_offset;

    int pos45 = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase);
    pos[4] =  pos45 + 1500 + iFk_offset;
    pos[5] = pos45 + 1581 - iFk_offset;

    int pos67 = iAmp*fKnee_amp * sin(fAfreq*t + fPhase);
    pos[6] = pos67 + 1500 + iBk_offset;
    pos[7] = pos67 + 1538 - iBk_offset;


message:
The L LED Keeps Itself On

I am using a Arduino Uno 3 for line follower robot. However when I power the Arduino Uno, the L led is turned on and is never turned off. After a bit of searching I found out that the L LED is connected to pin 13. So I set the pin 13 to low but still the led is on. Is there a problem with the arduino? Or there's something that I am unaware about? (Amongst a lot of other things that I don't know.)

body: An LED lights up when in forward bias.  That is, when the voltage on the anode is greater then that on the cathode.  If the anode is connected to an Arduino GPIO pin (and the cathode is connected to ground and an appropriate limiting resistor is used), the LED will light up when the pin has positive voltage.  This is when it is set to 1 in the code.  If the cathode is connected to an Arduino GPIO pin (and the anode is connected to positive voltage and an appropriate limiting resistor is used), the LED will light up when the pin has zero voltage. This is when it is set to 0 in the code.


body:
Its possible its the Power LED you are looking at - that will always be on.

Simplest test is to load up the Blink Example that's included in the Arduino IDE - and the LED should blink once a second. That will show you if your Pin13 LED is working ok.


body:
This is a “feature” introduced in the revision 3 of the Uno board. Up to
Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ
resistor. On Rev 3, the same LED+resistor combination is driven by pin
13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e.
`INPUT` mode, the default mode when the program starts), the input of
the op-amp is floating. The voltage at this input (and thus at the
output) is not controlled and depends only on the parasitic conductances
and on leakage currents.

If you want to turn the LED off, you not only need to write `LOW` to it,
you also (and most importantly) should set the pin to `OUTPUT`.


body: Now first check IC on your arduino UNO. if it is atmega328p, set the board to arduino nano in the software and set the processor th atmega328p. that makes it work.  :)


body: I guess the arduino is burnt cus it happens with me in the same way. The usb port of my PC is writing device not recognize, and the atmega328p on the arduino temperature is getting high. To save my time I bought another new one I think that should help.


message:
How to wake up Arduino Mega when in Power Saving Sleep Mode?

I'm using sleep mode to turn off my device after the routine has finished executing and want to use interrupts to wake it up every 33 milliseconds. Basically, the idea is that if the routine completes in less than 33 milliseconds the processor can shutdown and save power for whatever remaining time, which will hopefully translate to reduced power consumption. I've currenlty managed to turn off my device with the `sleepNow()` function you see below, but the interrupt I have programmed in doesn't seem to work. The program simply goes to sleep and never wakes up. What am I doing wrong?

    #include <avr/interrupt.h>
    #include <avr/power.h>
    #include <avr/sleep.h>

    const uint16_t PERIOD = 2150;

    void setup()
    {
      noInterrupts();
      TCCR1A = 0;            // undo the timer config done...
      TCCR1B = 0;            // ...by the Arduino core library
      TCNT1 = 0;             // reset the timer
      OCR1A = PERIOD - 1;    // set the period
      TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
      TCCR1B |= (1 << CS12); // ...and set the prescaler
      interrupts();

      Serial.begin(9600);
    }

    ISR(TIMER1_COMPA_vect)
    {
      Serial.println(millis());
    }

    void loop()
    {
      Serial.println("Program is on");
      Serial.flush();
      sleepNow();
    }

    void sleepNow()
    {

        // Choose our preferred sleep mode:
        set_sleep_mode(SLEEP_MODE_PWR_SAVE);

        // Set sleep enable (SE) bit:
        sleep_enable();

        // Put the device to sleep:
        sleep_mode();

        // Upon waking up, sketch continues from this point.
        sleep_disable();

    }

body:
It is certainly tempting to go into a very deep sleep in order to save
power, but you still need to keep awake whatever peripheral you want to
use as a wakeup source. If you want to use a 16 bit timer, there is no
other choice than `SLEEP_MODE_IDLE`.

But it may not be that bad. In IDLE mode you can selectively disable the
clock (and hence put to sleep) the peripherals you do not use. Or maybe
put them _all_ to sleep, and then wake up the few ones you do need. This
is achieved with the `power_*_disable()` and `power_*_enable()` family
of functions.

In the edited code below: all peripherals but the Timer 1 are disabled
while the CPU sleeps. The USART is enabled only for the time it needs to
send its message:

<!-- language: lang-c++ -->

    #include <avr/interrupt.h>
    #include <avr/power.h>
    #include <avr/sleep.h>
    #include <util/delay.h>

    const uint16_t PERIOD = 2150;  // 34.4 ms

    void setup()
    {
      // Disable all but the needed peripherals.
      power_all_disable();
      power_timer1_enable();

      // This is for debug pulses.
      pinMode(22, OUTPUT);

      // Configure Timer 1 to wake us up every 34.4 ms.
      TCCR1A = 0;            // undo the timer config done...
      TCCR1B = 0;            // ...by the Arduino core library
      TCNT1 = 0;             // reset the timer
      OCR1A = PERIOD - 1;    // set the period
      TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
      TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
             | _BV(CS12);    // ...and set the prescaler /256

      Serial.begin(9600);
    }

    ISR(TIMER1_COMPA_vect)
    {
      // Send a debug pulse.
      digitalWrite(22, HIGH);
      _delay_ms(2);
      digitalWrite(22, LOW);
    }

    void loop()
    {
      // Enable the USART only while needed.
      power_usart0_enable();
      Serial.println("Program is on");
      Serial.flush();
      power_usart0_disable();

      // And go to sleep in IDLE mode.
      sleep_mode();
    }

Notice also that the ISR does not print to the serial port: it just
sends a debug pulse to watch with the scope. This should be removed from
production code. The delay is achieved with the avr-libc function
`_delay_ms()` because the standard Arduino `delay()` would not work: it
relies on Timer 0, which has been disabled.


message:
Why doesn't the time update?

I am making an arduino clock/alarm. I use an LCD screen to display the time.

    void loop(){
        static unsigned long timing=micros();
        if (mode == 0) {//mode 0 is when the time should show
            timing=countTime(timing);
            writeTime(minutes, hours);//display time
      }
    }
      unsigned long countTime(unsigned long timing){
                if (micros() - timing >= 59946970) {
                  return timing += 59946970;//more precise because Arduino timing is not perfect
                  minutes++;

        }
            else{

             return timing;
            }

          }

        void writeTime(int minute, int hour) {
          lcd.setCursor(6, 1);
          if (minute >= 60) {
            minute = 0;
            hour++;
          }
          if (hour >= 24) {
            hour = 0;
          }
          if (minute < 10) {

            if (hour < 10) {
              lcd.print(String("0") + hour + ":" + "0" + minute);
            }
            else {
              lcd.print(hour + String(":") + "0" + minute);
            }
          }
          else {
            if (hour < 10) {
              lcd.print(String("0") + hour + ":" + minute);
            }
            else {
              lcd.print(hour + String(":") + minute); //possibly split if problems arise
            }

          }

      }

I used to do all this within the loop, but decided to make it separate. Why isn't this code working?

body:
This statement:

    static unsigned long timing=micros();

...only gives it an initial value.  It is not executed during `loop`.  These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.

This requires the definition to be pulled out, to the file scope:

    static unsigned long timing;

    void loop(){
        if (mode == 0) {//mode 0 is when the time should show
            timing=countTime(timing);

Here, the `static` keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.

Make sure to give it an initial value in executable code somewhere:

    void setup()
    {
      ...
      timing = millis();  // Just once?  When the alarm is set?
    }

... and update it as you do in `countTime`.
<hr>
**UPDATE**  It's not clear from your snippet as to *when* the `timing` variable should be initialized, so I originally avoided addressing that.  If it is really initialized just once, at program startup, you can set it in `setup`.  Otherwise, it should be set when the initial `timing` value is finally known.


message:
How can you determine the duration of a timer interrupt?

So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?

body:
The timer takes its time from the system clock. That may be, typically, 16MHz. We call this *F_clk_io* for the **F**requency of the **IO** **CL**oc**K**.

Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.

So first you need to divide the *F_clk_io* by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.

So say you have selected a 1:4 prescaler.  The timer's frequency is then *F_clk_io / 4*, or if it's 16MHz you're running at, then the timer's frequency is *16/4 = 4MHz*.

So at 4MHz each tick lasts for *1/4000000 = 250ns*.

If you want 20ms you need to know how many ticks that would be.

20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.

Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.

Set the prescaler to 1:8 and see what happens...

*16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.*

That fits.  See how doubling the prescaler has simply halved the number of ticks you get in the same time?

So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.

Except it doesn't.

It gives you 20.0005ms.

Why? Because the interrupt triggers and the counter resets when it *reaches* the target count, not when it *passes* the target count.  And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.

So the finished formula is:

    ticks = ((F_clk_io ÷ Prescale) × time) - 1

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible.  If it's not, then there are other tricks you can use.  My favourite is a manual pre-scale:

1. Run the timer at a multiple of your target frequency (10x is easy)
2. Count the number of times the interrupt triggers
3. When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count.  Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.


message:
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++][1] that might work. But I have not tested it yet.

  [1]: http://create.stephan-brumme.com/fnv-hash/

body:
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

  [1]: https://github.com/tzikis/ArduinoMD5


message:
Upload code on Arduino Leonardo using command line

I'm trying to upload a compiled .hex file on an Arduino Leonardo, using the terminal. Uploading a sample code using the Arduino IDE works well, and from the Arduino IDE I got the upload command

    avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

But executing it I got the following error

    Connecting to programmer: .avrdude: Send: . [1b]
    avrdude: Send: S [53]
    avrdude: Recv: . [15]

    avrdude: ser_recv(): programmer is not responding
    avrdude: butterfly_recv(): programmer is not responding

What's wrong?

body:
The problem with the Leonardo is it doesn't automatically reset when you open the serial port like boards such as the Uno do.

The Arduino IDE contains code to manually reset the board (by opening the serial port at 1200 baud and closing it again) which avrdude doesn't have.

Basically you need a different way to reset the board so it enters the bootloader. That may be as simple as just pressing the reset button at the right time (the LED fades in and out when it's in bootloader mode) or using some command line utility to open the serial port at 1200 baud and close it again just before running avrdude.

I don't have my Leonardo to hand right now, but you might have some luck running:

    stty -F /dev/ttyACM0 ispeed 1200 ospeed 1200 && avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i


body:
After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write `.hex` into flash.

In Arduino core `CDC.cpp` we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.

https://github.com/vanbwodonk/leonardoUploader

Only use this simple command:

    leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.


body:
For a Windows solution look here: [How can I force a Leonardo to reset with avrdude?][1]. I made simple bat file wrapper that automates avrdude invocation.
It identifies Leonardo COM port with WMI, resets this COM port to 1200 baud with mode command, then identifies bootloader COM port and invokes avrdude.

Firmware is supposed to be placed to firmware.hex, but bat file can be changed to be supplied from command line.

I've put the code to GitHub repo: [Simple wrapper for avrdude to allow firmware upload to Arduino Leonardo from command line][2].

  [1]: https://stackoverflow.com/a/44823174/8231249
  [2]: https://github.com/p1ne/arduino-leonardo-uploader


message:
Why are pull-up resistors needed?

Please tell me why is it necessary to access pull-up resistors and how can we access them in arduino?

body:
A short answer from [Arduino Playground](http://playground.arduino.cc/CommonTopics/PullUpDownResistor):

> Pull-up resistors are used in electronic logic circuits to ensure that
> inputs to the arduino settle at expected logic levels if external
> devices are disconnected or high-impedance. 'Just because you have
> nothing at all connected to an input pin doesn't mean it is a logical
> zero.'


body:
Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.

The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.

But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.

When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch.  Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.

If, for example, you have a *pull-up* resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low.
Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.

You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU.
The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.

To activate the internal pull-up resistor for a given pin on Arduino, use the following code:

    pinMode(N, INPUT);
    digitalWrite(N, HIGH):

where "N" is your pin number or with recent IDEs:

    pinMode(N, INPUT_PULLUP);


message:
arduino usb android controller

i am pretty much newbie with arduino and want to start my first project so i may be asking stupid questions.

My goal is to make usb controller for android tv (running on raspberry pi or s905). I want it rotary, so turning will be "arrow up/down" or "left/right" (i dont know exact android tv menu controlling) and "return" on push. I found [this](http://www.ebay.com/itm/1-10X-12mm-Rotary-Encoder-Push-Button-Switch-Keyswitch-Electronic-Components-New-/291289671106?var=&hash=item43d237a5c2:m:mFWqvrBn9_vgy9o4j9ucZeg) rotary switch on ebay, is it suitable?

To communicate i want to use arduino. I found libraries [MouseKeyboard](https://www.arduino.cc/en/Reference/MouseKeyboard), which might be suitable for my needs, will arduino nano support this library or do i need arduino uno?

Do i need something else, or just connect switch to pins on arduino and plug arduino to raspberry?

As i need this controller to operate in menu, not just in some application, will this work as some mouse or keyboard connected via otg to android and function immediately?

Thanks.

body:
Yes, that rotary encoder is fine.

Neither the Nano nor the Uno support that library. You will need a device that has native USB support such as the Leonardo or Due, just like it says on the page.

The rotary encoder library you use will tell you how to connect it.

As for specific Android functionality, you will need to ask on Android.SE.


message:
Timeout error uploading code to Arduino Mega 2560

I am new to Arduino programming, and my first sketch (from a tutorial) failed to upload. I am having trouble trying to figure out what is causing it (have tried to upload the sketch using different COM ports on my Mac).

Here's my setup:

> USB COM Port -> Arduino Mega 2560 -> Grove Mega Shield -> Grove Temperature Sensor
> v1.2 connected to Mega Shield UART0.

Here's the code from the tutorial:

    // Demo code for Grove - Temperature Sensor V1.1/1.2
    // Loovee @ 2015-8-26

    #include <math.h>

    //R0 = 100000 results in 'overflow in implicit constant conversion'

    const int B=4275;                 // B value of the thermistor
    const int R0 = 100000;            // R0 = 100k
    const int pinTempSensor = A5;     // Grove - Temperature Sensor connect to A5

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

    void loop()
    {
        int a = analogRead(pinTempSensor );

        float R = 1023.0/((float)a)-1.0;
        R = 100000.0*R;

        float temperature=1.0/(log(R/100000.0)/B+1/298.15)-273.15;//convert to temperature via datasheet ;

        Serial.print("temperature = ");
        Serial.println(temperature);

        delay(100);
    }

And here's the error output:

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_cmd(): short reply, len = 0
    avr_read(): error reading address 0x0000
        read operation not supported for memory "signature"
    avrdude: error reading signature data for part "ATmega2560", rc=-2
    avrdude: error reading signature data, rc=-1
    avrdude: stk500v2_ReceiveMessage(): timeout

What I have done so far:

1) Disconnect and reconnect USB Cable
2) Restart Arduino IDE (1.6.9)
3) Changed COM Ports
4) Press the reset button

Could someone please explain to me what the error output means?

body: Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.


body:
Connect Mega 2560 in one of your port, select the right com port, and try to load the white sketch, look if you obtain the same error..

    //white sketch
    void setup(){}
    void loop(){}


body: Under tools I think it is. Make sure that the arduino you are using is selected and also the right com port (usb port) That might fix the problem


message:
What is the Arduino compiler's version of `__unused` for function parameters?

When I first started with the Arduino environment I noticed that it had `File | Preferences | Compiler Warnings` set to `None`, so I set it to `All` - and there were many, many warnings in the supplied libraries! So I quickly set it to `None` again - until later.

Well, "later" is now, and I started going through the warnings to fix the code to quiet the compiler.

**Note that I don't want to _disable_ any warnings** - I want to placate the compiler at each spot so that it says to itself "No problem here!"

* If the compiler complains of an unused variable, I comment out the variable;
* If it complains of a signed/unsigned comparison, I change the type;
* If it complains of an unused parameter in a function, I...

...hmmm. If this was C++, I'd simply comment out the parameter name, leaving the type naked:

    void Fn(int /*param*/) {
    } // Fn(param)
> Arduino reports:
  `error: parameter name omitted`

But that isn't legal in C. With some compilers you can use the `__unused` attribute:

    void Fn(int __unused param) {
    } // Fn(param)
> Arduino reports:
  `error: expected ';', ',' or ')' before 'param'`
  It's interpreting `__unused` as the actual parameter name

or if they're fussy:

    void Fn(int __attribute__((unused)) param) {
    } // Fn(param)
> Arduino reports:
  `warning: unused parameter 'param' [-Wunused-parameter]`
  That's not the correct `__attribute__`, obviously

So none of the above work in the Arduino environment. Suggestions?

----

I've been programming in C and C++ for over twenty years, and I know that the #1 thing you should always do is ask the compiler to tell you about **everything** it notices. You need a warning-free compile at all times! Otherwise, you spend hours or _days_ trying to find a bug - only to discover that the compiler has been warning you about it all along...

body:
Well, I typed all that question up for posting, then tried one last thing. It worked!

    void Fn(__attribute__((unused)) int param) {
    } // Fn(param)

So, rather than let a good question go to waste: here's the answer!

Now all we need to do is get the maintainers of all the libraries to put these in... and fix the other warnings...


body:
Within the body of a function you can do this to suppress a warning:

    void do_something(int value) {
      (void) (value);
      . . .
    }
You can use a macro to do the same thing, for better clarity:

    #define UNUSED(v) (void) (v)

    void do_something(int value) {
      UNUSED(value);
      . . .
    }
This can be helpful in situations where you have conditional compilation:

    void do_something(int value) {
      #ifndef USES_PARAM
        UNUSED(value);
      #else
        other_stuff(value);
      #endif
      . . .
    }


message:
How to connect the 3.3v pin of arduino mega to multiple sensors

I am connecting 3 accelerometers to an arduino mega. I have everything except how to connect them to the 3.3v pin. I know that I can just connect the 3 of them to the same ground pin but I have been told I can't do the same with 3.3v pin. Can anyone tell me what is the best way to power them from the arduino mega?

body: You can connect all of them as long as the total current draw is not over 50mA as described [here](https://www.arduino.cc/en/Main/ArduinoBoardMega). If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).


message:
Where can I find magnetic declination lookup table?

Is there a way to get approximate value of [magnetic declination][1] from GPS coordinates?

My Arduino-based device has a Magnetometer and a GPS, and uses magnetic declination in calculations. I would like to avoid having to configure it by hand.

I have found references to https://www.ngdc.noaa.gov/geomag/WMM/soft.shtml online, but the site seems to be down (Google has a cache of the site but not of the code).

Is there another way of getting magnetic declination from GPS coordinates? Doesn't have to be precise, +/- 10% would work just fine.

  [1]: https://en.wikipedia.org/wiki/Magnetic_declination

body:
No, the North pointed by GPS coordinates are extracted using the velocity heading which would represent the true North. If you get the ECEF (earth centered earth fixed) coordinates from the GPS you can convert it to a local ENU (east north up frame) and calculate the heading from the velocity vectors (take a look [here](https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_ECEF_to_ENU) if you need the formulas for that).

However, this site http://www.magnetic-declination.com/ can provide you a estimate for magnetic declination at your location.

**EDIT**
From the comment I came across [this topic](http://diydrones.com/profiles/blogs/new-feature-automatic-compass-declination) which lead to [this](http://www.societyofrobots.com/robotforum/index.php?topic=11855.0)

you can play with the code provided and take it as a template for your needs to create a lookup table. The software used for creation of the files is the one present in the site you [pointed](https://www.ngdc.noaa.gov/geomag/WMM/soft.shtml). Just downloaded the linux zip file and tested it with the sample txt coordinates provided and all seems ok.

For the record the command used was (yes for some reason the extension exe is present but this is linux binary):

    ./wmm_file.exe f sample_coords.txt out.txt

which created a out.txt equal to sample output file provided. Now this file can be used by the function `void build_lookup_table()` (present on [grab60_char.c](http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=96aa505bb519df98640d9d1243f90d3b&action=dlattach;topic=11855.0;attach=4966)) to build the lookup table you need.


message:
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

body:
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...


body:
### 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);


message:
Arduino Micro Println prints 0

I am having troubles with my arduino micro.
In my programming, I am using the serial. When I use println, nothing shows up in the serial monitor except for `0`. So if I type `1`, I get back `0` instead of `1`, same goes for `3241234` or any random number.
Here is the code:

    void setup() {
      Serial.begin(9600); //Connect to the serial monitor console
    }

    void loop() {
        while (Serial.available() == 0); //Wait until Serial is available

        //Read val
        int val = Serial.read() - '0'; //Val that represents input
        delay(500);
        Serial.println(val);
    }

So I have another problem and people have asked for the code. Basically, printing a string returns 0.

     void setup() {
      Serial.begin(9600); //Connect to the serial monitor console
    }

    void loop() {
        while (Serial.available() == 0); //Wait until Serial is available

        //Read val
        int val = Serial.read(); //Val that represents input

        delay(1000);
        if (val == 1) {
          Serial.print('Firing the motor');
        } else {
          Serial.print('Please press 1 to fire the motor.');
        }

        delay(4000);
    }

Instead of printing Please press 1 to fire the motor, I get 0 in the console.

Thanks for the help!

body:
Try without

    - '0'

You read your data and save into in int. then print that int, when you pass only the int, you get the int as an ASCII-encoded decimal.
Why r u doing

    - '0'
?


body:
This time you are comparing an integer 1 with a character '1'.

    int val = Serial.read();
Is reading  you pressing the one key and storing it in an integer variable as the number 49 (ASCII '1')

    if (val == 1) {
You are now seeing it 49 is the same as 1, which it isn't.

To make your code easier stick to characters.
Change the Serial.Read line to:

    const char val = Serial.read(); // Val that represents input
                                    // (const because it will not change).

and the if line to:

    if (val == '1')  // '1' character 1

By making val const you stop yourself accidentally changing it so if you do

    if (val = '4') // Compilation error.

Hope that helps.


body: To your second question, strings in C are surrounded by the double-quote character: `"`, not the the single-quote or apostrophe character.


message:
Particle Electron to RS232 Serial gibberish

I've spent all day trying to monitor serial console output of a router. I'm using an "ebay" MAX3232 RS232 to TTL converter connecting only GND, TX and RX to the Electron. Trying to simply monitor the console output during bootup - all I get is gibberish.

Even connected to computer's COM1 port and was unable to echo back and forth. All I get is 0 or weird symbols. (this was tried with more code than below)

Here's my most basic code. I'm about ready to give up. Any ideas?

    #include "Particle.h"

    void setup() {
   Serial.begin(9600);
      Serial1.begin(9600); // tried with 2400/even 1200 really should be 9600
      Serial.println("Starting up Serial");
      Serial1.println("Starting up Serial1");
    }

    void loop() {
     while(Serial1.available()>0)
     {
       Serial.write(Serial1.read());
     }
     delay(50);
    }

body:
If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing.
Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.


body:
You do not need any hardware between the Particle and the router. Both the router and the Particle work at 3.3V logic levels.

* Connect the GND of the router the GND of the Particle
* Connect the TX of the router to the RX1 of the Particle
* Connect the RX of the router to the TX1 of the Particle

You only need the MAX3232 if you want to connect direct to your computer's RS232 port:

* Connect the GND of the MAX3232 to the GND of the computer and the GND of the router
* Connect the TX of the computer to RIN of the MAX3232
* Connect the RX of the computer to DOUT of the MAX3232
* Connect the TX of the router to the DIN of the MAX3232
* Connect the RX of the router to the ROUT of the MAX3232
* Connect the VCC of the MAX3232 to +3.3V from the router.


message:
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][1]).

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?

  [1]: http://www.clearwater.com.au/code/rc5

body:
    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


message:
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?
![Arduino](https://i.stack.imgur.com/I8HWi.jpg)

body: 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)


message:
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?

body: Declaring a variable inside a block means that they only exist within that block. Once the block is exited, they become inaccessible.


body:
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.


message:
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][1] 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.

  [1]: http://playground.arduino.cc/Code/Timer1

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


message:
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?

body:
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.


message:
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](http://www.filedropper.com/feeds8) 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.

body:
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.


message:
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

body:
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);