text:
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!

At the end of what you say the code outputs, is “(...)” part of the output that you see, or not?  If it isn't, how does the output differ from what you expected to see?  If there are four items in a vector, four i.pop_back() calls should empty the vector.

delete this->__data; //program crashes here ... should use delete[] right? Also there is no platform code in your class so you could debug on pc where there are much better debugging tools available.

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/deletes 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();
  }

}

Alright, thanks a lot! A lot of the issues were just plain distraction on my end, I was trying focus on fixing the memory problems I was facing at first.

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.]

I deleted the entire vector(T obj, int count = 1) constructor and it compiled without errors, so that wasn't the issue in this case, but you are right that __data was not initialized.

should never have compiled - it tested the functions rather than calling them. capacity is a member function, not a variable. I picked that up when I tried compiling it under clang.

Hee hee! I missed that - and you're right!

a bit of advice: Your code is practically unreadable. Use a better coding style: https://google.github.io/styleguide/cppguide.html

I also fail to see why you are doing this. While full-blown STL is not supported, there are several well-debugged implementations that you can find with a simple google search.
If you are doing it to learn C++, the arduino environment is probably the worst way of doing it!

You are quite right - for example see Maniacbug's StandardCplusplus. However in this case I wanted to make the answer a bit of a tutorial on writing classes.

I wasn't familiarized with a lot of the info, you're right. I should have started elsewhere. Anyway thanks a lot of pointing out those mistakes, it would have taken ages to find them by myself.

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.

You have a point here. In particular the push_back idea which incrementally allocates more memory (which is normally fine on a PC with 4 Gb of RAM) is likely to introduce memory fragmentation. I think even normal STL implementations allocate vector memory (capacity in this case) in batches (eg. 10 at a time) to reduce this issue.


text:
why my arduino uno r3 restart when plugged in to a battery(9v)
i have a personal challenge that is to make a arduino avoidance robot it has a"hc-sr04 ultrasonic sensor, a servo, bread board(for the sharing of vcc and gnd), l9110s motor driver, and two dc motors, and also the arduino uno itself"
but when i assembled it and upload the code it works if it's plugged in my laptop but if i plugged it in to a battery it keeps on restarting and doesn't run

please provide more info.  Do you mean a 9V alkaline cell to power the whole system?  If so this is a common beginners problem where the battery does not provide enough power.

PP3 batteries are, to put it mildly, complete and utter rubbish. Only suitable for powering smoke alarms. Not suitable for use with Arduino under any circumstances.

a 9V battery contains six AAAA cells ..... those would barely work in a tv remote control, let alone powering a motor

Let me guess: the Arduino resets just as one of the motors starts (or should start) right?
The 9v battery is incapable of supplying enough current for much of anything but a few LEDs. When the Arduino first turns on a motor, it needs, and tries to draw, more current than the battery can supply, resulting in the battery voltage dropping below the Arduino's voltage-regulator's minimum input voltage, and the Arduino is shut off. That stops the current draw, the battery voltage recovers, power up the Arduino, which resets (as they always do on power-up), and the cycle keeps repeating.
Try powering it from a more capable battery of greater than 7 volts. 5 AA cells in series, for example would provide 7.5 volts. This won't last terribly long but should work for a while. A second (third, ...) string of 5 in parallel with the first should double the life. Using C or D cells instead will increase the life a lot more.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Serial.parseInt() takes longer time than desired
My whole code for master. Please head to void read() where I've used parseInt()
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //Set up nRF24L01 on CE pin and CSN pin respectively

const uint64_t pipe = 0x0ABCDEF; //Address for communication between master and slave
uint16_t data[7];
const uint16_t buffer_size = sizeof(data); //Size of the payload for the RF
int i, flag;
int tx_counter = 0;

void read();
void setup() {

  Serial.begin(115200);

  radio.begin();
  radio.setChannel(2);
  radio.setDataRate(RF24_1MBPS);
  radio.setPALevel(RF24_PA_MIN);
  //radio.powerUp();
  radio.openWritingPipe(pipe);
  //radio.setPayloadSize(7);
  radio.stopListening();

  //Default values range from 100 to 700
  for (i = 0; i < 7; i++) {
    data[i] = 100 + (100 * i);
  }
  flag = 0;
  Serial.println("Enter 7 values");
}

void loop() {

  read();

  if (flag) {
    bool tx_ok = radio.write(data, buffer_size);
    tx_counter++;
    Serial.print("Transmission count:\t");
    Serial.println(tx_counter);
    print();
    if (tx_ok) {
      Serial.println("Transmitted Successfully");
      Serial.println("\nEnter Next set of 7 numbers");
    }
    else Serial.println("Transmission failed");

  }
}

void print() {
  for (i = 0; i < 7; i++) {
    Serial.println(data[i]);
  }
  flag = 0;
}

void read() {
  while (Serial.available()) {
    for (i = 0; i < 7; i++) {
      data[i] = Serial.parseInt();
    }
    flag = 1;
  }
}

My problem is that Serial.parseInt() takes some time. The code prints out the values to the serial monitor after sometime. I have timed it and it appears to be around 7 seconds. The arduino page on the function says default timeout is 1 sec. So I think 7 elements in the array takes 1 sec each. If I use Serial.setTimeout(2000), the same thing takes 14 seconds.
This has got to have a simpler way. I want it to behave like when we use Serial.read. Please help me on this.

i think that Serial.available() has a timeout of several seconds before it decides that there is no more data

I am confused. you send a 7 bytes long binary buffer over radio. and then you print the content of the buffer as numbers to local Serial Monitor and you parse data from Serial Monitor. do you enter numbers in Serial Monitor? every Serial.parseInt waits a second for a number sent from Serial Monitor

@jsotola the Serial.available returns how many bytes have been received (and are in the Serial receive buffer, waiting to be read). That's all, nothing else.

@Juraj Yes I enter numbers in the Serial monitor. I am printing it to just keep a track of the values in the array so that it should match at the receiver's end. If I enter the number '2' and wait for some seconds, it automatically timeouts and the rest all becomes zeroes. I want it to wait for the user's input infinitely.

this is what you want:
void read() {
  for (i = 0; i < 7; i++) {
    while (!Serial.available()); // wait forever for some input
    data[i] = Serial.parseInt();
  }
  flag = 1;
}

Thanks for this. Works except with a small issue. The first value transmitted alone is 0. And after each transmission, if I enter next set of integers quick enough this doesn't occur. A sample received value showing this  0 8 84 51 162 21 651

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Deploying an Arduino Uno R3 standalone
I have an Uno R3 with a sensor board and a temperature sensor. I'm running a simple temperature check and would like to store that data outside the Ardunio for keeping records, graphs, etc.
I powered it from my PC during development, but obviously I want something more compact when deployed. It's still inside the house, but I want the PC shut down, not running 24/7.
I do have wireless access, and a Raspbery Pi 3 model B. Can any of those help? Or should I buy an ethernet/WiFi shield and try to get acces with those?

you can connect the sensor to Raspbery

add Ethernet shield, log to SD card and download logs over Ethernet to PC for evaluation

How much data are you storing?  Use the 328P's internal EEPROM, download it to the PC when you power the PC up.

@Juraj - Thanks for your suggestion. I actually prefer to make this completely unattended, with no PC involvement except to access the rendered data.Using the raspberpi would be ideal to me.

@CrossRoads - Thanks for your suggestion. I actually prefer to make this completely unattended, with no PC involvement except to access the rendered data.Using the raspberpi would be ideal to me.

wifi shield and SD card .... run a web server on the arduino .... download the data file using a web browser

The simplest is to use an SD card shield and write your data to the card, occasionally exchanging cards. This can be very infrequent if you like; SD cards are pretty dense. Advantage: Simple and direct. Data remains under your direct control. Disadvantage: Finite (but potentially large) capacity; Data remains on your Arduino -- sort-of. Not sure how "outside the Arduino" you need it to be).
Another option, though a little more complex, is to use a networking device to log your data to an online service such as Thingspeak. I personally favor ESP8266 radios, as they're very cheap and easy to work with, but the choice of an Ethernet shield, WiFi shield, or whatever else, is up to you, and the techniques (from the Arduino's point of view) are similar. Advantage: Your data is saved off your Arduino immediately, somewhere with an "approximately infinite" capacity; provider may (Thingspeak does) offer plotting and analysis tools. Disadvantage: Your data does not remain under your direct control (though you can presumably collect it if you need/want to).

I eventually went with a separate ethernet shield

My first reaction is similar to Juraj's - go straight to the PI with the sensor; this is the most straightforward and maybe the simplest answre.  There are caveats - your sensor may not have a straight-forward hookup and, more importantly, the Raspberry PI uses 3.3V inputs - the Arduino can take up to 5V.  Don't fry your PI.
Next, you'll have to program your PI to read the sensor.
Another option is to use your Arduino to send the data serially to the PI. Again, verify your voltages.
Third, you can, mentioned, use an Ethernet shield, or some wireless daughter-board to talk to another computer like the PI or a server somewhere that stores/analyzes the data.  It tends to get more open-ended and can be as complicated as you like at this point.  Good luck!

So you would rather use your Raspberry Pi than your PC? Easy, as it
turns out that a Raspberry Pi is not that different from a PC running
Debian or a Debian-like OS (e.g. Ubuntu).
Just connect the Uno to the Raspberry Pi through the USB link. Log the
data on your Raspberry exactly like you would do on the PC. You don't
need any Ethernet or WiFi shield. You just need to make sure that
whatever logging program you use on the PC can run on the Raspberry Pi.
This is most often trivial if the PC is itself running a Linux distro.


text:
Is it possible to connect a camera to an arduino?
I working on a project that requires a small camera to be covering a (insect) nest entrance. The video needs to be transmitted to a computer to be processed. I am interfacing with Java using the RXTX library and will then be tracking objects using OpenCV.
This is the camera
My question is, it it possible to connect this camera to an Arduino (Uno or Yun) and transmit the data back to a computer?

Why don't you get a camera that connects directly to the PC?

@Gerben i don't think the insects will slow a PC near there nest.

I'd just go with a raspberry pi, and usb-webcam of the pi-camera-module. Then you could even run the OpenCV on the Pi itself. Having and Arduino, some camera, some kind of networking shield will quickly become expensive. PS what do you mean by the word slow?

Thanks. Ideally, the connection between the computer and the camera would be wireless. Would this be possible with the pi camera? The other option, is to scrap the Arduino and use a wireless transmitter and receiver set

Yes. Check out ArduCam. Do a google search. http://www.arducam.com

Thank you. I'm a bit confused about the Arducam. Am I able to just use the library with the camera that I specified or do I need to purchase the Arducam camera? Also, would I need the shield?

I didn't mean shield, I meant the board that they are using for the camera, but I think that it is just an Uno

I picked up one of these Arducam Mini Module Camera Shield 5 Megapixels OV5642 Camera Module for Arduino UNO Mega2560 Board https://www.amazon.com/dp/B013JUKZ48/ref=cm_sw_r_cp_api_wlbKxbSN0G2KK You find cheaper ones on eBay b

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to call class A's method from class B?
I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:
The main sketch:
#include "MainClass.h"
MainClass m;
void setup() {
  m.setup();
}
void loop() {
  m.loop();
}

MainClass.h:
/*
  MainClass.h
*/
#ifndef MainClass_h
#define MainClass_h
#include "Arduino.h"
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
};
#endif

MainClass.cpp:
/*
  MainClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
MainClass::MainClass()
{
  d DoClass(this);
}
void MainClass::setup(){
  Serial.begin(9600);
}
void MainClass::loop(){
  d.callMainClassFunct();
}
void MainClass::printStuff(){
  Serial.println("printing stuff");
}

DoClass.h:
/*
  DoClass.h
*/
#ifndef DoClass_h
#define DoClass_h

#include "Arduino.h"
#include "MainClass.h"
class DoClass
{
  public:
    DoClass(MainClass m);
    void callMainClassFunct();
  private:
    MainClass _m;
};
#endif

DoClass.cpp:
/*
  DoClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"

DoClass::DoClass(MainClass m)
{
  _m = m;
}

void DoClass::callMainClassFunct(){
  _m.printStuff();
}

This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.
For reference, in Java, I would achieve the same in the following way:
MainClass.java:
public class MainClass{
    DoClass d;

    public MainClass(){
        d = new DoClass(this);
}

    public void setup(){

}

public void loop(){
    d.callMainClassFunct();
}

public void printStuff(){
    Serial.println("print stuff");
}

}

DoClass.java:
public class DoClass{
       MainClass _m;
       public DoClass(MainClass m){
          _m = m;
       }
       public callMainClassFunct(){
         _m.printStuff();
}

}

Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).
I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.

Why are you putting the whole sketch inside a class? This is like shoehorning a Java paradigm into C++. Why don't you ask about the actual problem you want to solve, instead of asking for help in following your misguided attempt at transforming C++ into Java?

I am trying to create a program, which performs various tasks. Each class executes a task: in loop(), I call task1.loop(), task2.loop() etc. depending on the state of the program. Those classes need to respond to the main sketch to update the state of the program based on their completion. I haven't found a way to reference any fields or methods from the main sketch, so I created a MainClass, which would then be passed to those tasks to create aliases and access MainClass. The example that I gave is just a proof of concept - to see if I can reuse a very handy schematic from past Java projects.

In your Java version, you define MainClass like this (my comments added):
public class MainClass{ // Define a new Class
    DoClass d;          // Add a member variable to the class
    public MainClass(){
        d = new DoClass(this); // Initialise the member variable
    } // MainClass()
} // MainClass

In your C++ you don't do the same thing - but you should! The class needs a DoClass member so that you can use it in other MainClass functions:
// MainClass.h
...
#include "DoClass.h" // Need the .h here - remove it from the .cpp
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
  private:
    DoClass _d; // Create a private member variable to use
};

and
// MainClass.cpp
MainClass::MainClass() : // MainClass constructor (note colon)
           _d(*this) // Initialise member
{
} // MainClass::MainClass()

Now, you want DoClass to be able to use MainClass, so you passed it into DoClass's constructor. But DoClass cannot have a MainClass inside it - MainClass already has a DoClass inside it! Infinite impossibility! So you need DoClass to merely contain a reference to the MainClass that it sits inside. That's the C++ unary & operator (different from the binary & operator), which is used similar to the pointer * operator:
// DoClass.h
...
// Need to advise compiler MainClass exists...
// but can't #include MainClass.h! Infinite loop!
class MainClass;

class DoClass
{
public:
    DoClass(MainClass &m); // Reference to MainClass
    void callMainClassFunct();
private:
    MainClass &_m; // Reference to MainClass
};

and
// DoClass.cpp
DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
         _m(m) // Initialise member variable
{
}

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
using esp8266 feather to burn bootloader on redboard
Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an EPS8266 feather though.
If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.

Sparkfun Redboard? yes it is possible, but complicated and it will not help with port grayed out

The RedBoard has an FT232 chip for the USB interface.  Flashing the bootloader on the main MCU will have no effect at all on your problem.
While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.
Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.

well I guess my redboard is broken then. I've tried 3 different cables which I know isn't just for power and the ports work fine with other devices so those are good too, FT232 drivers? don't remember installing those but my arduino worked fine before, and loopback test doesn't work. Guess I need to get a new arduino

What OS are you using?  Check the chip next to the USB port - it should say "FT232" on it.

I am on Windows 10. Chip? on my redboard? This is what I see https://imgur.com/a/SQroRKO

Yep, that's the FT232. The strange looking one.

the latest project i used on it was this https://i.imgur.com/lyP0gkA.png.
I used an 8pack aa battery for 12v and wired it into the vin to power the arduino. reckon that burned it out?

You'd need to test the correct functionality of all the components on the board. Start with checking all the right voltages are in the right places.

It was working as intended. Everything was working fine and the voltages going to the rfid and solenoid was just about right. the voltage going into vin was the exact same as the solenoid at around 11.45v. It's just the next day it just stopped working


text:
ESP8266 feather huzzah wiring for MFRC522
I'm trying to wire the mfrc522 and the huzzah but i can't seem to figure out the rst pin.
I found the pin out diagram but it doesn't show or idk how its labeled as.

use Wemos table from your link. here is the mapping to esp8266 io pins
RST/Reset   D3 = io 0
SPI SS      D8 = io 15
SPI MOSI    D7 = io 13
SPI MISO    D6 = io 12
SPI SCK     D5 = io 14

If you want, you can use any pin for SS and reset. See the examples.
#define SS_PIN 4
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);

@xiao-ning-er, did it help?

Use GPIO0 (D3 on the Wemos).  The reset signal is under program control in the library and isn't the same as the ESP8266 reset input.


text:
Why does this scope-based timer not work as intended?
I wrote the following scope-based timer to help me profile my code and improve its efficency, but in testing I found that it reports durations far shorter than it should:
class CodeTimer {
 public:
  CodeTimer(const String& name) : _name(name) {
    Serial.println("Begin execution of \"" + _name + "\".");
    _begin = micros();
  }

  ~CodeTimer() {
    unsigned long duration = micros() - _begin;
    Serial.println("\"" + _name + "\" execution took " + duration + "µs.");
  }

 private:
  unsigned long _begin;
  String _name;
};

For example, I'd use it like so in my sketch:
void setup() {}

void loop() {
  CodeTimer("void loop()");
  int begin = millis();

  delay(100); // Simulation of work that takes 100ms.
  Serial.println(millis() - begin);
}

Then, when I go to run the above sketch on my Blue Pill board (STM32F103C8), I get something like this printed to the terminal:
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
Begin execution of "void loop()".
"void loop()" execution took 3µs.
101
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100

Something is very wrong with when the destructor to CodeTimer is being called, and I'm not exactly sure what it is.

the code is optimized by the compiler. It executes the prints and ready. there is no reason to hold the object on stack longer

@Juraj Interesting... Is there any way I can prevent it from doing this?

Access the instance after the delay.

@Juraj This makes sense, thank you. However, I'd still be interested in knowing if there's some sort of compiler flag or keyword I can use to prevent this behavior.

Sure, but I mean like for just this one class/instance.

Maybe if you make _begin a static member...? Untested, just off my head

:-) the coders on Stack Overflow have better eyes (or experience). the variable name is missing so there is no variable to live until the end of the scope https://stackoverflow.com/questions/60496359/prevent-compiler-from-calling-class-deconstructor-before-scope-completed

Yes, I discovered this earlier today. Kicking myself for not seeing this...


text:
What makes this library work exclusively with Atmega328P boards?
I've been looking into libraries that read CPPM signals that I can use on my Arduino Pro Micro, and this one looked promising (github.com/jmparatte/CPPM) until I read that it only works on Atmega328P chips. Sure enough, I tried it, and it doesn't function on the Pro Micro as it does on my Arduino Uno. Why is this the case, i.e. what does it have that the Atmega32u4 doesn't?

Implementation
This library works only on ATmega328 implementation of Arduino UNO,
  Duemillanove and similar, also Leonardo. It uses the 16bit Timer1. So
  PWM analogWrite() on pin 9 and 10 are unavailable. The library Servo
  is not compatible because it also uses Timer1.

I tried to do some research on my own, to no avail:

Timer1 isn't specific to 328P, 32u4 has it
For all I can tell, there isn't any difference in the interrupt capabilities of the 32u4...
ICR1 and TCNT are, again, features that the 32u4 has
My signal is connected to the OC1A pin that is used as the CPPM source (pin 9, PB5)

I'm new to this kind of thing and really stumped as to what could be the issue here.

That library relies mostly on Timer 1 and, as you already noticed,
the Timer 1 of the ATmega32U4 is very similar, if not identical, to
the one of the 328P. At least similar enough to expect the library to
work identically.
I took a look at both datasheets and the only difference I can see that
can possibly affect the library is the pinout. The pins relevant to the
library are:
       328P  32U4
ICP1 =  PB0   PD4
OC1A =  PB1   PB5

The pinout of the 328P is hardcoded into the library. CPPM.h contains
these lines:
#define CPPM_ICP1 8 // Input Capture Pin of Arduino UNO is pin 8 - ICP1 (Atmega328 PB0)
#define CPPM_OC1A 9 // Output Compare Pin of Arduino UNO is pin 9 - OC1A (Atmega328 PB1)

CPPM.cpp has two instances (here and here)
of this:
if ((PINB & _BV(PINB1))) // rising edge ?

If you change the code in these three places to match the pinout of the
32U4, I would expect the library to work for you.
You could also change that conditionally as
#ifdef __AVR_ATmega32U4__
    ...
#else // assume ATmega328P
    ...
#endif

in order to make the library compatible with both MCUs, and then submit
a pull request to the original author.

Excellent, when I get to it today, I'll try making that change. Thanks for the theory!

Hold on, what do I replace the PINB part with?

@ifconfig: PINB & _BV(PINB1) tests the state of the PB1 pin which, on the 328P, is the same as OC1A. On the 32U4 you would use OC1A = PB5 for the same purpose. The test then becomes PINB & _BV(PINB5).


text:
Arduino Pro Micro TX and RX leds flash quikly while power drawn from VCC pin
I just got a 5V Arduino Pro Micro, which I connected to an RC RX powered from the VCC and GND pins of the board.
However, whenever I do so and power on the board from a computer USB connection or a wall adapter USB connection, the board goes into an odd mode where the red RX and TX leds flash rapidly (~0.5s on and ~0.5s off) and USB serial ceases functionality. (presumably, because the MCU isn't on anymore)
If I remove the load and power the board again, everything works as normal.
This is an odd behavior, especially since I read online that the VCC pin is rated for ~150ma max and my device (FS-iA6b) isn't a very high power device, tested by me to draw 30-50ma max.
What is happening here? I haven't even connected the 5v signal pin yet!

It would help if you included a schematic.  It sounds like your receiver is drawing too much power.  Are you powering the micro from the USB port or from the RAW pin?  Try powering the micro using the RAW pin with a 4xAA battery pack.

@JeffWahaus I'm not really sure how to upload a schematic, it's a relatively simple set of interconnects: RC RX 5v VCC pin connected to Pro Micro VCC pin, RC RX GND pin connected to Pro Micro GND.

I've been trying to avoid adding an external power source if I can avoid it. The Arduino Uno had enough power on it to power the RC RX...

A standard USB port should be able to supply up to 500mA, it seems like either something is shorted or perhaps you have a 3.3V version of the Pro Micro.

Wouldn't the 4-6v RC RX not power on if the Pro Micro was 3.3v? It does power on.

Aah, I figured it out! @JeffWahaus was correct, the RC RX was placing too great a strain on the Arduino Pro Micro. My latest working theory is that when the RC RX is in communication with the RC TX, it has current spikes that allow the system current draw to exceed that required to drop the voltage coming out of the 5V regulator below that required to shut off the ATmega32U4 MCU.
The solution I found, upon recommendation, was to move the RC RX voltage source from the VCC pin to the RAW pin which taps power from ahead of the 5V regulator and add a 10uf capacitor in parallel with the RC RX to smooth out any current spikes.

simulate this circuit – Schematic created using CircuitLab


text:
Powering an esp32cam by a battery
I have an esp32cam that I've programmed and powered via an FTDI connected to a computer's USB. Now that this stage is over, I'd like to run it portably, using some sort of battery.
The esp32cam has a 5V input (also a 3.3V input which word is should be avoided because it causes brownout). I'm wondering if it's possible to power it (for a short period) using a 7.3V, 9V or 12.3V battery. All the datasheets I've seen seem to specify the input range is 5V, but, for the esp32 (non-cam version), unregulated 5V-12V seems to permissible. Is this true for the esp32cam? Also, what is the right way to search for this?

I'm researching the same topic. Could you please share any links about why 3.3V should be avoided?

The official ESP32-CAM has a AMS1117 voltage regulator that creates the 3.3V for the ESP.
The AMS1117 has an Absolute Maximum Input Voltage of 15V. It has a Dropout Voltage of 1.1-1.3V.
So you should stay above 4.6V to be on the safe side.
Since it's a linear voltage regulator, using a higher voltage battery has no advantage, as the "excess voltage" is converted to heat. It could even damage the regulator if too much heat is created.
You should pick the battery with the lowest voltage that still produces 4.6V when almost empty. So you could use the 7.3V battery you indicated. I'm assuming this is a 2-cell Li-ion battery, that has a voltage of 8.4V when full, and around 6V when empty. Which nicely fits your requirements.

This is awesome, thanks! I wish I knew how to find out these things on my own, but am not there yet. For example, how could I find it's an AMS1117?

Check schematics, and lookup datasheets for parts. Look through the entire datasheet. You'll see a lot of things you don't understand. Don't worry about that. In time you'll start seeing connections; know what things mean; know which parts are important, and which aren't. Some parts of datasheets I still don't (fully) understand, so don't beat yourself up. Learn Ohms law, and try to apply it everywhere. I found that electronics has quite a steep learning curve (coming from software development). So it may feel a bit overwhelming at first. Best of luck.

What if I connect 5V to the 3.3V terminal of the ESP32CAM?


text:
Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield
I need to control a brushless motor that came connected to this ESC using the Arduino CNC Shield V3.00 and Grbl 0.9j.
I connected the ESC's black wire to a GND from the shield and the ESC's white wire to the shield's Z+ limit (end stop).
I then tested by connecting everything but leaving the ESC unpowered, sending several M3 S*commands, where 0 <= * <= 1000, then powering the ESC, but nothing happened.

very interesting post, but unfortunately working only for ATMEGA2560: reference line: #ifdef CPU_MAP_ATMEGA2560 any suggestion to make it possible also for ATMEGA328 chip? it would be really helpful for the most of Arduino UNO+GRBL Shield owner. TKS

After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.
The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.
I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

Import grbl's library in Arduino IDE.
Find out where the library got installed and edit grbl/spindle_control.c, lines 89 and 94.
Change 0x02 to 0x05. Save and close the file.
Compile and download the library to Arduino Uno.
Connect everything but leave the ESC unpowered.
Send M3 S0 (that's a zero).
Power the ESC.
You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
Send S600. It should start spinning. If it doesn't, first send lower values from 0 to 600.
Send S500 to stop.


text:
Is it possible to simultaneously acquire 2 values from the Arduino?
I am currently making a project using a resistive touch screen and an Arduino Uno. The resistive touch screen outputs an X and Y coordinate pair, which I then want to be able to read and output on an X-Y scatter plot in Visual Basic. I am wondering if it's possible to collect these X and Y coordinates at the same time, and read them through the serial port so they can be used in Visual Basic.

no you cannot collect the X and Y coordinates simultaneously ..... those two values would be collected one after the other, some microseconds apart

Since this is a Arduino forum I will answer the Arduino part of your question. Yes you can get the coordinates and get them into the computer via a serial port.


text:
Sketch talks to Android via BLE on Serial2 but times out after 5 seconds when Serial cable disconnected or not present
From an Android phone I am using the "Serial Bluetooth Terminal" app to communicate to an Arduino Mega 2560 with a Bluetooth Low Energy HM10 (Jaycar XC-4382) module connected via Serial2.
If the physical USB serial cable (Serial) is connected to Arduino the very simple sketch below works fine and runs continuously. When the cable is disconnected mid sketch or the power is cycle without the cable connected the sketch will run for about 5 seconds and then stop.
How can I prevent the sketch from timing out when the serial cable is disconnected?
int counter = 0;

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

void loop()
{
    Serial2.print(counter); Serial2.println();
    delay(1000);
    counter++;
}

how do you power it when disconnected from USB?

12V dc power supply plugged in to the mains

The workaround is to switch to using SoftwareSerial, see code below. Data is continuously sent via Bluetooth from Arduino Mega to Android with or without the usb cable connected.
#include <SoftwareSerial.h>

// Connections
// Arduino HM10
// MEGA
// ----    ----
// 3.3v    VCC
// GND     GND
// 12      RX
// 13      TX

SoftwareSerial bte(12,13);    // RX, TX use (2,3) for UNO
int counter = 0;

void setup() {
  // set the data rate for the SoftwareSerial port
  bte.begin(9600);
  bte.println(counter);
}

void loop() { // run over and over
  bte.println(counter);
  counter++;
  delay(1000);
}

he has a Mega with 4 hardware Serials


text:
What components do I need to build Arduino based water pump controller?
I have situation at my home which is causing us a lot of headache. We get drinking water only at midnight and someone has to wake up and switch on electric pump. This electric pump will pump water from water tank present at ground floor to the water tank present on the terrace.
I want to automate this electric pump operation and I have come up with following rules for it:

When water tank at ground floor is almost full then automatically turn on the pump which will push water from ground floor to the tank on the terrace.
When water tank on the terrace is full then switch off motor.

I am a professional software engineer and I have vast experience in Java, Scala, REST API, Big Data and all but I am totally new to Arduino so I do not know which Arduino components I need to build the above mentioned system.
Any guidance will be deeply appreciated.
Thanks,
Chandra

Float Switches are probably all you need.

In fact you can probably do it with discrete logic gates.

How far away are both tanks from each other? It might not be feasible to get a wire from both tanks to the Arduino. Is the pump near the tank on the terrace of near the tank on the ground-floor. If the pump is on the terrace, and you can't get a wire (for the float-sensor) to the ground-floor tank, you could add a RTC module to the Arduino, and always start the pump and 1AM. Have a float sensor in the tank to make the pump stop when the tank is full. Maybe add a flow sensor or something, to make sure the pump isn't pumping air (which might damage it (maybe))

If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful!  http://www.powerswitchtail.com/

The easiest to build would be to use a real-time clock shield for time-keeping (examples: make or buy) and a relay- or solid-state switch shield (popular item - many choices) for switching the pump. A simple wall power supply providing 5volts to run the Arduino completes it. Oh, yes - an Arduino board, too!


text:
Trying to run Timer1 in ATmega2560 with assembly
I have a slight problem with Timer1 in arduino (ATmega2560) while coding it in assembly. I try to run the Timer1 in CTC mode - I configure everything well in my opinion, but the TCNT1 just doesn't increment each clock cycle, as it should. I checked the registers in Atmel Studio and everything seems okay, but maybe I forgot about something?
Here is the code
.ORG 0
jmp start

.ORG 0x22
call isr_toggle_PA0

.ORG 0x400
start:
LDI R16, HIGH(RAMEND)
OUT SPH, R16
LDI R16, LOW(RAMEND)
OUT SPL, R16 ; initialize stack pointer
clr r16

ldi r16, 0xff
out DDRA, r16 ; port A output
ldi r16, 0x00
out DDRD, r16 ; port D input
clr r16

ldi r20, 1<<OCIE1A
sts TIMSK1, r20 ; enable Timer1 A comapre match interrupt
sei

ldi r20, HIGH(25000)
sts OCR1AH, r20
ldi r20, LOW(25000)
sts OCR1AL, r20

ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20
ldi r20, 0
sts TCCR1C, r20

; --- start main
main:

inc r16
rjmp main
; --- end main

isr_toggle_PA0: // toggle bit on PA0
    ldi r16,0x00000001
    in r17, PORTA
    eor r17,r16
    out PORTA, r17
    reti

Thank you and have a good day :)

Here:
ldi r20, 0b00000010 ; CTC mode, int clk;
sts TCCR1A, r20
ldi r20, 0b000000101 ; prescaler /1024
sts TCCR1B, r20

you are setting the bit WGM11 on TCCR1A. The timer then runs in mode 2 (PWM, Phase Correct, 9-bit) rather than mode 4 (CTC).

Amazing!! Ineed that was the bug. For the ones wondering, the correct version is
ldi r20, 0b00000000 ; CTC mode, int clk;  sts TCCR1A, r20    ldi r20, 0b000001101 ; prescaler /1024  sts TCCR1B, r20


text:
How can I get my (Arduino) Pro Micro schematic to allow me to program it through GPIO instead of USB
I'm trying this project so far I've got the schematic of a Pro Micro, which is powered through GPIO from a Raspberry Pi Zero, and want to remove the micro usb connection and able to flash it using an avr programer and a few pins.
How do I get to Achieve that? also the Pro Micro is getting D+/D- from the the raspberry's D+/D- pads as well. Schematic below for reference.

Yes, you can program Pro Micro with programmer.

you cannot power the board through GPIO pins ... those are for input/output only

if Micro is connected to PI with USB, you can use it for serial upload to Micro from PI with avrdude.

I would like to understand what you want to build. PI has GPIO so why to attach a Micro?

Please provide an explanation of what you mean by this: "flash it using an avr programer and a few pins", and why you want to do that.

It's unfortunate m1gu3 wouldn't bother to answer my question. I believe I might provide a useful answer. In the latest avrdude 6.3.0-arduino14 from Arduino, a linuxspi programmer option was added. This allows you to use an RPi as an ISP programmer. You can find a general overview in the 2nd half of https://learn.sparkfun.com/tutorials/raspberry-pi-stand-alone-programmer and some more technical discussion at: https://github.com/per1234/Arduino_Boards/pull/1. Currently it only works if run as superuser. That bug should be fixed in the next avrdude release, after which I will release a package.

@per1234, thanks for getting back at me with this. Actually the whole goal of the project is to have this arduino compatible board that can house a button matrix, screen, battery and raspberry pi, such like the PocketChip. I want to avoid having this particular USB for the arduino part since the power supply will have a usb for charging. Hope that answers your question.

Welcome to arduino.stackexchange.
You can program your ATmega32U4 on at least two ways:
1. Use Arduino's bootloader and D+/D- pins. This way you won't need an external programmer. Try search for phase "programming ATmega32U4 with bootloader".
2. Use ISP (In-System-Programming) method. In this case you can use your avr programmer. To do so you also need access to PINs named Reset, MISO, MOSI, SCLK. See this link or this one
As always, the important read is ATMega32U4 datasheet.

Awesome, links and everything. Thanks a lot!

An avr programmer uses the ISP interface to program a chip. For this you need the pins for MOSI, MISO, SCK and Reset. Of course you have also to provide power to the board through Vcc and ground.
I'm not sure, if it's OK to keep the USB connection while programming via ISP, but since you want to remove that connection either way, this isn't a problem for you. You can remove the USB connection completely (no D+ or D- connection).
Note: when you are programming the Arduino Micro via ISP without also burning the bootloader, you won't be able to use USB for programming anymore, until you burn the bootloader again.

Sounds good, so basically a 4 pin header with MOSI, MISO, SCK and RST will do the trick. And yeah its exchanging data with the rPI without the USB plug I guess. Sorry not an expert on this kind of things, thanks!

Depending in the voltage, that the Micro runs on, you may need a level shifter, so that nothing gets damaged due to too high voltage

Why don't you buy a pi zero to USB  add-on board?
You can stack the pi on top and plug it into a normal female USB port on your computer.
The USB board has some pins that connect to the solder points of the mini USB, so you can delete all the connectors you won't need.
Other option is to solder a wire to the pi and extend the connector with a cable.
I'm not shire, if you can program the pi true its serial pins.
USB is a serial connection after all. So I think this should be possible

Hey @DAM, your idea sounds very doable but the main concept of this project is to have a mobile rPi, I want to flatten it most I can. But thanks for your input I might use some of those ideas too!


text:
What is 1.8 to 5.5 VDC?
I'd like to buy a standalone capacitive touch sensor to create interactive art.  It says it is powered by 1.8 to 5.5 VDC.  I am new to arduinos - what type of battery can I buy to power this sensor?  I'm hoping it's simple, not complicated. Thanks!

Welcome, Sarah. That means that you can power your sensor with anything that delivers at least 1.8 volts of direct current upto at most 5.5 volts. Depending on the model of your Arduino, it has either 3.3V and/or 5V outputs for powering other components and its pin are expecting signals of the same voltage level.

VDC is an abbreviation for volts DC. DC means Direct Current you can read more a detailed explanation about it here. Basically what powered by 1.8 to 5.5 VDC means is that the DC voltage on the input of your sensor can vary from 1.8 volts up to 5.5 volts. So you can use either 3 AAA batteries in series since the sum of their voltage will be: 1.5V * 3 = 4.5V what is in the range of recommended voltages for your sensor. Also, you can use a Li-ion battery in order to power your sensor since the voltage of this type of battery is 3.7V it is also in the range of recommended voltages for your sensor. However you would need an additional charge/discharge module in order to recharge and keep the battery in a good condition. You can read more about it on the web.

do you have a 5V power supply?
If you do I'd suggest connecting your arduino to the power supply and then you can power your sensor with a pin of the arduino.


text:
Transient buttons control non-transient behaviour of LEDs
Imagine a system where you have two transient non-exclusive buttons and two LEDs.
When you press button 1, the LED 1 is HIGH and LED 2 is LOW (and stays that way).
When you press button 2, the LED 1 is LOW and LED 2 is HIGH (also stays that way).
Which C++ code allow me, to keep the LED 1 turned on indefinitely (until button 2 is pressed)?
Basically, my problem is, that the buttons are transient and the behaviour of LEDs shouldn't be.
Here is code, that would work for pernament exclusive buttons, but doenst work for transient non-exclusive buttons.
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
}
else
{
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
}
else
{
    led2 = LOW;
}

Is the answer just: "remove else branches and add reset for other led to the same branches"?  And for that "attack" this isn't homework resolving facility. Without your code it was just too broad.

Something like this:
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
    led1 = LOW;
}

Don't react to the button by changing the LED; change a state-variable in memory, instead. That saves the information of which button was most recently pressed. Then, each time through your loop, set your LED's according to the contents of that persistent variable. Remember that it will have to be a static variable (global or static local), as an automatic one will disappear and reappear after each exit and re-entry to loop(), and you cannot count on its contents when that happens.
Update:

How do I prevent overwriting the state variable with different input ?

You don't prevent it - you must over-write it. The purpose of the state variable is to remember which button was last pressed. I had in mind something like the following, where lastButton saves the number of the most recent button:
void setup(){
   pinmode(LED1PIN, OUTPUT);
   pinmode(LED2PIN, OUTPUT);
   pinmode(BUTN1PIN, INPUT_PULLUP);  // you might not want the pullup
   pinmode(BUTN2PIN, INPUT_PULLUP);  //  depending on your wiring.
}

void loop(){
   static uint8_t lastButton = 0;

   // Save the number of the last button pressed.
   if (digitalRead(button1) == HIGH)
      lastButton = 1;
   else if (digitalRead(button2) == HIGH)
      lastButton = 2;

   // Set the LEDs according to most recent button
   // Note that at program-start, when no button has
   // been pressed yet, this code leaves both LED's off.
   if (lastButton == 1)
   {
      digitalWrite(LED1PIN, HIGH);
      digitalWrite(LED2PIN, LOW);
   }
   else if(lastButton == 2)
      digitalWrite(LED1PIN, LOW);
      digitalWrite(LED2PIN, HIGH);
   }
}

Thanks, but how do I prevent the corruption of the variable, by pressing another button ? Lets say, I make code in which, something is gonna happen after b1 (state-variable) is true. That is gonna send me into while loop, but when you as user press Button2, b1 gets reseted to false and the loop will be exited ?. How do I prevent overwriting the state variable with different input ?

I might make my question more intelligible and make another thread. I am not sure, if its clear enough.


text:
How to package a 16 bit integer to send it with serial.write?
I am trying to display the values i get from reading a potentiometer (0-1023) in the program called 'processing'.
when I just use Serial.write(integer) and display the value on a line graph in 'processing' the line will max out at 256 and loop back around to 0 as i vary the potentiometer.
I understand that this is because the serial.write can only write in bytes(8 bits) so I would need to package the 16 bit integer into 2 bytes.
i was considering using a union but as you can probably guess i am very new to arduino so i haven't been able to make that work.
here is the code i have tried:
union Data{  uint16_t now; } data;

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

}

void loop() {   // put your main code here, to run repeatedly:
    uint16_t sensorVal = analogRead(A1);
     union Data data;

    data.now = sensorVal;

    Serial.println(data.now);

    //Serial.write(sensorVal);
    delay(10); }

why do you prinln() the union, but write() the int? does Processing expect the number as text or as byte values? perhaps you need Serial.print(sensorVal) to send the value as text. btw: union with only one member is not an union. You can write int as write(&sensorValue, sizeof(int)), but I doubt that Processing will understand that

Send the 16-bit value as two 8-bit values (with a start byte as per JRobert's answer):
Serial.write(0xCC); // Send the start byte
Serial.write((sensorVal >> 8) & 0xFF); // Send the upper byte first
Serial.write((sensorVal & 0xFF); // Send the lower byte

You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).
Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).
The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.

This may help
Transmisor
int valor;
byte val;

void setup() {

Serial.begin(9600);
}

void loop() {

valor=analogRead(A0);
val=map(valor,0,1023,0,179);
Serial.println(val);
Serial.write(val);
delay(100);
}

Receptor
byte mensaje;
int valor;
void setup() {

Serial.begin(9600);
}

void loop() {

if (Serial.available()){
  mensaje=Serial.read();
  valor=mensaje;
  Serial.print(valor);
  Serial.println(" ");
}
}

Sometimes mapping values 0 .. 1023  to a range 0 .. 179 is nice. Sometimes it's easier, to map them to 0 .. 255 (By a division/4 or a right shift by 2 bits from 10 bit ADC to an 8 bit value).

I was checking out the documentation for Serial.write()
You can sent out an array of 2 8Bits in the form of Serial.write(buf, len)
Simply create an int buffer, and then use your original integer and do bit shifting. Notice the & 255 used to make sure there are no values beyond 8 bits.
int data = 1000;
short int buf[2];
buf[0] = data & 255;
buf[1] = (data >> 8)  & 255;
Serial.write(buf, 4);

Also, in C, the name of an array is used as the pointer for the first element. So if you look at the documentation for Serial.write(buf,len) again, you will find that you can probably get the pointer for your int value, and write 2 bytes itself!
Serial.write(*data, 2);

or Serial.write(&data, 2)


text:
Digispark don't work when I power it by 5v and GND inputs and chip starts heating
I'm beginner so probably I did something stupid, but now my digispark don't work when I power it by 5v and GND inputs but chip starts heating immediately. When I power it by USB everything works well. Did i broke it? And how can I check it?

Did you connect it backwards?

Thanks! Actually, I connect backwards my power supply to dashboard. Now it works fine.

You connected the power backwards - so all the current is being shunted straight through the ESD protection diodes (and likely other routes too) generating lots of heat and risking permanent damage to the MCU.
Take better care next time...


text:
Dynamically modifying the call stack using pointers
In a C++ Arduino library, can we modify the call stack from inside a function by intentionally decrementing a pointer to a stack variable so that it's out of range? Like this:
void FooBar()
{
  char a;
  char *ptr = &a;
  ptr -= 4;
  // Can we edit the call stack with ptr now?
}

Can we use this to, for example, change what function is "calling" FooBar() by replacing the function pointer of the calling function on the call stack to another function? Or can we change the values of function variables in the calling function in mischievous fashion?

Yes, you can. Learn the ABI first so you know what is where. https://gcc.gnu.org/wiki/avr-gcc#Frame_Layout However I wouldn't recommend doing so - nasty things can happen if you futz with the stack frame.

Yes, you can, but it won't work. The compiler can do many optimizations, so it is very doubtful that it will work. When you are serious about writing software, then you should never do such things. Stay far away from things that are bound to go wrong. Every software engineer that sees your piece of code is now feeling very uncomfortable and is banging his/her head against the wall screaming out loud: no, no, no.

I recommend you to generate an .lst file and see the assembly

I am answering in the context of the AVR calling conventions, as they
are the only ones I know well enough to be able to answer here.

Can we use this to, for example, change what function is "calling"
  FooBar() by replacing the function pointer of the calling function
  on the call stack to another function?

That will probably be impossible in C++. Let's say you have the
following call chain: main() → f() → FooBar(). In the body of
FooBar(), the stack will look like this (oldest stuff at top):
return address from f() to main()
registers saved by the f() prologue
return address from FooBar() to f()
registers saved by the FooBar() prologue

Getting the stack pointer is easy. No need to declare a dummy variable,
just:
char *stack_pointer = (char *) SP;

Now, to change the required return address, you need to skip over the
registers saved by the FooBar() prologue. And this is the big problem:
you do not know how many registers were saved there. Function prologues
are written by the compiler, and whatever they save depends on how many
registers are needed within the function, which in turn depends on the
complexity of that function. Even minor changes to the function can
modify the number of registers its prologue saves.
The only solution to this problem I can imagine is to forego the
compiler-generated prologue and write FooBar() in assembly. If you
wish to do it within a C++ file, you can attach the "naked" attribute to
the function and write its body using inline assembly.

Or can we change the values of function variables in the calling
  function in mischievous fashion?

No need to tamper with the stack for this. The compiler strives to store
as many local variable as possible in CPU registers rather than the
stack. The caller's local variables are most likely still in those
registers and you can modify them at will (in assembly). That's why you
have this register-saving prologue and register-restoring epilogue in
the first place. Indeed, if you make the function "naked" and don't do
the saving/restoring yourself, you will very likely end up corrupting
the caller's locals.


text:
Using TFT with hardware SPI and speaker with tone()
I want to make a device with a TFT screen and a speaker that uses the builtin tone() function. However, according to the documentation, using tone() interferes with PWM on pins 3 and 11. On the Arduino Uno, the MOSI pin is default on pin 11, and it seems like defining another pin for MOSI disables hardware SPI, which, according to the module page, slows down the device. As well, the examples are written for hardware SPI and the SD card is only available with hardware SPI. What should I do here? Is there a way to redefine the default MOSI pin without disabling hardware SPI?

It is no problem. The tone function uses timer2 which is the same timer when using pwm for pin 3 and 11. The tone function does not interfere with pin 3 and 11, it only uses timer2 for a software interrupt to create a tone on any pin. The tone function does not use the pwm capabilities of the microcontroller.

short version : "interference with PWM", not with SPI

You are getting your wires crossed in your brain and imagining a problem where there is none.
Both PWM on pins 3 & 11, and tone(), use the Timer2 device. Only one of those can use Timer2 at a time, and they both want to use it in different ways, so there is a conflict between them.
Timer2 has nothing to do with SPI. So tone() has no effect on SPI, and nor does PWM have any effect on SPI (other than the fact that only one can come out of pin 11 at any time), since there is no internal resource conflict.


text:
OTA update - sodaq board (arduino M0 compatible)
I am trying to perform a firmware update from an SD card, on a Sodaq Sara AFF board. If i use the SDU.h library in my sketch, it fails the board check. See this link please.
I have edited the SDU.cpp myself to force the selection of ARDUINO_SAM_ZERO. It is now :
__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x6000] = {
  #include "boot/mzero.h"
};

I have increased the size to 6000 otherwise it was complaining too many initializers.
I also have changed the SD_SS_PIN to match my pin on the SDUboot.ino, under extras. Afterwards, i recompiled it with build.sh in the same folder.
But I am unable to perform the firmware update. After power cycling the board (original code: the blink example, target update: blink with a faster rate) - the original firmware remains.
I exported the firmware using arduino IDE -> export compiled bynary, and tested both versions with and without bootloader.
Any help would be appreciated.

what bootloader has the board? the difference between MKR/Zero and M0 is for SDU the bootloader size which is 2kB for MKR and Zero and 4 kB for M0. why do you want to use SDU? is your sketch larger then half of the flash?

@Juraj the board has a ATSAMD21J18, 32-Bit ARM Cortex M0+. So, I assume 4 kB bootloader size. Is it relevant if the sketch is larger then half of the flash?

Zero and M0 are both SAMD21 but have different bootloaders. the sketch binary doesn't have to be smaller then half of the flash if it is loaded from SD card

https://github.com/arduino/ArduinoCore-samd/pull/344/commits

And what does it mean finally? What is the correct setup to get it work?

@phlegx, the correct way is create .h for SDU library matching pins of the board and this sketch encoded in .h must know the correct bootloader size. it the boards package is not Arduino SAMD but some third party, the it must be modified as the PR in my previous comment

SOLVED!
I have compiled my own SDUBoot.ino with fixed SDU_START 0x2000 and for SODAQ Sara (boot/sodaq_sara.h). My sketch with #include "SDU.h" compiles successfully. The board package is also installed in Arduino (http://downloads.sodaq.net/package_sodaq_samd_index.json). Here my code with changes (base is SodaqCore-samd-1.8.6-sodaq from Github):
File libraries/SDU/extras/SDUBoot/SDUBoot.ino:
#include <SD.h>
#include <FlashStorage.h>

#define SDU_START    0x2000
#define SDU_SIZE     0x4000

#define SKETCH_START (uint32_t*)(SDU_START + SDU_SIZE)

#ifndef SDCARD_SS_PIN
#define SDCARD_SS_PIN 10
#endif

#define UPDATE_FILE "UPDATE.BIN"

FlashClass flash;

// Initialize C library
extern "C" void __libc_init_array(void);

int main() {
  init();

  __libc_init_array();

  delay(1);

  if (SD.begin(SDCARD_SS_PIN) && SD.exists(UPDATE_FILE)) {
    File updateFile = SD.open(UPDATE_FILE);
    uint32_t updateSize = updateFile.size();
    bool updateFlashed = false;

    if (updateSize > SDU_SIZE) {
      // skip the SDU section
      updateFile.seek(SDU_SIZE);
      updateSize -= SDU_SIZE;

      uint32_t flashAddress = (uint32_t)SKETCH_START;

      // erase the pages
      flash.erase((void*)flashAddress, updateSize);

      uint8_t buffer[512];

      // write the pages
      for (uint32_t i = 0; i < updateSize; i += sizeof(buffer)) {
        updateFile.read(buffer, sizeof(buffer));

        flash.write((void*)flashAddress, buffer, sizeof(buffer));

        flashAddress += sizeof(buffer);
      }

      updateFlashed = true;
    }

    updateFile.close();

    if (updateFlashed) {
      SD.remove(UPDATE_FILE);
    }
  }

  // jump to the sketch
  __set_MSP(*SKETCH_START);

  //Reset vector table address
  SCB->VTOR = ((uint32_t)(SKETCH_START) & SCB_VTOR_TBLOFF_Msk);

  // address of Reset_Handler is written by the linker at the beginning of the .text section (see linker script)
  uint32_t resetHandlerAddress = (uint32_t) * (SKETCH_START + 1);
  // jump to reset handler
  asm("bx %0"::"r"(resetHandlerAddress));
}

File libraries/SDU/extras/SDUBoot/build.sh:
#!/bin/sh -x

ARDUINO=arduino
SKETCH_NAME="SDUBoot.ino"
SKETCH="$PWD/$SKETCH_NAME"
BUILD_PATH="$PWD/build"
OUTPUT_PATH="../../src/boot"

if [[ "$OSTYPE" == "darwin"* ]]; then
    ARDUINO="/Applications/Arduino.app/Contents/MacOS/Arduino"
fi

buildSDUBootSketch() {
    BOARD=$1
    DESTINATION=$2

    $ARDUINO --verify --board $BOARD --preserve-temp-files --pref build.path="$BUILD_PATH" $SKETCH
    cat "$BUILD_PATH/$SKETCH_NAME.bin" | xxd -i > $DESTINATION
    rm -rf "$BUILD_PATH"
}

mkdir -p "$OUTPUT_PATH"

buildSDUBootSketch "SODAQ:samd:sodaq_sara" "$OUTPUT_PATH/sodaq_sara.h"

File libraries/SDU/src/SDU.cpp:
#include <Arduino.h>

#include "SDU.h"

__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x4000] = {
  #include "boot/sodaq_sara.h"
};

Sketch file sdu_test.ino:
#include <Arduino.h>
#include "SDU.h"

#if defined(ARDUINO_SODAQ_SARA)
#define DEBUG_STREAM SerialUSB
#else
#error "Please select the SODAQ SARA as your board"
#endif

#define DEBUG_STREAM_BAUD 115200

String message;

void setup() {
  // Start communication.
  DEBUG_STREAM.begin(DEBUG_STREAM_BAUD);

  while (!DEBUG_STREAM) {
    // Wait for Serial Monitor to be opened.
  }

  message += "Sketch compile date and time: ";
  message += __DATE__;
  message += " ";
  message += __TIME__;

  // print out the sketch compile date and time on the serial port
  DEBUG_STREAM.println(message);
}

void loop() {
  // add you own code here
}

File arduino/50/.arduino15/packages/SODAQ/hardware/samd/1.8.6/variants/sodaq_sara/linker_scripts/gcc/flash_with_bootloader.ld add these lines:
KEEP(*(.sketch_boot))

. = ALIGN(0x2000);

here:
...
SECTIONS
{
    PROVIDE(__sodaq_firmware_state = ORIGIN(FLASH) - 0x100);

    .text :
    {
        __text_start__ = .;

        KEEP(*(.sketch_boot))

        . = ALIGN(0x2000);
        KEEP(*(.isr_vector))
        ...

On SD card (formatted as FAT32) I have stored the renamed file UPDATE.bin without bootloader of the compiled sketch file. Pin D10 is connected and used as chip select CS.
Build boot hex files:
$ cd libraries/SDU/extras/SDUBoot
$ ./build.sh

Version 1.8.6-sodaq has these missing lines on arduino_zero variant but not on sodaq_sara variant.

Hi, I was away due to things changing in Cororna times, but now I'm back.
This does not work. It compiles, but I am unable to load the new firmware without bootloader.


text:
AK4524 with Arduino
I have some AK4524 ADC/DAC chips from an old M-Audio Delta 10/10 sound card in my hand.
I would like to use them for precision sensor reading and voltage generating with a arduino nano.
My experience with digital electronics is limited, i have used mcp4822 as a dac before with arduino and a bit familiar with SPI.
Would you point me to the right direction on this matter.
https://people.freebsd.org/~lofi/4524.pdf
This is the datasheet.
Thank you.

You can't use those with an Arduino Nano. You need a microcontroller that can generate a full duplex I2S data stream, and that usually means one of the 32-bit boards. Probably a Teensy 3.x is your best bet.

Also audio CODECs aren't really suitable for sensors.

Thank you very much, why would an audio codec not suitable for sensors? Because of the DC AC difference? Also would these be easy to interface with a Teensy?

They don't work quite the same as a voltage DAC like you're used to. They need a constant stream of data feeding to them to control the output voltage (which is a differential output, not single-ended), and the ADC gives a constant high speed stream of data - tens of thousands of readings per second. You can't just go "Set DAC A to 23" or "Get me the current ADC value from channel 1".

Thank you I will do more reading on the differences.


text:
Programming an EL Sequencer
I have a EL Sequencer and FTDI 5V breakout board.  I have been have been unable to program it.  All my attempts get some variation of "programmer is not responding".
I was using these instructions as a starting place.  I soldered the 6 pinholes as indicated.  I have connected everything.  I am not sure if I should switch the FTDI jumper to 3.3V (it is currently at 5V).  The pin in the EL Sequencer is labelled 5V, but the instructions also say "the EL Sequencer runs an ATmega328p at 8 MHz and 3.3V".  Should I change the jumper to 3.3V?
I have downloaded the latest IDE from here.  But there is no board option for the EL Sequencer.  What board should I select?
Anything else I need to do to program the EL Sequencer?
Thank you,

is the FTDI board working correctly?

I am not sure how to check.  It was new when I purchased it.

just because it is new does not mean that it works ......... connect RX and TX together ..... plug the module into your computer .... open serial monitor, choose the correct com port ..... type something on the keyboard ..... you should see the characters on the screen .... you should also see the LEDs on the module flash

Thank you for telling me how to test the FTDI.  I did as you suggested and received the same characters that I typed.  I also saw the LED on the FTDI flash.  It appears the FTDI is working.  Is there a similar way to check the EL Sequencer?

no there is not .... just connect everything together as before and try choosing Arduino Uno in the Arduino IDE


text:
How to send characters to Arduino serial using Linux command line without tail -f?
I want to send characters to Arduino serial port which makes the Arduino turn on/off an LED. Here is the code:
int led_main=8;

void setup()
{
    pinMode(led_main, OUTPUT);

    Serial.begin(9600);
}

void loop()
{
    char chr;

    if (Serial.available())
    {
        chr = Serial.read();

        if (chr == '0')
        {
            digitalWrite(led_main, LOW);
        }
        else if (chr == '1')
        {
            digitalWrite(led_main, HIGH);
        }
    }
}

The Arduino is recognized as either /dev/ttyACM0 or /dev/ttyACM1 in my system. When I run the command echo "1" > /dev/ttyACM0, it doesn't work. But, when I open a second terminal, run tail -f /dev/ttyACM0, and then in the first terminal, run echo "1" > /dev/ttyACM0, it turns on the LED as expected. So why do I have to open a second terminal and keep monitoring the output with tail -f in order for this to work? Is there a way to do this with a single command?

Arduinos have auto-reset circuit to reset the board if new connection is initiated on USB. It is good for convenient upload or to reset for debugging at Serial Monitor open. But it causes troubles if you want to communicate with MCU from computer over USB from command line tools, scripts, python, C++, C#, Java. Always on new connection the board resets.
One solution is to disable the auto-reset circuit. Other option is to wait a second after the connection while the board resets.

Using stty -F /dev/ttyACM0 -hupcl worked (found in the link). Thanks!


text:
SSD1306 recognized in I2C scaner, can't get it to display
The gist of my issue is in the title. I have a cheap ebay SSD1306 128x64 display which I hooked up to my arduino, and checked the wiring at least 50 times and the address is correct, the display has the jumper set to 0x78 and the arduino (Nano with ATmega168) sees it on an i2c scanner as 0x3C which is expected.
Now I installed Adafruit's SSD1306 and GFX libraries and an OLED i2c library I found somewhere (can't find it, sorry. In the IDE it's called OLED_I2C) and ran both example codes (shortened Adafruit's to fit on a 168) and I can't get it to show anything. I've tried many things including trying the 128x32 code with no luck, not even missing every other line. I think the display works since it shows up in the scanner, does anyone have any idea what could be wrong? Thanks in advance
My shortened Adafruit code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Draw a single pixel in white
  display.drawPixel(10, 10, SSD1306_WHITE);

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);
  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  testdrawline();      // Draw many lines

  testdrawrect();      // Draw rectangles (outlines)
}

void loop() {
}

void testdrawline() {
  int16_t i;

  display.clearDisplay(); // Clear display buffer

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn line
    delay(1);
  }
  for(i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000); // Pause for 2 seconds
}

void testdrawrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

The scanner (?) finds the display at address 3C but you configure the lib for address 3D. Also the Adafruit code is not specified for a 168. That could be a problem.  I also would not expect to find the device at 0x3C if the jumper is set to 0x78, What did I miss? And where do you use the mizzterious  OLED I2C library? I don't seen an include. You mentioned "both examples" but showed only one. Perhaps I do not know enough to understand your question (or at least the facts) but I'm complete confused. ;-)

Yeah i only showed the adafruit one because i felt it was enough to show where my error was. I didn't use that library in my adafruit code, I tried using its example separately. From online tutorials apparently if the display is at 0x78 it shows up at 0x3C. can you show me where i set it to 0x3D? much appreciated

@Xilog Yeah it's probably an adressing problem, the Oled display you are using , the SSD1306 has an IIC interface, and IIC interfaces have around 127 adrsses as much as I know, the possible two address for such a display are 0x3C and 0x3D, but since it showed in the I2c scanner that it's at 0x3C you should declare that in the 19th line in the code you provide instead of 0x3D change it to 0x3C.

We know the address is 3C, so why want you to change it to 3D? You just can access it at the already configured address like @ShamsEl-Deen  proposed. Another thought: Are you sure the 0x3C is your OLEAD display? Perhaps you have another I2C device with address 0x3C connected the "scanner"'s I2C bus and your OLED at 0x78 is invisible, for some reason.

Thanks, I found it on line 19 and changed it but it didn't fix anything. I am sure that the display is 0x3C. When i disconnect it the scanner says no devices found.

I tried researching a while after asking this question. Turns out changing OLED_RESET to -1 fixed it.

The confusion about I2C address really comes from whether it's treated as a byte or 7-bit (MSB).
For example, on the OLED PCB, it's stated address I2C =  0x78, which is 0b_0111_1000 (I2C address write).
In the Adafruit Arduino SSD1306 library, it uses 7-bit I2C address, that 0x78 becomes 011_1100 (taking the 7-bit MSB) = 0x3C

I have some experience with the the screen you are using and I hope these tips can solve your problem.

Changing the Address in the code

The OLED display you are using uses what is called I2c or IIC protocol which is the abbreviation of "Inter Intergrated Circuit", here is it's Wikipedia page to read about it.
The IIC communication has 7 bit address space, that means there is 127 distinctive address for example 0x3C,0x3D,0x38 etc....
Your display might have either the address 0x3C or 0x3D so you might try changing theses values until anything would show up.

Unhooking any other IIC device

Although you can hook many IIC devices but as was said in the comments it's better to unhook everything except it, to troubleshoot.

Correct voltage ?

You might know that some displays uses 3.3v or some uses 5v, but as it showed in the IIC scanner, I don't think  that is the problem in your case but you should consider it.

Try using other sketches

Well, I think that 99% of the problem lays in your code (sometimes happens to me), so I suggest using other library examples or completely other libraries, or if you would like to take the challenge open the datasheet for the ssd1306 and make your own library and codes.
I hope these tips will help you or any other viewer.
As a side note I am a student, so I completely will appreciate anybody editing the answer to make better or more clear.

this is not an answer nor a solution.

Thanks so much i'll try your tips. Much appreciated

I copied your code and load to my display. It doesn't show anything. Here is the code that I had run successfully.
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

void setup() {

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x32

  display.display();
  delay(2000);

  display.clearDisplay();      //this line to clear previous logo
  display.setTextColor(WHITE); //without this no display
  display.print("Hello World!");//your TEXT here
  display.display();            //to shows or update your TEXT
}

void loop() {

 }

Good Luck,
Aung Myo Oo

Thanks, however I fixed it with something else. Check my answer if you need details


text:
Brushless Motor and Electronic Speed Controller Initialisation Issues
I have been trying to make a brushless motor, working in synergy with an electronic speed controller, to work, however, all I have been achieving is the motor vibrating at a specific potentiometer/throttle position.
The following is a description of my components, circuit setup, code and calibration approaches.

Circuit Schematic

In the code image, it should say pin 8 instead of pin 9.
One problem may be that the ESC is of a lower current and voltage level to that of the motor. I have been reading online that the ESC should have a current at about 10-20% higher than that of the motor, and a voltage of similar levels. However, to my understanding, this is to prevent any burnouts if operating at full voltage. In my case, the motor will be operating at 22V as full power (36V) is not required. I expected it to at least be turning, at a low speed, when 22V are supplied, which it is not.
Another issue I thought was that the initialization process I am undergoing is not correct, however, upon checking online and cross referencing to the instructions specified in the Hobbyking booklet they appear to be similar, so I do not think is an issue either.
Any advise or guidance would be highly valued.
Thank you!
The links in the screenshots are as follows,
1) https://www.ebay.co.uk/itm/Brushless-300w-6-5-Wheel-Tyre-Motor-Hoverboard-Swegway-Board-Replacement-Part-/292465000149
2) https://hobbyking.com/en_us/hobbyking-40a-esc-4a-ubec.html?___store=en_us&gclid=EAIaIQobChMIkvb39sq54AIVy53tCh3AhwPBEAAYASAAEgJ0RfD_BwE&gclsrc=aw.ds
3)https://cdn-global-hk.hobbyking.com/media/file/378561453X16958X28.pdf
4)https://docs-emea.rs-online.com/webdocs/13cc/0900766b813cc9bb.pdf

The fifth link is: https://dronesandrovs.wordpress.com/2012/11/24/how-to-control-a-brushless-motor-esc-with-arduino/

people are not going to read all of your post ..... when they realize that you posted pictures of text, then they move on ..... the circuit schematic is not a schematic ... it is a wiring diagram  .......... also, you have not asked a specific question


text:
2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage
hi does anyone know how to
1) set Max Brightness
2) change the start up splash screen from being white to black
3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable
The code from the sketch may answer some of your tecnical question re the environment i am working with
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

can be done w/hjardware usually, PWM'ing the backlight. 2 is just whatever the demo code does, there's no std splash screen. 3. you'll have to modify the gfx lib or use a custom font.

1) set Max Brightness

You set the brightness of the backlight (usually) using PWM.

2) change the start up splash screen from being white to black

That's not a splash screen. That's just the back light being on before the screen is initialised. Just don't turn on the back light until you need it.

3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

Either do it in software (tricky) or look at the MADCTL (many have it called that) register in the datasheet.  The library probably won't support it, but it's part of how it deals with display rotation, so you could examine that function and compare it with what's in the datasheet (hint: 180° rotation is actually flipping both the X and Y axis).

Thanks for the answers above. Sorry this is all very new to me

Thanks for the answers above. Sorry I dont have an electronics / component background please excuse the nievety.
Answer 1 above,
what is PWM and where do i find it and how do i use it to achieve point 1 objective
Answer 2 Above
So how do i turn offf the backlight as the uit backlight lights up as soon as power is connected even when the LCD is not connected to the processor, so i assume its not using the code to initally turn the back light on given there is no arduio processing any code yet the backlight is on
Answer 3
Where do i find the MADCTL  in order to alter it

Majenco i really do appreicate your assistance so far. I was hoping t find a graphics driiver option so i could code the reverse / mirror flip. I am looking to add an gyro to the unit so that if the unit is flipped so it faces driver not windscreen  (opposite to  default position the code detects this from gyro output & then changes the aspect of code being displayed so its readable by driver. Same logic to be applied if the driver wants it placed upside down form the default position so that power connector was on left side not right side (allowing for left / right hand drive)

PWM: Pulse Width Modulation. Involves turning an output on and off very rapidly with varying ratios of on-to-off times to simulate an analog output. Control the pins that have ~ by them with analogWrite().

How you control the back light depends on what shield you are using.

For MADCTL read the datasheet for the TFT screen on your chosen shield.

the 2.8 tft lcd qr4 5265s01 g3/2 TP28017

This one? https://www.adafruit.com/product/1651


text:
SPI Interface between Arduino UNO and EVK1100
I'm using Arduino Uno board as master and AVR32UC3A0512 as slave. I've written code for arduino using SPI.h library, and Atmel Studio 6.2 using spi.h. I'm sending data from arduino to atmel i.e from SPDR register in arduino to RDR register in Atmel, but the data is not getting recieved. Hence, I'm not able to read the data. I've successfully interfaced SPI between two arduino boards and I'm using the same Arduino Master code while interfacing it with slave EVK. I've also set the baud rate same, I'm not sure what the problem might be. Can anyone please help me out?

Please edit your question to include code, preferably compilable/runnable code that is minimal and exhibits the problem.   That may allow someone with comparable boards to help debug the problem. [To format the code here, highlight it then click the code icon above the edit box, or press F4 iirc]  Also show a wiring diagram or table or a photo of setup

As you have not responded to the request to post the problem code, I am going to close this question as "unclear what you are asking". We can't tell you why code - which we cannot see - doesn't work. Particularly without details about the connections. Please read How do I ask a good question?. Feel free to edit the question with new information. Thanks for your understanding and cooperation!


text:
connecting 3.3V to +3V
Well, I hope this question won' t be buried to the dark depths of this forum as my previous q' s:) But I suppose it won' t this time cause it's pretty short without this introduction part...
I have an Arduino pro mini works with 3.3V and in the other hand, I have a DS1307 DIP ic, works with +3V. I was wondering if I could connect the ic to my Arduino directly.
Thats all. Thanks already:)

The 3V input on the DS1307 is for a 3V battery, usually a CR2032 or similar. The supply voltage of the DS1307 is 5V, which means that it won't work with a 3.3V Arduino without a separate supply and level shifter.

Seems like Konko would be better off finding an RTC capable of operating on a 3.3v supply.  The present device might be usable with the upsteam source if the 3.3v Arduino is regulating down from something around 5v, but then an I2C level shifter would be needed, probably MOSFET-based.

Minimal supply voltage for the DS1307 is 4.5V

The supply voltage is specified as 5V±10%, but it's really intended to be used with as reasonably precise a 5V supply as you can get.

Thank you all, I have a 5v to 3.3v converter, I' m probably gonna use ic with that. I' m happy that I' ve learnt that DS1307 works with 5 volts...