text:
Check if any of loop's insides returns 1 and hold it until the whole loop is 0 again
I'm new to this, so, please, don't crucify me.
I have a function that checks if an entry in multilevel array is in a certain range. Using FOR loop I check the whole array with this function, which gives me true/false value for each record.
And now the problem:
I need to check if ANY entry in that loop returns true and hold it until every result of that loop is false again.
Any tips?
Thanks a lot.
There is my for loop:
  for(int i = 0; i < arrayTop; i++){
for(int j = 0; j < arrayDay; j++){
  for(int k = 0; k < arrayTime; k++){
    timeCompare(timeArray[i][j][k][0], timeArray[i][j][k][1], timeArray[i][j][k][2], timeArray[i][j][k][3], timeArray[i][j][k][4], timeArray[i][j][k][5], timeArray[i][j][k][6]);

    //Serial.print(i);Serial.print(j);Serial.print(k);Serial.print(" ");
    Serial.println(compareVar);

    if(i == 0){

      //set water switch
      if(compareVar == 1){
        waterOn = 1;
        Serial.println("Water ON");

        goto bailout;
      }
      else {
        waterOn = 0;
        Serial.println("water OFF");
      }
    }
    else if(i == 1){

      //set light switch
      if(compareVar == 1){
        lightOn = 1;
        Serial.println("Light ON");
        goto bailout;
      }
      else {
        lightOn = 0;
        Serial.println("light OFF");
      }
    }
  }
}

}
bailout:
and this is the called function:
//time compare with ON/OFF switch
int timeCompare(int hrOn, int minOn, int secOn, int hrOff, int minOff, int secOff, int timerSwitch){
  unsigned long int onTime = (hrOn*10000UL) + (minOn*100UL) + secOn;
  unsigned long int offTime = (hrOff*10000UL) + (minOff*100UL) + secOff;
  unsigned long int currentTime = (dt.hour*10000UL) + (dt.minute*100UL) + dt.second;

  if(timerSwitch == 1){
    if(onTime < currentTime && offTime > currentTime){
      compareVar = 1;
    }
    else {
      compareVar = 0;
    }
  }
 else if(timerSwitch == 0) {
    compareVar = 0;
  }

  //Serial.print("compare: "); Serial.println(compareVar);

}

I don't understand, what you exactly you are trying to do. I think it would help, if you would show us the code, that you already have. What does "hold it" means?

Sorry, I know it's confusing :-) I added the relevant parts of the code as the whole thing is already quite long. By holds it I mean I need to know if there is a 1 anywhere in the loop, but so far it just tells me if there is 1 in a single entry and then sets it to 0 with the next entry. I need to keep the 1 as long as there is 1 anywhere in the full run of the loop.

First, you should really not use a global variable to get the result of your comparison function. That is only confusion and unnecessary complicated code. For that we have return values. So instead of setting the compareVar variable inside the timeCompare() function, you should just return the corresponding value. In the timeCompare() function replace
compareVar = 1;

with
return 1;

and
compareVar = 0;

with
return 0;

Then in your main code: As I understood, you only need compareVar in the for loops, so you could delete the globally defined compareVar and declare it directly before the for loops:
int compareVar = 0;

Now we can do the magic trick. We want to go through our for loops and get a result of 1, if for any of the elements timeCompare() returns 1. For that we just doing an OR operation:
compareVar = compareVar || timeCompare(timeArray[i][j][k][0], timeArray[i][j][k][1], timeArray[i][j][k][2], timeArray[i][j][k][3], timeArray[i][j][k][4], timeArray[i][j][k][5], timeArray[i][j][k][6]);

This is a boolean OR ||. In C++ zero is treated as false, while any other number is treated as true. We are starting with compareVar begin zero. When timeCompare() for the element returns also zero, it stays zero. If it returns 1, compareVar will become 1. If it returns 1 again, it will stay one. If it returns zero, it will stay zero.
So now you can check for compareVar after the for loops. It will be 1, if any of the elements gave you 1.
Similarly you could check for all elements returning 1, if you replace the OR || by an AND && operation.

Lastly I want to strongly discourage you from using goto. It ignores some important principles and you can easily create really bad code with it. Refer to questions like this one to read more about it. I would say, that in every case you have better ways than goto. Here it seems, that you simply want to go out of both loops. I would pack these loops into a function, so that you could simply use a return statement to get out of them.

For another perspective: I use goto in exactly this (and only this) situation - breaking out of a nest of loops. I just make it super obvious that I'm doing it, why, and to where. Specifically, I always have (though I seldom need it) a #define PUNT goto punt, and keep the punt: label easy to notice....

... This accomplishes two things: my code doesn't actually say "goto" (so the purists aren't so easily offended, though I'm sympathetic to their argument); and second, if I were to try to jump around in my code using this, or to create another nested-loops-with-breakout, my labels would conflict (multiple definitions) and prevent it. Either way, It gives me a heads-up that I need to re-think my coding structure and find a better way.


text:
How do I detect the Computer's operating system?
I'm working on an emoji keyboard and it requires different input depending on the OS it's connected to. I've written the relevant methods using Arudion's default Keyboard library and can manually set which one is used. I'm wondering if there is a method or library for Arduino (currently using a Adafruit Feather 32u4 Bluefruit LE) that allows me to detect the OS.
If not, I'll set up a switch, but that'll cost me pins.

This information is not formally available to a USB peripheral like an Arduino; there might be ways you could "fingerprint" OS behavior from deep in the library code of a Leonardo-type board, but that could trivially change.

@ChrisStratton Thanks. That answer the question. I'm going to have to find a work around.

If you can't get the OS from the USB port, why not use the existing keys/inputs to set the mode on startup? That is, if you tell the user to press different combinations of 2 buttons on startup, you have 4 (2 bits => 4 values) different paths on startup:
00 => Normal startup, don't change mode
01 => OS 1
10 => OS 2
11 => OS 3

Might do that, but I like the idea of a clear multi option switch for the user to be understand/set at any point.

source: Stack Exchange

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

sort: votes


text:
USB Device not recognized (error 43, arduino uno)
I know that there's already post about this, but mine is different. Instead of not recognized, it gets recognized, and I can upload codes, but after a while, windows starts to not recognize it. And there is a temporary fix for this for my laptop, I need to restart. And even after restarting, it still becomes not recognized after a while
Edit : forgot to mention, even if it is not recognized, it still sends power to the arduino

Genuine Arduino board, or a cheap Chinese knock-off?

I am pretty sure it is a genuine arduino board. Also, this just happened recently, I had this board for over 5 months now, and this just happened

It sounds like the USB chip is dying. I would expect that from a Chinese clone, but not a genuine Arduino.

Does the USB chip get hot?

The USB Chip does not get hot

Are you using a USB hub, or plugging it in direct to the laptop?

I plug it in directly to the laptop without any other external stuff...Still, I guess I should try other cable first and then I'll see

"both of them has the same problem." sounds like it's a problem with your computer, USB cable, or with something you're connecting to the Arduinos.

The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND  both pins can be found on ICSP2 of the UNO.
This will surely solve the issue.
But,
if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.

I can confirm that this cannot be the case. As I have two arduino boards lying around and both of them has the same problem. I don't think both of them could get damaged at the same time. But I might try this option

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


text:
How do I find the whole number (n) that when multiplied by (m) will be closest to (x)?
I've designed an apparatus that uses stepper motors, and they are linked together so that when armature A turns, it consequently moves armature B by a ratio of 1/4. In order to keep armature B in the same position, for every 4 steps stepper A takes, I need stepper B to take 1 step. I want to "round" the amount of steps required so that A will always move an amount divisible by 4, otherwise armature B drift over time with (this thing runs for 12 hours at a time). I'm trying to find an efficient way to code this:
My formula for deriving motor A's steps from degrees is: steps = degrees / 0.45
So let's say I want to turn 93 degrees. That would be steps = 93 / 0.45 = 206.66->  I cannot simply round 206 up or down because neither 206 or 207 are evenly divisible by 4. The closest whole number to 206.667 evenly divisible by 4 is 208.
So I wrote this algorithm (it sounds much cooler than saying function :) that will find this closest whole number.
int calcSteps(float targetDegrees)
{
  int gearRatio = 4;
  int cwna = 0, cwnb = 0; // Closest Whole Number Alpha/Bravo

  float targetSteps = (targetDegrees / 0.45);
  for (int x = 1; x * gearRatio < targetSteps; x++) cwna = x;
  cwnb = (cwna + 1);
  int closestWholeNumber = (targetSteps - cwna * gearRatio) < (cwnb * gearRatio - targetSteps) ? cwna : cwnb;
  float newAngle = closestWholeNumber * gearRatio * 0.45;
  int calculatedSteps = closestWholeNumber * GEAR_RATIO;

  Serial.print("CWNA = "); Serial.println(cwna);
  Serial.print("CWNB = "); Serial.println(cwnb);
  Serial.print("Closest Number = "); Serial.println(closestWholeNumber);
  Serial.print("New angle = "); Serial.println(newAngle);
  Serial.print("Steps to turn: "); Serial.println(calculatedSteps);

  return calculatedSteps;
}

Example Outputs:
calc(93);

CWNA = 51
CWNB = 52
Closest Number = 52
New angle = 93.60
Steps to turn: 208

calc(87);

CWNA = 47
CWNB = 48
Closest Number = 47
New angle = 84.60
Steps to turn: 192

The good news is that this works, I just can't help but think there's a better mathematical way to do this. Any ideas?

First, I'll show you the "manual" way.
You can divide the resulting steps by the number they should be divisible by, round to the next integer, and multiply that again by the number. I'll call this number STEPS_PER_INCREMENT below.
const double DEGREES_PER_STEP = 0.45;
const int STEPS_PER_INCREMENT = 4;

//...
    int calculatedSteps = (unsigned int)(targetDegrees / DEGREES_PER_STEP / STEPS_PER_INCREMENT + 0.5) * STEPS_PER_INCREMENT;
//...

Of course, this can be optimized. But then explain the algorithm in a comment for the next reader of the source, including your future self:
const double DEGREES_PER_STEP = 0.45;
const int STEPS_PER_INCREMENT = 4;
const double DIVISOR = DEGREES_PER_STEP * STEPS_PER_INCREMENT;

//...
    int calculatedSteps = (int)(targetDegrees / DIVISOR + 0.5) * STEPS_PER_INCREMENT;
//...

The DEGREES_PER_STEP sound as if you use a calculated result of 1 / STEPS_PER_REVOLUTION with STEPS_PER_REVOLUTION equal to 800. So the next suggestion shows the facts even better. Source code should make things clear, not hide them. ;-)
const int STEPS_PER_REVOLUTION = 800;
const int STEPS_PER_INCREMENT = 4;
const int DEGREES_PER_REVOLUTION = 360;
const double FACTOR = STEPS_PER_REVOLUTION / STEPS_PER_INCREMENT / DEGREES_PER_REVOLUTION;

//...
    int calculatedSteps = (int)(targetDegrees * FACTOR + 0.5) * STEPS_PER_INCREMENT;
//...

This table shows some results:

target degrees
theoretical steps
calculated steps

90
200
200

91
202.222
204

92
204.444
204

93
206.666
208

94
208.888
208

95
211.111
212

96
213.333
212

97
215.555
216

98
217.777
216

99
220
220

Please be aware that his formula works only for non-negative values of the target degrees. If you have negative values, you can compensate by this extension:
const int STEPS_PER_REVOLUTION = 800;
const int STEPS_PER_INCREMENT = 4;
const int DEGREES_PER_REVOLUTION = 360;
const double FACTOR = STEPS_PER_REVOLUTION / STEPS_PER_INCREMENT / DEGREES_PER_REVOLUTION;

//...
    int calculatedSteps = (int)(targetDegrees * FACTOR + 0.5) * RESOLUTION;
    if (targetDegrees < 0) {
        calculatedSteps = calculatedSteps - STEPS_PER_INCREMENT;
    }
//...

Or you use different expressions. In this case the runtime might be more even.
const unsigned int STEPS_PER_REVOLUTION = 800;
const unsigned int STEPS_PER_INCREMENT = 4;
const int DEGREES_PER_REVOLUTION = 360;
const double FACTOR = STEPS_PER_REVOLUTION / STEPS_PER_INCREMENT / DEGREES_PER_REVOLUTION;

//...
    if (targetDegrees >= 0) {
        calculatedSteps = (int)(targetDegrees * FACTOR + 0.5) * STEPS_PER_INCREMENT;
    } else {
        calculatedSteps = (int)(targetDegrees * FACTOR - 0.5) * STEPS_PER_INCREMENT;
    }
//...

Now I'll show you the professional way by using existing C++ libraries.
The Arduino is programmed in C++, and the compiler comes with several standard libraries, most probably including the math library. Since I don't have an Arduino installation here, I'm just supposing that this will work:
#include <cmath>

const int STEPS_PER_REVOLUTION = 800;
const int STEPS_PER_INCREMENT = 4;
const int DEGREES_PER_REVOLUTION = 360;
const double FACTOR = STEPS_PER_REVOLUTION / STEPS_PER_INCREMENT / DEGREES_PER_REVOLUTION;

//...
    long calculatedSteps = lround(targetDegrees * FACTOR) * STEPS_PER_INCREMENT;
//...

Having said that source code should make things clear, you might want to rather use this. You can trust the compiler to optimize for you:
#include <cmath>

const double STEPS_PER_REVOLUTION = 800;
const int STEPS_PER_INCREMENT = 4;
const int DEGREES_PER_REVOLUTION = 360;
const double STEPS_PER_DEGREE = STEPS_PER_REVOLUTION / DEGREES_PER_REVOLUTION;

//...
    double theoreticalSteps = targetDegrees * STEPS_PER_DEGREE;
    double theoreticalIncrements = theoreticalSteps / STEPS_PER_INCREMENT;
    long roundedIncrements = lround(theoreticalIncrements);
    long calculatedSteps = roundedIncrements * STEPS_PER_INCREMENT;
//...

It seems so simple now...this is really great stuff. Cheers!

The simplest solution is probably to do the computation backwards: first
calculate the number of steps motor B has to turn, then multiply by four
to get the step count for motor A:
int steps_B = round(degrees / 1.8);
int steps_A = 4 * steps_B;

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


text:
I'm trying to make a game of life using an arduino nano and a 24x8 Led Matrix. When I try making area bigger it says not enough memory. What can I do?
I have a problem when changing MAX_X from 8 to 24. I know that the problem is that I am using to many global variables but I don't know how to fix it.
#include <LedControl.h>

#include "LedControl.h"

// "DIN" data in pin
#define DIN_PIN 12
// "CLK" clock pin
#define CLK_PIN 11
// "CS" pin
#define CS_PIN 10
// grid dimensions. should not be larger than 8x8
#define MAX_Y 8
#define MAX_X 24
// how many custom starting grid patterns
#define MAX_C 15
// time to wait between turns
#define TURN_DELAY 100
// how many turns per game before starting a new game
// you can also use the reset button on the board
#define TURNS_MAX 40
// how many turns to wait if there are no changes before starting a new game
#define NO_CHANGES_RESET 4

int TURNS = 0;       // counter for turns
int NO_CHANGES = 0;  // counter for turns without changes

// game state. 0 is dead cell, 1 is live cell
boolean grid[MAX_Y][MAX_X] = {
  {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
  {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
};

// custom starting grid patterns
boolean cgrids[MAX_C][MAX_Y][MAX_X] = {
  {
    {1, 1, 0, 0, 1, 1, 0, 0},
    {1, 1, 0, 0, 1, 1, 0, 0},
    {0, 0, 0, 0, 0, 0, 1, 1},
    {0, 0, 0, 0, 0, 0, 1, 1},
    {1, 1, 0, 0, 0, 0, 0, 0},
    {1, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 1, 1, 0, 0, 1, 1},
    {0, 0, 1, 1, 0, 0, 1, 1},
  },
  {
    {1, 0, 1, 0, 0, 0, 1, 0},
    {0, 1, 1, 0, 0, 0, 1, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 1, 0, 0, 0, 1, 1, 0},
    {0, 1, 0, 0, 0, 1, 0, 1},
  },
  {
    {1, 0, 1, 0, 0, 0, 0, 0},
    {0, 1, 1, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 1, 1, 0, 0, 0, 0, 0},
    {1, 0, 1, 0, 0, 0, 0, 0},
  },
  {
    {1, 0, 1, 0, 0, 1, 0, 1},
    {0, 1, 1, 0, 0, 1, 1, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
  },
  {
    {1, 0, 1, 0, 0, 0, 0, 0},
    {0, 1, 1, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
  },
  {
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 1, 1, 1},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 1, 0},
    {1, 1, 1, 0, 0, 0, 1, 0},
    {0, 0, 0, 0, 0, 0, 1, 0},
  },
  {
    // https://conwaylife.com/wiki/Mold
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 1, 1, 0, 0},
    {0, 0, 0, 1, 0, 0, 1, 0},
    {0, 0, 1, 0, 1, 0, 1, 0},
    {0, 0, 1, 0, 0, 1, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 1, 0, 1, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
  },
  {
    // https://conwaylife.com/wiki/Octagon_2
    {0, 0, 0, 1, 1, 0, 0, 0},
    {0, 0, 1, 0, 0, 1, 0, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {1, 0, 0, 0, 0, 0, 0, 1},
    {1, 0, 0, 0, 0, 0, 0, 1},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 0, 1, 0, 0, 1, 0, 0},
    {0, 0, 0, 1, 1, 0, 0, 0},
  },
  {
    {1, 0, 1, 0, 0, 1, 0, 1},
    {1, 1, 0, 0, 0, 0, 1, 0},
    {1, 0, 0, 1, 1, 1, 0, 1},
    {0, 0, 1, 1, 0, 1, 0, 0},
    {1, 0, 0, 0, 1, 1, 0, 0},
    {1, 0, 0, 0, 1, 0, 0, 1},
    {0, 0, 0, 0, 0, 0, 1, 0},
    {1, 0, 1, 1, 0, 1, 1, 1},
  },
  {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 1, 0, 0, 0, 0, 1, 1},
    {1, 0, 0, 1, 1, 1, 0, 1},
    {1, 0, 1, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 1, 0, 1},
    {1, 0, 1, 1, 1, 0, 0, 1},
    {1, 1, 0, 0, 0, 0, 0, 1},
    {1, 1, 1, 1, 1, 1, 1, 1},
  },
  {
    {1, 1, 1, 1, 1, 1, 1, 1},
    {1, 0, 0, 0, 0, 0, 1, 1},
    {1, 0, 0, 1, 1, 1, 0, 1},
    {1, 0, 1, 1, 0, 1, 0, 1},
    {1, 0, 1, 0, 1, 1, 0, 1},
    {1, 0, 1, 1, 1, 0, 0, 1},
    {1, 0, 0, 0, 0, 0, 0, 1},
    {1, 1, 1, 1, 1, 1, 1, 1},
  },
  {
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 1, 0, 0, 0, 0, 0},
    {0, 0, 1, 0, 0, 0, 0, 0},
    {0, 1, 1, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {1, 1, 0, 0, 1, 1, 1, 0},
    {1, 0, 1, 0, 1, 0, 0, 0},
    {0, 1, 1, 0, 0, 0, 0, 0},
  },
  {
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 1, 0, 0, 0, 0},
    {0, 0, 1, 1, 0, 0, 0, 0},
    {0, 1, 0, 0, 0, 0, 0, 0},
    {0, 0, 1, 1, 0, 0, 0, 0},
    {0, 0, 0, 1, 0, 0, 0, 0},
  },
  {
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 1, 1, 0, 0, 1, 1, 0},
    {0, 1, 1, 0, 0, 1, 1, 0},
    {0, 1, 1, 0, 0, 1, 1, 0},
    {0, 1, 1, 0, 0, 1, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
  },
  {
    {1, 0, 0, 0, 0, 1, 0, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 0, 1, 0, 0, 1, 0, 1},
    {0, 0, 0, 1, 0, 0, 0, 0},
    {0, 0, 0, 0, 1, 0, 0, 0},
    {1, 0, 1, 0, 0, 1, 0, 0},
    {0, 1, 0, 0, 0, 0, 1, 0},
    {0, 0, 1, 0, 0, 0, 0, 1},
  },
};

LedControl lc = LedControl(DIN_PIN, CS_PIN, CLK_PIN, 1);

void setup() {
  // seed random from unused analog pin
  randomSeed(analogRead(0));

  // initialise the LED matrix
  lc.shutdown(0, false);
  lc.setIntensity(0, 0);
  lc.clearDisplay(0);

  reset_grid();
  display_grid();

  // Serial.begin(9600);
  // debug_grid();
}

void loop() {
  delay(TURN_DELAY);

  play_gol();

  TURNS++;

  // reset the grid if no changes have occured recently
  // for when the game enters a static stable state
  if (NO_CHANGES > NO_CHANGES_RESET) {
    reset_grid();
  }
  // reset the grid if the loop has been running a long time
  // for when the game cycles between a few stable states
  if (TURNS > TURNS_MAX) {
    reset_grid();
  }

  display_grid();
}

// play game of life
void play_gol() {
  /*
    1. Any live cell with fewer than two neighbours dies, as if by loneliness.
    2. Any live cell with more than three neighbours dies, as if by
    overcrowding.
    3. Any live cell with two or three neighbours lives, unchanged, to the next
    generation.
    4. Any dead cell with exactly three neighbours comes to life.
  */

  boolean new_grid[MAX_Y][MAX_X] = {
    {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
  };

  for (int y = 0; y < 8; y++) {
    for (int x = 0; x < 8; x++) {
      int neighboughs = count_neighboughs(y, x);
      if (grid[y][x] == 1) {
        if ((neighboughs == 2) || (neighboughs == 3)) {
          new_grid[y][x] = 1;
        } else {
          new_grid[y][x] = 0;
        }
      } else {
        if (neighboughs == 3) {
          new_grid[y][x] = 1;
        } else {
          new_grid[y][x] = 0;
        }
      }
    }
  }

  // update the current grid from the new grid and count how many changes
  // occured
  int changes = 0;
  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      if (new_grid[y][x] != grid[y][x]) {
        changes++;
      }
      grid[y][x] = new_grid[y][x];
    }
  }

  // update global counter when no changes occured
  if (changes == 0) {
    NO_CHANGES++;
  }
}

// count the number of neighbough live cells for a given cell
int count_neighboughs(int y, int x) {
  int count = 0;

  // -- Row above us ---
  if (y > 0) {
    // above left
    if (x > 0) {
      count += grid[y - 1][x - 1];
    }
    // above
    count += grid[y - 1][x];
    // above right
    if ((x + 1) < 8) {
      count += grid[y - 1][x + 1];
    }
  }

  // -- Same row -------
  // left
  if (x > 0) {
    count += grid[y][x - 1];
  }
  // right
  if ((x + 1) < 8) {
    count += grid[y][x + 1];
  }

  // -- Row below us ---
  if ((y + 1) < 8) {
    // below left
    if (x > 0) {
      count += grid[y + 1][x - 1];
    }
    // below
    count += grid[y + 1][x];
    // below right
    if ((x + 1) < 8) {
      count += grid[y + 1][x + 1];
    }
  }

  return count;
}

// reset the grid
void reset_grid() {
  NO_CHANGES = 0;
  TURNS = 0;

  int grid_type = random(0, 4);
  int custom_grid_choice = random(0, MAX_C - 1);

  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      if (grid_type == 0) {
        // use a custom starting grid pattern
        grid[y][x] = cgrids[custom_grid_choice][y][x];
      } else {
        // create a random starting grid pattern
        if (random(0, MAX_X) <= 1) {
          grid[y][x] = 1;
        }
      }
    }
  }
}

// display the current grid to the LED matrix
void display_grid() {
  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      lc.setLed(0, y, x, grid[y][x]);
    }
  }
}

/*
  // dump the state of the current grid to the serial connection
  void debug_grid() {
  for (int y = 0; y < MAX_Y; y++) {
    Serial.print("y(");
    Serial.print(y);
    Serial.print("): ");

    for (int x = 0; x < MAX_X; x++) {
      Serial.print(grid[y][x]);
      Serial.print(", ");
    }

    Serial.println("");
  }
  Serial.println("");
  }
*/

The obvious “low hanging fruit” for memory optimization is cgrids.
This is an array of 8×24×15 = 2880 booleans that you never
modify. By making it const and storing it in PROGMEM, you should
save that many bytes of RAM.
Edit: Augustus73 asked

And how should I do that?

As explained in the documentation I linked to, using PROGMEM is a
two-step procedure. First, you have to ask the compiler to put the array
in PROGMEM:
PROGMEM const boolean cgrids[MAX_C][MAX_Y][MAX_X] = { ... };

Then, you have to use one of the pgm_read_*() macros when you want to
retrieve the data, as in:
grid[y][x] = pgm_read_byte(&cgrids[custom_grid_choice][y][x]);

And how should I do that, I am not that great with programming?

@Augustus73: see amended answer.

Are you sure your code is working properly when MAX_X is 8? I tried it and I just get weird flickering.

@NickGammon: As I do not have an LED matrix at hand, I emulated it with a serial terminal. For me, the program works as expected both at 8×8 and at 8×24.

Hmmm, I was trying to test his code. :)  With LEDs.

Your use of a byte per bit in your array is inefficient.
I have reworked the code to use a bit for each array item, as follows:
#include <LedControl.h>

// "DIN" data in pin
#define DIN_PIN 12
// "CLK" clock pin
#define CLK_PIN 11
// "CS" pin
#define CS_PIN 10
// grid dimensions. should not be larger than 8x8
#define MAX_Y 8
#define MAX_X 24
// how many custom starting grid patterns
#define MAX_C 15
// time to wait between turns
#define TURN_DELAY 1000
// how many turns per game before starting a new game
// you can also use the reset button on the board
#define TURNS_MAX 40
// how many turns to wait if there are no changes before starting a new game
#define NO_CHANGES_RESET 4

int TURNS = 0;       // counter for turns
int NO_CHANGES = 0;  // counter for turns without changes

// game state. 0 is dead cell, 1 is live cell

unsigned long grid[MAX_Y]; // Each unsigned long can hold 32 bits

// Added by Nick Gammon
void setBit (unsigned long *whichGrid, const unsigned char y, const unsigned char x, const bool value)
  {
  if (value)
    whichGrid[y] |= (1U << x);
  else
    whichGrid[y] &= ~(1U << x);
  } // end of setBit

bool getBit (unsigned long *whichGrid, const unsigned char y, const unsigned char x)
  {
  return whichGrid[y] & (1U << x);
  } // end of testBit

// custom starting grid patterns
unsigned long cgrids[MAX_C][MAX_Y] = {
  {
    0b11001100,
    0b11001100,
    0b00000011,
    0b00000011,
    0b11000000,
    0b11000000,
    0b00110011,
    0b00110011,
  },
  {
    0b10100010,
    0b01100010,
    0b01000010,
    0b00000000,
    0b00000000,
    0b01000010,
    0b01000110,
    0b01000101,
  },

  {
    0b10100000,
    0b01100000,
    0b01000000,
    0b00000000,
    0b00000000,
    0b01000000,
    0b01100000,
    0b10100000,
  },
  {
    0b10100101,
    0b01100110,
    0b01000010,
    0b00000000,
    0b00000000,
    0b00000000,
    0b00000000,
    0b00000000,
  },
  {
    0b10100000,
    0b01100000,
    0b01000000,
    0b00000000,
    0b00000000,
    0b00000000,
    0b00000000,
    0b00000000,
  },
  {
    0b01000000,
    0b01000111,
    0b01000000,
    0b00000000,
    0b00000000,
    0b00000010,
    0b11100010,
    0b00000010,
  },
  {
    // https://conwaylife.com/wiki/Mold
    0b00000000,
    0b00001100,
    0b00010010,
    0b00101010,
    0b00100100,
    0b01000000,
    0b00101000,
    0b00000000,
  },
  {
    // https://conwaylife.com/wiki/Octagon_2
    0b00011000,
    0b00100100,
    0b01000010,
    0b10000001,
    0b10000001,
    0b01000010,
    0b00100100,
    0b00011000,
  },
  {
    0b10100101,
    0b11000010,
    0b10011101,
    0b00110100,
    0b10001100,
    0b10001001,
    0b00000010,
    0b10110111,
  },
  {
    0b11111111,
    0b11000011,
    0b10011101,
    0b10110101,
    0b10101101,
    0b10111001,
    0b11000001,
    0b11111111,
  },
  {
    0b11111111,
    0b10000011,
    0b10011101,
    0b10110101,
    0b10101101,
    0b10111001,
    0b10000001,
    0b11111111,
  },
  {
    0b00000000,
    0b00100000,
    0b00100000,
    0b01100000,
    0b00000000,
    0b11001110,
    0b10101000,
    0b01100000,
  },
  {
    0b00000000,
    0b00000000,
    0b00000000,
    0b00010000,
    0b00110000,
    0b01000000,
    0b00110000,
    0b00010000,
  },
  {
    0b00000000,
    0b00000000,
    0b01100110,
    0b01100110,
    0b01100110,
    0b01100110,
    0b00000000,
    0b00000000,
  },
  {
    0b10000100,
    0b01000010,
    0b00100101,
    0b00010000,
    0b00001000,
    0b10100100,
    0b01000010,
    0b00100001,
  },

};

LedControl lc = LedControl(DIN_PIN, CS_PIN, CLK_PIN, 1);

void setup() {
  // seed random from unused analog pin
  randomSeed(analogRead(0));

  // initialise the LED matrix
  lc.shutdown(0, false);
  lc.setIntensity(0, 0);
  lc.clearDisplay(0);

  reset_grid();
  display_grid();

  Serial.begin(115200);
  debug_grid();
}

void loop() {
  delay(TURN_DELAY);

  play_gol();

  TURNS++;

  // reset the grid if no changes have occured recently
  // for when the game enters a static stable state
  if (NO_CHANGES > NO_CHANGES_RESET) {
    reset_grid();
  }
  // reset the grid if the loop has been running a long time
  // for when the game cycles between a few stable states
  if (TURNS > TURNS_MAX) {
    reset_grid();
  }

  display_grid();
}

// play game of life
void play_gol() {
  /*
    1. Any live cell with fewer than two neighbours dies, as if by loneliness.
    2. Any live cell with more than three neighbours dies, as if by
    overcrowding.
    3. Any live cell with two or three neighbours lives, unchanged, to the next
    generation.
    4. Any dead cell with exactly three neighbours comes to life.
  */

  unsigned long new_grid[MAX_Y]; // Each unsigned long can hold 32 bits

  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      int neighboughs = count_neighboughs(y, x);
      if (getBit (grid, y, x)) {
        if ((neighboughs == 2) || (neighboughs == 3)) {
          setBit (new_grid, y, x, 1);
        } else {
          setBit (new_grid, y, x, 0);
        }
      } else {
        if (neighboughs == 3) {
          setBit (new_grid, y, x, 1);
        } else {
          setBit (new_grid, y, x, 0);
        }
      }
    }
  }

  // update the current grid from the new grid and count how many changes
  // occured
  int changes = 0;
  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      if (getBit (new_grid, y, x) != getBit (grid, y, x)) {
        changes++;
      }
      setBit (grid, y, x, getBit (new_grid, y, x));
    }
  }

  // update global counter when no changes occured
  if (changes == 0) {
    NO_CHANGES++;
  }
}

// count the number of neighbough live cells for a given cell
int count_neighboughs(int y, int x) {
  int count = 0;

  // -- Row above us ---
  if (y > 0) {
    // above left
    if (x > 0) {
      count += getBit (grid, y - 1, x - 1);
    }
    // above
    count += getBit (grid, y - 1, x);
    // above right
    if ((x + 1) < MAX_X) {
      count += getBit (grid, y - 1, x + 1);
    }
  }

  // -- Same row -------
  // left
  if (x > 0) {
    count += getBit (grid, y, x - 1);
  }
  // right
  if ((x + 1) < MAX_X) {
    count += getBit (grid, y, x + 1);
  }

  // -- Row below us ---
  if ((y + 1) < MAX_Y) {
    // below left
    if (x > 0) {
      count += getBit (grid, y + 1, x - 1);
    }
    // below
    count += getBit (grid, y + 1, x);
    // below right
    if ((x + 1) < MAX_X) {
      count += getBit (grid, y + 1, x + 1);
    }
  }

  return count;
}

// reset the grid
void reset_grid() {
  NO_CHANGES = 0;
  TURNS = 0;

  Serial.println("Resetting the grid");

  int grid_type = random(0, 4);
  int custom_grid_choice = random(0, MAX_C - 1);

  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      if (grid_type == 0) {
        // use a custom starting grid pattern
        setBit (grid, y, x, getBit (cgrids[custom_grid_choice], y, x));
      } else {
        // create a random starting grid pattern
        if (random(0, MAX_X) <= 1) {
          setBit (grid, y, x, 1);
        }
      }
    }
  }
}

// display the current grid to the LED matrix
void display_grid() {
  for (int y = 0; y < MAX_Y; y++) {
    for (int x = 0; x < MAX_X; x++) {
      lc.setLed(0, y, x, getBit (grid, y, x));
    }
  }
  debug_grid ();
}

// dump the state of the current grid to the serial connection
void debug_grid() {
  Serial.print ("      ");
  for (int x = 0; x < MAX_X; x++)
     Serial.print (".");
  Serial.println ();

  for (int y = 0; y < MAX_Y; y++) {
    Serial.print("y(");
    Serial.print(y);
    Serial.print("): ");

    for (int x = 0; x < MAX_X; x++) {
      if (getBit (grid, y, x))
        Serial.print ("*");
      else
        Serial.print (" ");
    }

    Serial.println("");
  }
  Serial.println("");
  }

Note, in particular, the functions setBit and getBit which are designed to test, set or clear a particular bit, as indexed in your earlier implementation of arrays of one byte.
I then reworked the code to use these new functions, and changed your declaration of the cgrids to match. Testing on the serial terminal seems to work. Your code didn't do anything useful for me on my LED display.
// Added by Nick Gammon
void setBit (unsigned long *whichGrid, const unsigned char y, const unsigned char x, const bool value)
  {
  if (value)
    whichGrid[y] |= (1U << x);
  else
    whichGrid[y] &= ~(1U << x);
  } // end of setBit

bool getBit (unsigned long *whichGrid, const unsigned char y, const unsigned char x)
  {
  return whichGrid[y] & (1U << x);
  } // end of testBit

I also fixed a few bugs in your code where you were testing for X or Y reaching 8 rather than MAX_X or MAX_Y which would have worked when MAX_X and MAX_Y were 8, but not if you make them bigger.
This version uses a lot less memory:
Sketch uses 4876 bytes (15%) of program storage space. Maximum is 32256 bytes.

I reworked your debugging display a bit since the LEDs didn't work for me. Example output:
      ........................
y(0):           ****
y(1):   **        * *
y(2):   **     ** * **
y(3):          *  * *
y(4):             *
y(5):
y(6):
y(7):

      ........................
y(0):            ***
y(1):   **     *    **
y(2):   **     ** * **
y(3):          ** * **
y(4):              *
y(5):
y(6):
y(7):

      ........................
y(0):             ***
y(1):   **     *     *
y(2):   **    *
y(3):          ** *  *
y(4):              **
y(5):
y(6):
y(7):

      ........................
y(0):              **
y(1):   **         **
y(2):   **    * *
y(3):          *   **
y(4):              **
y(5):
y(6):
y(7):

Just for interest, I made a Game of Life in 2011 for the Lots Of LEDs shield. It's a fun project.
Edit - to be fair, I think the code was actually written by the author of the shield: "Created by Jimmie Rodgers on 12/30/2009".
However I do recall writing a Game of Life for the Apple II, many years ago. The source code for that is long gone. :)

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


text:
C++ Undefined reference to 'Class:Function()'
I have these files:

Project.ino
Sensor.h
Sensor.cpp
IMU/L3G.h
IMU/L3G.cpp

Sensor.h
#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

pivate:
    L3G gyro;
};
#endif

Sensor.cpp
#include "Sensor.h"

Sensor::Sensor()
{

}
Sensor::~Sensor()
{

}

void Sensor::Init(void)
{
  if (!gyro.init())
  {
    Serial.println("Failed to autodetect gyro type!");
    while (1);
  }
  gyro.enableDefault();
}

Project.ino
#include <i2c_t3.h>
#include <EEPROM.h>
#include <Servo.h>
#include "Sensor.h"

Sensor sensor = Sensor();

void setup() {

  sensor.Init();
}

I got this error
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:15: undefined reference to `L3G::init(unsigned char, unsigned char)'
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:20: undefined reference to `L3G::enableDefault()'

So, what is wrong?

pivate? typo?

Your question is tagged [tag:arduino-uno] and yet the i2c_t3 is for teensy devices

@Juraj - once the typo has been fixed, then the OP's error is seen.

What platform are you compiling on (OSX, Windows, Linux)? What version of the IDE are you using? 1.8.5? Where did you source your LMU library from?

As Juraj rightly points out, you have a typo, which should give you the following compile time error:
In file included from sketch/Sensor.cpp:1:0:
Sensor.h:17: error: 'pivate' does not name a type
 pivate:
 ^

Here is the correct code for Sensor.h
#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

private:
    L3G gyro;
};
#endif

Using Arduino IDE 1.8.5 with Teensyduino 1.42 with:

https://github.com/pololu/l3g-arduino
https://github.com/nox771/i2c_t3

However, once the typo has been corrected, as above, then I too can reproduce your problem (sort of), with these link errors:
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Sensor()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:3: undefined reference to `L3G::L3G()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:14: undefined reference to `L3G::init(L3G::deviceType, L3G::sa0State)'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:19: undefined reference to `L3G::enableDefault()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/core/core.a(main.cpp.o): In function `main':
/Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/cores/teensy3/main.cpp:53: undefined reference to `loop'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Servo.h"
 Used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/libraries/Servo
 Not used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/libraries/Servo
Error compiling for board Teensy 3.5.

You are probably getting this error, because you have placed the files L3G.cpp and L3G.h in a folder called IMU in the same folder as your .ino file. This causes the undefined error, as, while the IDE sees the declaration in the L3G.h file, the IDE can not find the definition in the L3G.cpp file.
This is easy to resolve.
If you download the l3g-arduino-master.zip file from https://github.com/pololu/l3g-arduino, and from within the Arduino IDE you then add the zipped up L3G library to the Arduino library, using Sketch ► Include Library ► Add. ZIP Library... and then change the line
#include "IMU/L3G.h"

to
#include <L3G.h>

Then it should compile and link without a problem


text:
RX and TX pin in Arduino Uno
I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).
Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?

buy a Mega. perhaps a mini version

is there no other way except buy a new device?

You can't magic more pins out of thin air. If you have used all your pins you have used all your pins. You are already multiplexing, so you can't use that to reduce your pin usage. You may be able to use charlieplexing to free up some pins. We'd need to see your schematics to know what is possible. Or just get a bigger board. Get one with more power while you're at it - and multiple UARTs, so you can use hardware serial for bluetooth and debug over USB at the same time.

my schematics just like LED Cube 4x4 in youtube https://www.youtube.com/watch?v=4pzxR-ZhbJA&t=548s

4x4x4 is 64 leds. You can do that with 8x8, which is only 16 pins. The software should be changed, but that would be a good programming exercise.

You can't magic more pins out of thin air.

Yes you can!
You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)
All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

You can use three (for example CD4094) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.
Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.
This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.
This way you can free most of your Arduino pins including TX and RX.

Using shift registers as extra parts is not "magic more pins out of thin air", but nontheless this is a valid answer how to get to the desired result.

It's just semantics and abstraction, but I think using the shift registers in this particular fashion is called "extending number of outputs" of microcontroller. Thinking about it this way allows you to mentally "blackbox" the microcontroler  with shift registers and just treat them as a single IC when designing rest of the circuit.


text:
Hex/Byte Reversing and Conversion
I'm working on an RFID system using a MFRC522 with this Library : https://github.com/miguelbalboa/rfid
Here's the code I have right now:
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);

This results in the following output:
UID is 35 C5 5A 59

My issue is - how do I first reverse that UID : from 35 C5 5A 59 to 59 5A C5 35
- and second convert and print the corresponding decimal value of that reversed UID. In this case, it would be 1499120949.
I should mention that I need it as a string at the end to add it to the end of a POST command.

Already has an answer on Arduino.cc  http://forum.arduino.cc/index.php?topic=561413.0

A standard way to convert individual bytes to a number is to use bit
shifts and bitwise OR, as shown in chrisl's answer. When doing this,
however, one has to take care not to overflow the bit shifts. On the
AVR-based Arduinos, an int is 16 bits long. Shifting it by
24 bit positions to the left is guaranteed to overflow, which in
C++ leads to undefined behavior.
The solution, as explained in Majenko's comment, is to cast to the final
type before shifting, like this:
uint32_t uid = (uint32_t) mfrc522.uid.uidByte[0] << 0
             | (uint32_t) mfrc522.uid.uidByte[1] << 8
             | (uint32_t) mfrc522.uid.uidByte[2] << 16
             | (uint32_t) mfrc522.uid.uidByte[3] << 24;

Note that I got rid of the useless intermediate variables A through
D.
Once you have have the numerical value, you may try to use it without
explicitly converting to a string. Instead, you rely on the print()
or println() methods to implicitly do the conversion only when needed,
as in
Serial.print("UID = ");
Serial.println(uid);

or even, on a network connection:
client.print(uid);

This will save you the memory needed to store the string. If you really
need to have the converted string in memory, which could happen if you
need to provide a Content-Length before sending the data, you can do so
with the function ultoa() from the avr-libc:
char uid_str[11];  // max = 10 digits + terminating NUL
ultoa(uid, uid_str, 10);  // convert to base 10

Please note that ltoa() is not appropriate here, as calling it
will implicitly convert the value to a signed long, which has the
potential to overflow and yield a negative result.
This “C string” – a NUL-terminated character array – can then
be converted to a String object if needed, but I advice you against doing so
if at all possible. String objects are more convenient to manipulate,
but they are absolutely not memory friendly, which can quickly become an
issue on most Arduinos.

To add a bit to the whole hex and decimal story:
Those are just representations of numerical values your computer/microprocessor does not really care about.
int x = 0
int y = 0b0
int z = 0x0

these are all the same value and internally stored as binary, just like any other number.
You specifically told the println function to display said number(s) in hexadecimal representation with the format specifier %x
Serial.println("UID is %x %x %x %x", A, B, C, D);
using %d or %i(for integer) will print out decimal values for each number.
Converting byte array to larger data type
If you actually want them to be reversed, you could simply cast the array variable (which is nothing but a pointer) to an uint32_t pointer:
uint32_t dec_value = *(uint32_t*)mfrc522.uid.uidByte

Note the *s
We first cast the pointer to a pointer of a different type (uint32_t*)
and then access it's value, by prepending another *, which is then stored in dec_value, equaling 1499120949 now.
This works because in C/++ data structures in memory are guarenteed to be in the order you specified.
 Therefore, you essentially tell the computer to 'see' these very 4byte (32bit) as a single value rather than a independent bytes.
Usually, when converting byte arrays to larger data types, you will find the values you receive are not what you would expect. This is because they are stored in a different order (depending on the machine) known as endianness
Here is a function that addresses this issue (similiar to the other answers)
uint32_t bytearray_to_uint32(unsigned char *buffer)
{
    uint32_t value = 0;

    value |= (uint32_t)buffer[0] << 24;    // cast to target type before
    value |= (uint32_t)buffer[1] << 16;    // shifting to avoid overflow
    value |= (uint32_t)buffer[2] << 8;     // no parentheses needed due to operator precedence
    value |= buffer[3];

    return value;
}

Applying this function to your case would result in 902126169 (0x35c55a59) instead of the desired 1499120949 (0x595ac535).
Also check out ntohl when dealing with endianness still puzzles you.

As already stated in Majenko's comment to chrisl's answer, and restated in my own answer, buffer[0] << 24 will overflow on most Arduinos. 2. ntohl() is not be available on most (maybe all) Arduinos.

I referred to ntohl for educational purposes only. Shifting an 8 bit value by > 8 will not overflow unless the target is too small (WinAVR). Again, the function utilizing shifting is just included for educational purposes, as it is not suited for OP's application in it's given form.

This may be just my personal opinion, but I don't think “educational purposes” excuses undefined behavior.

Behavior depends on target architecture and used compiler. Any decent one will either cope or throw a shift-count-overflow instead.

Your UID has 4 bytes, which correspond to 32 bits. To get a decimal value from these bytes, you have to put them together in one variable. For this you can use an unsigned long. To put the bytes together, you can shift the values to the byte boundaries:
unsigned long dec_value = (D << 24) | (C << 16) | (B << 8) | A;

<< shifts the bits of the byte by the specified amount of bits to the left; The bitwise OR | puts the now not overlapping bytes together in one value. I have reversed the order of the bytes in this code, as you wrote, that this is necessary.
To convert this unsigned long to a string you can use the function ltoa():
char buf[50];
ltoa(dec_value, buf, 10);  // 10 is the base value not the size - look up ltoa for avr

If you want to use a String object (which should be avoided because of heap fragmentation), you can contruct the String directly from the long value:
String my_UID = String(dec_value);

Fantastic! I tried printing the result just to test with Serial.println("%s\n", my_UID); but I'm getting an error: no matching function for call to 'HardwareSerial::println(const char [4], String&)'

Serial.println() does not work like sprintf(), so you can't use that syntax there. But you should be able to get the correct result by simply writing Serial.println(my_UID);. There is really no need to format the string again (also because println already adds a line break at the end, so that you can ditch the extra "\n").

Ah. Managed to get it to print - but I'm getting 4294952245 as my decimal answer. An online converter said that 595AC535 = 1499120949. I'm testing it using fixed hex bytes - https://pastebin.com/i2NPjv60

You need to use "unsigned long" instead of "int" for your A,B,C and D - otherwise the shifting overflows.

dec_value is a poorly chosen variable name, as it implies there is something “decimal” about it. It's not decimal: it's just a number, internally stored in binary, just as any other numerical variable is stored in binary.

I think this does what you need.  You already have the data in an array so to reverse it you go backwards through the list and assemble the number.  To fit 4 bytes into 32bits you need to multiply each byte by (256 * its position), which is what the left shift << does.  So by placing the code in a small loop you get some compact code that should do the job.
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);
// ^ Your code
uint32_t reversed = 0;
for (int x = 3; x > -1; --x) // go backwards through the array
{  // Take the existing value and multiple by 256 (left shift by 8) then add the latest byte on.
   reversed = (reversed << 8) + mfrc522.uid.uidByte[x];
}
String decValue = String (reversed);  // Covert the number to a string


text:
Longruner Nano ATMega 328P input stays HIGH for 1s longer than the reality
I have a Longruner Nano ATMega 328P (copy of arduino nano, main difference being the USB connector, CH340 instead of the usual FT232, from what I could find using google searches).
I wrote a super basic code to test its signal detection capabilities:
setup(){
  pinMode(13, OUTPUT);
  pinMode(2, INPUT);
}

loop(){
  digitalWrite(13, digitalRead(2));
}

Hard to make it simpler to test a simple thing: when I give a HIGH signal to D2, D13 is HIGH too.
To test it, I used a simple male-male jump cable and connected VIN pin to the D2 one, for a very brief moment. And I notice D13 stays HIGH for around a second (measured with serial, lowest I could get was 996ms after super quickly touching D2 with the jump cable).
I tried to change the pinMode to INPUT_PULLUP following a similar question I found, but it didn't change anything regarding this delay.
Am I doing something wrong? Maybe a wrong configuration? Or is this just a hardware issue due to the fact that I'm using a copy and there's more than just the USb connector that changes?
I can adapt and work with this if it's required, but being able to have an accurate signal detection would help me greatly.

Don't use Vin as a logic source. Use the +5V pin.
Also, disconnecting the pin is not the same as grounding it. It is "floating". For a proper test, connect a +5V to the pin, and follow it with a Gnd.
A floating pin has an undefined logic level.
What would work in your case is to have a (say) 1k resistor between D2 and Gnd. That way, the moment you disconnect the voltage input the "pull-down" resistor will return it to 0V.

@Supamiu alternatively (for testing) configure D2 as INPUT_PULLUP and connect it to ground with the jumper

So you mean I should have a jumper between D2 and GND, and use another jumper to connect +5V to D2 and observe the trigger on D2?

@Supamiu No, you should add a resistor between D2 and GND, not a jumper. A jumper would end up with a short circuit when you connect D2 to +5V. https://www.electronics-tutorials.ws/logic/pull-up-resistor.html


text:
Windows upload from command line gives Access Denied
saw somewhere that in order to upload a hex file to an arduino you can look at the Arduino IDE - see the command it runs, then replace the hex file with your file.
this is the command I see in the output window:
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\yossi\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i
I try running this from command (as admin):
cd "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

gives me Access is denied.
in fact, just running avrdude gives the same error, so really - this has nothing to do with the COM port (which works fine from the IDE)
I tried closing the IDE and running again, tried rebooting - the same.
*** edit 1 ****
I actually ran this:
cd "C:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

since I didn't want to mess with wrapping the params - but I don't really think it matters - as the problem is running avrdude without any parameter still gives me the same error: Access is denied.

This is because you are running the Windows App Store version of the IDE.
Windows doesn't like you messing with the insides of App Store programs (I think it scares it...).
Install the real version of the IDE from the Arduino.cc website and it will work.


text:
Why does this sketch give MPU FIFO overflows?
I'm transmitting this program over an NRF24l01, data from mpu, and I'm getting a FIFO overflow. Im not sure what the problem is but it gives me a lag when I put it on processing so I know the problem is in the code. I posted the code the below. Pleas help find the issue.
// Include libraries necessary for the radios
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8);

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    MPU6050 mpu;

    #define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;
    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer
    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================
    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }
    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================
    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
          //TWBR = 8; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.

        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        radio.begin();

        radio.setRetries(15, 15);
        radio.openWritingPipe(0xF0F0F0F0A1LL);

        radio.stopListening();
        Serial.begin(115200);

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        mpu.setXGyroOffset(54);
        mpu.setYGyroOffset(15);
        mpu.setZGyroOffset(33);
        mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
        mpu.setXAccelOffset(-4009);
        mpu.setYAccelOffset(332);

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;
            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {

            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }
        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }
    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================
    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;
        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

          /*Do some computational stuff here*/

        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();
        // get current FIFO count
        fifoCount = mpu.getFIFOCount();
        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();

            Serial.println(F("FIFO overflow!"));
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {

            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            fifoCount -= packetSize;

                /*Object to Transmit Yaw, Pitch, and Roll*/
                typedef struct YPR_TX {
                  int y;
                  int p;
                  int r;

                } YPR_TX;

                YPR_TX ypr_tx;

             //   ypr_tx = calcYPR(ypr_tx.y, ypr_tx.p, ypr_tx.r);

                ypr_tx.y = ypr[0] * 180/M_PI;
                ypr_tx.p = ypr[1] * 180/M_PI;
                ypr_tx.r = ypr[2] * 180/M_PI;

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];

                Serial.print("teapotPacket/t");
                Serial.print("\t");
                Serial.print(teapotPacket[2]);
                Serial.print("\t");
                Serial.print(teapotPacket[3]);
                Serial.print("\t");
                Serial.print(teapotPacket[4]);
                Serial.print("\t");
                Serial.print(teapotPacket[5]);
                Serial.print("\t");
                Serial.print(teapotPacket[6]);
                Serial.print("\t");
                Serial.print(teapotPacket[7]);
                Serial.print("\t");
                Serial.print(teapotPacket[8]);
                Serial.print("\t");
                Serial.println(teapotPacket[9]);
               // radio.getDataRate();

                radio.write(&teapotPacket, sizeof(teapotPacket));

            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }

    }

No need to shout - we can hear you.

Shouldn't you clear the fifo every time you have handled the message or when you start sending a new message? If you usually never clear it, it will get full at some point.

@Paul A FIFO by definition is usually self-emptying.

@Majenko good point, but printing out "fifoCount" may help, to see if/when it starts overflowing or doesn't get handled.

It sounds to me like the MPU is sampling faster than the nRF is able to transmit.

@Eduardo I edited your question and removed the shouting; http://www.netlingo.com/word/shouting.php

@Majenko if thats so, How would I fix the code to it samples slower than the nRF?

I have been playing around with the MPU6050 with DMP library too. I see you have used Jeff's example code (as have I). I was getting a lot of FIFO overflows too, but that was because my "do computational stuff here" was taking too long (code with delay()) and the FIFO on the DMP was filling up. Perhaps your radio.write() is taking too long?
The code as written by Jeff is really quite robust, but perhaps not what is necessary in all cases. I have put an extra mpu.resetFIFO() below the Serial.println's. Kind of a hack, but it works. I found the suggestion here:
How to clear FIFO buffer on MPU6050?
Also check on Jeff's own suggestion of lowering the data rate on the DMP by altering the header file:
https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99
Hope this helps.

Yah I  added that and the FIFO overflow goes away. However when you connect it to Processing, the visualization for it " skips" due to this mpu.restFIFO() hack. I'll give it to you anyways but still, its not the right way to fix it.

No, I agree it's not the right way to fix it. But I am not skilled enough to figure out yet what the right way is. Perhaps not resetting the FIFO every iteration of the loop, but once in 3 times might be an idea?
If you are interested, the working code for my sketch, which changes the direction and speed of the pattern on the led strip depending on pitch of the MPU. https://pastebin.com/sU7vEuGf

You are declaring a FIFO overflow every time the mpu sends interrupt 0x10.  Is that correct?
You are using the value in fifoCount before you have set it to a value.  Now with the Arduino IDE you are OK doing that, but its not a good practice.
You are checking that the fifoCount is exactly 1024. It might be better to check if it is >1023 because that will handle the case when it is 1025.
Is there a reason why you have chosen 1024?  Since the packet size defaults to 42 that's 24.3 packets.
Around
while (!mpuInterrupt && fifoCount < packetSize) {

You never get the fifoCount again, so fifoCount < packetSize is always true, therefore you wait until there is an interrupt.  If there first time there is an interrupt is to tell you 0x10 (which I guess is) fifo full from the MPU's perspective) then that will be the reason it is always full.
   // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

      /*Do some computational stuff here*/
      fifoCount = mpu.getFIFOCount(); // Don't forget to get the latest fifo size.
    }

1024 was on the MPU6050 datasheet, thats why I left it for that number. So to fix this problem, I should incorporate "fifoCount = mpu.getFIFOCount();" into where I commented " Do some computational stuff here" and put fifoCount > 1023 instead of leaving it at fifoCount = 1024?

I tried what I stated before and I still get a fifo overflow. It is possible to run two loops that we could initialize the MPU-6050 and nRF24L01 after
the counter achieves some number? If so how could I do that?

authors: Слава Светослав


text:
Programming the ATMega328P without Arduino board always returns the error: avrdude: stk500_recv(): programmer is not responding
I have a microcontroller: ATMega328P.
I don't have any Arduino Uno board.
I want to program the ATMega328P using my FTDI programmer.
But when I try to program the ATMega328P without Arduino board I always get this error:
avrdude: stk500_recv(): programmer is not responding
I've followed this YouTube Tutorial to build this.
And ended up with this diagram:

All the connections seems OK.
I choose the board: "Arduino Pro or Pro Mini" because only with this one I can choose the correct processor: "ATMega328P (5V, 16MHz)"
The port is correct: "/dev/ttyUSB0"
And as for the the programmer I've choose: "USBasp", which I don't know if this is correct. I've used this FTDI programmer to program the STM32 microcontroller and the programmer was "Serial", which I don't see the very same option here.
I'm lost, what am I missing up here?
BTW I've seen this, this and this but couldn't get it fixed.

What happens if you try to program it as a Arduino Uno?

The same @VE7JRO. Using as Arduino Uno with programmer USBasp I get the same error (stk500_revc() programmer is not responding)

For the programmer, please try "AVRISP mkll".

same result :((

If you are certain the IC has a boot loader installed, you could try to use a button or jumper wire from the reset pin to GND instead of the FDTI programmer. The trick is to connect the reset pin to GND, press the upload button in the Arduino IDE, then disconnect the reset pin from GND when the IDE says it starting to upload.

A new chip cannot be programmed in that manner until it has the Bootloader installed. The Bootloader starts after a reset and monitors the serial interface to see if something is attempting to download code via the serial port.
Selecting a Programmer has no effect on serial download, that only comes into play when Programming via the SPI pins SCK/MOSI/MISO/Reset/Power/Gnd.
Your "design" needs a couple more parts: 0.1uF caps between VCC and Gnd, and AVCC and Gnd.
The Cryslal and 22pF caps could also be a lot closer to the device - like right next to it.
I can't read the FTDI markings, so I can't tell if you have Rx and Tx swapped there.

I already have a 0.1uF caps between VCC and Gnd. So I need to place another one between AVCC and GND?

I've put the Crystal and the caps closer to the device but the result is the same. Can I force the reset pin to be on? Something like: put 5V (dont know if it is 5V tolerant) and then try right away to upload the code?

If the chip does not have a Bootloader programmed in it already, it will not be able to  upload via the FTDI module.

no bootloader was programmed! thank you!


text:
How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?
I'm using a Genuino MKR1000 and I want to use the SPI interface, which I've seen that there is no Slave Select (SS)/Chip Select(CS) pin usage.
How can I use the SPI interface with multiple slaves then?

What doesn't have a slave select pin?

I don't know... (question edited to see that there is no SS/CS pin)

Question: how do you use SPI with just one slave...?

I want to use with multiple slaves.

I know, you said. Answer my question first: How do you use SPI with just one slave?

connecting SCK, MISO, MOSI and...SS/CS from master to slave.

SS/CS from master to slave. ... So, if you have no SS pin where do you connect that on the Arduino for ONE slave?

By the way - these are all questions which are intended for you to end up realising the answer for yourself. You should get a penny-drop moment when the answer becomes obvious.

How can I connect multiple SPI devices if I only have one SS pin? The Arduino doesn't need to have a slave pin, since it's the master. You can use any pin to connect to a devices SS pin.

@Majenko thanks. But my slave have SS pin, so I should follow up what Gerben said and choose any pin available for the SS pin, right?

Damn you, @Gerben ;) I was trying to make him answer it himself.

@Gerben I can choose any pin available than, right? Like D3 for instance? And I will need to set this up on the code, right?

@waas1919 Yes, the Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

@Majenko right:)thanks! You should say that on the answer so I can close this topic:p

Some libraries require a specific pin, but on most you can specify your own.

The Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.
The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.

How does SPI.transfer knows where to send data?

It sends it out through the SPI port.

If a slave is connected to pin 3, we can set it to low and transfer data. But what if other pins say 4, 5 are also low. Now how does spi knows which is slave select?

Slave select is the pin that is low that is connected to the chip select pin of a slave. SPI neither knows nor cares what it is. If the slave's chip select pin is low then the slave is listening to the bus.

If the number of slaves is large, consider using a multiplexed arrangement for select lines.  As an example, the 16-pin 74LS138 Decoder/Demultiplexer pulls one of eight lines low depending on the state of its three address lines, while the 24-pin 74LS154 pulls one of sixteen lines low depending on the state of its four address lines.  Both of these chips have two or three enable lines, allowing use of two to four of them together to multiply the number of output lines by two to four via use of one or two more address lines.


text:
Arduino Mega reading same information that it's sending out via serial
So I have an Arduino Mega and I'm attempting serial communication with another device, and I ran into this weird issue.
Let's say I use Serial1.write to send out hex A-F. If I read on that same port (Serial1, print out what I read on Serial0), with NO wires plugged in the serial port, I get a mirror of what I'm sending out in my read function. I've tested this theory on multiple serial ports, as well as different Megas.
How is this interference happening? Do I have an incorrect understanding of the serial buffers? What can I do to stop it? It's causing interference in communicating with my external device.
Here is a super short program to test this theory.
void setup()
{
  Serial.begin(9600);
  Serial1.begin(115200);
}

void loop()
{
  char test[15];
  for (int i = 0; i < 15; i++)
    test[i] = i;

  for (int i = 0; i < 15; i++)
     Serial1.write(test[i]);

  while(Serial1.available() > 0 )
   {
    byte c = Serial1.read();
    Serial.print(' ');
    Serial.print(c, HEX);
  }
}

UPDATE:  I came back the next day with my O-scope and the yellow line is the TX and the blue line is the RX. I was not getting the crosstalk anymore in the Serial port, but on the scope shows the RX line was only being effected about 250mV in perfect unison to the TX. I tried connecting everything back up the same way but I was not able to replicate the issue. Somehow whatever I had going on when I posted this was causing the RX line to be affected great enough for the Mega to pick up on it over serial. For now I'm just blaming it on escaped aliens from Area 51 :)

it is acting as if the local echo is enabled ... there does not appear to be a setting for it though

does this happen if you swap serial and serial1? What happens if you try them both at 9600?

you reinvented radio communication :-)

@esoterik idk, I need serial for seeing my data so I didn't swap. I tried it on Serial2, same issue, then I tried it on Serial3 and it worked better, but not great. I tried different baud rates as well

Note that a scope typically has 1 MΩ input impedance. This would be increased by a factor 10 if using a 10× probe. Connecting the scope to RX is equivalent to adding an extremely weak pull-down resistor, which is enough to significantly reduce the cross-talk effect.

I got the same results from my setup; 0-5V on the Tx line, 0-.3V on the Rx line.  As an experiment I connected two parallel 30cm wires to Tx & Rx. This resulted in a higher cross-talk level, but still did not result in any 'echo reads'. I'm pretty sure that in order to get the necessary 0-3V or so on the Rx line to actually get successful data reads would require some sort of wired connection.  I think your escaped aliens may have pulled one over on you ;-).

I ran a slightly modified version of your test code on a Mega 2560 and got no echo at all;  Unless I totally misunderstood your problem description, there must be something else going on.  Here's the code I ran:

char test[15];

void setup()
{
    Serial.begin(9600);
    Serial1.begin(115200);
    for (int i = 0; i < 15; i++)
    {
        //Serial.print(i);
        test[i] = i;
        Serial.print(test[i],HEX);
    }
    Serial.println();

    for (size_t j = 0; j < 15; j++)
    {
        Serial.print("test["); Serial.print(j);
        Serial.print("] = ");Serial.println(test[j],HEX);
    }
}

void loop()
{
    for (int i = 0; i < 15; i++)
    {
        Serial1.write(test[i]);
    }

    Serial.println(Serial1.available());

    while (Serial1.available() > 0)
    {
        byte c = Serial1.read();
        Serial.print(' ');
        Serial.print(c, HEX);
    }
}

And here's a bit of the output seen on Serial0:
Opening port
Port open
VMDPV_1|1_�Se�
0123456789ABCDE
test[0] = 0
test[1] = 1
test[2] = 2
test[3] = 3
test[4] = 4
test[5] = 5
test[6] = 6
test[7] = 7
test[8] = 8
test[9] = 9
test[10] = A
test[11] = B
test[12] = C
test[13] = D
test[14] = E
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

As you can see, the Serial1 read buffer was always empty.
Did I misunderstand something you said?

I updated my post, see the new info. I ran the same thing again a few days later and I couldn't replicate it, however the perfectly matching RX and TX on the scope leads me to believe that something I had going on made the interference great enough that I could read it back.

Thank you for helping out


text:
'Serial1' was not declared in this scope
Trying to do serial communication between 2 Arduino Unos.
Code:
#include <SoftwareSerial.h>

int ledPin = 13;
int board;   // 1 = Uno. 2 = Mega.
int on_off;  // 1 = On. 0 = Off.
int buzzerPin = 9;
int Ack_tx = 2; //Acknowledgement tx.
int rec;

void setup()
{
  Serial.begin(9600);      // start serial communication at 9600bps
  Serial1.begin(9600);     // start serial1 communication at 9600bps

  pinMode(ledPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);

  Serial.flush();
  Serial1.flush();

} // End Setup

void loop()
{

  Serial.println("Enter Uno=1/Mega=0 ...");  //Select board
  //  if(!Serial){ board = Serial.read();}
  while(Serial.available()==0) { // Wait for User to Input Data
  }
  board = Serial.parseInt();  //Read the data the user has input

  Serial.println("Enter LED On=1/Off=0 ...");  //Select On or Off
  while (Serial.available()==0) { // Wait for User to Input Data
  }
  on_off = Serial.parseInt();

  Serial.println();

  switch (board) {

  case 0:  //Mega board
    if (on_off == 1) digitalWrite(ledPin, HIGH); //Select Uno LED On
    else digitalWrite(ledPin, LOW);              //Select Uno LED Off
    break;  //End Case

  case 1:  //Uno board
    //Serial.println("Off to Uno...");
    //Send on_off info to Uno
    Serial1.write(on_off/256); //Send the Quotient or "how many times" value
    Serial1.write(on_off%256); //Send the Modulo or Remainder.
    delay(50); //Wait for the serial port.

    while(Serial1.available()<2) //Wait for 2 bytes to arrive
     {
      //do nothing
     } //End While

  byte b1=Serial1.read();  //Read Upper byte
  byte b2=Serial1.read();  //Read Lower byte
  rec=(b1*256)+b2;

    if (rec == Ack_tx) tone(buzzerPin, 300, 300); //Ack_tx from Uno
    break;
  } //End Switch Case

}

Error:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void setup()':

sketch_mar06a:13: error: 'Serial1' was not declared in this scope

   Serial1.begin(9600);     // start serial1 communication at 9600bps

   ^

C:\Users\Akshit\Documents\Arduino\sketch_mar06a\sketch_mar06a.ino: In function 'void loop()':

sketch_mar06a:51: error: 'Serial1' was not declared in this scope

     Serial1.write(on_off/256); //Send the Quotient or "how many times" value

     ^

Multiple libraries were found for "SoftwareSerial.h"
 Used: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial
 Not used: C:\Program Files (x86)\Arduino\libraries\SoftwareSerial
exit status 1
'Serial1' was not declared in this scope

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

This is a very basic problem I know, but nothing on the internet is helping.

Why do you think "Serial1" should exist?

I picked this code off of the internet.
I feel it should exist because we would need one serial for communication with the serial monitor of computer
and a second one for the actual serial communication between the two arduinos
Pls correct me if I am wrong.

So... you saw it in random code and thought it would work everywhere?

The code made sense to me. Couldnt think of any changes to make..
Ill try the answer given by Majenko

@Aki An Uno has only one hardware serial interface (Serial). What do you expect Serial1 to be?

@gre_gor read my 1st comment. I am an extreme noob at this..

The Uno has no Serial1. It only has one serial port, called Serial. To use Serial1 you will need a bigger board such as a Mega2560, or define it as a SoftwareSerial port and use two other IO pins of your choice for it, though at lower baud rates than Serial can run at.

I have arduino micro, and I can use serial (form comunication pc )and serial1 (form com. wifi module).

You import the SoftwareSerial library but you however never instance an object of the SoftwareSerial class.
You just need to add the line
 SoftwareSerial Serial1(10, 11); // RX, TX

after including the library header (taken from here)
This now creates an object Serial1 on which the operations down there should work the same as with a real hardware serial (API-wise).
Side note: Careful with the wiring. You are using this Serial1 emulated UART to communicate between the boards, so if you're using above pin numbers (D10 = RX, D11 =TX) then you must connected D10 (Board1) -> D11 (Board2), D11 (Board1) -> D10 (Board2), i.e. RX->TX, TX->RX.


text:
How to change baudrate of ESP8266 (12e) permanently?
IMPORTANT: DO NOT USE AT+IPR=9600! (see update)
I have an ESP8266 12E module that communicates at 115,200 bauds. Since I use it with an Arduino Nano with SoftwareSerial things get messy. So I found that I should reduce the baud rate of the ESP module.
I found this link on how to do it.
I am wondering

Is this a permanent change or do you need to do this every time after the module is powered?
Can I achieve the same by sending the command from the Arduino over SoftSerial? Well, I guess not since I tried and I always get an error on AT+CIOBAUD=9600 or AT+IPR=9600.
I read somewhere that in newer firmware versions of the ESP8266, the baud rate defaults to 9,600. Can anyone confirm this and if so, is it better to flash this newer firmware?

The module's vendor:
Ai-Thinker Technology Co.,Ltd.

I think the current version of the firmware is 0.3.0. If I send  AT+GMR I get:
sending AT+GMR

response: ?AT¥TJÕ¨H(Q�²•ÉÍ¥½¹é‚r¢‚r‚r‚BÕ��Â’‚ŠªŠ¢Ò¢ªÒªÂJm
 SDK versioo:0.3.0
 Ai�½½
 ‚Šj

Again some garbage because of the baud rate which is too high.
Other info on the module:
sending AT+RST
response: ?AT+RST
OK
WRT
"%M
<99CT
 ets Jan  8 2013,rst catse:2, boot lode:(3,7)
load 0x40100000ntail 4
chksum 0x89
ld tail 4
chm3 tail 8 r 0 aM
 ón't use rtc mem dat`
sl��oÌÿ
Ai-Thinker Technology Co.,Ltd.

UPDATE
(*) I used an FTDI232 module to send AT+IPR=9600 to my ESP8266-12E module and I bricked it!
DO NOT USE AT+IPR=9600 ON AN ESP8266(-12E).
I did not manage to recover it so far! I tried re-flashing it but I get Invalid head exceptions.
On a new module I sent the AT+CIOBAUD=9600 command and it worked. Permanently!
My module specs:
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK

You could try the hardware serial?
Or pull the reset pin low and then talk to the ESP directly through USB.
Might check if those work.

@Paul: the nano has only one set of hardware serial ports. So if I use those I cannot send data to the Arduino Serial Monitor anymore, making it hard to understand what is happening... Guess I'll need to go for firmware upgrade.

well you could make use of the software serialport for debugging? You'll need a "usb-serial/ttl" cable though.

http://stackoverflow.com/questions/34248581/set-baud-rate-to-esp8266-at-9600 This will answer your question.

Seems that setting the baud rate with AT+IPR=9600 also bricks an ESP01. I tried several suggestions in this thread to recover it. The solution in the link Marco Andre Silva supplied worked for me.

So you could "unbrick" your module?

This video, 1. How to flash ESP01 with latest AT command firmware, helped me re-flash the firmware to my ESP01.

Has anyone worked out why that command appears to brick the ESP?  That seems really weird

I Connected an FTDI232 module at 115200 baud and could read the specs of the ESP8266 module now:
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK

After that I sent the AT+IPR=9600 command, which first seemed to do the trick.
But after reboot of the module, all I got was garbage response, at any baudrate.
DO NOT SEND AT+IPR=9600 TO YOUR ESP8266(12e) MODULE
Maybe the AT+UART_DEF command - as mentioned by JRobert - works, but I used the  AT+CIOBAUD=9600 command and it worked. Permanently!
I hope this can help others.

Depending on how recent a version of the AT Instruction Set interpreter your chip has, the two instructions you tried may not be valid ones; they are not listed in Espressif's ESP8266 AT Instruction Set document. Searches for either "CIOBAUD" or "IPR" in the current document (version 1.5.3) return no results.
The baud rate commands are now "AT+UART_CUR" and "AT+UART_DEF" which configure the entire UART for the current session or the current and future sessions, respectively. The manual's prototype for the command is:
AT+UART_DEF=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>
Example:
AT+UART_DEF=115200, 8, 1, 0, 3

I have used these and can confirm that they work.
What I've found using software serial is that it can push 115200 baud well enough to send commands to the device (though I wouldn't build an application that depends on it) but it can only read reliably up to 9600 baud. I've been able to change my devices' baud rates from 115200 baud to 9600 over software serial; you just have to expect garbage coming back and ignore it:
// Set ESP8266 baud rate to 9600. You only need to do this once per device
set software serial baud to 115200;
send "AT+UART_DEF=9600,8,1,0,0";
set software serial baud to 9600;
// From now on, communicate with your device at 9600 baud.

I bricked my Esp with the same command, too. After hours of searching I found a way to reset the bricked esp. https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware I had to set the baudrate to 115200 instead of 9600, and between the uploading files I had to disconnect the esp from power. I hope that helps you and everybody who did the same and found your post over Google.

Power cycling the ESP between each file was the key thing to me too - other sites combine all the files into a single esptool.py command, but that did not work for me. Only after breaking it into individual commands, one per file, and cycling between each one, was I finally able to restore the AT firmware. Thanks for the hint!

Also, I tried using the esptool.py that comes with the ESP32 IDF (v2.1-beta1) and that one works successfully with a single command to flash all files on my ESP8266 (which it also supports) - so only one power cycle + GPIO0-GND required.

Using this firmware:
 https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware
and this flasher:
http://yaab-arduino.blogspot.com.br/2015/12/flashing-esp8266-firmware-arduino.html
i was able to recover my esp 8266 12f

Looks like you are you are having power supply issue. What is your power supply rating ? and try adding a small capacitor between vcc and ground.
Also its good idea to update the firmware to 0.9 which has baudrate issue fixed.
You can find new firmware at
https://github.com/espressif/esp8266_at

I don't think this is a power supply issue. I have an external power supply which is more than capable. I tried without before and then the Arduino kept restarting... I found on a forum that that was due to power supply issues. So now I'm fine there. I really think the issue is that the SoftSerial cannot cope with the 115k baudrate.

esp is really picky, add a small capacitor between vcc and ground. I also power mine from external power source and was experiencing restarts.


text:
Changing Text Arduino inkShield
I have just received inkshield purchased from Nerd Creation Labs, I stacked inkshield on my Arduino Mega and uploaded THIS CODE provided by the creator of inkshield,and it works pretty well.
I can print text ;)
Questions :
1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?
2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?
Please help
Thank you

The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the rowsPerChar value). The least significant bit is the bottom row.
So to change the font all you need to do is change those bitmaps.

Is there any software or online tool  to create such bitmaps?

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

Sure you can.

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

The top 700-odd lines of the code are the font. You just need to find a way of creating the same kind of data from your own chosen font.


text:
Write your own program to control Arduino Uno
Is it possible to write a program to control the Arduino Uno, without using
the Arduino IDE?

Do you mean without the IDE or using other IDEs?

In addition to alternate ways to write "Arduino" programs you can also directly target the ATmega328 without using the Arduino stuff at all.  Though as a practical matter, the easiest way I've been able to ask someone got get avr-gcc and avrdude installed for such a project is to ask them to install the Arduino IDE and then look in the directory where a given version puts the compiler and flashing tool.

Possible duplicate of What are the other IDEs for Arduino?

Possible duplicate of Running Arduino IDE in terminal?

Or is the question, if it's possible to make a program on a PC, to communicate with the Arduino, without the Serial Monitor inside the Arduino IDE?

I would like to integrate the Arduino into an existing control system. Therefore I need to communicate with it without having to use / run the Arduino IDE.

You can program the Arduino hardware without using the Arduino IDE. Using avr-gcc and a handful of other tools, including make and avrdude, you can compile and download to the target Aduino hardware. You can even dispense with the Arduino bootloader, and program the hardware using the common ICSP interface. To do this, you need a hardware programmer, but you can make another Arduino into one very easily. Using this method frees up the space used by the bootloader for your own code. Naturally, you use the editor of your choice. For a bit of a taste, have a look at the Adafruit page on programming a trinket (technically not an Arduino, but the methods still apply).

Most of the time I wrote code for arduino on codeblocks.
The other times on sublime text.
So the answer is yes.

I assume you mean the Arduino IDE?
Yes there are many options, for example plugins for Eclipse or Microsoft Visual Studio.
This link show others like:

CodeBender
Electron
Stino
GEdit
Komodo

Personally use normally the default Arduino IDE, but I don't like the fact you can use just a few files before it does not fit In the top bar, so than I use the Visual Studio plugin VisualMicro.


text:
Averaging input from multiple input over a fixed amount of time (estimated)
I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.
I am using:
// read 6 sensors and append to the string:
for (int analogPin = 0; analogPin < 6; analogPin++) {
  int sensor = analogRead(analogPin);
  dataString += String(sensor);
  if (analogPin < 6) {
    dataString += ",";
  }
}

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.
but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).
I am doing this to stabilize my values a bit better and remove jitter.
Any suggestions?

Can you show us your entire sketch?

take 10 readings, discard the highest and the lowest, then average the remaining 8 readings

https://github.com/MajenkoLibraries/Average

This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.
int aveAnalogRead(int pin, int ave=10, int delayms = 0)
{
    int tot = 0;
    for(int i=0; i<ave; i++)
    {
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    }
    return tot/ave;
}

in your loop():
for (int analogPin = 0; analogPin < 6; analogPin++)
{
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
}

There is almost never a good reason to add a delay.

With this though I have to run it multiple times, one for each input. Is it possible to have it also cycle though the inputs such as a loop within a loop?

yes use it inplace of your analogInput call above loop within a loop

so this:`int pin,
for (int n=0, n<10, n++){
pin = n;
int aveAnalogRead( int ave=10, int delayms = 50)
{
int tot = 0;
for(int i=0; i<ave; i++)
{
tot += analogRead(pin);
delay(delayms);
}
return tot/ave;
}}`

that's not how C++ works; you put this function somewhere outside your loop() on your sketch, then call then function. you don't need to copy the definition of the function to call it.

@EdgarBonet depends on what your sampling; one could remove it, or set it to 0, i just wanted to show how to do it with that in case its needed.