text:
DigiKeyboard - type a backslash (\)
I'm using digiKeyboard library to type to a powershell, but I need to type a backslash (a lot of them), but I can't figure it out.
I have been looking for the solution for about 3 hours and I still can't find it.
Please let me know how to make a backslash work.
The powershell command that I want to execute:
cmd /C "start /MIN powershell iwr -Uri https://tinyurl.com/WjnAU6 -OutFile c:\windows\temp\b.jpg;sp 'HKCU:Control Panel\Desktop' WallPaper 'c:\windows\temp\b.jpg';$a=1;do{RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True;sleep 1}while($a++-le59)"
It just changes the wallpaper with a downloaded image, try in on your friend.

this is what you are missing? it prints one backslash: print("\\")

You don't need a backslash. You can use forward slash for path separation in any version of Windows from Vista onwards (maybe even earlier).

@Juraj this somehow worked!

To include \ in a string so it can be printed you have to escape it.  \ is itself the escape character, so doubling it up "escapes the escape character" so it is interpreted as a normal character.
So to print "c:\windows" you would actually have to type "c:\\windows" and the \\ gets changed by the compiler into just \


text:
Sending data to UART using Atmel Studio with Attiny84
I want to send data to TFDI. It can be hello world or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

The Attiny84 does not have a hardware USART interface. Use something like the SoftwareSerial library. I got it working on an Attiny85.

yes I know.But I haven't found working example.If you have working example,can you share with me?

Doesn't the SoftwareSerial example from the Arduino IDE work? What happens, if you try it? What is going wrong with it?

I don't want to burn bootloader.I want to use atmel studio.And,I haven't still find any way.

The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.
You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.
I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.
If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found this site, which is about implementing UART with the USI. They also link to Atmel's Application Note  AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.

source: Stack Exchange

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

sort: votes


text:
Fast data logging
I want to store noise data (basically from A0) from an Arduino Uno to an SD card with faster writing speed, preferably by using 512 data together and the write it at once. What should be the code?

What did you come up yourself?

Please read [ask].

why do you need fast data logging ....... noise that is sampled at one hour interval, still results in a random data set .......... are you referring to noise as being random data? ..... or are you referring to recording a sound?

Read the values into an array big enough to store them
Write the array with the write(const uint8_t *buffer, size_t size) method.

Each write then gives you a block of binary data (512 values, 1024 bytes if they're 16-bit integers) written to the SD card. What you do with it then is up to you.
Note: an Arduino UNO only has 2kB of memory. If you have 512 integers that's half your memory gone. The SD card library needs another 512 bytes or more for its internal sector buffer. That's another 25% of your memory used. Already you're up to 75% of your memory gone.

Sounds like a small customization of the SD card lib is in order so it doesn't gobble up a quarter of your memory.

@ratchetfreak That wouldn't be a "small" optimization...  SD card sectors are 512 bytes. You can only read or write entire sectors. You need somewhere to store the current sector...

You could reuse the user's buffer. Then flip-flop 2 512 byte buffers as you transfer the data accross.

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


text:
I want to reset a variable after each 1 second on an Arduino
I want to reset this counter variable which I created after each 1 second, but I don't want to disturb the if statement.
Here is the code:
int button=A0;
int val;
int count=0;
int presss;

void setup() {
  pinMode(button,INPUT);
  Serial.begin(9600);
}

void loop() {
  val=analogRead(button);
  if(val>1000){
   presss=count++;
   delay(200);
 }
  Serial.println(presss);
  delay(1000);
 }

I would do it the following way:

Use a variable declared as: unsigned long time_passed;
In the setup() section I would add the line time_passed = millis();
In the loop() section I would add the if condition:

if(millis()-time_passed > 1000) {
   time_passed = millis();
   presss = 0;
   }
I think this is still not working properly with your example, I recommend to make two changes in your code:

you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop
I cannot understand how presss = count++; should work. For proper counting I would suggest to do it this way: presss = presss + 1;
Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms

You could do something like this:
void loop() {
  for (int i = 0; i < 5; i++) {
    val = analogRead(button);
    if (val > 1000) count++;
    delay(200);
  }
  Serial.println(count);
  count = 0;
 }

This will sample the button five times and count the number of times the value is larger than 1000, with a 200 ms delay between each read. This give approx. 1 s.
But this might not be the logic you are looking for.
Cheers!

If I understood the project, you want to count how many button clicks you did in one second, so I've adjusted your code a little bit. If you don't want your program to do something after a certain amount of time, but don't want it to wait don't use delay(ms) use millis() instead (see https://www.arduino.cc/reference/en/language/functions/time/millis/ )
int button=A0;
int val;
int presss=0;

int millisBegin = 0;
int millisNow;
int millisBorder = 1000;

void setup()
{
  pinMode(button,INPUT);
  Serial.begin(9600);
}

void loop()
{
  val=digitalRead(button);

  if(val==HIGH)
  {
    presss++;     //If the button is pressed it will count + 1

    while(val==HIGH)
    {
      val=digitalRead(button); //It will wait till you release the button here
    }
  }

  Serial.println(presss);

  millisNow = millis();

  if(millisNow-millisBegin >= millisBorder)
  {
    presss = 0;
    millisBegin = millisNow;
    Serial.println("~1 second passed");
  }
}

I checked it and it worked for me (I changed the if(val>1000) to if(val==HIGH), otherwise it might not always detect a button press


text:
Seeburg Consolette Jukebox
I am working on a Seeburg Jukebox wall unit, I have it playing one track at a time form a SD card no problem. But what I need help with being new to programming is:
1. The code is long because it can play 160 songs.
2. would be nice to have it line up the next selection if possible.
Any help with this code would be appreciated.
#include <SD.h>
#include <SPI.h>
#include <Adafruit_VS1053.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin
Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

int opto = 18;

void setup() {
  Serial.begin(9600);
  if (! musicPlayer.begin()) {}
  if (!SD.begin(CARDCS)) {}

  musicPlayer.setVolume(1,1);

  pinMode(opto, INPUT); //initialize the digital pin as an input from the opto-isolator.
  digitalWrite(opto, HIGH);} //turns on the internal pull up resistor.

void loop() {

  int number = 0;  // counts the alphabet pulses
  int letter = 0;  // counts the digit pulses.
  int buffer[4] = {1,1,1,1}; // buffer for reading input. If 4 reads in a row are all the same it is valid input.
  int buffndx = 0;
  int pausecnt = 0; // counts the number of HIGHs read in.
  int maxpause = 30; // when pausecnt reaches maxpause we are at the pause between alpa and numeric or else we are at the end of transmission.
  int countpause = false;
  buffer[0] = 1;
  buffer[1] = 1;
  buffer[2] = 1;
  buffer[3] = 1;

Serial.println("SEEBURG CONSOLETTE JUKEBOX");

  //Number loop//
  while( pausecnt < maxpause ) {
     buffer[buffndx] = digitalRead(opto); // read the input pin
     if(buffer[buffndx] != 1){}
    delay(8); // space out the reads a little.
     buffndx++;
     if (buffndx == 4) buffndx = 0; // rotate the buffer index.
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
    if (countpause == true) pausecnt++;}} // else no valid input

  // Letter Loop//
    pausecnt = 0;   // Reset the pausent counter. Ready for the next stream of pulses to arrive.
    countpause = false; // loop forever until a pulse is recieved.
    while( pausecnt < maxpause ) { // Begin the digit loop
    buffer[buffndx] = digitalRead(opto); // read the input pin
    delay(8);
    buffndx++;
    if (buffndx == 4) buffndx = 0; // rotate the buffer index.
    if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        letter++; //increment the aphabet counter.
        while(! ((buffer[0] == 1) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
     if (countpause == true) pausecnt++;} // else no valid input// else no valid input

  }

 //change signal//
    {number = 10 - number;
    letter = 21 - letter;}

  String signal = "";

  if(letter == 1) signal += "A";
  if(letter == 2) signal += "B";
  if(letter == 3) signal += "C";
  if(letter == 4) signal += "D";
  if(letter == 5) signal += "E";
  if(letter == 6) signal += "F";
  if(letter == 7) signal += "G";
  if(letter == 8) signal += "H";
  if(letter == 9) signal += "J";
  if(letter == 10) signal += "K";
  if(letter == 11) signal += ("L");
  if(letter == 12) signal += ("M");
  if(letter == 13) signal += ("N");
  if(letter == 14) signal += ("P");
  if(letter == 15) signal += ("Q");
  if(letter == 16) signal += ("R");
  if(letter == 17) signal += ("S");
  if(letter == 18) signal += ("T");
  if(letter == 19) signal += ("U");
  if(letter == 20) signal += ("V");

  signal += String(number);
  Serial.println(signal);
  delay(1000);

        //////////A////////////
   if(letter == 1 && number == 1);
   {musicPlayer.playFullFile("A1.mp3");}

   if(letter == 1 && number == 2);
   {musicPlayer.playFullFile("A2.mp3");}

   if(letter == 1 && number == 3);
   {musicPlayer.playFullFile("A3.mp3");}

   if(letter == 1 && number == 4);
  {musicPlayer.playFullFile("A4.mp3");}

   if(letter == 1 && number == 5);
  {musicPlayer.playFullFile("A5.mp3");}

   if(letter == 1 && number == 6);
  {musicPlayer.playFullFile("A6.mp3");}

   if(letter == 1 && number == 7);
  {musicPlayer.playFullFile("A7.mp3");}

   if(letter == 1 && number == 8);
   {musicPlayer.playFullFile("A8.mp3");}

           //////////B////////////
   if(letter == 2 && number == 1);
   {musicPlayer.playFullFile("B1.mp3");}

   if(letter == 2 && number == 2);
   {musicPlayer.playFullFile("B2.mp3");}

   if(letter == 2 && number == 3);
   {musicPlayer.playFullFile("B3.mp3");}

   if(letter == 2 && number == 4);
   {musicPlayer.playFullFile("B4.mp3");}

   if(letter == 2 && number == 5);
   {musicPlayer.playFullFile("B5.mp3");}

   if(letter == 2 && number == 6);
  {musicPlayer.playFullFile("B6.mp3");}

   if(letter == 2 && number == 7);
   {musicPlayer.playFullFile("B7.mp3");}

   if(letter == 2 && number == 8);
   {musicPlayer.playFullFile("B8.mp3");}

    //////////C////////////
   if(letter == 3 && number == 1);
   {musicPlayer.playFullFile("C1.mp3");}

   if(letter == 3 && number == 2);
   {musicPlayer.playFullFile("C2.mp3");}

   if(letter == 3 && number == 3);
   {musicPlayer.playFullFile("C3.mp3");}

   if(letter == 3 && number == 4);
   {musicPlayer.playFullFile("C4.mp3");}

   if(letter == 3 && number == 5);
   {musicPlayer.playFullFile("C5.mp3");}

   if(letter == 3 && number == 6);
    {musicPlayer.playFullFile("C6.mp3");}

   if(letter == 3 && number == 7);
    {musicPlayer.playFullFile("C7.mp3");}

   if(letter == 3 && number == 8);
    {musicPlayer.playFullFile("C8.mp3");}

       //////////D////////////
   if(letter == 4 && number == 1);
   {musicPlayer.playFullFile("D1.mp3");}

   if(letter == 4 && number == 2);
   {musicPlayer.playFullFile("D2.mp3");}

   if(letter == 4 && number == 3);
   {musicPlayer.playFullFile("D3.mp3");}

   if(letter == 4 && number == 4);
   {musicPlayer.playFullFile("D4.mp3");}

   if(letter == 4 && number == 5);
   {musicPlayer.playFullFile("D5.mp3");}

   if(letter == 4 && number == 6);
   {musicPlayer.playFullFile("D6.mp3");}

   if(letter == 4 && number == 7);
   {musicPlayer.playFullFile("D7.mp3");}

   if(letter == 4 && number == 8);
   {musicPlayer.playFullFile("D8.mp3");}

       //////////E////////////
   if(letter == 5 && number == 1);
   {musicPlayer.playFullFile("E1.mp3");}

   if(letter == 5 && number == 2);
   {musicPlayer.playFullFile("E2.mp3");}

   if(letter == 5 && number == 3);
   {musicPlayer.playFullFile("E3.mp3");}

   if(letter == 5 && number == 4);
   {musicPlayer.playFullFile("E4.mp3");}

   if(letter == 5 && number == 5);
   {musicPlayer.playFullFile("E5.mp3");}

   if(letter == 5 && number == 6);
   {musicPlayer.playFullFile("E6.mp3");}

   if(letter == 5 && number == 7);
   {musicPlayer.playFullFile("E7.mp3");}

   if(letter == 5 && number == 8);
   {musicPlayer.playFullFile("E8.mp3");}

          //////////F////////////
   if(letter == 6 && number == 1);
   {musicPlayer.playFullFile("F1.mp3");}

   if(letter == 6 && number == 2);
   {musicPlayer.playFullFile("F2.mp3");}

   if(letter == 6 && number == 3);
   {musicPlayer.playFullFile("F3.mp3");}

   if(letter == 6 && number == 4);
   {musicPlayer.playFullFile("F4.mp3");}

   if(letter == 6 && number == 5);
   {musicPlayer.playFullFile("F5.mp3");}

   if(letter == 6 && number == 6);
   {musicPlayer.playFullFile("F6.mp3");}

   if(letter == 6 && number == 7);
   {musicPlayer.playFullFile("F7.mp3");}

   if(letter == 6 && number == 8);
   {musicPlayer.playFullFile("F8.mp3");}

          //////////G////////////
   if(letter == 7 && number == 1);
  {musicPlayer.playFullFile("G1.mp3");}

  if(letter == 7 && number == 2);
  {musicPlayer.playFullFile("G2.mp3");}

  if(letter == 7 && number == 3);
  {musicPlayer.playFullFile("G3.mp3");}

  if(letter == 7 && number == 4);
  {musicPlayer.playFullFile("G4.mp3");}

  if(letter == 7 && number == 5);
  {musicPlayer.playFullFile("G5.mp3");}

  if(letter == 7 && number == 6);
  {musicPlayer.playFullFile("G6.mp3");}

  if(letter == 7 && number == 7);
  {musicPlayer.playFullFile("G7.mp3");}

  if(letter == 7 && number == 8);
  {musicPlayer.playFullFile("G8.mp3");}

            //////////H//////////;//
   if(letter == 8 && number == 1);
  {musicPlayer.playFullFile("H1.mp3");}

  if(letter == 8 && number == 2);
  {musicPlayer.playFullFile("H2.mp3");}

  if(letter == 8 && number == 3);
  {musicPlayer.playFullFile("H3.mp3");}

  if(letter == 8 && number == 4);
  {musicPlayer.playFullFile("H4.mp3");}

  if(letter == 8 && number == 5);
  {musicPlayer.playFullFile("H5.mp3");}

  if(letter == 8 && number == 6);
  {musicPlayer.playFullFile("H6.mp3");}

  if(letter == 8 && number == 7);
  {musicPlayer.playFullFile("H7.mp3");}

  if(letter == 8 && number == 8);
  {musicPlayer.playFullFile("H8.mp3");}

            //////////J//////////;//
   if(letter == 9 && number == 1);
  {musicPlayer.playFullFile("J1.mp3");}

  if(letter == 9 && number == 2);
  {musicPlayer.playFullFile("J2.mp3");}

  if(letter == 9 && number == 3);
  {musicPlayer.playFullFile("J3.mp3");}

  if(letter == 9 && number == 4);
  {musicPlayer.playFullFile("J4.mp3");}

  if(letter == 9 && number == 5);
  {musicPlayer.playFullFile("J5.mp3");}

  if(letter == 9 && number == 6);
  {musicPlayer.playFullFile("J6.mp3");}

  if(letter == 9 && number == 7);
  {musicPlayer.playFullFile("J7.mp3");}

  if(letter == 9 && number == 8);
  {musicPlayer.playFullFile("J8.mp3");}

            //////////K////////////
   if(letter == 10 && number == 1);
  {musicPlayer.playFullFile("K1.mp3");}

  if(letter == 10 && number == 2);
  {musicPlayer.playFullFile("K2.mp3");}

  if(letter == 10 && number == 3);
  {musicPlayer.playFullFile("K3.mp3");}

  if(letter == 10 && number == 4);
  {musicPlayer.playFullFile("K4.mp3");}

  if(letter == 10 && number == 5);
  {musicPlayer.playFullFile("K5.mp3");}

  if(letter == 10 && number == 6);
  {musicPlayer.playFullFile("K6.mp3");}

  if(letter == 10 && number == 7);
  {musicPlayer.playFullFile("K7.mp3");}

  if(letter == 10 && number == 8);
  {musicPlayer.playFullFile("K8.mp3");}

              //////////L////////////
   if(letter == 11 && number == 1);
  {musicPlayer.playFullFile("L1.mp3");}

  if(letter == 11 && number == 2);
  {musicPlayer.playFullFile("L2.mp3");}

  if(letter == 11 && number == 3);
  {musicPlayer.playFullFile("L3.mp3");}

  if(letter == 11 && number == 4);
  {musicPlayer.playFullFile("L4.mp3");}

  if(letter == 11 && number == 5);
  {musicPlayer.playFullFile("L5.mp3");}

  if(letter == 11 && number == 6);
  {musicPlayer.playFullFile("L6.mp3");}

  if(letter == 11 && number == 7);
  {musicPlayer.playFullFile("L7.mp3");}

  if(letter == 11 && number == 8);
  {musicPlayer.playFullFile("L8.mp3");}

              //////////M////////////
   if(letter == 12 && number == 1);
  {musicPlayer.playFullFile("M1.mp3");}

  if(letter == 12 && number == 2);
  {musicPlayer.playFullFile("M2.mp3");}

  if(letter == 12 && number == 3);
  {musicPlayer.playFullFile("M3.mp3");}

  if(letter == 12 && number == 4);
  {musicPlayer.playFullFile("M4.mp3");}

  if(letter == 12 && number == 5);
  {musicPlayer.playFullFile("M5.mp3");}

  if(letter == 12 && number == 6);
  {musicPlayer.playFullFile("M6.mp3");}

  if(letter == 12 && number == 7);
  {musicPlayer.playFullFile("M7.mp3");}

  if(letter == 12 && number == 8);
  {musicPlayer.playFullFile("M8.mp3");}

              //////////N////////////
   if(letter == 13 && number == 1);
  {musicPlayer.playFullFile("N1.mp3");}

  if(letter == 13 && number == 2);
  {musicPlayer.playFullFile("N2.mp3");}

  if(letter == 13 && number == 3);
  {musicPlayer.playFullFile("N3.mp3");}

  if(letter == 13 && number == 4);
  {musicPlayer.playFullFile("N4.mp3");}

  if(letter == 13 && number == 5);
  {musicPlayer.playFullFile("N5.mp3");}

  if(letter == 13 && number == 6);
  {musicPlayer.playFullFile("N6.mp3");}

  if(letter == 13 && number == 7);
  {musicPlayer.playFullFile("N7.mp3");}

  if(letter == 13 && number == 8);
  {musicPlayer.playFullFile("N8.mp3");}

              //////////P////////////
   if(letter == 14 && number == 1);
  {musicPlayer.playFullFile("P1.mp3");}

  if(letter == 14 && number == 2);
  {musicPlayer.playFullFile("P2.mp3");}

  if(letter == 14 && number == 3);
  {musicPlayer.playFullFile("P3.mp3");}

  if(letter == 14 && number == 4);
  {musicPlayer.playFullFile("P4.mp3");}

  if(letter == 14 && number == 5);
  {musicPlayer.playFullFile("P5.mp3");}

  if(letter == 14 && number == 6);
  {musicPlayer.playFullFile("P6.mp3");}

  if(letter == 14 && number == 7);
  {musicPlayer.playFullFile("P7.mp3");}

  if(letter == 14 && number == 8);
  {musicPlayer.playFullFile("P8.mp3");}

              //////////Q////////////
   if(letter == 15 && number == 1);
  {musicPlayer.playFullFile("Q1.mp3");}

  if(letter == 15 && number == 2);
  {musicPlayer.playFullFile("Q2.mp3");}

  if(letter == 15 && number == 3);
  {musicPlayer.playFullFile("Q3.mp3");}

  if(letter == 15 && number == 4);
  {musicPlayer.playFullFile("Q4.mp3");}

  if(letter == 15 && number == 5);
  {musicPlayer.playFullFile("Q5.mp3");}

  if(letter == 15 && number == 6);
  {musicPlayer.playFullFile("Q6.mp3");}

  if(letter == 15 && number == 7);
  {musicPlayer.playFullFile("Q7.mp3");}

  if(letter == 15 && number == 8);
  {musicPlayer.playFullFile("Q8.mp3");}

              //////////R////////////
   if(letter == 16 && number == 1);
  {musicPlayer.playFullFile("R1.mp3");}

  if(letter == 16 && number == 2);
  {musicPlayer.playFullFile("R2.mp3");}

  if(letter == 16 && number == 3);
  {musicPlayer.playFullFile("R3.mp3");}

  if(letter == 16 && number == 4);
  {musicPlayer.playFullFile("R4.mp3");}

  if(letter == 16 && number == 5);
  {musicPlayer.playFullFile("R5.mp3");}

  if(letter == 16 && number == 6);
  {musicPlayer.playFullFile("R6.mp3");}

  if(letter == 16 && number == 7);
  {musicPlayer.playFullFile("R7.mp3");}

  if(letter == 16 && number == 8);
  {musicPlayer.playFullFile("R8.mp3");}

              //////////S////////////
   if(letter == 17 && number == 1);
  {musicPlayer.playFullFile("S1.mp3");}

  if(letter == 17 && number == 2);
  {musicPlayer.playFullFile("S2.mp3");}

  if(letter == 17 && number == 3);
  {musicPlayer.playFullFile("S3.mp3");}

  if(letter == 17 && number == 4);
  {musicPlayer.playFullFile("S4.mp3");}

  if(letter == 17 && number == 5);
  {musicPlayer.playFullFile("S5.mp3");}

  if(letter == 17 && number == 6);
  {musicPlayer.playFullFile("S6.mp3");}

  if(letter == 17 && number == 7);
  {musicPlayer.playFullFile("S7.mp3");}

  if(letter == 17 && number == 8);
  {musicPlayer.playFullFile("S8.mp3");}

              //////////T////////////
   if(letter == 18 && number == 1);
  {musicPlayer.playFullFile("T1.mp3");}

  if(letter == 18 && number == 2);
  {musicPlayer.playFullFile("T2.mp3");}

  if(letter == 18 && number == 3);
  {musicPlayer.playFullFile("T3.mp3");}

  if(letter == 18 && number == 4);
  {musicPlayer.playFullFile("T4.mp3");}

  if(letter == 18 && number == 5);
  {musicPlayer.playFullFile("T5.mp3");}

  if(letter == 18 && number == 6);
  {musicPlayer.playFullFile("T6.mp3");}

  if(letter == 18 && number == 7);
  {musicPlayer.playFullFile("T7.mp3");}

  if(letter == 18 && number == 8);
  {musicPlayer.playFullFile("T8.mp3");}

              //////////U////////////
   if(letter == 19 && number == 1);
  {musicPlayer.playFullFile("U1.mp3");}

  if(letter == 19 && number == 2);
  {musicPlayer.playFullFile("U2.mp3");}

  if(letter == 19 && number == 3);
  {musicPlayer.playFullFile("U3.mp3");}

  if(letter == 19 && number == 4);
  {musicPlayer.playFullFile("U4.mp3");}

  if(letter == 19 && number == 5);
  {musicPlayer.playFullFile("U5.mp3");}

  if(letter == 19 && number == 6);
  {musicPlayer.playFullFile("U6.mp3");}

  if(letter == 19 && number == 7);
  {musicPlayer.playFullFile("U7.mp3");}

  if(letter == 19 && number == 8);
  {musicPlayer.playFullFile("U8.mp3");}

            //////////V////////////
   if(letter == 20 && number == 1);
  {musicPlayer.playFullFile("V1.mp3");}

  if(letter == 20 && number == 2);
  {musicPlayer.playFullFile("V2.mp3");}

  if(letter == 20 && number == 3);
  {musicPlayer.playFullFile("V3.mp3");}

  if(letter == 20 && number == 4);
  {musicPlayer.playFullFile("V4.mp3");}

  if(letter == 20 && number == 5);
  {musicPlayer.playFullFile("V5.mp3");}

  if(letter == 20 && number == 6);
  {musicPlayer.playFullFile("V6.mp3");}

  if(letter == 20 && number == 7);
  {musicPlayer.playFullFile("V7.mp3");}

  if(letter == 20 && number == 8);
  {musicPlayer.playFullFile("V8.mp3");}
}

I'm trying to start a similar project - I'm wondering if you could point me to where you got your hardware interface information? Thanks in advance!

This answer only involves help for the first problem:

The code is long because it can play 160 songs

Also, you can align your code by selecting it and press Ctrl-K.
I will go part by part to improve it (leaving the manual work to you):
Align code
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)

Align this code, making all the values under each other nicely and comments starting at the same column.
Use for loop
  buffer[0] = 1;
  buffer[1] = 1;
  buffer[2] = 1;
  buffer[3] = 1;

You can use a for loop, like:
for (int n = 0; n < 4; n++)
{
    buffer[n] = 1;
}

However, you can remove this code, since the values are already initialized in:
int buffer[4] = {1,1,1,1}; // buffer for reading input. If 4 reads in a row are all the same it is valid input.

Prevent almost identical duplicate code
In the number/letter loop part:
//Number loop//
  while( pausecnt < maxpause ) {
     buffer[buffndx] = digitalRead(opto); // read the input pin
     if(buffer[buffndx] != 1){}
    delay(8); // space out the reads a little.
     buffndx++;
     if (buffndx == 4) buffndx = 0; // rotate the buffer index.
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
    if (countpause == true) pausecnt++;}} // else no valid input

  // Letter Loop//
    pausecnt = 0;   // Reset the pausent counter. Ready for the next stream of pulses to arrive.
    countpause = false; // loop forever until a pulse is recieved.
    while( pausecnt < maxpause ) { // Begin the digit loop
    buffer[buffndx] = digitalRead(opto); // read the input pin
    delay(8);
    buffndx++;
    if (buffndx == 4) buffndx = 0; // rotate the buffer index.
    if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        letter++; //increment the aphabet counter.
        while(! ((buffer[0] == 1) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.
        countpause = true; //we are receiving input so start counting pauses instead of looping forever.
        continue;}else{
     if (countpause == true) pausecnt++;} // else no valid input// else no valid input

  }

First add brackets and align them (I do it for the Number part):
 while( pausecnt < maxpause )
 {
   buffer[buffndx] = digitalRead(opto); // read the input pin

   if(buffer[buffndx] != 1)
   {
   }

   delay(8); // space out the reads a little.
   buffndx++;

   if (buffndx == 4)
   {
     buffndx = 0; // rotate the buffer index.
   }

   if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) )
   {
     // we got valid input so proccess it.
     pausecnt = 0; // we got our pulse so restart the clock for the next one.
     number++; //increment the number counter.
     while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) )
     {
        //Loop until we get a valid HIGH
        buffer[buffndx] = digitalRead(opto); // read the input pin
        buffndx++; // rotate the buffer index

        if (buffndx == 4)
        {
          buffndx = 0;
        }
      } // rotate the buffer index.

      countpause = true; //we are receiving input so start counting pauses instead of looping forever.
      continue;
    }
    else
    {
      if (countpause == true)
      {
        pausecnt++;
      }
    } // else no valid input

Note it is longer, but much clearer (clear code is more important than short code).
Now because the code starting from:
buffer[buffndx] = digitalRead(opto); // read the input pin
...

Until the end of the number loop code is almost equal to the letter loop code, try to find the differences between the two parts: only the number and letter variable. So you make a new function (e.g. processKey), you pass the number or the letter (so for the number call processKey(number) and for the letter call processKey(letter). Note that both are integers. The new function will be:
int processKey(int key) // Item is a number or letter
{
    ...
    return key;
}

You return a key (which is the possibly increased value (because of number++ in the original code. A slightly advanced way is to pass it as pointer:
void processKey(int* key) // Item is a number or letter

and change the key with (*key)++; and call the functions with processKey(&number) and processKey(&letter).
Use define
Note that instead of 4, it's better to use a #define.
     if(buffer[buffndx] != 1){}

Remove dead code
This line does not anything; to make this clear, always align brackets:
     if(buffer[buffndx] != 1)
     {
     }

Always use brackets { }
if (buffndx == 4) buffndx = 0; // rotate the buffer index.

Use:
if (buffndx == 4)
{
    buffndx = 0; // rotate the buffer index.
}

Avoid code duplication
     if ((buffer[0] == 0) && (buffer[1] == 0) && (buffer[2] == 0) && (buffer[3] == 0) ){ // we got valid input so proccess it.
        pausecnt = 0; // we got our pulse so restart the clock for the next one.
        number++; //increment the number counter.
        while(! ((buffer[0] == 1 ) && (buffer[1] == 1) && (buffer[2] == 1) && (buffer[3] == 1)) ) { //Loop until we get a valid HIGH

In this part you check twice to see if values are 0 or 1, make a function for this (e.g. areAllValues(buffer, 0) for the first call and areAllValues(buffer, 1) for the next.
If 0 and 1 are the only values use a boolean (True/False).
    if (buffndx == 4) buffndx = 0;} // rotate the buffer index.

Use here the same #define that I proposed above.
Do not check against true/false
    if (countpause == true) pausecnt++;}} // else no valid input

It is not needed to check against true:
    if (countpause) ...

Use correct casing
Also it's better to use always correct casing, so countPause instead of countpause.
Avoid repetition of if statements (1)
  if(letter == 1) signal += "A";
  if(letter == 2) signal += "B";
  if(letter == 3) signal += "C";
  if(letter == 4) signal += "D";
  if(letter == 5) signal += "E";
  if(letter == 6) signal += "F";
  if(letter == 7) signal += "G";
  if(letter == 8) signal += "H";
  if(letter == 9) signal += "J";
  if(letter == 10) signal += "K";
  if(letter == 11) signal += ("L");
  if(letter == 12) signal += ("M");
  if(letter == 13) signal += ("N");
  if(letter == 14) signal += ("P");
  if(letter == 15) signal += ("Q");
  if(letter == 16) signal += ("R");
  if(letter == 17) signal += ("S");
  if(letter == 18) signal += ("T");
  if(letter == 19) signal += ("U");
  if(letter == 20) signal += ("V");

Instead of this, use the ASCII character value.
 if ((letter >= 1) && (letter <= 20))
 {
     signal += (char) ((int)('A') + letter - 1);
 {

Avoid repetition of if statements (2)
For your largest part:
 if(letter == 1 && number == 1);
   {musicPlayer.playFullFile("A1.mp3");}

   if(letter == 1 && number == 2);
   {musicPlayer.playFullFile("A2.mp3");}

 ...

Use two if statements, filling in the first and second character of the file name.
char[] fileName = "XX.mp3";

if ((letter >= 1) && (letter <= 20))
{
    if ((number >= 1) && (number <= 8))
    {
       fileName[0] = (char) ((int)('A') + letter - 1);
       fileName[1] = (char) ((int)('0') + number - 1);
       musicPlayer.playFullFile(fileName);
    }
}

Start with 0
Btw, for software engineers, it is more common to start arrays/counters etc. with 0 instead of 1; that saves some - 1 conversions.

My interpretation of would be nice to have it line up the next selection if possible was to have the next song start playing once the current one is finished :-)

I only addressed the first problem; I will add this in the answer.


text:
I have a problem with my nano arduino and the nrf24l01 as receiver
Hello I have a problem with my nano arduino and the nrf24l01 as receiver . I'm trying to upload my code to my board, but it say that my code have this mistake:
Receiver:45:10: error: void value not ignored as it ought to be
exit status 1
void value not ignored as it ought to be
the complet code is:
#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>

//Receiver Code (Hand)

#include <Servo.h>    //the library which helps us to control the servo motor
#include <SPI.h>      //the communication interface with the modem
#include "RF24.h"     //the library which helps us to control the radio modem

//define the servo name
Servo myServo1;
Servo myServo3;
Servo myServo4;
Servo myServo2;
Servo myServo5;

RF24 radio(9,10);     /*This object represents a modem connected to the Arduino.
                      Arguments 9 and 10 are a digital pin numbers to which signals
                      CE and CSN are connected.*/

const uint64_t pipe = 0xE8E8F0F0E1LL; //the address of the modem,that will receive data from the Arduino.

int msg[5];

void setup(){

  //define the servo input pins
  myServo1.attach(15); //A1
  myServo2.attach(16); //A2
  myServo3.attach(17); //A3
  myServo4.attach(18); //A4
  myServo5.attach(19); //A5

  radio.begin();                    //it activates the modem.
  radio.openReadingPipe(1, pipe);   //determines the address of our modem which receive data.
  radio.startListening();           //enable receiving data via modem
  }

void loop(){
  if(radio.available()){
    bool done = false;
    while (!done){
    done = radio.read(msg, sizeof(msg));

    myServo1.write(msg[2]); //A1
    myServo2.write(msg[4]); //A2
    myServo3.write(msg[3]); //A3
    myServo4.write(msg[1]); //A4
    myServo5.write(msg[0]); //A5
    }
  }
}

and the problen is here:
done = radio.read(msg, sizeof(msg));
I don't know hoy to make that comes out as a code. I'm sorry.
I'm trying to program a bionic hand but i have just started to work with arduino boards and their respective prongram. If someone can help me I would be very grateful. thanks

radio.read() does not return a value.  You can't assign "no value" to a boolean.
If radio.available() is true then radio.read() will succeed. There is no need to test if it worked or not.


text:
LCD displaying weird text
I am doing a project that requires input from a keypad to be displayed on the LCD display.
lcd.print() displays in proper form, but when the I press characters on the keypad, they are overwritten as weird symbols.
Any help would be appreciated.
Here's the code:
void setup()
{
  Serial.begin(9600);
  Serial.println("LCD test with PWM contrast adjustment");
  pinMode(13,OUTPUT);
  analogWrite(6,Contrast);

  lcd.begin(16,2);

  pinMode(buzzer, OUTPUT);
  lcd.print(" Electronic ");
  Serial.print(" Electronic ");
  lcd.setCursor(0,1);
  lcd.print(" Keypad Lock ");
  Serial.print(" Keypad Lock ");
  delay(2000);
  lcd.clear();
  lcd.print("Enter Ur Passkey:");
  Serial.println("Enter Ur Passkey:");
  lcd.setCursor(1,0);
  for(int j=0;j<4;j++)
    EEPROM.write(j, j+49);
  for(int j=0;j<4;j++)
    pass[j]=EEPROM.read(j);
}

So, where in your code are you working with a keypad? I don't see a single line that would have anything to do with a keypad.

stick to one type of variable, to prevent mix-up
So if you stick to a byte (uint8_t) type for keypad:
uint8_t keys[4][3] = {
  {1,2,3},
  {4,5,6},
  {7,8,9},
  {0xF,0xA,0xB}                 // F-*  B-#
}

then you can save it to your EEPROM as a byte and read it as a byte.it will prevent mix-up.
your code which you are not displaying (everybody here can write one of those faster then to download it from here)already translate numbers to numbers and then you are growing them to symbols with higher value

I think you should use 48 instead of 49.
48 is the ASCII symbol of 0. If you add a number from 0-9 to it, than you get the ASCII symbols of '0' to '9'.
(and a small sidenote: Enter Ur Passkey: is more than 16 characters; also it is more 'professional not to make slang texts to try to fit it, why not using Enter Passkey: instead?


text:
How can I assign the value of a char array to a uint8_t array?
I have a char array variable that has a value.
I need to send this value through LoRa. The library I use for the LoRa implementation accepts an array of uint8_t. How can I pass the value of a char[] to a uint8_t[] variable (and the opposite)?
if (Udp.parsePacket()) {
  int udp_received = Udp.available();
  char udp_buffer[udp_received + 1];
  Udp.read(udp_buffer, udp_received);
  udp_buffer[udp_received] = '\0';

  uint8_t udp_to_lora[] = "???";
  rf95.send(udp_to_lora, sizeof(udp_to_lora));
  rf95.waitPacketSent();

}

I need to pass the udp_buffer to uint8_t udp_to_lora[].

I don't have a compiler at hand, but you can cast the array  as a char and uint8_t are similar in size:
rf95.send((char*) udp_to_lora, sizeof(udp_to_lora));

How could it be so easy? Thanks! But help me understand. What's the purpose of the dereference asterisk in this cast?

Same the other way round: rf95.send((uint8_t*)udp_buffer, udp_received);

a char is a character, a char * is a POINTER to a character. However, an array of characters is the same, as it points to the first character of a text.

"What's the purpose of the dereference asterisk in this cast?" It's in the context. In a type specification (which a cast is) the '*' is part of the type, where it means "pointer to". In a value, it is the dereference operator and means "the value of what [thing] points to", or more literally, "the value contained in the memory location(s) whose address is the value of [thing]". Locations is plural because Arduino memory, being byte addressable, most variables are multi-byte.

dereference is *a


text:
Is it necessary to reduce the size of libraries?
For example RTClib library have codes for DS1307, DS3231, PCF8523 and softRTC. but I'm only using DS3231 and don't need the extra codes there to occupy my Arduino flash memory.
Does Arduino IDE only "upload" those parts of libraries that is being used in the sketch or just uploads the whole library?

Normally a library supports various kinds of components; because mostly those components share a lot functionality, so it prevents to make very many different libraries.
Note that all functions that you do not call within your program (and are not called from within the library), will NOT end up in your sketch, thus also will not affect your flash memory usage.
If the library is full of if statements to make a difference between models, that code is in (if a function is called, the entire function is stored in flash). (Unless the if statement can be evaluated compile time, see remark of Edgar Bonet below about link time optimization).
So if you want to remove that 'unnecessary' code (for you at least), than copy the library into your project and remove the unnecessary code yourself.
However, I would not do that until you run out of flash memory.
You can do an easy test:

Include a library, and compile your sketch. You will see (possibly) some difference.
Now call a function from the library. Compile the sketch again, you will see the flash memory usage has increased. This means, before that, that function was not part of your compiled sketch.

A thing I would worry more about, is SRAM memory usage, but mostly buffers are created depending on the model, and SRAM is not wasted (since the Arduino Uno has only 2 KB for example).

Re “if the library is full of if statements to make a difference between models, that code is in”: Since version 1.6.10, the Arduino IDE enables link time optimization, and this is no longer always true. If the conditions in the ifs are compile-time constants, the optimizer notices that some parts of the code is unreachable, and discards them.

@EdgarBonet Thanks for that remark; I updated my question (credits for you). I didn't knew about this feature.

The Arduino IDE uses the gcc compiler.
Gcc is an optimizing compiler, and is quite good at it.  So basically it's going to do a good job of identifying and including only the functions you actually use in your code.
Unless you are quite experienced you will probably not do a better job than the compiler itself.


text:
Rounding float number
I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.
(X) x 255 / 60000 = minute

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.
if (plusButton == HIGH) {
    PWMduration += (X);
}

The nearest number i found is 235.29 which equals to almost 1 minute:
235.29 x 255 / 60000 = 0.9999

How can i round that number to 1? or is there any other alternative solution to calculate this?

Use 235.294117647?

@Majenko equals 0.99999999999975

In float terms that's 1. I don't think you can actually represent 1 in a float.

so what's the solution? can i convert it to int?

What's the problem with such a tiny difference from 1?

i'm gonna lcd.print() it!

I think you're tackling the whole thing backwards. Also, what use is PWM that has a period of minutes?

turns the light on slowly during a period of time.

So you want to fade the PWM? That's different to defining a PWM period. It has little to no relationship to the PWM. All you want is a delay.

take a look at this question

What you want to do is calculate the delay based on the number of minutes. Not change the delay depending on the number of button presses. Keep the minutes as an integer. Then use that integer to calculate how long each delay interval should be.

You can cast it to an integer after adding an offset.
Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:
int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:
float f = 12.0 / 3.0;

or
float f = 12f / 3f;

Than calculate the rounded value:
int roundedValue = (int)(f + 0.5);


text:
Can I do something like this to simplify the code for arduino?
Can I simplify the code in arduino where it doesn't promote any error.
Example:
Int led =13;
Blink = digitalWrite(led, HiGH);
             delay(1000);
             digitalWrite(led, LOW);
             delay(1000);

void setup(){
pinMode(led, OUTPUT);
}

void loop(){
Blink
}

Please paste the code directly instead of posting an image. Noone will waste their time to type your code.

The previous version was better, just select the code after pasting, and press ctrl-k to indent it so you get the proper 'code style layout'.

Note that, as long as loop() does nothing but blink(), there is no simplification in defining blink() as a separate function.

There are indeed some errors.
First, you cannot assign a function body to a variable.
So you have to rewrite the Blink function:
void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

Also for calling a function, even without parameters, you should use ( and ):
void loop()
{
    blink();
}

Also you need to use the correct capitals or not:
int led = 13;

You can make it constant since it does not change:
static const int led = 13;

So all together you get:
static const int led = 13;

void setup()
{
    pinMode(led, OUTPUT);
}

void loop()
{
    blink();
}

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

I suggest you read a book about C or C++ to get used to the syntax.
Also, note that int is written as int, not Int. Case matters.

Thank you so so much. It was a good learning experience for me.

You're welcome, if it helping you, please upvote and if it solves your problem, accept the answer (clicking on the button next tot he answer). Have fun with the Arduino.

Your code
Blink = digitalWrite(led, HiGH);
         delay(1000);
         digitalWrite(led, LOW);
         delay(1000);

Is attempting to define a function Blink that you can call later. You don't do that with an assignment (=)
You want to define a function. I'd suggest naming it blink(), not Blink. (all lower case.
Functions have parentheses after the name, which is where you put parameters if your function has any parameters. If not you still need the parentheses. The basic syntax of a function definition is:
return_type function_name(param_type param_name)

If your function doesn't return a value, use the type void which means "no type."
So for a function foo that doesn't take any parameters and doesn't return any value, you'd use:
void foo () {
   //Code for function foo()
}

Michael's excellent answer (voted!) shows you what changes you need to make to your code to make it work. The above explains in a little more detail WHY you need to make those changes.

Of course C++ has nice things.
For fun ad learn a working Arduino sketch based on the code from the Question:
int led =13;

auto Blink = []() { digitalWrite(led, HIGH);
             delay(1000);
             digitalWrite(led, LOW);
             delay(1000);
};

void setup(){
pinMode(led, OUTPUT);
}

void loop(){
Blink();
}

Note: use normal functions in your sketches and save lambdas for special occasions.

Lambdas are way, WAAAAY beyond the OPs current abilities. You do them a disservice by even mentioning them at this stage in their learning.

And this should be byte, vs int, to save on memory:
static const int led = 13;

HiGH should be HIGH, all caps.

For a const it makes no difference to the memory use if you use byte, int, long or even long long.


text:
What is the purpose of '&' while passing bool as a function parameter
If I use this function without & before change_x (in function parameter), change_x never changes to false and it keeps on printing forever. Why do I need &?
void some_function(bool &change_x, int pin_x) {
 if (change_x == true) {
 delay(time_delay);
 if (digitalRead(pocket_pin_1) == HIGH) {
  Serial.print("State 1");
  }

 else {
  Serial.println("state 2");
 }
 change_x = false;
 }
}

If you have a boolean b you normally assign it to true or false. If you pass in a function a boolean (or integer, char and most other simple types), a copy is made. So if you change it in the function, when the function returns, the copy is destroyed and the original value is kept.
However, you do not want a copy, so you need a reference (pointer) to that boolean. That is where the & is for. So bool &change is not a boolean, but a reference to a boolean. Whenever you change that reference, the original value of the boolean is changed, which is what you want.
Note, this is a C++ feature, it does not exist in C (there you use pointers instead: bool* change).

As always in C++ the argument is passed by value by default (just like in plain old C). By using '&' you can pass it by reference. Therefore you are not copying the value of the variable into the method but the original variable with the possibility to mutate it inside the function and it will reflect the changes outside the function.
Perhaps you can paste more of your code so we see how the variable is passed into the function. For instance calling some_function(true, 3) won't be useful.
But anyway this is not an Arduino specific question and belongs to stackoverflow.


text:
How to parse multi line serial data with an unknown number of lines?
Here's the example data I've read in H-Term:
\r\n
\r\n
NO:0015\r\n
G:   5.97kg\r\n
T:   0.00kg\r\n
N:   5.97kg\r\n
\r\n
\r\n

How to save the number including "kg" to each variable (NO, G, T, N)?

so you need to save strings?

yes, i need to save that into 4 variable represent each line

what did you try?

This is an overly broad question which borders "write me the code" - this isn't a coding service - and if anything belongs on StackOverflow since it regards processing.  That being said, this question would be flagging as overly broad there too.
I'm providing an answer because I believe it may help others here as it speaks to some fundamental programming concepts.  This is not a perfect solution by any means, for example it doesn't take program size into account. See the end of the post for a sketch.
There are two main problems you face:

Model the input data
Process the data

Modeling the input data means structuring your expected input in a meaningful way.  Looking at the input data provided, I see this format

0-N chars indicate some metadata delimited by a colon (:)
0-N white space
0-N digits with optional decimal point (0015,5.97)
0-N unit designation (kg)
data is delimited with a CRLF (\r\n)

Now think of each line as a packet of information.  In that sense, let's create some data structures that describe the data of the packet.
// Types
typedef enum {
  NoType,
  NO,
  G,
  T,
  N,
} Type;

// Units
typedef enum {
  NoUnit,
  uKg, // kilogram
  uG,  // gram
} Unit;

// Values - unions are handy to model variants.
typedef union {
  char str[5];
  float dval;
} Value;

Given the basics above, let's model a Packet:
// the data model for a CRLF delimited packet
typedef struct {
  Type type;
  Value value;
  Unit unit;
  byte valid;
  // metadata
  byte expectUnit; // 1 if a Value has a Unit; 0 otherwise.

} Packet;

OK, so that's a basic model of the input data.  How to process?  Always break down big problems to the smaller, manageable units to provide a solution.
Now there's a huge number of possibilities to parse/interpret your data packets.  I am providing a bare bones, brute force approach that you may learn from, and hopefully improve upon.  For example I am not providing much in the way of array overruns which can crash a program.
Here's the main processing function, which takes a string of input data (a line) and produces a Packet.  In all I am only going to provide for the Type 'G' and leave the rest to you.
// readPacket processes the input string pszBuffer and fills pPacket accordingly.
//
// pszBuffer should be a string of characters delimited by \r\n.
// pPacket is a pointer to a Packet which is filled by this function.
//
// returns 1 if packet is valid, 0 otherwise.
byte readPacket(Packet* pPacket, const char* pszBuffer) {
  byte isvalid = 0;
  if (pszBuffer && pPacket) {
    char tmp[10];
    char* psz = (char*)pszBuffer;
    char* pszTmp = 0;
    byte len = 0;
    // initialize packet
    pPacket->type = Type::NoType;
    pPacket->unit = Unit::NoUnit;
    pPacket->valid = 0;
    pPacket->expectUnit = 0;
    // get the Type
    psz = processType(pPacket, psz);
    if (psz) {
      // skip any space characters now.
      psz = trimLeadingSpaces(psz);
      psz = processValue(pPacket, psz);
      // if Type handled, check units and finish.
      if (psz) {
        if (pPacket->expectUnit)
          pPacket->valid = processUnit(pPacket, psz);
        else
          pPacket->valid = 1;
      }

    } // Type not found

    isvalid = pPacket->valid;
  }
  return isvalid;
}

OK that's not a lot.  The logic is

Get the packet Type
IFF a packet Type was found, get the packet Value
IFF a value was found, get the Unit if required

It's important to breakdown these steps in smaller, manageable functions.  First, the code for getting the packet Type.
// processType
// Sets pPacket->type to the type found in psz.  Type is delimited by a colon (:)
// Returns 0 (null) if a known Type wasn't found.
// Otherwise a ptr to the data past colon delimiter.
//
char* processType(Packet* pPacket, const char* psz) {
  // find the colon (:) delimiter and return what it leads to.
  byte len = 0;

  char* ptr = strchr((char*)psz, ':');
  char* pResult = 0;
  if (ptr) {
    // found the colon.
    char buffer[4];
    byte len = (ptr - psz) / sizeof(char); // pointer math to find length.
    strncpy(buffer, psz, len);
    // null term buff
    buffer[len] = 0;
    // assume succcess; default will rest to fail.
    pResult = (char*)psz + len + 1; // +1 to skip colon character.
    switch (buffer[0]) {
    case 'G':
      pPacket->type = Type::G;
      pPacket->expectUnit = 1; // unit should be given.
      break;
    default:
      pPacket->type = Type::NoType;
      pResult = 0; // fail, didn't find a known type.
    }
  }

  return pResult;
}

So processType sets up the packet Type and adds information about whether to look for Unit information later.
If processType() found a valid Type, the next step is to get the value based in that type with the function processValue
// Sets pPacket->value according to the packet Type.
// Returns null (0) if type not supported or value not found,
// otherwise a pointer to the remaining characters following the value handled.
char* processValue(Packet* pPacket, const char* psz) {
  char* ptr = 0;
  // value is construed by Type
  switch (pPacket->type) {
  case Type::G:
    ptr = processFloat(pPacket, psz);
    break;
    //
    // add your additonal Type implementations...
    //
  default:
    // invalid, set psz to null.
    ptr = 0;
  }
  return ptr;
}

Great. Now, let's look at a way to get the value for a float:
// Sets pPacket->value.dval
// Returns 0 (null) if a value wasn't found.
// Otherwise a ptr past the last character of the decimal value.
char* processFloat(Packet* pPacket, const char* psz) {
  const char *float_chars = ".0123456789";
  char* ptr = (char*)psz;
  if (ptr) {
    // scan ptr until we don't find a match.
    byte index = 0;
    while (strchr(float_chars, (char)ptr[index]))
      index++;

    if (index) {
      //  get the float using a temporary buffer.
      //  dangerous! assuming this will not overrun!
      char buf[10];
      strncpy(buf, ptr, index);
      // null term buff
      buf[index] = 0;
      pPacket->value.dval = atof(buf);
      // advance ptr past the decimal characters for return valie.
      ptr += index;
    }
    else ptr = 0; // fail
  }
  return ptr;
}

Finally if all went well, the code should look for the Unit if expected (based on the Type)
// Sets pPacket->unit to the unit given in psz.
// Returns 0 if no unit was found, non-zero otherwise.
byte processUnit(Packet* pPacket, const char* psz) {
  pPacket->unit =  Unit::NoUnit;
  if (psz) {
    switch ((char)*psz) {
    case 'k':
      pPacket->unit = Unit::uKg;
      break;
    case 'g':
      pPacket->unit = Unit::uG;
      break;
    default:
      break; // unit initialized to NoUnit.
    }
  }
  return pPacket->unit != Unit::NoUnit;
}

Here's a GIST of an arduino sketch using the code above.
Good luck, hope this helps.  In the future, pose questions regarding processing on StackOverflow.


text:
programming STM32 with arduino IDE issues
I'm currently trying to program an STM32 with arduino, but along the way, i encountered some issues with pin modes. To be more specific, programming certain pins to certain modes. Some pins have consistent digital outputs like PC13, while others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

here is what i get from PA12

here is what i get from PA11
i've read the pinout diagrams, and im not too sure if both mentioned pins can be used digitally according to this pinout diagram :

can anyone help me explain what is going on, how do i program an STM32 with Arduino IDE exactly (stm32duino programming procedures, rule of thumb, etc), and can an stm32duino be used to do complex programs like an arduino like for example driving a motor with PWM in a balancing robot or do we have to use C or C++ using atollic TrueSTUDIO and all of those software?

others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.
You can't use those pins for both USB and other GPIO roles at the same time.
Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC.  Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).
There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.


text:
How to turn on Solenoid based on Soil Moisture value?
I am powering solenoid with 24 volt as required however I am using TIP122
transistor that has base connected to Arduino Digital Pin 6 via a 1K Resistor.
And the collector is connected to negative side of 1N4001 diode, this also serves as the Negative out for solenoid. and emitter is connected to the 24 volt power input.
The positive input from power source is connected to positive terminal of diode is directly connected to solenoid.

As per the logic I am trying to turn on Solenoid based on Signal from Arduino PIN 6, but for some reason Solenoid doesnt power up.
In my code below I want to turn on solenoid if soil moisture goes above 60. the signal is coming from Pin 6 but solenoid doesnt power up.
#include <SPI.h>

int solenoidPin = 6;    //This is the output pin on the Arduino we are using

int GLED = 5; // Wet Soil Indicator at Digital PIN D5
int RLED = 9; // Dry Soil Indicator at Digital PIN D9
int SENSE = 1; // Soil Sensor input at Analog PIN A1
int val = 0;

int greenLedPin = 2; // LED on pin 2
int yellowLedPin = 3;
int redLedPin = 4;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  pinMode(solenoidPin, OUTPUT);           //Sets the pin as an output

  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  pinMode(greenLedPin, OUTPUT); // LED on pin 2
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);

  pinMode(GLED, OUTPUT);
  pinMode(RLED, OUTPUT);

}

void loop() {
  val = analogRead(SENSE);
  val = val / 10;
  analogValue = analogRead(lightSensorPin);
  Serial.print("LDR value: ");
  Serial.print(analogValue);
  digitalWrite (redLedPin, analogValue < 55) ;
  digitalWrite (yellowLedPin, analogValue >= 55 && analogValue <= 100) ;
  digitalWrite (greenLedPin, analogValue > 100) ;

  Serial.print(" Soil Moisture: ");
  Serial.println(val);
  digitalWrite(GLED, (val < 50));
  digitalWrite(RLED, (val > 50));
  // Turn on Solenoid Valve if soil moisture value greater than 60
  digitalWrite(solenoidPin, (val > 60));

}

I am doubting on the diode to use , because I am  powering solenoid of 24 volt and not sure if the diode is correct , as per my knowledge, diode can get direct if higher voltage is passed.
Any help will be greatly appreciated.

Maybe connect it to pin 6 instead of to pin 4?

Also 24V on Vin is pretty big voltage. Power regulator might be (and it will be) overheating.

Sorry ignore power input shown in image above as I mention sources of power are different for solenoid and Arduino Vin is not connected to anything

Determine whether it's a problem with your code or a problem with your circuit by connecting the yellow wire to the 5v output of the Arduino - see whether the solenoid actuates.

@MarkSmith I have added updated Fritzing as per the code .  With above circuit solenoid is getting 3.4 volts whether the soil moisture sensor is dipped in water or out of water. Is TIP122 perfect for 24 Volt/3Amp input coming from power adapter

My suggestion is still the same - except for the wire colour as you changed it: break the problem into smaller parts.  Determine whether it's a problem with your code or a problem with one of your circuits by connecting the light blue wire to the 5v output of the Arduino - see whether the solenoid actuates.

@Mark Smith, +1 for breaking down in smaller parts. That way you can find and resolve problems one by one.

J Picqurd's answer is correct BUT a look at your original diagram shows it cannot  work as shown. You show a single wire between Arduino proper and output system. You MUST have two wires (minimum so that one supplies voltage relative to the other. Ground in both systems is usually joined and then the Arduino output voltage relative to ground is produced by the ARduino and "seen" by the controlled circuit.

When looking your schematic and assuming that J1 connector is not powered by your MacBook as your Arduino board, the main problem is located to the GND signal.
In order to have a commutation current to the Base of the TIP122 through the 1K resistor, you need to link the GND signal its Emitter with the GND signal of your Arduino board.
See a proposed schematic from "High-Power Control: Arduino + TIP120 Transistor"

would it be ok, if I take power from 5volt pin of UNO and use stepup xl6009 to convert to 24 volts and power solenoid ?

O boy I used xl6009 to convert 5 volt to 24 volt and supply to solenoid with common ground as you mentioned and its working as expected

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


text:
Getting maxretry error when trying to ping using python requests or urllib3
I have written this code working on SimpleHost example from ESP8266Ping library,
the code works,
#include <ESP8266WiFi.h>
#include <ESP8266Ping.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>

#define HTTP_REST_PORT 80

const char* ssid     = "usernaem";
const char* password = "password";

const char* remote_host = "10.10.10.12";

ESP8266WebServer http_rest_server(HTTP_REST_PORT);

void get_online_status() {
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& jsonObj = jsonBuffer.createObject();
  char JSONmessageBuffer[200];

  Serial.print("Pinging host ");
  Serial.println(remote_host);

  if(Ping.ping(remote_host)) {
    Serial.println("Success!!");
    jsonObj["roku_express"] = 1;
  } else {
    Serial.println("Error :-(");
    jsonObj["roku_express"] = 0;
  }
  jsonObj.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  http_rest_server.send(200, "application/json", JSONmessageBuffer);
}

void config_rest_server_routing() {
    http_rest_server.on("/", HTTP_GET, []() {
        http_rest_server.send(200, "text/html",
            "Welcome to the ESP8266 REST Web Server");
    });
    http_rest_server.on("/ping", HTTP_GET, get_online_status);
}

void setup() {
  Serial.begin(115200);
  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println("Connecting to WiFi");

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }

  Serial.println();
  Serial.print("WiFi connected with ip ");
  Serial.println(WiFi.localIP());
  config_rest_server_routing();
  http_rest_server.begin();
  get_online_status();
}

void loop(void) {
  http_rest_server.handleClient();
  }

if I try to access my wemos D1 Mini from web browser I get correct message :
if offline
{
  "roku_express": 0
}

if online
{
  "roku_express": 1
}

but if I try to get the REST URL from python code either using requests or urllub3
import urllib3
http = urllib3.PoolManager()
url = "http://10.10.10.4/ping"
response = http.request('GET', url)

I get below error

MaxRetryError: HTTPConnectionPool(host='10.10.10.4', port=80): Max
  retries exceeded with url: /ping (Caused by
  NewConnectionError(': Failed to establish a new connection: [Errno -536870212]
  Unknown error: -536870212'))

Is the computer running the Python code on the same network as the ESP8266? What happens if you try to access the ESP8266 URL from a web browser?

like I said in the opening post, from web browser it worked.


text:
DS18B20 and Arduino - Internall Pull-Up
Can this DS18B20 sensor be used with Arduino internal pull-up or it require exactly 4.7k pull-up resistor?

The Arduino internal pull-up is something like 50k. That is a lot different from 4.7k. You would probably find that the pull-up is not strong enough to get clean pulses from the device. Also if you are using it in one-wire (parasitic) mode notice this from the datasheet:

To assure that the DS18B20 has sufficient
  supply current, it is necessary to provide a strong pullup on the 1-Wire bus whenever temperature
  conversions are taking place or data is being copied from the scratchpad to EEPROM.

Notice the words 'strong pullup'. The internal pullup is not strong.

Yeah you are right. Also I find out that these internal pull-ups depends also from type of Arduino (Uno, Nano, Mega etc.) so they have different values as well.

It varies from chip to chip in the same family, and even pin to pin depending on what other functions the pin has. Last time I measured them on a range of chips they varied from about 25k to 40k

If the datasheet specifies a 4.7kΩ resistor then a 4.7kΩ resistor is what you need.

Do people not like the fact that the datasheet knows best? They don't put these things in datasheets for fun you know.

4.7kΩ is a great starting point, but you should choose differently depending on your supply voltage. At 5V with 4.7kΩ pullup, the device has to sink about 1mA to pull the line low. If instead you're operating at 3.3V you should use 2.7kΩ to sink the same current.

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


text:
Standalone Programmer
I am trying to make my small stand-allone programmer to work using this code:
https://github.com/adafruit/Standalone-Arduino-AVR-ISP-programmer
But when I hookup everything and press button to flash my IC, I get this:
AdaBootLoader Bootstrap programmer (originally OptiLoader Bill Westfield (WestfW))

Type 'G' or hit BUTTON for next chip
Starting Program Mode [OK]

Reading signature:200
Searching for image...
 Not Found
Image fail

When I try to flash the same IC (just to make sure that IC is fine) via Arduino, there's no issues.
Any idea what can be wrong with this?

What IC are you programming?

I am trying to program ATMega328P-PU and with other assembled programmer which already have firmware which contains some variation of this OptiBoot_atmega328.hex it works.

Is images.cpp missing?

Nope, images.cpp is there, and signature there is fine

Looks like the problem was with fuses, fuses are not being set properly with this sketch. Once I write this IC with some other tool (like original OptiLoader) this sketch started to work.


text:
Junk values in EEPROM. while writing large values
Facing an issue while writing a large value (like 2000-5000) to EEPROM using EEPROM.put().
For example, While writing 2000 values to address 5 of EEPROM. Some junk values are written automatically to a nearby address (address 4, 6, 7...).
Note : Not trying to write an array of 2000 elements
Board Used : Arduino Uno (Atmega328P)
Q1 : What is the typical range of a each address by using EEPROM.put() . Like EEPROM.write() has range limit of 0-255.
Q2 : How to write large value EEPROM addresses without effecting the nearby address.

Are you writing the value 2000 or are you trying to write an arry of 2000 elements? Thats not clear in your question

@chrisl I am trying to write value 2000.

It depends on what type of variable you have.  If you have single byte variables like byte or char then it is one value to one address.  But if you have an int value like:
int x = 2000;

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size.  So if you write that to address 5 it will take 5 and 6 to write it.
If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.
If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written.  I don't remember.  But you certainly can't fit 2000 into a byte so it's going to have to take more than one.

The literal 2000 is always interpreted by the compiler as an int.

Yes the compiler does but I don’t know how the put function works. It could be like print where int ends up promoted to long in the function.

It's a template: it uses whatever type its argument has. Unlike print(), which is a collection of overloads.

Ok thanks.  Wasn’t able to look it up when I wrote the answer.  Wasn’t sure how it was handled but knew for sure we needed more than one byte.


text:
My indivually addressable LED strip is acting weirdly and I have no idea why
EDIT: I had a typo in the code. I updated the code below to reflect what is shown in the video.
Video of the problem
I'm controlling my LEDs via the Neo_pixel Library for Arduino. My strip (SK6812, RGBW) takes 5V. I wrote very simple instructions for the strip: flash the whole strip one color, rest for 200ms, then flash the whole strip a second color, then rest another 200ms. This should be repeated indefinitely but when either chosen color is red (rgbw[255, 0, 0, 0]) or green (rgbw[0, 255, 0, 0]) the strip will function up as expected for a second or two then remains a solid red or green (depending on which color was chosen). This problem only seems to occur with red or green; blue and white appear to not be an issue. If someone has an idea I should try, please let me know!
The following code is what was executed in the video above:
Neo_Pixel Class Reference
strip.fill(strip.color(255, 0, 0, 0), 0); //fills entire LED strip the color red
strip.show(); //Updates LED strip to reflect changes
delay(200);   //200ms delay
strip.fill(strip.color(0, 0, 0, 255), 0); //fills entire LED strip the color white
strip.show();
delay(200);

There's an error in your code, you're specifying the same color both times.
Also, if you're commanding full-on white, I suspect you may be overloading your power supply and causing it to do whatever it does when you overload the power supply.

That code just shows red over and over.  How would you ever know if that has stopped?  Please post a complete code.

that is not the code that is running in the video ... either delete the video or delete the sketch

try strip.color(32, 0, 0, 0), strip.color(0, 32, 0, 0), etc. If that works you need a bigger PSU.

@Delta_G  Ah that's a typo! I copied the instructions to turn the LED strip red and forgot to change the RGBW value to white. The code now reflects what is shown in the video.

@Harper-ReinstateMonica I thought this might be a problem but I wasn't sure how to tell. I figured if I overloaded the strip, it would go blank instead of remaining a color. I should also mention that the problem does not occur if I light up only half the pixels.

@dandavis I'm still learning the ropes of arduino, is a PSU just power supply?

yup. wall wort. usb charger. psu. dc supply. they have a lot of synonyms...

@dandavis I decreased the RGB values as you suggested and the strip works as expected, guess I gotta get more power! Thanks!


text:
Copy Uno Analog Input Configuration To ESP32
I started a project using the arduino uno and as a challenge I'm attempting to make it work with the esp32 but I've run into a roadblock. I may not describe it in proper terms, but I noticed that the analog input signal on the esp32 functions differently from how analog input works on the uno. After some research I found that the esp32 has a default analog width of 12, instead of the default 10 on the uno. This got me wondering what other analog settings (reference voltage, pin attenuation, width, etc.) on the esp32 are different from the uno and how I might go about getting similar results on the esp32. I found this useful page detailing some functions to mess around with the adc channels but, other than analogSetWidth(), I haven't been able to figure out what they do. I tried messing around with the functions mentioned in the linked page, but I ultimately made things worse.
tl;dr What analog input settings (analog width, pin attenuation, etc.) on the esp32 are different from the uno?

You've found a datasheet equivalent (or API description) for the ESP32 ADC. Find one also for the ATmega328P (Uno/Nano MCU) to compare their ADC capabilities. These are different peripherals from different manufacturers. Some features may not be present on both.

@6v6gt Your advice led me to find https://ece-classes.usc.edu/ee459/library/documents/ADC.pdf and https://www.best-microcontroller-projects.com/arduino-adc.html which told me exactly what I needed to know! Thanks!

Per the advice of @6v6gt, I was able to find this resource and this resource that told me the following information about the ADC configuration for the Uno's MCU (aka ATmega328P):

The analog width defaults to 10 bits (** definitely the most important)
The reference voltage is determined by the AVCC (power source) by default
The ADC clock defaults to a divisor of 128 (assuming 13 ADC cycles per conversion)

Wasn't able to find anything useful about pin attenuation, though.


text:
Arduino UARTS Auto addressing slaves
i'm using this serial topology to connect my Act ATmega328p (Arduino) slaves together to a master ESP32.
They are in total 10 ATmega328p slaves and one master:

With this type of wiring i'm sure that only one slave per time will talk back to master (when requested), now here comes the problem, basically i need dynamic addressing of slaves: they can be many (up to 30) and i need to access in order the slave devices.
In order to solve the "dynamic addressing" problem i'm thinking about that:
The first slaves will be plugged in and will send to the master his default address (i.e.: 0xFF)
The master will check if the address is used and then reply back to the device with the first available address (i.e.: 0x01)
The slave will get back the response from the master and set an internal variable with the new address (maybe it's a good idea to store the variable in a EEPROM like M24C02: enter link description here)
Starting from the next cpu cycle, the master will ask sequentially to all enumerated slaves to (for example) do an analog read using this workflow:
The master will send a message to the serial bus with address 0x01 asking to do an analog read
The respective slave will handle the request, read the analog input and then reply back to the master
I think that this can work, but i've not found any kind of this implementation...maybe i'm totally out of mind?
New idea and concept
Guys, what do you think about sequentially power up the circuits and using the same mechanism to assign dynamically the address?
This assumption will avoid me to save the assigned id to the eeprom and some other id software function defined functionalities like address reset, etc...
It can be a good (and dynamic) method to solve the problem, about that, how I can implement this sequential power up?

I would probably solve the problem using the I2C bus. Each I2C slave would have external inputs to determine the unique address. For 30 devices you would need 5 input pins on each STM board to determine the address. Maybe this is not what you are looking for, so look at my second proposal.
The second solution could be to use the SPI bus, where ESP32 would communicate with the devices using a chip select signal  (CS, SS). I would solve the problem with the lack of pins on the master development kit (ESP32), for example, using an I2C expander.

I forgot to mention that your solution, unlike mine, is non-standard.

I know man that is a non standard solution, but I have a constraint: from the ESP32 to the slave clients I can only have 4 wire cable: Vcc, gnd, RX and TX

In that case you can still use I2C.

How? Please give me an example: I need dynamic addressing of slaves and I can't place any dip switches on the PCB

You did not mention you can not use DIP switches or jumpers or other external signals on STM boards . Without external signals (on STM), of course, it can not be solved in the standard way...

Yep, my fault, in any case... thanks man :)

The first slaves will be plugged in and will send to the master his
  default address

If this happens while the master is talking to one of the other slaves,
you risk a collision.
I suggest a very small variation on your scheme. Each slave has a
default address (0xff). When you turn it on, it doesn't say anything.
The slaves only talk when they are addressed.
Every now and then, the master sends a “ping” message to 0xff. The newly
installed slave responds, then the master gives it a real address, and
goes back to its business of collecting sensor data. If no response is
received for the ping within some specified timeout, the master assumes
there is no unconfigured slave.
Since no slave ever sends unsolicited messages, this should avoid any
kind of collision. You just have to make sure that new slaves are added
at a slow rate: after connecting a slave, you wait for slightly more
than the ping period before connecting another one.

Thanks Edgar, your answer is directly what I was looking for! I'll implement like that, I have two remaining question: 1.) how I can implement the "ping" code and manage the dynamic addressing, are you able to give me an example on your post? 2.) You think that a "conditional" power up of slaves (driving a MOSFET from gpio to give Vcc to relative cascading slave when the preceding slave will obtain the address) will help me to avoid to power up the system and then add manually the devices one by one?

You will probably have to invent your own protocol, where each message sent by the master has a slave address, a message type (ping, configure new address, data request), possibly a data field (the address being given) and maybe a checksum.

Yes, sure! It can be feasible without so much effort...the only doubt that I have is about the serial ping: you suggest to use functions like serial write and serial.available? Or I have to implement some dumb loop that listen on serial for a specific amount of time?

For implementing the timeout, you can check Serial.available() for a specific amount of time.

Upvote, this answer confirm me what I was thinking!

You could also at the start let the master contact every possible slave address in the needed range. That way you can check for which slaves are already connected. An address where the master doesnt get an answer within timeout is not connected.

@chrisl: My understanding is that the OP wants dynamic addressing because he cannot add DIP switches to the PCB and does not want to hard-code addresses into them.


text:
PulseIn tachometer
I tried to create a tachometer for my motorcycle using an Arduino Uno.
I am trying to measure the voltage of the ignition coil (stepped down to not destroy the Arduino).
I am trying to determine the time between two explosions (one ignition coil high voltage).
I tried to use the pulseIn command in the following way:
unsigned pin=8;
float t;

unsigned long rpm;

void setup() {
    Serial.begin(9600);
    pinMode(pin,INPUT);
}

void loop() {

    rpm=pulseIn(pin,LOW);

    Serial.println(rpm/60);
}

The problem with it is that it won't display stable values. It will go all crazy.
With an open circuit it still displays random values.

Are you sure that pulse is not shorter than 10ms?

i tested both pulseIn(pin,LOW) and pulseIn(pin,high) and neither worked. At most, my bike does 14.000 rpm, meaning 14.000/60 (233) rps.
233 rps ..... 1000 ms
x rps............1 ms
x=233/1000.
I guess it is less than 10 ms.
Is that the problem?

https://www.arduino.cc/en/Reference/pulseIn - under 10ms it wont work right

but if you have tested it with smaller speed, the problem will be somewhere else

I am curious, how do you get to incorporate ignition coil into your circuit?

I suspect that it is already too late for that Arduino. How are you safely stepping the voltage down in such a way that it doesn't a) kill the Arduino, and b) kill you?

btw: http://arduino.stackexchange.com/questions/318/how-precise-is-the-timing-of-pulsein?rq=1

pulseIn works for values less than 10ms, it returns time in 'micro Seconds'. Try        Serial.println(pulseIn(pin,LOW));

I did not use the high voltage terminal. I took the minus from the coil primary minus (the 12v terminal) and the plus from the battery, since the ground is the one that continuously varies in an ignition coil. I used a voltage divider to step the voltage down to acceptable levels.

No one mentioned that there is back EMF from primary coil when switch (or points) becomes open. This means that there is 200-300V applied backwards to your voltage divider while you think there is only 0-12V.

I can't tell you why that isn't working, but I can give you a working alternative.
unsigned int pin=8;

void setup() {
    Serial.begin(9600);
    pinMode(pin,INPUT);
}

void loop() {
    unsigned float rpm = 0;

    while (digitalRead(pin) == FALSE) {
        rpm++;
        delayMicroseconds(1);
    }

    Serial.println(rpm/60);
}

I might've forgotten something, but that should work.
Edit: the comments may be right, are you stepping down your input voltage?


text:
IR sensor not detecting light or dark sufaces
I wrote code for the vibrating motors to vibrate when an IR sensor detects a darker surface. I have 4 vibration motors for corresponding 4 IR sensors. My program is not able to read the values from the sensor. In the serial monitor the values that are read from the sensor is a huge non stopping value. None of my IR sensors is detecting the surface. As a result no vibrations are produced. I am using Arduino Pro Mini and my code is:
#include <EEPROM.h>
// pin numbers
const int irLED = 7; // wire connected to transistor/220 ohm resistor (all on same pin)
const int collectors[] = {A0,A1,A2,A3}; // (with pullup resistors)
const int vibrations[] = {3,5,6,9}; // vibration motors

// thresholds for each finger
int detectionThreshold[] = {940,960,970,975};
int whiteThreshold[] = {600,600,600,600};

// timers (in milliseconds)
int lastVibration[] = {0,0,0,0};
const int numFingers = 4;
int readings[] = {1023, 1023, 1023, 1023, 1023, 1023};
boolean vibrating[] = {false, false, false, false};

void blackLoop()
{
  int now = millis();

  // get the current readings
  for(int i = 0; i < numFingers; i++)
  {
    readings[i] = analogRead(collectors[i]);
    Serial.print(readings[i]);
  }

  // vibrate on black, with minimum vibration time
  for(int i = 0; i < numFingers; i++)
  {
    if(readings[i]<=detectionThreshold && readings[i] >= whiteThreshold[i])
    { Serial.print(readings[i]);
      digitalWrite(vibrations[i], HIGH);
      vibrating[i] = true;
      lastVibration[i] = now;
    }
    else // if(now - lastVibration[i] > vibrationDuration)
    {
      digitalWrite(vibrations[i], LOW);
      vibrating[i] = false;
    }
  }
}
void setup()
{
  // put your setup code here, to run once:
  for(int i=0; i<numFingers; i++)
  {
    digitalWrite(collectors[i], HIGH);  // set pullup
    pinMode(vibrations[i], OUTPUT);
  }

   pinMode(irLED, OUTPUT);
   digitalWrite(irLED, HIGH);
   Serial.begin(9600);
   Serial.println("my sketch has started");

}

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

}

IR may not reflect off your dark and light surfaces in the same way as visible light.  Your IR sensors may not be able to tell the difference between what you perceive with your eyes as dark and light.

In addition, may types of IR receivers are designed to automatically adjust the receiver's gain so as to, for example, mitigate poor performance from randomly located IR transmitters.  IR receivers found in remote controlled TVs or remote controlled Stereos normally auto adjust their own gain.


text:
Problem uploading to board
avrdude: stk500_getsyn(): not in sync_resp=0*00
avrdude: stk500_disable: protocol error, expect=0*14,resp=0*51

These are the errors occurring when I am trying to upload to the board.
I've tried all the suggestions that suggested in this. When I am trying to burn the bootloader the same error is showing.

You forgot to add the link referred by "this".

What board and serial port have you selected?

I don't know if I got the exact error (maybe another sync error), but what helped in my case (in this order, try again every time):

Reinsert the USB cable
Use a different (shorter) USB cable
Put the USB cable in another USB port
Restart the Arduino IDE
Restart the computer
Reinstall the Arduino IDE
Go to device drivers (control panel), check for COM ports, remove Arduino and reinstall


text:
Using attachInterrupt() to make a reset button for my code?
I have used attachInterrupt() to reset my program to the beginning. It actually interrupts while running the 3 states as shown below inside of the if statement but when I press the actual button it does not exit, it goes to the function and continuing to the next state. It only works (means exiting/resetting) after all three states have executed completely.
if(buttoncount<2){
  originalstate();
  alertstate();
  evacuationstate();

I would like to make a button to stop the program while running in the middle and start again.
Code:
// Declaring pins

// Input pins
const int sensor1button_pin = 6;
const int sensor2button_pin = 3;
const int sensor3button_pin = 4;
const int sensor4button_pin = 5;
const int sensor5button_pin = 2;
const int sensor6button_pin = 15;
const int sensor7button_pin = 15;

// Output pins
const int led1_pin = 8;
const int led2_pin = 9;
const int led3_pin = 10;
const int led4_pin = 11;
const int buzzerpin = 15;

// Initialy buzzer at false mode
boolean flag1;
boolean flag2;
int flag3 ;

// for leds
int ledState1 = LOW;   // Original
int ledState2 = LOW;   // Alert
int ledState3 = LOW;   // Evacuate
int ledState4 = LOW;   // Isolate

// Buttons
int button1_state = LOW;
int button2_state = LOW;
int button3_state = LOW;
int button4_state = LOW;
int button6_state = LOW;
int button7_state = LOW;
int button5_state = LOW;

// Other variables
int buttoncount = 0;
int reset_switch=0;

void setup() {
  // INPUT pins
  pinMode(sensor1button_pin, INPUT);
  pinMode(sensor2button_pin, INPUT);
  pinMode(sensor3button_pin, INPUT);
  pinMode(sensor4button_pin, INPUT);

  pinMode(sensor5button_pin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(sensor5button_pin), clearreset, CHANGE);

  pinMode(sensor6button_pin, INPUT);
  pinMode(sensor7button_pin, INPUT);

  // OUTPUT pins
  pinMode(buzzerpin, OUTPUT);
  pinMode(led1_pin, OUTPUT);
  pinMode(led2_pin, OUTPUT);
  pinMode(led3_pin, OUTPUT);
  pinMode(led4_pin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  button1_state = digitalRead (sensor1button_pin);
  button2_state = digitalRead (sensor2button_pin);
  button3_state = digitalRead (sensor3button_pin);
  button4_state = digitalRead (sensor4button_pin);
  button5_state = digitalRead (sensor5button_pin);
  button6_state = digitalRead (sensor6button_pin);
  button7_state = digitalRead (sensor7button_pin);

  Serial.println(digitalRead (sensor5button_pin));

  if( button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    delay(280);
    buttoncount = buttoncount + 1;
  }

  if (button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    if(buttoncount<2){
      originalstate();
      alertstate();
      evacuationstate();
    }
  }
}

// LED lighting arrangements
void originalstate() {
  digitalWrite(led1_pin, HIGH);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void alertstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, HIGH);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void evacuationstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, HIGH);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void isolatestate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, HIGH);
}

// Clear or reset back to the begin

void clearreset() {
 button1_state = LOW;
 button2_state = LOW;
 button3_state = LOW;
 button4_state = LOW;
 button5_state = LOW;
 button6_state = LOW;
 button7_state = LOW;

 digitalWrite(led1_pin, LOW);
 digitalWrite(led2_pin, LOW);
 digitalWrite(led3_pin, LOW);

 buttoncount = 0;
 exit;
}

The arduino has a reset pin,   pull it to ground with switch,and it will reset from the beginning.

i tried your one but it completely reset the arduino , but that's fine for the reset button  .any way ,i can interrupt the program while running and change to any other function  of the program . such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

set a flag variable in the interrupt service function ... check the flag at the beginning of each state function and skip digitalWrite() and delay() commands if the flag is set

you could also use a state variable and call the state functions depending on its value .... use the interrupt to set the state variable to a specific value

you have two identical if statements one after another .... merge the contents into one

You should enable verbose compilation in the IDE. You will then have a
chance to see this compiler warning:
warning: statement is a reference, not call, to function ‘exit’
  exit;
      ^
warning: statement has no effect

Naming a function without calling it is a way to get a pointer to the
function. It's equivalent to &exit. But since you do nothing with that
pointer, the statement has no effect, and that's exactly what the
compiler is warning you about.
You presumably want to call the exit() function, like in:
exit(0);

Edit: That being said, exit() is probably not what you want.
This function just stops your program by putting it in an infinite loop.
If you want it to restart from scratch, you can first declare
extern "C" void __init();

then, instead of exit(0); call __init();. This will send your
program to the beginning of the initialization code from the C runtime,
which is responsible of resetting the stack and initializing the memory
(.data and .bss sections). Note that this is not equivalent to a
hardware reset because:

doing this does not run the bootloader
more importantly, it doesn't reset the IO registers of the peripherals
to their default reset state.

You need non-blocking code in combination with a finite state machine:
 1. Non-blocking code: You should not use delay(), since it is just busy waiting. Instead use the millis() function to measure the time distance between the last execution of the code part and the current time. If it has reached a certain level (like 1500ms), execute the code and save the current time in a timestamp as a reference for the next execution. Refer to the BlinkWithoutDelay example of the Arduino IDE. There are also many tutorials for that on the internet, so I will not explain this further here.
 2. Finite state machine: Here your loop() function contains of a switch statement with a (mostly numerical) state variable as parameter. Every case contains only the code for its special case. To get from one state to another you would just change the state variable to the corresponding value. You can also do this in an ISR (if you set the state variable as volatile). If you non-blocking code as described above, the loop() function is executed very fast, so that the change of the state variable inside the ISR takes effect almost immediately (delay will not be sensable by a human). Something like this:
volatile int state=0;

void isr_function(){
    state++;
    if(state>1) state=0;
}

void loop(){
    switch(state){
        case 0: // state 0
            do_something();
            break;
        case 1: // state 1
            do_another_thing();
            break;
    }
}

Note: Depending in your target you may want to add code for button debouncing, so that one button press is really sensed as one press, not more. This is relevant most times you have non-blocking code. Debouncing has been described many times in the internet, so just Google it

... .any way, I can interrupt the program while running and change to any other function of the program. such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

Interrupt will not help you achieve your requirement. You want to 'reset the state' of your running sketch. But after the interrupt the MCU returns in the code where it was before interrupt and continues.
You should implement the 'reset of the state' in your algorithm. In a loop of a non-blocking sketch you can check the button and if it is pressed, then 'reset the state' of the sketch.

Did you read my answer? __init() completely resets the state of the program. There is no “after the interrupt”: since __init() does not return, the following reti (return from interrupt) instruction will never be executed. And there is no “state where it was before interrupt”: that state was on the stack, and the stack is reset by __init().

@EdgarBonet, I did read your answer and it is correct. I answer other point of view, not what he coded, but what he wants to achieve (second comment). He doesn't want to reset the program, only the 'state of the program'.

Then you should clarify your answer, say that you are proposing a different approach (the OP specifically asked to “stop the program [...] and start again”), adjust the wording accordingly (“must” → “should”), tell if/how the proposed approach is better, and maybe explain how resetting the “state of the program” (whatever you mean by that) is different from resetting the program itself.


text:
The code does not produce the serial output
#include <Streaming.h>
#include <StopWatch.h>
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"
const byte adcPin = A0;
void setup(void)
{
    Serial.begin(9600);
    while(!Serial);
    Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
    for(int i=0; i<10; i++)
        testAnalogRead();
}
void testAnalogRead()
{
    static Stopwatch stopwatch(micros);
    //delay(1000);

    stopwatch.start();
    int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
    stopwatch.stop();
    int t1 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc2 = analogRead(adcPin); // 425us on SAMD21
    stopwatch.stop();
    int t2 = stopwatch.interval;

    analogReadResolution(10);
    stopwatch.start();
    int adc3 = analogReadFast(adcPin); // 23us on SAMD21
    stopwatch.stop();
    int t3 = stopwatch.interval;

    analogReadResolution(12);
    stopwatch.start();
    int adc4 = analogReadFast(adcPin); // 24us on SAMD21
    stopwatch.stop();
    int t4 = stopwatch.interval;

    Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
    analogReadResolution(10); // restore default
}
void loop()
{
}

This code does compile in the Arduino Zero, but does not produce the serial output on the serial monitor (serial plotter) at all.
What am I doing wrong?

Can you please confirm, that the Arduino really executes the whole setup() function to the end, by turning on an LED at the end of the function? Maybe Serial cannot be initialized correctly, so that it stays in an infinite while loop. Also try a simple example sketch for serial communication to test, if this works

Thanks all for the suggestions. I was able to figure it out after spending few days. The main problem was the Albert.h library was not necessary for this code. I commented out # <Arduino.h> and this worked!!!


text:
Arduino Zero AnalogReadFast Compiling Error
#include <Streaming.h>
#include <StopWatch.h>
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

When I try to compile this code in the Arduino Zero, it throws out the following errors:
/Users/RAJU/Documents/Arduino/libraries/avdweb_AnalogReadFast/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:1:23: fatal error: Streaming.h: No such file or directory
 #include <Streaming.h>
                       ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Zero (Programming Port).

Can anyone help to resolve this error?

install the library that contains Streaming.h ... the error message tells you that the compiler cannot find it

You can find the Streaming library here at Github