text:
Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space?
In order to allow bigger user program size, is it possible and advisable to reload Pro Mini with the boot loader originally designed for UNO. This will save 1.5 KB flash space (UNO boot loader is 0.5KB, Pro Mini is 2KB).
Using a smaller boot loader is an 'intermediate' step to get more space while still enjoy the easy benefit of the Arduino IDE and many library/code example. Of course, ultimate step is to remove all boot loader (only small saving of 0.5KB if above is possible) and switch to ATmel development environment, ATmel studio, which is complex but programmer has full control of everything.
Did I miss anything in the followings?
I tend to believe that it is possible as
a) same ATMega328 chip is used in both board
b) Pro Mini is essentially cutting UNO into two halves, the MCU and the USB/Serial converter now use external USB to Serial converter
If the Pro Mini board is reloaded with UNO boot loader, how should the boards.txt file be edited to reflect the changes so that the IDE will handle it correctly?
Many thanks in advance

Wouldn't it be simpler to just pick up an ISP programmer and use that instead?

Thanks for comment. Question edited to clarify the intermediate (save 1.5KB) and ultimate (save 2KB but much more complex) steps.

No, the intermediate step is to use a programmer. Tools | Programmer, File | Upload Using Programmer

@IgnacioVazquez-Abrams - No. That is the final step.  The intermediate step (and imho the one usually worth stopping at) is to use a small bootloader and leverage the same serial interface connector for debug and loading.

@ChrisStratton: Using ISP doesn't prevent Serial and the serial monitor from working. It simply allows you to control the fuse bytes and use all of the flash and EEPROM on the chip.

Of course it doesn't prevent it, but removing the bootloader and relying on ISP does prevent you from using the serial connection for program loading.  And it's explicitly not what the poster wants to do or is asking about for this stage of their project.

If you have an ISP setup, you are in a position to find out of the Uno or other small bootloader will work, and to restore the original if it doesn't (which would likely be only for some odd quirk, such as a mutual baud rate approximation)

Thanks responders for pointing out that Arduino IDE can do both boot loader and ISP modes. The later is new information for me and helpful in choosing best approach under different stages and situations.

You can just flash the newest optiboot_atmega328-Mini.hex. That one should also be only .5k in size, as it starts writing at the same address (7E00).
If you divide 7E00 by two you get 3F00 (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)
3F00 is exactly the start of the Boot Loader Flash Section when you  have selected a 256-words Boot Size (page 291 of the datasheet). 256-words is the 0.5kb you want.
Just make sure you have the BOOTSZ1, BOOTSZ0 fuses set to 1
As for the boards.txt. I think you only need to change mini328.upload.maximum_size=28672 to mini328.upload.maximum_size=32256.


text:
Audio Frequency White Noise generation using Arduino Mini Pro
For DIY, how to program Arduino Mini Pro to act as an Audio Frequency White Noise generator?
Presumably,
a) using one Digital Output pin
b) feed to a simple passive RC low pass filter to reduce out of band signal
c) feed to a simple class-D IC chip audio amplifier and speaker
d) since it is DIY and noise, lo-fi (not hi-fi) is good enough.
Specific questions,
a) How to program?
b) Wonder if it is better to use to chip act a Pulse Width Modulated 'digital to analogue converter'?
c) How to calculate value for RC filter (assume amplifier has high input impedance)?
Many years ago, I have programmed a hardware sound generator chip as part of a game machine. It has two registers for amplitude and 'frequency' control (band of 'white' noise). It worked very well. I once looked at the output using oscilloscope and it was square wave. I believe that it works, basically, using the above principles. Since I do not have the chip now, I cannot verify it. Now, I would like to duplicate its function using Arduino in software.

I don't know that you need all that - just an Arduino and a piezo speaker and a pot if you want to play with the volume.
byte speakerPin = 1;

void generateNoise() {
  static unsigned long int reg = 0x12345678; //seed
  unsigned long int newr;
  unsigned char lobit;
  unsigned char b31, b29, b25, b24;
  b31 = (reg & (1L << 31)) >> 31;
  b29 = (reg & (1L << 29)) >> 29;
  b25 = (reg & (1L << 25)) >> 25;
  b24 = (reg & (1L << 24)) >> 24;
  lobit = b31 ^ b29 ^ b25 ^ b24;
  newr = (reg << 1) | lobit;
  reg = newr;
  digitalWrite (speakerPin, reg & 1);
  delayMicroseconds (50);  // Changing this value changes the frequency.
}

After reading your answer, I did some searching and realize that your answer is based on, quoted from wikipedia, "pseudo-random binary sequence (PRBS) generated by a linear feedback shift register (LFSR)". Any pointers to non-pure-maths (and simple) information on how to choose the "polynomial" (bit 24, 25, 29 and 31 in your example) so as to achieve the white-noise property?

The https://en.wikipedia.org/wiki/Linear_feedback_shift_register article points to tables of good polynomials for different bit-length shift registers at http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf .  The main difference between a good polynomial and a less good one is whether the length of the cycle until it repeats is as long as possible (2^n-1 is the max).  http://users.ece.cmu.edu/~koopman/lfsr/index.html points to a table with 67,108,864 equally good 32 bit alternatives.

I think you need to edit unsigned long int newr; to be unsigned long int reg, newr; (and add const int speakerPin = 8;)

I'd really like to understand this anwser, but there is no explanation as to whats going on here. I don't know what the "reg" keyword is, nor what these bitwise operations are accomplishing, or why they aren't just defined, as they appear to be constants. On an Arduino, how is this better than using the "random" function with the values between the min and max frequency?

Also the shift register reg must be (a) defined as either a global or as static and (b) assigned an non-zero value. I used global: uint32_t reg = 0xfeedfaceUL ; . The solution in the answer by Dave X works without changes.

Mike's answer uses a Fibonacci Linear Feedback Shift Register configuration, but the compactness Galois Linear Feedback Shift Register Configuration could be faster:
#define speakerPin 8

unsigned long lastClick;

void setup() {
  // put your setup code here, to run once:
   pinMode(speakerPin,OUTPUT);
   lastClick = micros();
}

/* initialize with any 32 bit non-zero  unsigned long value. */
#define LFSR_INIT  0xfeedfaceUL
/* Choose bits 32, 30, 26, 24 from  http://arduino.stackexchange.com/a/6725/6628
 *  or 32, 22, 2, 1 from
 *  http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf
 *  or bits 32, 16, 3,2  or 0x80010006UL per http://users.ece.cmu.edu/~koopman/lfsr/index.html
 *  and http://users.ece.cmu.edu/~koopman/lfsr/32.dat.gz
 *  or generate a one with https://github.com/hayguen/mlpolygen
 */
#define LFSR_MASK  ((unsigned long)( 1UL<<31 | 1UL <<15 | 1UL <<2 | 1UL <<1  ))

unsigned int generateNoise(){
  // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs
   static unsigned long int lfsr = LFSR_INIT;  /* 32 bit init, nonzero */
   /* If the output bit is 1, apply toggle mask.
                                    * The value has 1 at bits corresponding
                                    * to taps, 0 elsewhere. */

   if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
   else         { lfsr >>= 1;                      return(0);}
}

void loop() {
      /* ... */
      if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
        lastClick = micros();
        digitalWrite (speakerPin, generateNoise());
      }

}

For a 16 bit implementation (faster, but only a cycle of 2^16) try:
#define LFSR_MASK 0x8016
static uint16_t lfsr = LFSR_INIT;  /* 16 bit init, nonzero */

Written in a more compact form:
#define speakerPin 8

#define LFSR_INIT 0xfeed /* non-zero seed value for generateNoise() */
#define LFSR_MASK 0x8016 /* magic number from http://users.ece.cmu.edu/~koopman/lfsr/ */

unsigned long lastClick;

void setup() {
  // put your setup code here, to run once:
   pinMode(speakerPin,OUTPUT);
   lastClick = micros();
}

unsigned int generateNoise(){
   // Return 1 bit of noise using a Galois Linear Feedback Shift Register
   // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs

   static uint16_t lfsr = LFSR_INIT;

   if(lfsr & 1) { lfsr =  (lfsr >>1) ^ LFSR_MASK ; return(1);}
   else         { lfsr >>= 1;                      return(0);}
}

void loop() {
      /* ... */
      if ((micros() - lastClick) > 50 ) { // Changing this value changes the frequency.
        lastClick = micros();
        digitalWrite (speakerPin, generateNoise());
      }

}

For an 8 bit implementation (faster than 32 bit, slightly slower than 16, but only a cycle of 2^8) try:
#define LFSR_MASK 0x8e

static byte lfsr = LFSR_INIT;  /* 8 bit init, nonzero */

Where the mask constants are from the 8.txt and 16.txt files at http://users.ece.cmu.edu/~koopman/lfsr/index.html
The https://github.com/hayguen/mlpolygen program can search for maximum length feedback polynomials of various bit sizes.

be great for this to have more comments on this code to explain whats going on here for people still learning bitwise. I'm getting throw off because if "lfsr" is defined by the constant every time the function is called and then bitwised by another constant, how is this generating random numbers. why is the definition for LFSR_MASK so complex if its just a constant? please help?

@dprogramz: In C, the static keyword in the declaration protects against just what you are worried about--the initialization with the constant only happens once on the initial declaration of the function, and the changing lfsr state is maintained through successive calls to the function.   The bit-shifting definition of LFSR_MASK looks complicated, but it is easier to check, explain, change, and maintain than constants like 0b10100010100000000000000000000000UL  The actual selection of the mask is more complicated, so see the refs.

Thanks for the reply, that makes total sense now. I had a misunderstanding of the use to the Static keyword, but it's much more clearer now how it functions, thanks again!

source: Stack Exchange

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

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

sort: votes


text:
Random access to SD card using SD.h or another library (ESP32)
I'm trying to use a SD card with my ESP32 in order to save some variables in a txt file. Each variable uses 1 byte, so they can be represented by an 8 bit extended ASCII character.
The issue is it seems that the SD.h library has only 3 open modes (Read only, FILE_WRITE, FILE_APPEND), and I cannot figure out how to use random access for writing a specific byte of the file.
Imagine the situation: I have a file called myFile.txt which initially has a size of 5 bytes, and its content is:
abcde
The code I'm using is the following:
#include <SPI.h>
#include <SD.h>

#define SD_CS_PIN 5

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Initializing SD card...");

  if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("/myFile.txt", FILE_WRITE);
  myFile.seek(3);
  myFile.write('a');
  myFile.close();

}

void loop() {}

But after running the code, the file has an unexpected behaviour, its size changes from 5 bytes to 4 bytes, and its content is:
abca
instead of the expected
abcae
I know it happens because when writing into the file I'm using the open mode FILE_WRITE which uses the FILE_APPEND mode internally, so when doing myFile.seek(3);, I'm truncating the file to 4 bytes since the FILE_APPEND mode needs to point to the end of the file.
So, my question is, how can I open a file in random access mode with SD.h, or another library?
Thanks in advance!

I would try to seek() to the end before close(). note: the SD library in ESP32 boards support package is different than the standard Arduino SD library.

@Juraj I tried it out but I got the same result, the first myFile.seek(3); truncates the file before.

Solved!
The solution was to migrate from the SD library to mySD, which seems to be a SdFat wrapper for ESP32.
You can see in the file mySD.h that the FILE_WRITE mode is defined as:
#define FILE_WRITE (F_READ | F_WRITE | F_CREAT)

Which means that it allows random access to the file for writing (F_WRITE instead of FILE_APPEND).
PS: I want to remark @Juraj comment since the forum is mainly for Arduino board questions

the SD library in ESP32 boards support package is different than the standard Arduino SD library

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


text:
Can Arduino UNO be used to emulate a PS4 joystick?
I Want to know if there is a library that can be used in order to make a PS4 controller with Arduino.
I have a PS2 steering wheel and I want to use it thorugh Arduino with PS4. I know that PS4 has his own protocol but I think there may be a way to do it.
Cheers!
EDIT: I already have the code for reading the PS2 steering wheel, but now I need to "transform" that into PS4 protocol

I have just edited it. I want to know if there is a library that i can use to emulate a PS4 joystock using an Arduino UNO

Tie a string to the joystick and the sides of the steering wheel. So that when you turn the wheel, it pulls the thumbstick to left/right? Best case you can use an Arduino to replace the actual thumbsticks on a controller, by taking it apart.

TLDR: Not sure but the PS4 protocol is known and written for other MCUs, and can be found on github.
Not sure if there is a library for it in Arduino, but there are libraries out there (such as Passing Link) that emulate the protocol on other platforms. You can look at that.
BUT...
PS2 and PS4 are completely different beasts. PS2 uses SPI for its protocol. PS4 uses USB with specific USB drivers. Even if you manage to get the PS4 protocol working, the next problem is authenticating you are a legit/licensed controller. For every legit controller, there lies a security chip inside. And that chip also has a proprietary way to be talked to as well. When a legit controller is talking to a PS4, the PS4 will sometimes ask for the contents in the security chip for authentication. If you can't deliver the contents it wants, your controller is locked out until next power up (maybe even next PS4 power up, not sure).
So while it may be possible, the two huge hurdles are:

Implementing the USB code properly with custom drivers defined by Sony.
Circumventing the security chip by either ripping contents off a legit controller or mining it and placing it in your own circuit. Both of which will require an understanding how how to communicate with said chip.


text:
how to display text to 8x8 matrix with 64-bit long integers?
I have an array of 64-bit integers to display on an 8x8 led matrix
const int LEN1 = sizeof(Hours);
const uint64_t Hours[] = {
  0x00043c3c3c3c3c00,
  0x000c3c3c3c3c3c00,
  0x001c3c3c3c3c3c00,
  0x0000001818000000,
  0x0000001818100000,
  0x0000001818180000,
  0x00000018181c0000,
  0x000000181c1c0000,
  0x0000001c1c1c0000,
  0x0000041c1c1c0000,
  0x00000c1c1c1c0000
};

and here I have a loop to display it:
void displayImage(uint64_t image) {
  for (int i = 0; i < 8; i++) {
    byte row = (image >> i * 8) & 0xFF;
    for (int j = 0; j < 8; j++) {
      lc.setLed(0, i, j, bitRead(row, j));
    }
  }
}

but I can't use a loop in this way and I'm not proficient in byte shifting principles too.
can you please explain how the loop above works or help me to write this loop as
const int LEN1 = sizeof(Hours);

void displayImage(Hours[]) {
  for (int i = 0; i < LEN1; i++) {
    //display Hours
    }
}

it is about displaying text on 8x8 led matrix using arduino/

its not really about loops in c++,  what would be helpful is more detail about the hardware, platform, and the libraries in use. Data-types and libraries seem to be the main issues here.

@jsotola, it is an Arduino question. it is about the use of Arduino's Print.print(num, HEX) function which doesn't have a version for uint64_t type so it must be replaced with at least two prints and the leading 0 must by handled

@Juraj i am probably missing something then ... i see no Serial.print code in OP's listing ... deleted my comments

@jsotola, sorry, some display libraries implement base class Print and the Answer by j0h confused me to think it is the case in this Question

ok, well there are some things I don't know about your code, and hardware, like if the LCD library can handle uint64_t datatypes. I know the Serial.print() function can only handle up to a unit32_t, so I'm using that.
I think your length variable might not be the right length, you might want to add in a check for that in your code. Much of the Arduino code is 8 bit.
void setup() {
Serial.begin(9600);
uint32_t b = 0x0;

const uint64_t Hours[] = {
  0x00043c3c3c3c3c00,
  0x000c3c3c3c3c3c00,
  0x001c3c3c3c3c3c00,
  0x0000001818000000,
  0x0000001818100000,
  0x0000001818180000,
  0x00000018181c0000,
  0x000000181c1c0000,
  0x0000001c1c1c0000,
  0x0000041c1c1c0000,
  0x00000c1c1c1c0000
};

//const int LEN1 = sizeof(Hours[0]);
const int LEN1 = sizeof(Hours)/sizeof(uint64_t);
       Serial.print("Length: ");
       Serial.println(LEN1);

   for (int i = 0; i < LEN1; i++) {
       b=Hours[i]>>16;
       Serial.println(b,HEX);
       }
}

void loop() {
}

I think this code will do what you want, at least as I understand it.
beware of what data-types your LCD library can handle.

welp, I see where I borked this code, but im tired and huingry, and gotta go home. But I still think this will put you close to where you want to be


text:
Conversion of Arrays into Matrix?
I'm going through problem in Arduino code. I have three Arrays and want to convert them into a matrix. I have tried hard but couldn't solve issue.
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float Loadbase,Loadshift;

void setup() {
    for (int i=0;i<24;i++){
        Loadbase={lb1[i],lb2[i],lb3[i]};
    }
}

void main() {
}

Why don't you use two dimensional array directly? Anyway, Loadbase is not an array. The == is equality operator. You should start with some C++ tutorial.

@KIIV i know the logic how arrays are converted to matrix in Matlab. But Arduino coding is bit different than matlab. please give me some example to solve this issue.

I'm not sure what do you want to archieve exactly. I can try to answer it..

@KIIV i want to get a matrix of (3*24) from three arrays.

Google "c multidimensional array".

This is your third general programming question (not specific to Arduino) and the third time we've told you this is off-topic. Don't you care about the site rules?

I'm voting to close this question as off-topic because this is a generic programming problem totally unrelated to Arduino.

Two dimensional arrays in C++ (directly):
float matrix[3][24] = {
    {1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730},
    {1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450},
    {500,500,600,600, 380.3005 ,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250}
};

Two dimensional array indirectly (array of pointers):
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

If you want two dimensional array with copies of lb1/lb2/lb3:
float matrix[3][24];
for (int i = 0; i < 24; ++i) {
    matrix[0][i] = lb1[i];
    matrix[1][i] = lb2[i];
    matrix[2][i] = lb3[i];
}

Btw: you were saying something about "mistakes" if I split definition on more lines, but guess what:
float lb3[24]={500,500,600,600,  380.3005  ,3155. This is a valid float number, but you have only 23 items then.
If you use at least space as a number separator, it can't be even compiled:
float lb3[24] = { 500, 500, 600, 600, 380. 3005, 3155, 530, 400,  400, 600, 350, 250, 250, 500, 500, 250, 1655, 1655, 3155, 2130, 250, 150, 250};

I need this type of stuff, i am giving you material from your answer. but is not working. and giving error."Error compiling for board Arduino/Genuino Mega or Mega 2560".  float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

@HafeezAhmadFiiZue  My code is tested. However your code pasted here is full of extra characters (and those are invisible in Arduino IDE) that can't be compiled. Some kind of zero width spaces.

in next comment i will paste the code please check it once again,  for arduino mege 2560 in arduino IDE. it is giving error,"Error compiling for board Arduino/Genuino Mega or Mega 2560".

float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float * matrix[3] = {lb1, lb2, lb3};

Please do not post code in comments. If you need to post code please edit your question and use a proper code block (indent it 4 spaces).

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


text:
Serial communication with more than two Arduinos
Is my syntax "SoftwareSerial uno1(0,1); // RX, TX" is right to communicate with more than two Arduinos?. How can I communicate with three Unos via single Mega?
#include <SoftwareSerial.h>
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

float lt[24]={3530,1580,3880,2780,4040,11260,7935,6655,2100,5100,1450,2200,2200,5900,6180,4230,2405,3560,4535,12635,12085,3500,930,3430};
float gt[24]={0,0,0,0,0,0,6320,5496.9,5948,4124.1,3848.4,3573,3022.2,3297.6,3298.2,3573,4123.2,0,0,0,0,0,0};
float lbt[24]={3530,1580,3880,2780,4040,7960,7935,2655,900,1400,1450,1300,1000,3400,3680,1730,2405,3560,4535,9635,9885,3500,930,3430};
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float lst[24]={0,0,0,0,0,3300,0,4000,1200,3700,0,900,1200,2500,2500,2500,0,0,0,3000,2200,0,0,0};
float les1[24]={0,0,0,0,0,0,0,2000,1200,0,0,0,0,2500,2500,2500,0,0,0,0,1200,0,0,0};
float les2[24]={0,0,0,0,0,3300,0,0,0,0,0,900,1200,0,0,0,0,0,0,2000,0,0,0,0};
float les3[24]={0,0,0,0,0,0,0,2000,0,3700,0,0,0,0,0,0,0,0,0,1000,1000,0,0,0};
float BatCap[24]={405.83,405.83,405.83,305.83,305.83,305.83,305.83,305.83,588.91,576.24,799.08,936.45,1050.87,811.05,570.85,493.19,590.53,637.47,397.47,397.47,397.47,397.47,397.47,397.47};

float Pvpin=41,Batpin=42,Gridpin=43;

void setup() {
// DEFINING THE MODES OF LOADS, OBEVIOUSLY OUTPUT.
  pinMode(Pvpin,OUTPUT);
  pinMode(Batpin,OUTPUT);
  pinMode(Gridpin,OUTPUT);

  Serial.begin(9600);
  uno1.begin(9600);
  uno2.begin(9600);
  uno3.begin(9600);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB
  }
}

void loop()
{
  for (int i=0;i<24;i++)
  {
   if (gt[i]>lt[i])
   {
       uno1.write( "100");
       uno2.write( "100");
       uno3.write( "100");
       digitalWrite(Pvpin,HIGH);
   }
   else if (gt[i]+BatCap[i]>lt[i])
   {
       uno1.write( "110");
       uno2.write( "110");
       uno3.write( "110");
       digitalWrite(Batpin,HIGH);
       digitalWrite(Pvpin,HIGH);
   }
   else
   {
       uno1.write( "001");
       uno2.write( "001");
       uno3.write( "001");
       digitalWrite(Gridpin,HIGH);
   }
  }
}

Why use SoftwareSerial when you have 4 UARTs on the Mega?

@EdgarBonet how can i access 4UARTs in Mega? i need syntax for the case of three UARTs.

@EdgarBonet please amend my code for serial communication with more than two Unos via single Mega. tha above code is for Mega.

Serial1.begin(9600); Serial2.begin(9600); ...

@gre_gor yes it is.

If you want to use 3 SoftwareSerial instances, then you need to use 3 different sets of pins. Hence, replace:
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

with something like:
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX

Also, since SoftwareSerial and Serial (hardware) are interchangeable in code, you should take advantage of the hardware Serial of Arduino UNO:
HardwareSerial uno1 = Serial;

Note that, on UNO, HardwareSerial uses pins 0 and 1, hence you should not use these for something else:
HardwareSerial uno1 = Serial;
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX


text:
WeMos D1 ESP-Wroom-02 Mother Board ESP8266 - where is reset pin for deep-sleep
This item was bought for battery use with deep sleep purposes. For doing so in ESP8266 reset pin must be connected to Gnd pin in order to wake up. This board lacks a reset on- board pin.
Since spec states it has a such capabilities - I wonder if someone has succeeded with putting it to sleep ( and wake it back on ).
PS - I know that on-chip gpio16 can be soldered to on-chip gnd - I'm hoping there is a more elegant, not soldering invloved, solution.
Guy

So the board does not break out the reset pin. You can try to solder a wire to the reset button. But what is your actual question? Asking for a specific, cheap, bad documented one from aliexpress most likely will not lead to good results. The possibility, that someone else here used the exact same module, is very low. Also: Where does it state, that it has a broken out reset pin? I don't see anything like that on the site.

Both GPIO16 and RST are available on ESP-WROOM-02 module, see https://www.espressif.com/sites/default/files/documentation/0c-esp-wroom-02_datasheet_en.pdf.

@jsotola question is rephrased now.

@chrisl I hope question  is clearer now. I tried to create such "soldering" as you suggested - but a awke up did not occur

This support page has the instructions for enabling deep sleep:
Support for WeMos D1 ESP-Wroom-02 Nodemcu
edit by Guy: in short, solder/connect pins as shown circled in red:


text:
Wemos Mini & Pro Micro Serial connection
While using a 3.3v Pro Mini & Wemos mini to communicate via Serial was successful, when tried with a 5v Pro Micro it fails.
To overcome different logic level I used a 10K + 20K resistors to lower Pro-Micro's 5v to 3.3v successfully to Tx and Rx pins. Also since they are on the same PCB, GND pins are connected and RAW to 5V at wemos mini  is also connected. At the moment, it is powered up using MCU's USB input ( tried to connect to Pro-Micro only, Wemos Only, and both ).

What might be the problem ?

It sounds like you have tried to put level shifting on both the TX and the RX pin. You want it only between the Arduino's TX pin and the ESP's RX pin. Not between the ESP's TX and Arduino's RX.

@Majenko see added schematic.

Yes, I thought you might have. ESP TX to Arduino RX needs to be a simple wire, nothing more.

Also you may find that your resistors are too high value. I use 1k/2k.

@Majenko - OK.. Now I get it :)

@Majenko - I followed an on-line tutorial :/

Yeah, you can never trust those online people. =)

@timemage - I see you are a keen follower for my endless mistakes ( Majenko 2 ) :)

@Majenko - to avoid my next question, as timemage suggested in my last question, when I2C between 3.3 and 5v - will I need a both resistors ?

For I2C you really want an active I2C level shifter. I2C is not push-pull like serial, but open drain. However you can probably just ignore it since the Arduino's internal pullup resistors will limit the current to such a tiny amount that the ESD diodes in the ESP8266 won't care (and there are somewhat unsubstantiated rumours that it's 5V tolerant anyway).

@Majenko - Jumpering 10K resistor did not solve the problem :(

Is your usb power coming from a computer?

@Majenko - Wrongly jumpered the Rx @ Pro-Micro. Now when Tx is has 10K and 20K and Rx is connected directly + Juraj's Serial1 - Problem is now SOLVED

You don't need a logic level conversion between 5 V Micro Arduino and 3.3 V Wemos D1 mini. The 5 V ATmega 328p reads 3.3 V as HIGH and the esp8266 can tolerate 5 V logic level for tests. For long term connection you can add logic level conversion with a voltage divider to convert the 5 V of ATmega TX to 3.3 V of esp8266 RX.
RX/TX pins on Arduino Mini are Serial.
RX/TX pins on Arduino Micro are Serial1.
Serial is only USB on Micro.

But it has Tx and Rx actual pins, which are use Serial.begib(9600) the same way

This I know. Does it change Majenko’s answer?

@Guy.D, the logic level difference is not the problem. so I guessed you used the same sketch with Serial for Mini and Micro, instead of using Serial1 for Micro. you don't need to use level shifting for a test.

yes, same code was used.

@Guy.D, then I guessed right and that was the problem. for Micro use Serial1 to communicate with the Wemos

Changing to Serial1 all Serial instances did not solve the problem. Nor Majenko's solution.

Nothing transferred... what / how would you suggest to try?

Only when applying Majenko's + your solutions, solved the problem. please update

Taking off the RX ( at PRO-Micro side ) side. It didn't work when it was installed


text:
Is it possible to measure analog output?
I'm using PWM to control LED brightness using MOSFET, using analogWrite(pwmPin,val), while val is a 12 bit bit value.
pwmPin is defined as- pinMode(pwmPin, OUTPUT);
Since val changes in time due to external lightning, I wish to measure PWM value, for later use in code. Using analogRead(pwnPin) yielded a changing value ranges 7-14.
Is there a way to measure PWM value defined as an output ?
EDIT 1:
Saving val's value won't save the problem I'm looking for, since code reaches a deepSeleep phase, which val can be stored, but I want an actual incidication of its value, and if it actually on.

Why not storing val and calculate what you need depending on that? That seems better than measuring something you already know (or knew) as it is/was in the variable val.

@MichelKeijzers - see EDIT1 in my Q

@Guy.D "I want an actual indication of its value" When you are measuring the output, you are actually only writing code to test your code. In most cases this does not really make sense. If your code is written correctly, you can trust the output to do, what you want. Any event, that might change that (like some kind of hardware failure), is high likely to also effect your testing code, which you then also cannot trust. Why do you really need this indication? If for safety, then you should think about the scenarios, that you want to cover, and then build a seperate device for this purpose.

The fact that you sleep doesn't matter. If you keep in a variable the value that you used to analogWrite(), it will still be there when you wake up.

Doesn't analogRead from analog pins but analogWrite write to digital pins? And don't the analog and digital pins have their own numbers (digital 0 is a different pin to analog 0)?

Sorry but I don’t follow....

you could use an rc filter to sample the average voltage.

First: Why would you need to measure the PWM value. You already know it; it's saved in the val variable. Why not just use this variable for later use in code?
Second: Doing the analogRead on the same pin as the PWM output is not going to work. Internally there are 2 different hardware peripherals, that are responsible for these functions: The ADC is responsible for measuring analog voltages, while one of the Timers is responsible for generating the PWM output. Only one of them can connect to the pin at any time. Thus you are not measuring the PWM signal, when you do an analogRead(pwmPin). This function set's the pin for measuring analog voltages (means it connect it to the ADC and configures the ADC) and thus disconnects the Timer hardware.
Third: Doing an analogRead() directly on a PWM signal is not going to work. PWM is still a digital signal, so measuring it's analog voltage would yield only values around 0 and 1023. This signal is transformed to a real analog voltage through a low pass filter, either electrically or mechanically (here I mean because mechanical elements often cannot follow the relatively fast PWM signal - like a motor or a speaker - which results effectively in a low pass filter).
How to measure a PWM signal then? First you definitely need to use a different pin, than the PWM output pin. Then you have 2 ways of measuring the current PWM value:

You can connect the PWM output to a low pass filter (combination of resistor and capacitor; you can google this and get very detailed descriptions), and the output of the low pass filter to an analog input pin of the Arduino. Then you can do analogRead()s to measure the current value.
You can measure the PWM signal directly, meaning measuring the actual pulse width of the signal. There are multiple ways of doing this, one being the pulseIn() function, which wait's for a pulse to complete and returns the length of the pulse.


text:
WiFiManager - Combine NonBlocking portal AND addParameter
I wish to config WiFiManager and addParameter of MQTT topic and local server on its ConfigPortal.
Additionally in a case of a power outage or any, in case of losing WiFi, to continue in a NonBlocking way.
The problem is when combining both features in one sketch, I get some errors.
Entire code is ( please notice comments marked Marker[i] ):
#include <WiFiManager.h>
#define MQTT_SERVER "192.168.3.200"
WiFiManager wm;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  WiFiManagerParameter custom_mqtt_server("mqtt_server", "mqtt server", MQTT_SERVER, 40);
  WiFiManagerParameter custom_mqtt_user("mqtt_user", "mqtt user", "", 10);
  WiFiManagerParameter custom_mqtt_pwd("mqtt_pwd", "mqtt password", "", 10);
  WiFiManagerParameter custom_mqtt_topic("mqtt_topic", "mqtt topic", "", 10);
  WiFiManagerParameter custom_mqtt_group("mqtt_group", "mqtt group", "", 10);
  WiFiManagerParameter custom_mqtt_root("mqtt_root", "mqtt rootTopic", "", 10);
  wm.addParameter(&custom_mqtt_server);
  wm.addParameter(&custom_mqtt_user);
  wm.addParameter(&custom_mqtt_pwd);
  wm.addParameter(&custom_mqtt_topic);
  wm.addParameter(&custom_mqtt_group);
  wm.addParameter(&custom_mqtt_root);

  WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  //  wm.resetSettings();

  //  wm.setConfigPortalTimeout(180);
  // wm.setConfigPortalBlocking(false);  // <--- Marker [#1]

  //  if (!wm.autoConnect("AutoConnectAP")) {
  //    Serial.println("failed to connect and hit timeout");
  //    delay(3000);
  //    //reset and try again, or maybe put it to deep sleep
  //    ESP.restart();
  //    delay(5000);
  //  }

  bool res;
  res = wm.autoConnect("test123", "password"); // password protected ap
}

void loop() {
  // put your main code here, to run repeatedly:
  //  wm.process(); //<--- Marker [2]
  Serial.println("hi");
  delay(100);

}

When Marker[1] & Marker[2] are commented out ConfigPortal works as expected, and in Blocked state - meaning there is no hi's on Serial monitor.

When only Marker[2] is commented out, ConfigPortal is reached, lacking all addParameter fields.

When Marker[1] & Marker[2] are not commented out, ConfigPortal is now reachable, but not having Non-Blocking feature...

What is the purpose of wm.process() ?

Guy

what errors do you get?

@jsotola see at the bottom of code. It is noted already

autoConnect will end the portal if WiFi can connect. use startConfigPortal to let the portal run. wm.process handles client of a started wm web server. see the OnDemandNonBlocking example's doWiFiManager function

@Juraj - thanks for clarifying. I saw the usage of wm.process() only in NonBlocking example, and as far as understood in use only when Portal in hosted while not connected to WiFi ( what is traditionally - Blocking mode ). Is it correct ?

@Juraj Can you explain about startConfigPortal and why it is not used in relevant built in example ?

The WiFiManger's autoConnect function starts the configuration web server (and AP) only if connection to configured WiFi network is not established.
If you want to run the WiFiManger's web server to reconfigure WiFi or to set other parameters, you can start the WM web server with the startConfigPortal function.
autoConnect and startConfigPortal are blocking by default. The library has a loop inside this functions which runs until the web server is stopped calling [Exit] action on the configuration web page or the timeout set with setConfigPortalTimeout is reached after last contact from browser.
To run the WM web server 'parallel' to your sketch you can configure it as not blocking with setConfigPortalBlocking(false). Then to allow WM handling of the web server the sketch must periodically call wm.process().
In not blocking mode the [Exit] action on the configuration wen page doesn't stop the web server. The server must be stopped in code.
The parameter definitions must by global in sketch, if you want to run WiFiManager with parameters outside of setup(). Parameters local in setup() don't exist after setup() finishes. WiFiManager detects this and doesn't use the parameters.
The OnDemandWebPortal example and OnDemandNonBlocking example demonstrate startConfigPortal in blocking and not blocking use.

If I didn't explain myself right - I'm looking on 2 scenarios: 1) first time boot, creditials have to be set ( including addParameter's ) 2) After some failure which WiFi is not found for some reason, I need my system continue running ( minus All WiFi + MQTT functionality ), during THIS time I rather have ConfigPortal accessible for some time ( 180 sec ).

@Guy.D, now you have the insight to do that

please review my answer below


text:
How to free up Flash space by removing the bootloader on UNO?
In order to fit maximum user program into the chip, how to free up Flash space (0.5 kilo bytes for UNO, 2 KB pro Mini, 8KB for ATMega2560) by removing the bootloader on Atmega328 (UNO, Pro Mini, or similar)?
What software development tools needed (like Atmel AVR Studio software or similar)?
What hardware flash writing / debug tools needed (like JTAG hardware programmer/debugger)?
How is the procedure? Where can I get more information.
Many thanks in advance.
edit: Update boot loader size for different boards

On UNO, the optiboot loader takes only 0.5KB not 2KB, so removing it will not be a big gain.

You'd need something like an USBASP programmer. You can use the regular Arduino IDE for programming, though you'd probably have to edit the boards.txt file a bit.

I looked at C:\Program Files\Arduino\hardware\arduino\broads.txt and, to my surprises, many boards use different boot loaders (hex file has different name)

You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the BOOTRST fuse in the high fuse byte.


text:
Sleep mode and months of operation on small battery
In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to sleep and power down modes, so as to run on one set of battery for months, appreciate idea and comment.
Initially, I looked at web postings and get the following general idea. Did I miss anything?
Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.
Are there several such library?
How are they?
Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)
Many thanks in advance

"Seems like sleep mode is done via user contributed library, instead of core 'official' IDE." Wat. The API is in avr/sleep.h, which is even more "core" than the IDE.

Followed your lead, got http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html and look like this is one of the several lib mentioned on web postings.

Yeah, why do it the simple way when you can add 5 files and 10kB of code :/

@IgnacioVazquez-Abrams 5 files and 10kB of code?

@geometrikal: A slight exaggeration. But all the functionality required is built into AVR Libc already.

@IgnacioVazquez-Abrams In the jee lib I linked to there is a great function called loseSomeTime which falls to sleep for a set amount of time (using periodic watchdog interrupts to keep track). Also there is some code to turn off brown out detect which is not in the link from John Williams. For space saving one can simply copy the Sleepy class out into a separate file, it is only a few functions.

As an aside, the watchdog stinks for keeping track of time. If you need accuracy then use an asynchronous timer instead.

Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.
http://jeelabs.org
There is also a library based on this project called Jeelib:
http://jeelabs.net/pub/docs/jeelib/
Jeelib contains a class called Sleepy that allows for easy sleeping.
Rocketscream did a thorough test of the current consumptions with the different modes here:
http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/
According to them, you can get the ATMega328P down to 1.7uA.
Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:
Arduino powering from 9V battery

+1 for resourceful pointers to rich sources of info. Edit the question on the power supply regulator chip. Some chip are uA rated while other are traditional higher power consumption.

You also should desolder the power-led on the boards. I prefer to skip the voltage regulator and get a battery pack that has the right voltage. E.g. three AA (3 x 1.5V = 4.5V). Most AVR chips have quite a range in acceptable voltages. Also running the chip without the crystal reduces the power use a bit I've heard. I never used crystals on my own homemade boards. Just read chapter 9 of the datasheet, especially 9.10!

I could reproduce these power requirements - main thing is to get rid of the Arduino board and start with a Bareduino or sth similar. (find a detailed description here)

Another way is to use Pro Mini board. First, de-solder the power on LED light as it takes about 3mA. Battery feeds to the 5V pin without using the regulator. The LDO voltage regulator on my board takes up about 20 micro ampere in this un-used mode (likely, different brand/model of that chip has different current consumption). De-solder if necessary.

I have a page about saving power with the Atmega328P chips (similar techniques apply to other chips): Power saving techniques for microprocessors
I made a Temperature and humidity sensor - battery powered - this runs from 3 x AA batteries, and writes to an SD card. From memory it ran for 2 years before I needed to replace the batteries.
Another project flashes an LED every second: Simple project - torch-locator. I made something similar a couple of years ago that is still running from the same button battery.

As a rule-of-thumb, you should be able to achieve 100 nA of current consumption, and still be "alive" and able to respond to external events, like button-presses (eg. a calculator or TV remote). To wake periodically (without an external event) takes more current, because you need the watch-dog timer to be active, but that can still be as low as 6 µA.


text:
Trouble uploading sketch / error in sketch
I am following this tutorial of a very basic serial communication between 2 arduino unos.
I have made the connections as given and connected the arduino unos to 2 separate laptops via USB.
Code1:
char mystr[3] = "Hello"; //String data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.write(mystr,5); //Write the serial data
  delay(1000);
}

Code 2:
char mystr[5]; //Initialized variable to store recieved data

void setup() {
  // Begin the Serial at 9600 Baud
  Serial.begin(9600);
}

void loop() {
  Serial.readBytes(mystr,5); //Read the serial data and store in var
  delay(1000);
}

Error on arduino following code 1:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

Sketch uses 1602 bytes (4%) of program storage space. Maximum is 32256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1860 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

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

Arduino running code 2 is stuck on the uploading and does not fininsh uploading.
The solutions on the internet only talk of the scenarios where the arduino is having trouble communication with the computer and so the solutions given are:

check com port
check that correct board is selected
do not insert the arduinos in usb 3
press reset button

None of these is my problem as I have checked them all. The arduinos themselves are working fine. I have a very strong feeling that there is a problem with the pins 0 and 1, i.e. with serial comm.
Please help.

When you program the Arduinos you need to unplug all cables from D0 and D1, otherwise the upload will fail. Have you anything connected to D0 or D1 while uploading?

While not a solution to the problem you posed, this line in Code 1: char mystr[3] = "Hello"; //String data is not good -- you can't allocate 3 bytes in an array and assign a string that requires 6 bytes of data (5 characters, plus null terminator.)

Also, the error text you list for Code 1 can't be right with that code, because it should give a compile error. Are you sure you have pasted the right responses?

@josecanuc yes pretty sure I have pasted the right errors..
and I changed [3] to [6]

@MaximilianGerhardt yes the error goes away but now nothing is being printed. But what should be the correct algorithm to make the connections?
Like:
Ard 1 with pins empty to USB then
Ard 2 with pins empty to USB then
Common GND to both then
Rx tX in ard 1(or ard 2 first?) then
Rx tx in ard 2
??
Also are the codes correct?

Flash both Arduino boards without anything attached to them. Then plug the cables in (cross-over, i.e. D0 -> D1, D1 -> D0 from Board1 -> Board2), then plug both boards into your USB ports. Board1 will transmit data to board2 which you might see in the serial monitor for board2. This code uses the only hardware serial available and no other "debug serial port" from which you can observer something though. Your SoftwareSerial approach would be better.

one of the things that you have to learn in programming, is to identify a problem correctly. .... you are unable to upload a sketch to an arduino, yet your question title is Problem in serial communication between 2 arduinos ... that title is absolutely incorrect

I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.
Break this connection before upload and then it should work. You can reconnect them after upload.
If you want to avoid this you can use different pins with software serials for communication.
Also consider using Serial.available() on the reading end to see if there is data to be read.

Normally "guessing" is discouraged, but as this absolutely horrible "tutorial" literally instructs the unsuspecting to make this problematic connection, you are probably right.   Whoever wrote that terrible guide has done the world a disservice.


text:
convert 32 bit long to 4 bytes and back again - CAN Bus
So after 2 days attempting this I can't get my head round it.
So I am using CAN bus to transfer accelerometer data and time data (the micros() function if under 71 minutes will output data that can be an unsigned long), however I have to send the data as bytes. I have managed to bit shift a 16-bit int into 2 bytes but I am having trouble extrapolating that method (will add later) to using longs. I am having trouble understanding the union method as I am new to creating my own functions, so, how would you guys accomplish this? As simple as possible please :)

you subtract the maximum byte 3 can be from the total, and from that subtract the maximum byte 2 can be to get byte 3. byte 4 is just max byte 4 minus number minus max byte 3 +1.

You can achieve what you want by using bitshifting and bit-wise and operators.
Here is an example that lets you extract the individual bytes of your long variable. I think it should be straigtforward to extend it to variables of different length:
void loop() {
  long a=0x12345678, c=0;
  byte b[4];
  Serial.println("Original:");
  Serial.println(a,HEX);
  delay(1000);
  Serial.println("Individual bytes:");
  for (int i=0; i<4; i++)
  {
    b[i]=((a>>(i*8)) & 0xff); //extract the right-most byte of the shifted variable
    Serial.println(b[i],HEX);
    delay(1000);
  }

  for (int i=0; i<4; i++)
  {
    c+=b[i]<<(i*8);
  }
  Serial.println("Reconstructed:");
  Serial.println(c,HEX);
  delay(1000);
}

Depending on what byte ordering (big or little endian) is expected, you might need to reorder the bytes before sending or after receiving.

Very straightforward and easy to understand the principle so thankyou, however under "reconstructed" it only prints 5678?

Did you copy the code snippet from my answer? Because if I run the code on my nodemcu I get the right answer.

Yes, i copied and pasted the code, added void setup(); and Serial.begin(9600); to get the code to run on my arduino nano

by default on an 8 bit AVR, to the right hand side of the equals defaults to int arithmetic which is signed sixteen bit. So i cast the array to a uint32_t in the loop. Unsure of if that is the most efficient way, but it works! Thankyou for your help

yes right. I didn't think about the arduino controller, when I tried on the nodemcu.

I'm trying to get this with a long, but no joy
Original:
5294A
Individual bytes:
4A
29
5
0
Reconstructed:
294A

Anyone have an update to this answer?  It should work on reconstruction (I don't see anything wrong), yet it doesn't.  Am I missing something?

The union type is similar to a struct except that each of the members of the element occupy the same memory. If you define a struct so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.
union packed_long {
  long l;
  byte b[4];
};

This is the type, so you have to declare the variable to be of that type:
packed_long mydata;

Now, you have two sub-elements of mydata: l and b[].
To save your long value, write to the l part:
mydata.l = myaccel.getY();

To access each of the 4 bytes:
byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];

On the receiving end, you take each of the 4 bytes:
mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();

As long as you receive the bytes in the same order in which you sent them, you can now access your long value in mydata.l.
The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: int32_t (signed 32-bit integer) or uint32_t (unsigned 32-bit integer).

A way to send a long is to mask off and send the LSB byte (CAN standard), then shift the next one into LSB position, for 4 bytes:
uint32_t data;

// Send to CAN bus LSB-first
// This method is destructive; data should be a temp if the
// Arduino is to retain the data after sending it.
for( uint8_t b = 4; b > 0; --b ){
   sendByte(data & 0xFF);  // send curr byte
   data >>= 8;             // shift that byte away
}

// Read from CAN bus
for( uint8_t b = 4; b > 0; --b ){
   data >>= 8;                 // make room for byte
   data |= (readByte() << 8);  // read next higher byte
}
//

OK, so CAN standard is LSB first. As you have knowledge of CAN, from what i can find they send an 8 byte packet, is only one or two of those the data? So for a total of 16 bytes of information, would 8 packets be needed?

You caught me! That's about everything I know about CAN bus, and that was from Wikipedia. There is a lot of CAN bus documentation online; that article's bibliography is good start.

8 byte is the size of the data payload of a standard can-frame. so you need two standard frames to send 16 byte of information. the newer can-fd supports 64 byte data payload per frame.


text:
Triggering an ultrasonic sensor
I made a smart blind stick for my class project. It uses an ultrasonic sensor to detect obstacles and I was asked this question in VIVA...
Why is it necessary for giving a digital high for 10 μS on the trigger (Trig) pin of an ultrasonic sensor ?
Why 10 μS only?
I changed it to 5 μS then to 20 μS and to 50 μS and it still works fine! Why so?

obviously i googled for an explanation but couldn't find my answer for "Why 10u" and neither could i find it in your answer

The specification1 says (emphasis is mine):

using IO trigger distance, the high signal to at least 10us.

So, longer than 10 μS is not a problem.
With respect to less than 10 μS, well 5 μS may also work, but it is out-of-spec and therefore not guaranteed to work and so may not always work correctly, or as expected.
From Source 1:

From Source 2:

As to why must it be 10 μS, well that is probably (at a guess) down to the design of the logic upon the silicon and the resultant propagation delay through the logic gates. Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.
To confirm this, you would need to speak to either the designers, or take a look at the mask used to fabricate the IC. Test simulations were probably run during the design phase, and they suggested a minimum trigger pulse of 10 μS. The figure could also be arrived at by simply looking at the design and counting the number of stages and multiplying that by the propagation delay per stage.
However, as Valbhav points out, the HC-SR04 is controlled by a STM8 (actually it is a STC11F), and after having looked at the STM8 programming manual, it is more related to instruction cycles. The Trig pin is, I assume, an interrupt, and from section 3.2 CPU registers

When an interrupt occurs, the CPU registers (CC, X, Y, A, PC) are pushed onto the stack.
This operation takes 9 CPU cycles and uses 9 bytes in RAM

So, 9 CPU cycles just begin to to service the interrupt, and then however many needed to actually do the rest. I can't find any timing diagrams in the Programming Manual which would show the minimum interrupt signal length.  This information, is however in the Reference Manual
The length of a CPU cycle will obviously depend upon the clock frequency., which according to this schematic, from An Ultrasonic Shortcut – Getting the HC-SR04 Transducer Up and Running Fast!, is 4 MHz:

So, 10 μS is 40 CPU cycles.

1 Sources for downloading HC-SR04 pdf datasheet:

Source 1
Source 2

HC-SR04 Specifications

Working Voltage: DC 5V
Working Current: 15mA
Working Frequency: 40Hz
Max Range: 4m
Min Range: 2cm
Measuring Angle: 15 degree
Trigger Input Signal: 10µS TTL pulse
Echo Output Signal Input TTL lever signal and the range in proportion
Dimension 45 * 20 * 15mm

But it is still a question why > 10us. Its like the logic that internally lies in ULTRASONIC SENSOR has something like it checks the TRIG pin status for 10us or more if he gets it high it will generate the 8 pulse of 40Khz.

Propagation delay through the logic gates? Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.

It contains an STM8 Controller

@Vaibhav - Ok, so then, in that case. it is more to do with instruction cycles rather than propagation delays. STM8 Programming manual

@Vaibhav - I think it is actually a STC11F

It might vary, in some datasheet I had seen STM8.


text:
How many UNO pins have internal pull up resistors?
I am referring to all digital I/O pins 0 to 13 and A0 to A5.

All of them have.

Note that you need to initialize the pins as INPUT_PULLUP to actually enable the pullup resistor. (Just in case this isn't clear.)

no i dont think it does because it didnt for me

All of them. It's a standard feature on all IO pins in the AVR range.

Thank you very much :)
This is NOT the case in other Microcontrollers am I right?

Not all microcontrollers have them, that is true (low-end PIC for example). Some only have them on some pins (such as older PIC32MX chips). They are getting more and more popular though (now all modern PIC32MX chips and PIC32MZ chips have them), so more modern chips tend to have them rather than not.

Also some MCUs (such as STM32) have also pull down resistors.

@MichelKeijzers So do modern PIC32 chips (anything since the release of the MX1 / MX2 series).

#Majenko thanks for the addition (I'm quite unfamiliar with PIC32 chips).

Note that while all all AVR chips offer pull-up resistors, you have to turn them on. To do that, use the command pinMode(pin, INPUT_PULLUP) to activate the pullup resistor on the pin pin


text:
Arduino Uno - Building a Controller
I have the Arduino Uno and I'm working on a project to build a controller with different inputs and some outputs for readouts. In classic style, I got the Arduino Uno before realising that I might not have enough I/O points to connect everything I want.
I believe there is a way to expand my Uno by using an I/O Expander? Has anyone done something similar? The controller will be for a specific game called Kerbal Space Station. There are quite a few articles helping with the build but not specific to what I am looking at.
Components I'll be using:
INPUTS:

2x 3 Axis Joysticks
11x Microswitches
6x Toggle switches
1x Analogue slider
1x 10 point rotary switch

OUTPUTS:

4x 12 pin LED Bargraphs
1x Serial LCD module display

yes, that sort of a thing has been addressed before ..... what type of joysticks will you be using?

Yes, all those things have been done before.  Here's some suggestions for components:

MCP23S17 / MCP23017 - SPI / I2C IO expander (16 IO pins, many can be connected together) (MCP23S17 library)
MCP3208 - 8 channel 12-bit SPI ADC (MCP3208 library)
TLC59116 - I2C Constant Current LED PWM driver (16 channel) (TLC59116 library)

Some other useful tutorials that may help:

Keypad - read lots of buttons / switches with not many pins
Multiplex - Control many LEDs with not many IO pins


text:
I2C_graphical_LCD_display, fatal error: avr/pgmspace.h: No such file or directory
I have a problem with an ESP32 devkit V1 card. I'm trying to connect a WG12864A Winstar mod graphics display via the I2C MCP23017 adapter (RobotDyn), using Nick Gammon's I2C_graphical_LCD_display.h library.
Everything works well by connecting it to the Arduino Uno - Duemilanove board. Loading the sketch LCD_Demo_Using_I2C present in the library is compiled correctly without errors.
If I connect the display to ESP32 devkit V1, I try to compile it I get the following error:
C: \ Users \ Topolino \ Documents \ Arduino \ libraries \ I2C_graphical_LCD_display-master / I2C_graphical_LCD_display.h: 62: 26: fatal error: avr / pgmspace.h : No such file or directory.
Compilation terminated.
exit status 1
Error during compilation for DOIT ESP32 DEVKIT V1 card.

I tried to compile it with PlatformIO presents the usual compilation error.
You can help me, someone has some ideas to solve the problem.

The authors of the ESP32 core didn't bother to create a proper set of compatability shims for the PROGMEM system - chiefly because it's not needed for ESP32 operation.
We did for chipKIT, though, and you can grab a copy of ours here and place it in with the core files for the ESP32 in your Arduino installation (you only need the pgmspace.h file, and place it in an avr folder inside the core source folder).
It's completely architecture agnostic and basically defines some pretty much empty macros, and maps _P variants of various functions to the non _P alternatives.


text:
How do I make a counter that counts the amount of active inputs
I want to make a direction guide using green, yellow and red LEDs. The lights need to change when ever the active input1 reaches a set value, for example:

Green when the value is lower than 12;
Yellow when the value is higher than 11 and lower than 20;
Red when its higher than 19.

I've been searching for a few days but I couldn't find any references.

1 By active inputs I mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on.

The reference you would look for would be something on the C or C++ language. That would describe the basic structure of "conditional statements" like if (x < 5) {...} and so on.

What do you mean by "active input"? What kind of input, and what does the value indicate?

You need something like:
const int BUTTON_MAX = 29;
const int button[BUTTON_MAX] = { 5, 6, 7, ... };
const int GREEN_LED = 2;
const int YELLOW_LED = 3;
const int RED_LED = 4;
int current_led;

void setup()
{
   // Setup inputs (buttons)
   for (int i = 0; i < BUTTON_MAX; i++) pinMode(button[i], INPUT_PULLUP);

   // Setup outputs (led)
   pinMode(GREEN_LED, OUTPUT);
   pinMode(YELLOW_LED, OUTPUT);
   pinMode(RED_LED, OUTPUT);

   // Initial state
   current_led = GREEN_LED;
   digitalWrite(GREEN_LED, HIGH);
   digitalWrite(YELLOW_LED, LOW);
   digitalWrite(RED_LED, LOW);
}

void loop()
{
   // Count number of active buttons
   int count = 0;
   for (int i = 0; i < BUTTON_MAX; i++) count += digitalRead(button[i]);

   // Map number of active buttons to led
   int new_led;
   if (count < 12)
      new_led = GREEN_LED;
   else if (count < 20)
      new_led = YELLOW_LED;
   else
      new_led = RED_LED;

   // Check for change and update
   if (new_led != current_led) {
      digitalWrite(current_led, LOW);
      digitalWrite(new_led, HIGH);
      current_led = new_led;
   }

   // Add a few milli-seconds for debounce
   delay(20);
}

This seems like a decent answer, ignoring whatever "active inputs" means...

@DuncanC by active inputs i mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on. not sure if this helps.

@oliversindahl thanks for the info. That allows an update to the answer :)


text:
Arduino_Debug doesn't successfully upload sketch to Arduino if JAVA is not installed
I use arduino_debug to upload my sketch to an Arduino Mega 2560 and to an Arduino Due from my application (Windows).
I saw the following issue:
When JAVA is not installed or it was installed only after the Arduino SW installation, the command:
arduino_debug --port COM6 --upload mysketch.ino

doesn't successfully to upload the sketch. My Arduino is connected to COM6 (I verified it) and the sketch's path is correct.
I got the following output:
Initializing packages...

Preparing boards...

Verifying...

Sketch uses 6222 bytes (19%) of program storage space. Maximum is 32256 bytes.
Global variables use 318 bytes (15%) of dynamic memory, leaving 1730 bytes for local variables. Maximum is 2048 bytes.

Uploading...

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x87

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x87

An error occurred while uploading the sketch

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x87

Has anyone seen this issue? Does anyone know why JAVA must be installed?

Have a look at this question

arduino_debug.exe is a build of Arduino IDE to debug the Arduino IDE. So normally you should use arduino.exe command for CLI too. The Arduino IDE is a Java application. It has Java bundled in installation. In your case I would guess that the reset of the board is not invoked for some Java related reason.

The error message is not related to Java, it's usually either wrong COM port being selected, wrong bootloader or a temporary glitch that resolves when you try to reupload.


text:
How do you call to a previous function?
I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions?

You need to get your head around the Finite State Machine (FSM).
It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State").  One state would be reading pressure. Another state would be "testing", or whatever.
I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine

What do you mean by "previous"? In the call stack or in the code?
Either way, you can call any (public|member|static) function you want at any time, even call the very same function you're already in (recursion, but not recommended on Arduino or any other embedded system).

fsm does seem like a good way to handle it. your tutorial is very easy to follow

by previous, I mean  I had a void testing routine that once voltage reading in met it goes to  void main run I was trying to get it to  read a  high/low signal and after 2 cycles of reading low i wanted it to go back to void testing.

Ok, I see. To me it sounds like you should read up on the basics of programming, before posting questions here.


text:
Addressing contents of array using incrementing variable
Why would this simple code which prints out array values give the right value 240 when the array is addressed with index directly addressed by number
but give 184 when addressed usin a varibale n that is incrementing?
PROGMEM const unsigned char COLSA[8] = {
      240, 240, 240, 240,
      240, 240, 240, 240};  //Stored pattern

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

void loop() {
  int n;
   for(n=0;n<8;n=n+1)
    {
      Serial.println(n);
      Serial.println(COLSA[1]);
      //n=2;  //If I use n in this way things are fine. It prints 240. Else it prints 184
      Serial.println(COLSA[n]);
    }
     delay(100);
}

Because the array is a constant the compiler can, when it knows the entry number (i.e., using a numeric literal) replace the access to the array with the contents of that array index - so it's not looking up the value of 240 at runtime, instead the value 240 has been used where the access to the array was.
However, when accessing it using a variable the compiler can't do that, so it has to actually access the array in RAM.
BUT the array isn't in RAM, it's in PROGMEM, so the address that it's being given for where the array is located is completely wrong.  You're program is telling it "It's in the bedroom" - but you're omitting the important information of: "... of the house next-door.".
PROGMEM and RAM are two completely different things accessed through two completely separate data and address buses - just like two separate houses, they both have a number of rooms in them, and those rooms are called the same thing, but they're not the same room.
So instead of accessing an array by index like that you have to use special instructions to say "Get this value from PROGMEM", such as:
     Serial.println(pgm_read_byte_near(COLSA + v));

That says "Give me the byte that is located at v addresses on from the start of the COLSA array in PROGMEM.


text:
Attach Interrupt with Library
I am trying to make a library for Arduino, which requires an interruption, but the problem is that when I try the attachInterrupt function inside my library, there's a problem about attachInterrupt is static. Right now, in the library I have this in the header file:
#ifndef RegletaCMA_h
#define RegletaCMA_h

#include "Arduino.h"

class DimmerGlider {
public:
    DimmerGlider(int min, int max, int increase);

    int getMin() { return _min; }

    int getMax() { return _max; }

    int getIncrease() { return _increase; }

    void setMin(int min) { _min = min; }

    void setMax(int max) { _max = max; }

    void setIncrease(int increase) { _increase = increase; }

private:
    int _min, _max, _increase;
};

class Dimmer {

public:
    Dimmer(DimmerGlider &glider, int outputPin, int t3);

    void Dimmer::begin() {
        pinMode(_outputPin, OUTPUT);
        digitalWrite(_outputPin, false);
    }

    void Dimmer::dim() {
        delayMicroseconds(_DIMMER_counter);
        digitalWrite(_outputPin, true);  // Turn _DIMMER_pinDimmer on
        delayMicroseconds(_t3);
        digitalWrite(_outputPin, false); // Turn _DIMMER_pinDimmer off

        if (_DIMMER_dir) _DIMMER_counter += _glider.getIncrease(); // If dir is negative add _DIMMER_increase
        else _DIMMER_counter -= _glider.getIncrease();                  // If dir is negative substract _DIMMER_increase

        if (_DIMMER_counter > _glider.getMax()) _DIMMER_dir = false; // Change dir if reached bottom
        if (_DIMMER_counter < _glider.getMin()) _DIMMER_dir = true;  // Change dir if reached top

        _DIMMER_lastExecutionTime_micros = micros(); // Reset timer
    }

    void Dimmer::force(bool status) {
        digitalWrite(_outputPin, status);
    }

private:
    DimmerGlider &_glider;

    int _outputPin;

    int _DIMMER_counter = 1000;
    bool _DIMMER_dir = true;

    unsigned long long _DIMMER_lastExecutionTime_micros = 0;

    int _t3;
};

class DimmerImplementor {
public:
    DimmerImplementor(Dimmer dimmerList[], int optoPin);

    void DimmerImplementor::begin(){
        attachInterrupt(_optoPin, dimAll, RISING);
    }

    void DimmerImplementor::dimAllDimmers() {
        for (int c = 0; c < sizeof(_dimmerList); c++)
            _dimmerList[c].dim();
    }

    void DimmerImplementor::dimAll() {
        DimmerImplementor::dimAllDimmers();
    }

private:
    int _optoPin;
    Dimmer _dimmerList[];
};

#endif

and this in the cpp file:
#include "Arduino.h"
#include "RegletaCMA.h"

DimmerGlider::DimmerGlider(int min, int max, int increase) :
        _min(min),
        _max(max),
        _increase(increase) {
}

Dimmer::Dimmer(DimmerGlider &glider, int outputPin, int t3) :
        _glider(glider),
        _outputPin(outputPin),
        _t3(t3) {
}

DimmerImplementor::DimmerImplementor(Dimmer *dimmerList, int optoPin) :
        _dimmerList(dimmerList),
        _optoPin(optoPin) {
    for(int c = 0; c < sizeof(dimmerList); c++){
        DimmerImplementor::dimmers[c] = dimmerList[c];
    }

    for (int c = 0; c < sizeof(dimmers); c++) {
        Dimmer dimmer = dimmers[c];

        dimmer.begin();
    }
}

and when I try to run the library with the Arduino IDE, with this code:
DimmerGlider dimmer1Glider = DimmerGlider(_DIMMER_1_tempMin, _DIMMER_1_tempMax, _DIMMER_1_increase);
Dimmer dimmer1 = Dimmer(
                   dimmer1Glider,
                   _DIMMER_1_pin,
                   _DIMMER_t3
                 );
DimmerGlider dimmer2Glider = DimmerGlider(_DIMMER_2_tempMin, _DIMMER_2_tempMax, _DIMMER_2_increase);
Dimmer dimmer2 = Dimmer(
                   dimmer2Glider,
                   _DIMMER_2_pin,
                   _DIMMER_t3
                 );
DimmerGlider dimmer3Glider = DimmerGlider(_DIMMER_3_tempMin, _DIMMER_3_tempMax, _DIMMER_3_increase);
Dimmer dimmer3 = Dimmer(
                   dimmer3Glider,
                   _DIMMER_3_pin,
                   _DIMMER_t3
                 );

Dimmer dimmers[] = {
  dimmer1, dimmer2, dimmer3
};

DimmerImplementor implementor = DimmerImplementor(dimmers, _DIMMER_pinOpto);

void Dimmer_Init() {
  implementor.begin();
}

It throws the following error:
C:\Users\Arnym\Documents\Arduino\libraries\RegletaCMA/RegletaCMA.h: In member function 'void DimmerImplementor::begin()':

C:\Users\Arnym\Documents\Arduino\libraries\RegletaCMA/RegletaCMA.h:73:44: error: invalid use of non-static member function

         attachInterrupt(_optoPin, dimAll, 3); // 3 is the same as RISING

                                            ^

I have been messing around with this problem for some days and I can't find an answer, so I would be really pleased if you can help me.
If you need any more info, don't doubt on asking.
Thanks in advance.

In C++, you need to distinguish between two separate copies of an object, or having a reference to an existing object. @chrisl got it right when he identified that you were trying to create a second copy of DimmerGlider, so he suggested using a reference - and then showed using a pointer (*) instead.
He was right: Dimmer should hold a reference to the DimmerGlider object, but that is done with &. You need to make the following changes to the given code:
In the .h:
class Dimmer {

public:
    Dimmer(DimmerGlider &glider, int outputPin, int t3);
.
.
.
private:
    DimmerGlider &_glider;
.
.

And in the final .cpp:
DimmerGlider::DimmerGlider(int min, int max, int increase) :
              _min(min),
              _max(max),
              _increase(increase) {
}

Dimmer::Dimmer(DimmerGlider &glider, int outputPin, int t3) :
        _glider(glider),
        _outputPin(outputPin),
        _t3(t3) {
}

The syntax for the Dimmer constructor had to change. You were assigning the class members the values from the constructor parameters. References need to be initialised, not assigned. This is the syntax you need (note how they’re before the {?)
I fixed the DimmerGlider constructor code while I was at it...
Also, note the difference between using a reference versus using a pointer. A pointer needs to be dereferenced, so you need to use *ptr and ptr->_min to refer to the original object. A reference is already dereferenced, so you can simply use it like the original object: ref and ref._min.

Edit: If you want to use the function dimAll() as an interrupt handler function, then it cannot be a (non-static) member of a class. All class functions have a hidden this pointer as the first parameter in the argument list, since it has to know which DimmerImplementor's members to modify. Thus you have to declare the function as static. And as soon as you do that, you cannot call dimAllDimmers(), because that functions accesses an instance of DimmerImplementor's variables. Luckily, you have a global object called implementor, so you could use that:
static void DimmerImplementor::dimAll() {
    implementor.dimAllDimmers();
}

But it's usual to make that variable a static member of the class itself:
class DimmerImplementor {
    .
    .
public: // Static variables
    static DimmerImplementor implementor;
    .
    .
}; // DimmerImplementor

You'd initialise that as follows:
DimmerImplementor DimmerImplementor::implementor(dimmers, _DIMMER_pinOpto);

Thanks, this solved my first problem, but I am still having troubles with attachInterrupt, the compiler throws error: invalid use of non-static member function, see modified question for the full program

@ArnyminerZ Check the edit to my answer

The error message says, that in the constructor of Dimmer it cannot find a matching constructor of DimmerGlider. The problem here is that you pass the parameters by value, which will create a new variable of the given type and content for the function/constructor call. So when you create a new Dimmer variable you are calling the constructor of the class. Since the parameters of the constructor contain a DimmerGlider instance, it also has to be created for you, which means calling the constructor. When passing variables by value the default constructor (without any parameters) is used. But the DimmerGlider doesn't have a default constructor (as you didn't define it). The compiler then tells you, that is needs some parameters for the constructor to create a DimmerGlider instance.
I don't know a way to pass these parameters for the DimmerGlider constructor directly through the Dimmer constructor. Also I don't think this is desirable for you. You are creating the DimmerGlider first and sure want the Dimmer objects to refer to exactly this instance, not a different (cloned) instance, that was created with the Dimmer constructor.
So my suggestion is the following: Pass the DimmerGlider by reference, meaning you only pass a pointer to the DimmerGlider object. In the constructor definition of Dimmer change to the following:
Dimmer::Dimmer(DimmerGlider *glider, int outputPin, int t3);

The * says, that this variable will not hold an instance of the DimmerGlider class, but only a pointer to one. A pointer is simple to create, because it is basically an unsigned int (a 16 bit memory address).
Then in your sketch you are passing not the variable itself, but only the address in memory (a pointer to the object) by using the &:
Dimmer dimmer1 = Dimmer(
                   &dimmer1Glider,
                   _DIMMER_1_pin,
                   _DIMMER_t3
                 );

Now the constructor of Dimmer doesn't have to create an instance of DimmerGlider, but only a simple pointer of the type Dimmerglider. The & retrieves the memory address (the pointer) of an object instance. The constructor now simply writes the pointer, that it got as a parameter, into the glider variable of type DimmerGlider-pointer.
If you don't understand, how pointers work, please google for a tutorial on this. This isn't something, that can be easily explained in the short question-answer format of this site.

But that constructor should be the Dimmer constructor, not the DimmerGlider one

The constructor you sent, is the Dimmer one, as specified on the line 29 of the header file:
Dimmer(DimmerGlider glider, int outputPin, int t3);
and then initialized in the cpp file:
Dimmer::Dimmer(DimmerGlider glider, int outputPin, int t3) {     _glider = glider;     _outputPin = outputPin;     _t3 = t3; }
The DimmerGlider class only needs three int parameters:
DimmerGlider::DimmerGlider(int min, int max, int increase)

You are right, I haven't seen that, But now I rellay understand whats happening there. I will change my answer.


text:
Arduino Nano Circuit grounding
I am making an LED circuit for a Lobot (from star wars) costume headset that will not be on a PCB or stripboard. It will all be running inside the walls of the plastic shell I am making. Please see Gif of what I am hoping to do:

EDIT:
The LEDs will run through 4 different programs. Here is one program as an example:
-Far left and right led pairs will alternate on/off
-Single LEDs will blink twice then off for a cycle
-The (4) pairs on the left and right will rise and fall like a soundboard
-The (3) pairs of white(blue in the demo) will chase bottom to top and back down again
I am new to electronics so I am a little nervous about running the ground wire for it. Here is my circuit:
EDIT 2:
Here is a reworked diagram based on the suggestions i received below:

The reds were switched to blue for the simulation but will actually be white. So they are 3v each but running in parallel will need 100ohm.
Now that we have that out of the way, is the ground wire run correctly?
The simulation runs perfectly, but I want to make sure that I am not overlooking something important before I try it on my arduino IRL. Is there a neater way to do this? Google searches availed me not. What is the accepted method for this type of circuit?

Hello and welcome. Most of your LEDs miss their current limiting resistor. I am not sure about the Arduinos digital outputs but typically that is not a safe thing to do.

Could you describe how you want it to behave, please? The circuit is unusual, but perhaps it makes sense when you know what you're trying to achieve.

@MarkSmith I edited my original post with more details on the program i am running. I had to double-up the LEDs to slim down the circuit due to the limited number of pins on the nano.

The schematics is unfortunately somewhat complicated to read as one has to look at the pinout to understand it. When comparing it to the pinout however I find a few things that are odd, e.g. one of the green wires (top, fourth pin from the right) is connected to GND.
Note that the sum of the forward voltages of the LEDs connected in series need to be (significantly) lower than the supply voltage of the Arduino. This forward voltage is different for differing LEDs (depending on the colour). Blue LEDs have a higher voltage (typically 3.0 - 3.5 volts). Connecting two blue LEDs or some more red LEDs in series leads to a necessary forward voltage higher than what the Arduino can provide.
Be sure to add the current limiting resistor for the LEDs in the appropriate places. Due to the non-linear current-voltage characteristic of (light emitting) diodes those resistors are a must-have (unless driving them with a current source, which the Arduinos GPIO pins are not). Do use one resistor per LED or if LEDs are connected in series. Do not use only one resistor for LEDs wired in parallel. For more details on this topic see here.
Edit to add (revision of question):
Given 3 V forward voltage and 100 Ohm series resistor one LED presumably leads to a current of about 20 mA. But since you intent to drive two LEDs in parallel (so 40 mA) from each pin, you're well out of spec and hitting Absolute Maximum Ratings:
DC current rating, source:

DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  20 mA

Absolute Maximum Rating, source

DC Current per I/O Pin . . . . . . . . . . . . . . . . . .  40.0mA

Furthermore you intend to connect 18 pairs of LEDs (give or take the red LEDs). This would be a total current of 720 mA which is significantly above the limits of the microcontroller. Consider that all the current flowing through the LEDs into the GPIO pins also needs to flow to VCC through the controllers power supply lines (just two pins!). Those have limits too:
Absolute Maximum Rating, source

DC Current VCC and GND Pins  . . . . . . . . . .  200.0mA

You need an external driver (such as the ULN2803, as presented in this answer) or transistors.

I apologize for the confusing schematics. The Arduino i used in the fritz was a micro, not a nano. The major difference is the micro has two additional rows of pins that i am not using see image here: link

@AndrewMetzger, Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D

As to the resistors, i have tested it on an uno without having any issues but I can add them onto the circuit. Based on a calculator i used online, i would need 30ohms of resistance for the reds and for the whites the current is too low, which i am fine with a lower output.

Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino

I am putting all comments here as answer.
Micro, Macro, Nano, Uno, Mega... It doesn't matter, all run at 5V. Your schematics won't work.Ghanima is giving you basic, but MUST components. Also i would suggest to use ULN2803 chips. Easy to use transistors. You won't need to calculate resistors for transistors :D
Additional, your arduino will burn in first few seconds, because the current will be to big. you should not drive LEDs from Arduino.
To make it SUPER COOL i would suggest WS2812B LEDs. They need 5V, GND, and Data in. And you can make it any color you want and control all LEDs separately.
Some video about WS2812B
I would strongly recommend it.

Thank you so much for the advice. If I had not already programmed this using the Arduino I would definitely look into your suggestion of the alternate chip. Provided I add the resistors has everyone suggested comma would the circuit work with the ground wire the way it is?

This chip does not require to change your code, and it is easiest to change few lines in your code, rather than make new pcb. When i will get back home i will make few hints for you.


text:
Arduino Nano + (2* tlc5940) + 34 LEDs = Power Questions
This is an adapted layout for two tlc5940 hooked up to an Arduino nano. The original project can be found here. I am a little unsure about the capacitors and resistors as that project had it hooked up to a 5v wall plug.
My Design will be running a pattern of PWM, blinking and chasing lights. The two red lights are off of the TLC5940s circuits because reds need a different resistance. If i am wrong, please let me know as that would simplify things.

Also as is the way of the stack community, any other red flags you can point out would be greatly appreciated as i am new to this game.

TLC5940 is a constant current driver.

Also, its supply is given as 5.5V max.

No resisor in the red leds? As for the capacitor; it might not be needed, but doesn't hurt. I'd move the smaller capacitor as close to the TLC as possible.

Hey @Gerben I have added the resistors to the reds, i always forget them! Should i use two smaller capacitors so i can get them even closer to each tlc5940?

That would be ideal. Adding some decoupling capacitors near the chip can prevent (electrical) noise, and thus prevent weird behavior of the chip.

As Ignacio has mentioned the TLC5940 is a constant current driver. The 2kΩ resistor sets the current for the LEDs regardless of the forward voltage (or colour) or the supply voltage.
Also as Gerben says, move the 0.1µF (100nF) capacitor close to the TLC5940 as you can. There should be one for each TLC5940 since they are decoupling capacitors.
You might like to increase the capacitance of the electrolytic too. The purpose of that capacitor is to provide a low impedance energy source to supply the circuit (batteries are actually quite high impedance by comparison). Since you have lots of LEDs being controlled by PWM the current draw will be fluctuating wildly all the time, and lots of energy over brief periods will be wanted.
Another thing to watch, mentioned again by Ignacio, is the supply voltage for the TLC5940 is 5.5V absolute maximum. I wouldn't go much above 5V. Depending on what your batteries actually are you may be better running from 3 of them (4.5V alkaline AA - Ni-MH would be ~3.6V, so 4 of them, giving 4.8V, would be better in that situation).
I would also question your use of the TLC5940. They are not the easiest chips to drive requiring quite a strange protocol. Personally I prefer the TLC59116 which is the I2C variant of the same chip. Much easier to control from an Arduino, and requiring just 2 pins. Not so easy for bread-boarding though as they're SMD only.

Hi @majenko Thank you for the great explanation!  What size electrolytic capacitor would you suggest i use?

Whatever you have handy. 10µF minimum.


text:
How to use this specific arduino shield
I am trying to understand how to wire this Arduino Uno shield properly.
My goal/main questions: I have 6 servo motors and I am trying to wire them properly to this shield. Do I need an external battery pack? If yes, how do I wire that? I need all the wiring details because I cannot find information about this shield anywhere.
I've provided an actual photo of the shield and I even made a schema for you guys, if somebody wants to draw. I bought this arduino + servos + shield from aliexpress and there wasn't any documentation, explanation, schema or anything like that for that specific shield.

Useful info:

Servos are MG996.
4 motor && 16 servo board - name of the shield
http://doit.am - website of the maker
https://github.com/SmartArduino/SZDOITWiKi/wiki/Module-Preface - An incredibly cramped and unclear github that the maker provided for more info but it's yet again, unclear.

Conclusive question: Do I even need this shield at all? Can I just use a regular UNO to be able to freely operate with 6 servos?

CODE UPDATE:
#include <Servo.h>

Servo myservo;

void setup() {
  myservo.attach(2);
}

void loop() {
  myservo.write(0);
  delay(1000);
  myservo.write(90);
  delay(1000);
}

the datasheet shows the used UNO pins ... there is also a zip file with servo example code ... https://github.com/SmartArduino/ESPboard

@YulianProdanov When you still have problems, you can write comments under my answer and include the new information in your question. Edits on answers are not meant for replying to an answer

Do I even need this shield at all? Can I just use a regular UNO to be able to freely operate with 6 servos?

You don't really need this shield for 6 servos. The standard servo library supports 12 servos on the Uno by using a hardware timer. In your case the shield would mainly help with

Freeing up the hardware timer (in the case you need it)
Providing a dedicated power line to the servos (since the current for the servos should not run through the Arduino)

If that is enough for you to still use the shield, you can absolutely do that.

I need all the wiring details because I cannot find information about this shield anywhere.

If you look at the wiki (whose link you provided) and navigate to the page for this shield you will see this diagram

The servos are connected to the header names "16 road servo", each having the pins (from top to bottom in the image) PWM signal, positive power and ground.

At the header marked "insert short circuit module" you can use jumpers to select the handling of the power supply, which you connect left to that to the terminals marked supply power. It is not described clearly there, but I would read the following meaning:

The VM terminal is used for the motor voltage. You might choose to provide your motors with a different voltage than 5V. If you set the jumper between VM and Vin you can connect that power input to the Vin input of the Arduino, thus powering it from the same power source as the motors (Vin goes to the Arduinos voltage regulator to get the voltage down to 5V). If your power supply is still just 5V, you should leave the jumper out and connect the power supply directly to the VM input (and of course also its ground).
Vs should be the power input for the logic circuit of the shield. If you put a jumper between the pins Vs and +5V, you will connect the power of the logic circuit on the shield to the 5V line of the Arduino. I would suggest doing that, because then you don't need to provide Vs from outside.

The other headers are for DC motors and for different modules, which can be connected.

Do I need an external battery pack?

Here it is important to know, how you are powering the Arduino and how much current the servos need. This datasheet of the MG996 states a stall current of 2.5A, way too much for the Arduino to handle and also way to much for any normal USB port (which will give you up to 500mA). As stated above, you should never run that much current through the Arduino. Provide the motors with power from a power source capable of providing the needed current (+ some headroom). If that is a battery pack or a power supply connect to mains is up to you.

Yes, sorry, I didn't mean to edit your answer, @chrisl , I'm not sure what happened there. Anyhow, I tried to follow your instructions thoroughly but I still couldn't quite achieve the end result, namely "make possible to move a servo back and forth, at least 1 out of 6".
I've included 3 pictures of my setup in the link below.
link
Btw, I uploaded the code I used in my question above, so you can take a look too.

You cannot use the normal Servo library, when you are using the shield. The nornal servo library uses an internal timer to switch a digital output pin with the correct signal. That shield uses a dedicated chip for that. Have you looked for a fitting library to use it?