text:
Multiple Interrupt Pins Generates Wrong Pulses
On MKR WAN 1300 board I added pulldown resistors to 0,1,4,5,6,7,8 pins to count pulses.I can catch interrupts, but sometimes pulses occur on other pins even though they are not touched. For example, button pulses are generating on pin 2 but shows pins 3 is also triggered , it shows like
pin 2=1
pin 2=2
pin 2=3
pin 2=4
pin 2=5
pin 2=6
pin 3=1
pin 2=7
What can be the reason ? How can I solve it ?
#include <MKRWAN.h>

#define debugSerial Serial
#define loraSerial Serial1

int DEBUG = 0;

/* Pins of External Interrupts */
const byte WATER_METER_1 = 0;
const byte WATER_METER_2 = 1;
const byte WATER_METER_3 = 4;
const byte WATER_METER_4 = 5;
const byte WATER_METER_5 = 6;
const byte WATER_METER_6 = 7;
const byte WATER_METER_7 = 8;

volatile int watMeterPulseArray[7] = {0, 0, 0, 0, 0, 0, 0};

unsigned long pulseTime[7] = {0, 0, 0, 0, 0, 0, 0};
unsigned long lastTime[7] = {0, 0, 0, 0, 0, 0, 0};
const long interval = 2000;// interval for next pulse

int  watMeterPulseArraySize = sizeof watMeterPulseArray / sizeof watMeterPulseArray[0];

void checkAndVerifyPulse(int pin) {
  pulseTime[pin] = millis();
  if (pulseTime[pin] - lastTime[pin] > interval ) {
    lastTime[pin] = pulseTime[pin];
    watMeterPulseArray[pin] ++;
    printlnToScreen("pin " + String(pin) + "=" + String(watMeterPulseArray[pin]));
  }
}
void incrementWatMeter1() {
  checkAndVerifyPulse(0);
}
void incrementWatMeter2() {
  checkAndVerifyPulse(1);
}
void incrementWatMeter3() {
  checkAndVerifyPulse(2);
}
void incrementWatMeter4() {
  checkAndVerifyPulse(3);
}
void incrementWatMeter5() {
  checkAndVerifyPulse(4);
}

void incrementWatMeter6() {
  checkAndVerifyPulse(5);
}

void incrementWatMeter7() {
  checkAndVerifyPulse(6);
}

void setup() {
  debugSerial.begin(115200);
  // If debugSerial is available(device connected to PC) set debug
  while (!debugSerial && millis() < 10000) ;
  if (millis() < 10000) {
    DEBUG = 1;
  }

  delay(100);

  pinMode(WATER_METER_1, INPUT_PULLDOWN);
  pinMode(WATER_METER_2, INPUT_PULLDOWN);
  pinMode(WATER_METER_3, INPUT_PULLDOWN);
  pinMode(WATER_METER_4, INPUT_PULLDOWN);
  pinMode(WATER_METER_5, INPUT_PULLDOWN);
  pinMode(WATER_METER_6, INPUT_PULLDOWN);
  pinMode(WATER_METER_7, INPUT_PULLDOWN);

  attachInterrupt(digitalPinToInterrupt(WATER_METER_1), incrementWatMeter1, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_2), incrementWatMeter2, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_3), incrementWatMeter3, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_4), incrementWatMeter4, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_5), incrementWatMeter5, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_6), incrementWatMeter6, RISING);
  attachInterrupt(digitalPinToInterrupt(WATER_METER_7), incrementWatMeter7, RISING);

  delay(100);
}

void loop() {

}

// If Serial port is available on PC, print message to screen
void printToScreen (String message) {
  if (DEBUG) {
    debugSerial.print(message);
  }
}
void printlnToScreen (String message) {
  if (DEBUG) {
    debugSerial.println(message);
  }
}```

What is the value of the pull down resistor used?

I used 10k Ohm for pull down resistor


text:
Creating a Library Help with errors
I am attempting to create a library out of an existing code to use inside of another code.  To clarify, I have one code, I need to add the functionality of another code to.  Instead of plopping the 400+ lines inside of my existing code, I would like to create a library to house the other code so I can make my code easier to read.  I followed the Arduino Library tutorial to get to where I am, but their code is simpler than mine.  Ironically, my code is also about Morse code.  I have included the library files and the code I am using to troubleshoot.  I have attempted to troubleshoot these errors on my own by googling problems, I managed to cut the list about in half, but I just can't seem to root out these last few.
I am posting in this order: Morse.cpp, Morse.h, Library Test Code, The errors I need help with (all of which relate to the above three files) and the functioning code as it was before I tried to create this library.
The Following is the Morse.cpp Library File
/* Morse.cpp - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#include "Arduino.h"
#include "Morse.h"

Morse::Morse(int LED);
{
pinMode(LED, OUTPUT);
_LED = LED;
}
Morse::Morse(int BEEP);
{
pinMode(BEEP, OUTPUT);
_BEEP = BEEP;
}

_note = 587;

_dotLen = 75;

_dashLen = dotLen * 7;

_elemPause = dotLen * 4;

_Spaces = dotLen * 10;

_wordPause = dotLen * 14;

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

void Morse::MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);     // start playing a tone
delay(dotLen);                // hold in this position
}

void Morse::MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);    // start playing a tone
delay(dashLen);               // hold in this position
}

void Morse::LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position
}

digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

void Morse::GetChar(char tmpChar)
{
// Take the passed character and use a switch to find the morse code for that character
switch (tmpChar) {
    case 'a':
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        break;
    case 'b':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
    case 'c':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
/*This continues for the rest of the alphabet as well as numbers and characters,
however to save space and time I have only listed a,b, and c */

The following is the Morse.h Library file
/* Morse.h - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#ifndef Morse_h
#define Morse_h

#include "Arduino.h"

class Morse
{
public:
Morse(int LED, int BEEP, int delayTime, char tmpChar);

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

private:
int _LED;
int _BEEP;
int _delayTime;
char _tmpChar;
int _note;
int _dotLen;
int _dashLen;
int _elemPause;
int _Spaces;
int _wordPause;
};

#endif

The following is the test code
#include <Morse.h>

int delayTime;
int tmpChar;

Morse dot();
Morse dash();
Morse dark(int delayTime);
Morse set(char tmpChar);

char stringToMorseCode[] = "N 36° 00.19518   W 084° 13.88856";    //Final Coordinates

// Create variable to define the output pins
int LED = 13;      // blink an led on output 12
int BEEP = 14;      // output audio on pin 8
int i;

void setup()
{

}

void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++);
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
set.GetChar(tmpChar);
}

// At the end of the string long pledause before looping and starting again

dark.LightsOff(8000);            // hold in this position

}

These are the errors I get when I run this code.
/Users/DMYoung1/Documents/Arduino/Morse_Library_Test/Morse_Library_Test.ino: In function 'void loop()':
Morse_Library_Test:33: error: request for member 'GetChar' in 'set', which is of non-class type 'Morse(char)'
   set.GetChar(tmpChar);
       ^
Morse_Library_Test:38: error: request for member 'LightsOff' in 'dark', which is of non-class type 'Morse(int)'
 dark.LightsOff(8000);            // hold in this position
      ^
exit status 1
request for member 'GetChar' in 'set', which is of non-class type 'Morse(char)'

In case this will also help, this is the original code which I know works.  Hopefully this could help someone else understand the transformation of a slightly more complicated morse reader code into a library, so please feel free to respond as though I know nothing.  It will help me and could help someone else.
/*
Morse Code Project
This code will loop through a string of characters and convert these to morse code.
It will blink an LED light and play an audible tone on a piezo speaker.
*/

char stringToMorseCode[] = "Convert to Morse"; //String to Convert

// Create variable to define the output pins
int led13 = 1;      // blink an led on output 12
//int led6 = 0;        // blink an led on output 6
int BEEP = 0;      // output audio on pin 8
int note = 587;      // music note/pitch

/*
Set the speed of your morse code
Adjust the 'dotlen' length to speed up or slow down your morse code
(all of the other lengths are based on the dotlen)

Here are the ratios code elements:
Dash length = Dot length x 3
Pause between elements = Dot length
(pause between dots and dashes within the character)
Pause between characters = Dot length x 3
Pause between words = Dot length x 7

*/
int dotLen = 75;     // length of the morse code 'dot'
int dashLen = dotLen * 7;    // length of the morse code 'dash'
int elemPause = dotLen * 4;  // length of the pause between elements of a character
int Spaces = dotLen * 10;     // length of the spaces between characters
int wordPause = dotLen * 14;  // length of the pause between words

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output for LED lights.
pinMode(led13, OUTPUT);
pinMode(BEEP, OUTPUT);

}

// Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
GetChar(tmpChar);
}

// At the end of the string long pause before looping and starting again
LightsOff(8000);
}

// DOT
void MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);   // start playing a tone
delay(dotLen);              // hold in this position
}

// DASH
void MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);   // start playing a tone
delay(dashLen);               // hold in this position
}

// Turn Off
void LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

}

// *** Characters to Morse Code Conversion *** //
void GetChar(char tmpChar)
{
// Take the passed character and use a switch case to find the morse code for that character
switch (tmpChar) {
case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'b':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;

//Again, this switch case would continue through the alphabet, but I am stopping
//here because that would dramatically increase the length of this page

The problem is that you are trying to call a class function without an object (hence the error). The original code works because the functions are created without a class. When you add the class (in the library), you need to create an object to perform those functions with it. To do this, use the constructor className object(parameters)
So in your case, you'd do Morse Object(LEDpin)
To use your functions you can now do Object.Function(parameters)

I read about this, I just couldn't figure out how to fix it!!  I understand everything you have told me except for the parameters.  What / how should I set those?

Let me rephrase, I understand conceptually everything you have told me and I really appreciate your response.  I'm afraid I just can't seem to make the connection from concept to my code.  I have been reading about objects and function parameters, I just can't seem to understand how to actually implement them.  For example, should I put this code in the library file?  Or does it go in my program code?  Either way, how should I proceed.  When I said treat me like I know nothing, I really don't know anything about this, but I can't learn if I don't try.

There is this thing called a 'class constructor'. You can look it up for a more detailed explanation, but basically you have a function without a type inside your class, named the same thing as your class. You have a couple of them, Morse() - I would combine them into one Morse() with a bunch of parameters. Basically, when you create the object Morse() will automatically run, using the parameters you put in where I said. I would look it up - I'm not sure I explained it that well!

Great, I will look it up and if I get stuck I will post back here, probably in a few hours.  Thanks for the help so far!!

I have fixed it would seem all the errors I had before, but I have two more they are both the same, but relate to different members in objects.  These seem to be common errors as I have been able to read a great deal about other people's troubles with them, but I seem to be unable to diagnose their problems or mine.  The errors are as follows:

I have edited the code and errors in the question to reflect the new issues.

So now we have an answer which is accepted but it's not any more related to the question as the question has been changed... I'm not sure this is the right way to use SE

source: Stack Exchange

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

sort: votes


text:
Help Improving Debouncing
In short, I am attempting to debounce several buttons using something like a while loop instead of delays.
This code runs in a box with a series of buttons on it, if the correct sequence of buttons is pressed, then the arduino will run a flashing LED sequence and open a solenoid.  There are two correct sequences, a "right" answer (Green LED), and a master code (Blue LED).  Anything else results in the failed sequence (Red LED).  The problem I am currently having is that my current debouncing system is very finicky, I would like to implement something allowing more flexibility for speed of button press etc.
The problem currently is I am relying on delay to debounce.  If I delay long enough it becomes difficult to type the correct code in because the user has to know to wait a certain amount of time before pressing the next key.  If I do not delay long enough my combination is regularly corrupted  with extraneous button pushes.
Below is my code, The debouncing occurs on lines 128-160.  Below that is a lot of LED flashing.
#define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
#define CPU_RESTART_VAL 0x5FA0004
#define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

const int button5 = 2;    //fifth  button is on pin 2
const int button4 = 3;    //fourth button is on pin 3
const int button3 = 4;    //third  button is on pin 4
const int button2 = 5;    //second button is on pin 5
const int button1 = 6;    //first  button is on pin 6
const int systemLED = 7;  //Red LED on front of Box (Power Indicator)
const int redLed1 = 8;    //red LED is on pin 7
const int greenLed1 = 9;  //green LED is on pin 8
const int blueLed1 = 10;   //blue LED is on pin 9
const int redLed2 = 11;   //red LED is on pin 10
const int greenLed2 = 12; //green LED is on pin 11
const int blueLed2 = 13;  //blue LED is on pin 12
const int solenoid = 14;  //activates solenoid Relay Circuit
const int relay2 = 15;     // >:-}

int code[] = {1,2,3,4,5}; //the desired code is entered in this array, separated by commas

int entered[5]; //create a new empty array for the code entered by the user (has 4 elements)

void setup(){ //run once at sketch startup
  Serial.begin(9600); //begin Serial
  pinMode(systemLED, OUTPUT);
  pinMode(button1, INPUT); //button 1 is an input
  pinMode(button2, INPUT); //button 2 is an input
  pinMode(button3, INPUT); //button 3 is an input
  pinMode(button4, INPUT); //button 4 is an input
  pinMode(button5, INPUT); //button 5 is an input
  pinMode(redLed1, OUTPUT); //the red LED is an output
  pinMode(redLed2, OUTPUT); //the red LED is an output
  pinMode(greenLed1, OUTPUT); // the green LED is an output
  pinMode(greenLed2, OUTPUT); // the green LED is an output
  pinMode(blueLed1, OUTPUT);
  pinMode(blueLed2, OUTPUT);
  pinMode(relay2, INPUT_PULLUP); //enable relay outputs as input_pullup in order to prevent triggering when initial power is provided
  pinMode(solenoid, INPUT_PULLUP);

  delay(500);

  pinMode(relay2, OUTPUT);   //convert pinmode for relay back to operable mode
  pinMode(solenoid, OUTPUT);//this prevents the relay and relay2 from triggering at startup

  digitalWrite(relay2, HIGH);
  digitalWrite(solenoid, HIGH);

  digitalWrite(blueLed1, HIGH); //turn both
  digitalWrite(greenLed1, HIGH);
  digitalWrite(blueLed2, HIGH);
  digitalWrite(greenLed2, HIGH); //LEDs on
  delay(100); //wait
  digitalWrite(blueLed1, LOW); //turn both
  digitalWrite(greenLed1, LOW);
  digitalWrite(blueLed2, LOW);
  digitalWrite(greenLed2, LOW); //LEDs off
  digitalWrite(systemLED, HIGH); //turn the red LED on
  delay(75); //wait

  for (int i = 0; i < 5;i++){ //work through numbers 0-4
    Serial.println(code[i]); //print each digit of the code
    Serial.println(entered[i]); //print each element of the entered[] array (this was for me to check that it started at 0)
  }
}

void checkEntered1(int button /* define the 1,2,3 or 4 as an integer called button */){ //check the first element of the entered[] array
  if (entered[0] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered2(button); //move on to checkEntered2, passing it "button"
  }

  else if(entered[0] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[0] = button; //set the first element as the button that has been pressed
    Serial.print("1: ");Serial.println(entered[0]); //for debugging
  }
}

void checkEntered2(int button){ //check the second element of the entered[] array
  if (entered[1] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered3(button); //move on to checkEntered3, passing it "button"
  }

  else if(entered[1] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[1] = button; //set the second element as the button that has been pressed
    Serial.print("2: ");Serial.println(entered[1]); //for debugging
  }
}

void checkEntered3(int button){  //check the third element of the entered[] array
  if (entered[2] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered4(button); //move on to checkEntered4, passing it "button"
  }

  else if (entered[2] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[2] = button; //set the third element as the button that has been pressed
    Serial.print("3: ");Serial.println(entered[2]); //for debugging
  }
}

void checkEntered4(int button){ //check the fourth element of the entered[] array
  if (entered[3] != 0){ //if it is not a zero, i.e. it has already been input
    checkEntered5(button); //set the final element as the button that has been pressed
  }

  else if (entered[3] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[3] = button; //set the fourth element as the button that has been pressed
    Serial.print("4: ");Serial.println(entered[3]); //for debugging
  }
}

This is where I need help debouncing, as can be seen I have attempted to debounce with delay(75) originally I had delay(1000) as the debounce which worked but required the user to wait or break normal rhythm while entering the code due to the long delay between inputs being accepted.
void checkEntered5(int button){ //check the fifth element of the entered[] array
  if (entered[4] == 0){ //if it is zero, i.e. if it hasn't been defined with a button yet
    entered[4] = button; //set the final element as the button that has been pressed
    Serial.print("5: ");Serial.println(entered[4]); //for debugging
    delay(100); //allow time for processing
    compareCode(); //call the compareCode function
  }
}
void loop(){ //run repeatedly
  if (digitalRead(button1) == HIGH){ //if button1 is pressed
    checkEntered1(1); //call checkEntered and pass it a 1
    //delay(1000); //wait
    while( digitalRead(button1) == HIGH) { } // do nothing
    delay(75);//wait, needed for correct functioning, otherwise
              //buttons are deemed to be pressed more than once
  }
  else if (digitalRead(button2) == HIGH){ //if button2 is pressed
    checkEntered1(2); //call checkEntered1 and pass it a 2
    //delay(1000); //wait
    while( digitalRead(button2) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button3) == HIGH){ //if button3 is pressed
    checkEntered1(3); //call checkEntered1 and pass it a 3
    //delay(1000); //wait
    while( digitalRead(button3) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button4) == HIGH){ //if button4 is pressed
    checkEntered1(4); //call checkEntered1 and pass it a 4
    //delay(1000); //wait
    while( digitalRead(button4) == HIGH) { } // do nothing
    delay(75); //wait
  }
  else if (digitalRead(button5) == HIGH){ //if button4 is pressed
    checkEntered1(5); //call checkEntered1 and pass it a 5
    //delay(1000); //wait
    while( digitalRead(button5) == HIGH) { } // do nothing
    delay(75); //wait
  }
}

Everything below this point is included simply to provide context for the check entered code seen above.  Everything functions as is expected except that the debounce is imperfect.
void compareCode(){ //checks if the code entered is correct by comparing the code[] array with the entered[] array
  for (int i = 0; i<4;i++){
    Serial.write(entered[i]);
  }
  if ((entered[0]==code[0]) && (entered[1]==code[1]) && (entered[2]==code[2]) && (entered[3]==code[3]) && (entered[4]==code[4])){ //if all the elements of each array match the passcode

    //--. .-. . . -.

    digitalWrite(solenoid, LOW);
    digitalWrite(greenLed1, HIGH); //turn the green LED on
    digitalWrite(greenLed2, HIGH); //turn the green LED on
    delay(50); //wait for a bit
    digitalWrite(greenLed1, LOW); //turn the green LED off
    digitalWrite(greenLed2, LOW); //turn the green LED off
    delay(500);
    digitalWrite(solenoid, HIGH);
    delay(2500);

  }

  else if ((entered[0]==code[4]) && (entered[1]==code[2]) && (entered[2]==code[0]) && (entered[3]==code[3]) && (entered[4]==code[1])){

    //-... .-.. ..- .

    digitalWrite(blueLed1, HIGH);
    digitalWrite(blueLed2, HIGH);
    delay(1000);
    digitalWrite(solenoid, LOW);
    delay(4000);
    digitalWrite(blueLed1, LOW);
    digitalWrite(blueLed2, LOW);
    delay(50);
    digitalWrite(redLed1, HIGH);
    digitalWrite(redLed2, HIGH);
    delay(1000);
    digitalWrite(redLed1, LOW);
    digitalWrite(redLed2, LOW);
    delay(50);
    digitalWrite(solenoid, HIGH);
    delay(1000);
  }

  else { //if you (or the intruder) get the code wrong
    flash(); //call the flash function
    for (int i = 0; i < 4; i++){ //this next loop is for debugging
      entered[i] = 0;
      Serial.println(entered[i]);
    }
  }
}

void flash(){ // this is basically the blink example
  //.-. . -..

  digitalWrite(relay2, LOW);
  digitalWrite(redLed1, HIGH);
  digitalWrite(redLed2, HIGH);
  delay(50);
  digitalWrite(redLed1, LOW);
  digitalWrite(redLed2, LOW);
  delay(250);
  digitalWrite(redLed1, HIGH);
  digitalWrite(redLed2, HIGH);
  delay(50);
  digitalWrite(redLed1, LOW);
  digitalWrite(redLed2, LOW);
  digitalWrite(relay2, HIGH);
  delay(2500);
  CPU_RESTART;

If you want to solve the denouncing problem, make a simpler sketch that only accepts input, and maybe outputs the result to the serial monitor.  On the other hand if you can accept input in isolation and the issue seems more in the interaction with your input vs. display code, see if you can make a simpler case (fewer outputs, etc) that illustrates the interaction.  At present this is still too big to be readily understood, but is it possible you may have a situation where each distinct user input triggers a time-consuming sequence of output operations?

I believe I understand you, however I may have phrased my question poorly, I am simply looking to see if anyone knows of a simple method of debouncing which is more reliable than the delay function.  This code is adapted from someone else's which I found a long time ago, I do not entirely understand the intricacies of it to simplify on my own.

The simplest means of debouncing is that once you have any input you will accept, you ignore all inputs for some fraction of a second.  If you also trigger time consuming operations from the inputs is when that gets complicated - simplest there is to not accept new input until they are done, but the user may not enjoy that.  Or if you need to recognize a different button immediately and only have a debounce delay to the same button. Or if you want to have auto-repeate if a button is held down long enough.

    while( digitalRead(button2) == HIGH) { } // do nothing

Doing that right after a digital read assumes there is only one bounce, That's highly unlikely. I would put the delay right after the read and before the delay. Depending on the type of switch bouncing varies, but shouldn't be over 150mS. Less for the little tactile push button used on pcboards.
    // read button
    delay(75); //wait
    while( digitalRead(button2) == HIGH) { } // do nothing

You can always use an RC filter to debounce each button, then you don't have to worry about the difficult key presses, just the extra parts and expense.

Many of the lines shown in the program box are superfluous – totally redundant and unnecessary.  I suggest that you revise it [see (a)-(d) below], then replace all the stuff in the program box with the revised version.
(a) Use more subroutine parameters.  In cases where you have four or five otherwise-identical routines that differ only in some constants, pass those values into one routine as parameters.  Don't write out long lists of nearly-identical routines.
(b) Don't create artificial dependencies.  Your code in the five checkEntered- routines is obscure, so I can't say without taking more time than I care to spend, but it appears that you have made tests for button 2 depend on tests for button 1, and so on down the line.  That makes no sense.  Test each button separately and in an identical manner, using a parameterized subroutine.  To enforce an order of button presses, create an array P of 5 bytes (or however many you like) and initialize a counter Q to zero.  Whenever your debounce routine detects a valid button press, if Q is small enough store the button number in P[Q] and then increase Q.  (If Q is (size P) or more, don't store.)
(c) Don't nest subroutine calls more deeply than necessary.  Your checkEntered1() can call checkEntered2(), which can call checkEntered3(), and so forth.  Besides not making sense, that series of calls uses five times as much stack memory as necessary.  (Generally, RAM is a scarce resource on AVR microcontrollers.)  Just use five calls, one after another, to a properly parameterized subroutine.
(d) For repetitious sequences like the following,
digitalWrite(greenLed1, HIGH); //turn the green LED on
digitalWrite(greenLed2, HIGH); //turn the green LED on
delay(1000); //wait for a bit
digitalWrite(greenLed1, LOW); //turn the green LED off
digitalWrite(greenLed2, LOW); //turn the green LED off
delay(250); //wait for a bit

which seem to recur with minor variations about a dozen times, write a properly parameterized subroutine and call it as necessary.  For example:
void flashPair(byte L1, byte L2, int del1, int del2) {
  digitalWrite(L1, HIGH);   // turn the green LED on
  digitalWrite(L2, HIGH);   // turn the green LED on
  delay(del1);          // wait a little
  digitalWrite(L1, LOW);    // turn the green LED off
  digitalWrite(L2, LOW);    // turn the green LED off
  delay(del2);          // wait a little
}
...
flashPair(greenLed1, greenLed2, 1000, 250);
flashPair(redLed1,   redLed2,     50, 2500);
...

There are, of course, other ways of handling those dozen tedious repetitions.  For example, one could write a for loop that gets pin numbers and delays from an array and turns LEDs on or off as needed.
For example, see an answer to question 17453 for a method of treating multiple buttons systematically using information in arrays along with a for loop.

I have used and know of many others who use the Bounce2 Library to provide an easy way to debounce the switch without using any delays so the user wouldn't have to pause between presses. Behind the scenes it uses the Millis function to provide the debounce which doesn't interrupt the sketch running at all. You could also write the Debounce with Millis function yourself.

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


text:
Can I create a serial.read command with the arduino code alone?
I am trying to manipulate a project and the simplest way to do what I am trying to do would be to use the existing code.  This code is designed to take an input from the serial monitor using serial.read() and manipulate it.  For example if I type hello into the serial monitor's command bar, the code would read it and manipulate it.  I was wondering if there is any way to create a serial command to run in the code which would act in a way as to bypass the serial monitor since this project is not going to be connected to a computer when it is in use.  The command will be the same every time and will be in response to a single switch input.
#include <avr/pgmspace.h>
#include <MorseEnDecoder.h>
#include <stdio.h>

// Pin mapping
const byte morseInPin = 7;
const byte morseOutPin = 13;
String check = "";
String origin = "S";
const int maxItems = 3;
char myStr[] = "Help is Coming";
int x;
char myArray[maxItems], curChar;
char nextChar;
int i;
int y;

// Instantiate Morse objects
morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
morseEncoder morseOutput(morseOutPin);

// Variables dealing with formatting the output somewhat
// by inserting CR's (carriage returns)
long lastTransmissionTime;
long currentTime;
boolean transmissionEnded = true; // Flag to mark old trans finished

// Minimum transmission pause time to insert carriage returns (CR)
// Adjust depending on Morse spd. IE 13 wpm = 646 ms btw words (no CR).
const long transmissionPaused   = 1000; // Suitable for 13 wpm?

void setup()
{
Serial.begin(9600);
Serial.println("Morse EnDecoder Geocache");

// Setting Morse speed in wpm - words per minute
// If not set, 13 wpm is default anyway
morseInput.setspeed(5);
morseOutput.setspeed(5);

lastTransmissionTime = (long)millis();

}

void loop()
{
currentTime = (long)millis();

// Need to call these once per loop
morseInput.decode();
morseOutput.encode();

// SEND MORSE (OUTPUT)
// Encode and send text received from the serial port (serial monitor)
if (Serial.available() && morseOutput.available())
{
// Get character from serial and send as Morse code
char sendMorse = Serial.read();
morseOutput.write(sendMorse);

// Not strictly needed, but used to get morseSignalString before it is      destroyed
// (E.g. for morse training purposes)
morseOutput.encode();

// Also write sent character + Morse code to serial port/monitor
Serial.write(' ');
Serial.write(sendMorse);
// Morse code in morseSignalString is now backwards
for (int y=morseOutput.morseSignals; y>0; y--)
{
  Serial.write(morseOutput.morseSignalString[y-1]);
}
}

// RECEIVE MORSE (INPUT)
// If a character is decoded from the input, write it to serial port
if (morseInput.available())
{

char receivedMorse = morseInput.read();
//Serial.print(receivedMorse);
// A little error checking
if (receivedMorse == '#') Serial.println("< ERROR:too many morse   signals! >");
morseOutput.write('#');
morseOutput.encode();

//Create Array out of receivedMorse Chars

    curChar = 0;
    nextChar = receivedMorse;
    curChar +=nextChar;
    myArray[i] = curChar;
    check.concat(myArray[i]);
    Serial.println(check);

  //Check input and respond
  if (check == origin)
  {
Serial.println("check = origin");

// Encode and send text set in myStr[x]

for (x = 0; x < sizeof(myStr) - 1; x++)
{
char sendMorse = myStr[x];
morseOutput.write(sendMorse);

// Not strictly needed, but used to get morseSignalString before it is destroyed
// (E.g. for morse training purposes)
morseOutput.encode();

// Also write sent character + Morse code to serial port/monitor
Serial.write(' ');
Serial.write(sendMorse);
// Morse code in morseSignalString is now backwards
for (int y=morseOutput.morseSignals; y>0; y--)
{
Serial.write(morseOutput.morseSignalString[y-1]);
}
}

  }

 if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
 }
 // two strings not equal:
 if (check != origin) {

 }
 }

This is a morse code encoder and decoder.  I have adapted it to do a certain thing when a certain string of morse code is entered.  I am trying to get it to then encode and respond with a morse string, but the only way it is programmed to do such a thing is through the serial.read() command  There is a library that I am not sure how to attach, it can be found here
https://www.dropbox.com/s/eg21qmg0151gxz6/Morse_EnDecoder_2012.11.25.tar-2.gz?dl=0 this also includes all of the original codes.  My additions can be found directly under the comment //Create Array out of receivedMorse Chars and continuing to the bottom (The last 45 lines or so not including char, string, and int declarations).  I apologize if some of the edits I have made are hideous or "not in the spirit of the language".  I am a novice and a hobbyist.
The Code I have adapted will print my string exactly as it appears (myStr[]), however it will not encode it to Morse nor will it output it through the LED or the buzzer.  The 'serial.read()' command appears to work outside of my if statement, but really I have no idea how I would fix this.

Is the “switch input” (mentioned in last sentence) on your host computer or on an arduino?

The switch is an independent input into the arduino.  It is not on the computer, it will be built into the project assembly which includes the housing for the arduino board.

Perhaps you can edit your question. (1) Include the “existing code” in the question, using code-formatting to format it; (2) Say what the new program is supposed to do, rather than talking about “bypass the serial monitor”, which seems like a wrong approach; (3) indicate how many positions the switch will have or how many switches there are

I have added my code.  This code encodes and decodes Morse signals.  It will decode a morse input from a switch and output the text to the serial monitor.  It will also accept text from the serial monitor and output Morse code with and LED and Buzzer.  I have adapted the code to compare the input from the switch with a predetermined string and when they match to do XYZ.  In this case I want to output morse code through the LED and Buzzer, but I cannot figure out an alternative to the serial.read() command.  There is one switch, it is SPST switch in other words, it has on and off only.

The serial input is read into a variable.
You could comment out the serial read and assign whatever value you need directly to the variable.  By commenting out the serial read, you will have a marker of where you made the changes.
This should work since you are saying the inputs are known and do not change.

I'm afraid I forgot to mention that the response is several characters long, for example test could be a response or correct.  I am able to get the code to output a single character, but not the entire string.  I attempted to bypass this with a for loop which would increment a variable assigning it all values in the string, however it seems this did not work.  Could this be because the for loop runs entirely on a single loop of the main code?  Or does it only loop once per code cycle as well?

More importantly, this section is inside an if statement which is only triggered based on the switch input.  I believe this is why the code doesn't work.


text:
Debugging my created Library - Error - request for member ... which is of non-class type
This seems to be a very common error, I am struggling to understand what exactly the solution to this is.  I am attaching everything, library files, code, and errors.  If you have a moment, I need help with these two errors which appear to be caused by the same problem.  Fixing these errors may however not be the end of my problems so if you notice something else please point it out!!  I recognize my own incompetence regarding this topic any help will be appreciated.
This is a Morse Code Encoder, my goal is to transform the original functional code into a library so that I can insert it into another code more easily.
The Following is the Morse.h Library File (I created this with the Arduino Library Tutorial)
/* Morse.h - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#ifndef Morse_h
#define Morse_h

#include "Arduino.h"

class Morse
{
public:
Morse(int LED, int BEEP, int delayTime, char tmpChar);

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

private:
int _LED;
int _BEEP;
int _delayTime;
char _tmpChar;
int _note;
int _dotLen;
int _dashLen;
int _elemPause;
int _Spaces;
int _wordPause;
};

#endif

The following is the Morse.cpp Library (I created this with the Arduino Library Tutorial)
/* Morse.cpp - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#include "Arduino.h"
#include "Morse.h"

Morse::Morse(int LED);
{
pinMode(LED, OUTPUT);
_LED = LED;
}
Morse::Morse(int BEEP);
{
pinMode(BEEP, OUTPUT);
_BEEP = BEEP;
}

_note = 587;

_dotLen = 75;

_dashLen = dotLen * 7;

_elemPause = dotLen * 4;

_Spaces = dotLen * 10;

_wordPause = dotLen * 14;

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

void Morse::MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);     // start playing a tone
delay(dotLen);                // hold in this position
}

void Morse::MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);    // start playing a tone
delay(dashLen);               // hold in this position
}

void Morse::LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position
}

digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

void Morse::GetChar(char tmpChar)
{
// Take the passed character and use a switch to find the morse code for that character
switch (tmpChar) {
    case 'a':
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        break;
    case 'b':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
    case 'c':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
//This continues through z and then 0-9, I have shortened it hear for ease of
//reading.  Each break statement functions fine in the original code.

The following is the test code
#include <Morse.h>

int delayTime;
int tmpChar;

Morse dot();
Morse dash();
Morse dark(int delayTime);
Morse set(char tmpChar);

char stringToMorseCode[] = "String to be converted to morse code";

// Create variable to define the output pins
int LED = 13;      // blink an led on output 12
int BEEP = 14;      // output audio on pin 8
int i;

void setup()
{

}

void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++);
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
set.GetChar(tmpChar);
}

// At the end of the string long pledause before looping and starting again

dark.LightsOff(8000);            // hold in this position

}

These are the errors I get when I run this code.
/Users/Young1/Documents/Arduino/Morse_Library_Test/Morse_Library_Test.ino: In function 'void loop()':
Morse_Library_Test:31: error: request for member 'GetChar' in 'set', which is of non-class type 'Morse()'
set.GetChar(tmpChar);
    ^
Morse_Library_Test:36: error: request for member 'LightsOff' in 'dark', which is of non-class type 'Morse()'
dark.LightsOff(delayTime);            // hold in this position
     ^
exit status 1
request for member 'GetChar' in 'set', which is of non-class type 'Morse()'

This is an exercise for me in improving my own skills.  I have spent a day since my last issue (trying to call a class function without an object) researching my problems, however I have been unable to relate the variety of similar questions and answers to my own code.  It seems that most of them deal with a misplaced ().  If you find something that is wrong, please assume that I know nothing.  Post as though you are trying to teach a child how to use Arduino.
I am adding the original code which I am trying to transform into a library for the purpose of inserting it into another code without inserting all 453 lines.
/*
Morse Code Project

This code will loop through a string of characters and convert these to morse code.
It will blink two LED lights and play audio on a speaker.
*/

char stringToMorseCode[] = "String to convert to Morse";

// Create variable to define the output pins
int led13 = 1;      // blink an led on output 12
//int led6 = 0;        // blink an led on output 6
int BEEP = 0;      // output audio on pin 8
int note = 587;      // music note/pitch

/*
Set the speed of your morse code
Adjust the 'dotlen' length to speed up or slow down your morse code
(all of the other lengths are based on the dotlen)

Here are the ratios code elements:
Dash length = Dot length x 3
Pause between elements = Dot length
(pause between dots and dashes within the character)
Pause between characters = Dot length x 3
Pause between words = Dot length x 7
*/
int dotLen = 75;     // length of the morse code 'dot'
int dashLen = dotLen * 7;    // length of the morse code 'dash'
int elemPause = dotLen * 4;  // length of the pause between elements of a character
int Spaces = dotLen * 10;     // length of the spaces between characters
int wordPause = dotLen * 14;  // length of the pause between words

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output for LED lights.
pinMode(led13, OUTPUT);
pinMode(BEEP, OUTPUT);

}

// Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
GetChar(tmpChar);
}

// At the end of the string long pause before looping and starting again
LightsOff(8000);
}

// DOT
void MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);   // start playing a tone
delay(dotLen);              // hold in this position
}

// DASH
void MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);   // start playing a tone
delay(dashLen);               // hold in this position
}

// Turn Off
void LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

}

// *** Characters to Morse Code Conversion *** //
void GetChar(char tmpChar)
{
// Take the passed character and use a switch case to find the morse code for that character
switch (tmpChar) {
case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'b':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;

//This continues through z and then 0-9, but it adds a few hundred lines we
//don't need to read here.

The problem lies with your object instantiation. I will explain shortly - I am eating right now.

That's fine, I am not in a rush, after all I can't figure it out on my own!!

The main problem lies with your object instatiation:
int delayTime;
int tmpChar;

Morse dot();
Morse dash();
Morse dark(int delayTime);
Morse set(char tmpChar);

Morse has a constructor format thus:
Morse(int LED, int BEEP, int delayTime, char tmpChar);

When you instantiate an object from a class and call the constructor you have to pass all the parameters to the constructor (unless they have been given a default value, in which case you can leave them out from the right-most only).
You never provide () if there are no parameters needed for the constructor - this is a little idiom of C++ that I have never understood.  To break it down:
Morse dot();
Morse dash();

These have no parameters being passed. Lose the () if that  is intentional (and you have a matching constructor with no parameters) or add the four parameters for the constructor.
Morse dark(int delayTime);
Morse set(char tmpChar);

In these two you are trying to pass one parameter only, and for some reason you are also trying to give it a type at the same time. I can only think that it may be to try and indicate which parameter you mean. That is not right. You must provide all the parameters. Also you are passing values from variables that haven't been given a value yet, so it is actually completely meaningless.
I am not entirely sure what you are hoping to achieve with those last two there...
A further issue, digging into your actual class, is these odd constructors:
Morse::Morse(int LED);
{
pinMode(LED, OUTPUT);
_LED = LED;
}
Morse::Morse(int BEEP);
{
pinMode(BEEP, OUTPUT);
_BEEP = BEEP;
}

They have no matching prototype in the class header, and even if they did, the compiler will have no way of differentiating between them. They both have the same type (int). Overloading operates on the type, not the name of the variable.
Oh, and the one constructor you do have a prototype for just plain doesn't exist in your code.

I have no idea what I am doing, I have just tried to compare this to the Library tutorial, and well, my ignorance is obvious, thank you for the help.  If you don't mind, could you explain to me how to use parameters?  I understand I can pass a value, but not much more than that.  I will upload the original code, but essentially, it takes a string, assigns a temporary character to each value incrementally, then calls each switch break command that corresponds with the character in the string thus outputting an encoded morse string which represents the original string.

@user26383 http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

Wish I had stumbled upon this yesterday!!


text:
How much maximum current do the Arduino Wemos D1 (R1 & R2) consume?
I have been powering my WeMos D1 R1 and D1 R2 Arduinos (with ESP8266) using a simple USB cable connected to a standard charger whose rating is 3.1 amps.  Is this sufficient to charge two such Arduino boards (it has two USB slots) simultaneously?
Also, should I be using the other Power Input which I understand is 9V?
All the specs I have seen specify the voltage but not the current usage.
Either way, what is the maximum amperage that the board might need/is rated for?  Is it different for the R1 vs. R2?  Is it possible to measure how much it is using from any of the pins?

an USB 2 port gives max 500 mA. so 3.1 A should be more than enough.

You can use a USB meter like this.

It is possible to measure how much it is using from any of the pins?

Put an ammeter (multimeter in current mode) in series with the power supply and measure it, when configured in the way you intend to use it.

Good suggestion, but it will be hard to do without splicing the USB cable.  Now this becomes a project! :-) If I were to do that, which would be the right wire to put the multimeter on?

Just about every USB wire I've cut into contain a red (+5V) black (ground) and green & white (data).  You can cut either the black or red wire in such a cable and insert an amp meter.  Note, always try the high Amp meter first! When you are confident you can not read a current because it is too small, then switch to the mA meter configuration. That said, there are many Common Off The Shelf (COTS) USB devices that measure Amperage.

I will do that.  Meanwhile, is there any place a maximum rating is specified?

I believe USB 2.0's maximum is 500mA. Other USB definitions exist.  Later versions of USB exist. Some companies have done odd things to detect and support higher current capabilities.  And then there is negotiations between the USB peripheral and USB host. You are going to have to do some digging for your specific situation.

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


text:
How to get version of Arduino board remotely
I have multiple Arduino WeMos D1 boards, with a mix of versions bought months apart.  One of these boards is working but I need to update it and I am not sure if it is R1 or R2 (the pinouts are different).  I do not have physical access to it (it is 200+ miles away in an area that is locked down) but I can connect through another device over WiFi.
It has the following included:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include <WiFiUdp.h>
#include <ArduinoOTA.h>

So, I can even browse to a Webserver to run commands.  How can I add to the code (or even replace it) to return a value that tells me which version the board is?  According to this you can do it with an AT command, but I am not sure how to pass an AT command from the WebServer interface (or any other way).
EDIT: I guess I may have confused the issue with my phrasing.  I can connect to the board and upload a new sketch (using OTA).  My question is, can I put something in a new sketch to determine the board details and upload it.  Once I get that, I can then put in a the actual sketch that I want.

If you upload your own sketch it replaces the AT firmware. Do you have the original code you burned to it? That would indicate (based on pin defs) which version--in hindsight, it's always a good idea to track what software goes onto which board, e.g., by MAC address or sthng.

the AT command is for AT firmware version, not for board id. the software running on esp8266 doesn't have to know the pinout of the board. io 5 is still io 5 no matter where it is on board's headers. so unless you have something special in your sketch what tells you the version of board set at compilation, there is no way to know if it is a D1 (R1) or D1 R2

@Juraj The two versions use different ESP8266 modules - 12B/E vs 12F. There may be a way (in software) to find that out.

you could replace the sketch with a new simple one that compares the boards config names to a numeric literal, ex: if(D4==2){...}. Make sure you have OTA on your test sketch. Then reflash the board with the current sketch. This is why I moved to an interpreted language on top of arduino c: you can see the code from SPIFFS in plain text, edit it from the web, and re-run, all w/o flahsing.

@dandavis Can you elaborate?  Which language?  Links?

@Majenko that sounds promising.  Perhaps that AT command or similar that I linked to? But how do I use it?

@Majenko and Chiwda, not with currently uploaded sketch. but I doubt it with any program. it is still the same esp8266 chip. you may get the serial number but I am not sure if that would help you.

I don't need to do it with the currently uploaded sketch!  I can upload a new one (as I said in my question "...or even replace it...") and then, when I have determined the correct version, put the correct sketch back on there.

I think about all you'd be able to do is exercise the board itself, e.g., is something connected to some pin, that's different on the two versions you created. Or if the code allows you to read the code that's on the board you might be able to reverse-engineer it to figure out what pins are defined as what. It's super-important to understand what code is deployed where. The easiest solution is to have somebody take a picture of it and send it to you.

dave is on the right track about reading the hex back off.  search "rip code off arduino" to find a forum post that may be relevant.  Once you have it, compare to your code's builds

There's nothing you can do with your currently loaded sketch. The board can only do exactly what you have programmed it to do and nothing more.

There are no "AT" commands. They only exist if you load the AT firmware instead of your own firmware
You can't magically make your code do things it wasn't programmed to do1

However the only real differences between the two boards is the version of the ESP8266 module in use: ESP-12E vs ESP-12F, (and the only difference between those modules is the layout of the PCB antenna in order to achieve FCC certification) and the addition of some unpopulated serial and I2C pins.
Aside from that the only other differences are purely cosmetic or of no consequence to your software.
So it really doesn't matter which board you have or which you compile your code for.

1: Unless you can cause some buffer overflow and inject new code into memory to execute, but to do that you'd need to be a l33t h4x0r.

Addendum:
It appears they have two boards, named the same, with different pin arrangements (both sadly very stupidly designed, but there you are).  All I can suggest is compile for one, install it, and see if it works. If it doesn't, then compile for the other and see if that works.
Or compile some special firmware that will probe what you have attached and work out what is attached where - then install and run that.

the problem is that on the same header pin R1 has a different io pin then R2.

@Juraj Well that's stupid of them, isn't it? TBH the pinouts of both boards are just stupid, since there are far more "pins" than the ESP8266 actually has, so the pinout is pretty much meaningless.

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


text:
Making three led's blink at different times in Arduino
I have a breadboard connected to an Arduino Uno, 220k resistors connected to an led, of course it has a common ground and a pin connected to 5v. All pins are digital.
Now, I want led 1 to turn on for one second, the next led for two seconds and the next for three seconds, but that means, when the second led which has to be on for two seconds then the first led will come back on after one second has past on the second led, the third led would be on for three seconds, so the second led will also be on when two seconds pass and the first would be on when one second passes. So basically, all leds are on for their given duration.
How do I do this? I have been trying to do this since three days. It would be a pleasure if someone helps me out. Thanks.
int ledPin1= 2;
int ledPin2 = 4;
int ledPin3 = 7;

void setup(){
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  }

  void loop(){
  digitalWrite(ledPin1, HIGH);
  delay(500);
  digitalWrite(ledPin1, LOW);
  delay(500);

  digitalWrite(ledPin2, HIGH);
  delay(1000);
  digitalWrite(ledPin2, LOW);
  delay(1000);

  digitalWrite(ledPin3, HIGH);
  delay(1500);
  digitalWrite(ledPin3, LOW);
  delay(1500);
    }

So far this is the code. But it delays the whole program. Need leds on at given times.

What exactly is not working ? can you post the code you have tried so far ? Are you able to light On at least one LED ? (220k resistor seems much to me, usually it's somethink arround 330Ohm depending on the choosen LED)

Sorry 220 ohms, sorry my mind was somewhere else, yes I can switch on LED's and stuff but I need it in this pattern

Using a 220k Ohm resistor will lead to approximatively 20µA to light the LED. This is not enough to light the LED, you should replace the resitor by one of value 330Ohm (220 to 470 could be OK depending of the LED)

Sorry, the resistor is 220ohms,

Seems like you want a pattern like this ?
LED1 : 1 0 1 0 1 0 1 0 1 0 1 0 ... repeat
LED2 : 1 1 0 0 1 1 0 0 1 1 0 0 ... repeat
LED3 : 1 1 1 0 0 0 1 1 1 0 0 0 ... repeat

In which case you'll need something like this pseudo code
// set up the relevant pins as output etc
....
// set up a counter
counter = 0

loop
  toggle LED1
  if (counter modulo 2 == 0) then toggle LED2
  if (counter modulo 3 == 0) then toggle LED3

  counter++
  if counter > 11 then counter = 0 // your pattern repeats every 12 seconds

  delay for 1 second

Toggling the LED is just a case of checking if it is high or low and setting it to the opposite value.


text:
LM393 Speed sensor - Counting pulses
I'm trying to calculate the rotation speed of a DC motor.
I'm using the sensor shown in the picture and a slotted disk attached to the motor. The results I was getting made no sense and after several tests I realised the following:
Most of the times I manually blocked or unblocked the sensor, two pulses were counted. That would mean that for each tooth of the slotted disk, up to four pulses were counted instead of one.
Below is a test code. I count pulses on the interrupt handler and reset the counter when calculating the motor speed.
Am I doing something wrong or is the sensor suffering from bouncing signals?
    int encoderCounter = 0;
    int encoderDiscSlots = 21;

    int encoderPin = 19;

    void encoderIncrementISR()
    {
      encoderCounter++;
    }

    double calculateMotorSpeed(int interval)
    {
      Serial.print("enc ");
      Serial.println(encoderCounter);
      double rpm = (encoderCounter*1.0/encoderDiscSlots)*60000/interval;

      encoderCounter = 0;
      return rpm;
    }

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

      pinMode(encoderPin, INPUT_PULLUP);

      attachInterrupt(digitalPinToInterrupt(encoderPin), encoderIncrementISR, RISING);
    }

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

      delay(1000);
      double rpm = calculateMotorSpeed(1000);
      Serial.print("rpm ");
      Serial.println(rpm);
    }

The sensor uses the LM393 IC from TI, a spec sheet can be found here

the picture does not tell us anything about the sensor, other than validating the type of the sensor .... please add a link to the datasheet in you question above

@jsotola added aditional sensor information to the question.

I've done some more search on the interwebs and found someone (in Spanish) describing the same problem. That person owns an oscilloscope and could confirm that there is some bouncing on the data signal both going up and down.
The hardware solution presented is to place a 100 nF capacitor between the signal pin and ground.
I've tried it and it works.


text:
A proper way to get the roll, pitch and yaw values
TL, DR : What is the method (in terms of sensors and algorithm) to get the roll, pitch angles of an aircraft at any instant?
I am planning to build a hobby aircraft. I am so confused about which kind of sensors should I use and how to use them in order to get the roll, pitch and yaw angles of the aircraft.
I think I also have some problems understanding the concept. I consider these P, R, Y angles similar to the x,y,z coordinates as if they are able to describe the attitude of a body. If something in the below list contains "nonsense" arguments, please also enlighten me about them.
What I want is to be able to know at any instant:

What is the pitch angle of the aircraft, i.e how much degrees its nose pointing away from the horizontal plane of the earth.
What is the yaw angle, i.e to what direction(north, east etc) is the aircraft pointing through.
What is the roll angle, i.e what is the angle between aircrafts body surface ( wing to wing x tail to head surface ) and the horizontal plane of the earth/sky.

In some sources there is something going on as the importance of order of the application of roll, pitch and yaw. But I cannot understand why this is related.
I have used accelerometer values by inputting them into some formulas on the internet (those arctangent formulas, which everybody uses but nobody explains well) to get the roll and pitch values. However could not understand how to manipulate them in order to meet my requirements (different axis orientations of the sensor).
I also have basic understanding about what a gyroscope is.
I have an MPU6050(Accelerometer+Gyroscope).
P.S : my goal is to build a quadcopter but I guess in order to understand these concepts a fixed wing standard plane model.

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.
First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.
Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis:
Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.
This is different from the last result: order of rotation matters.

I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).
When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).
As you can see from the following image, the angle of rotation θ = atan2(x, z).

The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).
Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.
Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used Sebastian Madgwick's algorithm for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.
Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.
Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.
It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.
If you want to, you can also get the quaternion from the acceleration vector directly:
    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
         * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
         * where (x y z) is a unit vector representing the axis about which
         * the body is rotated; ϑ is the angle by which it is rotated.
         *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
         * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
         */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }

Well, what can I say, a very well explained answer. Thanks a lot.

One another mystery for me also related to something in your answer: while z axis is pointing upwards and xy plane is level, the accelerometer outputs +g in z component. But you mentioned it to be as -g. So how should I interpret the output of an accelerometer? As gravitional acceleration or the imaginary acceleration due to normal force act on the body?

@muyustan I usually just add minus signs to the appropriate coordinates when reading the accelerometer, so I have a righthanded coordinate system with the z axis pointing upwards (gravity pointing downward).

"To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error."
I think this is incorrect when the noise distribution mean value is zero (no bias), and evenly distributed around it. Offset-corrected gyroscope values often follow this pattern.
In fact, in the long run, integration eliminates noise.
In my tests, I actually removed any filters and multi-sampling


text:
options for wireless data broadcasting to hundreds of nodes
I would like to build approx 100 arduino devices that can talk to each other, I have a set of constraints that I'm looking to get some insight on :

all devices would operate within a 300 meter proximity of each other
the devices each need to broadcast some data (their speed and
orientation from a gyro) to the rest of the devices in the group for
storage
They need to update each other roughly every 500ms/1s
Some of the devices need to be added and removed from the pool regularly
The devices need to start broadcasting their data to the rest of the
devices in the pool immediately when added (<1s delay)
The spectrum needs to be public & unlicensed

Which method of communication would you recommend? For the range, it seems like a 433hz RF transceiver and receiver would be appropriate or wifi could work but I have concerns about overloading the channels. Bluetooth seems like it has too long a handshake period and the range is too low.
Are there any other options I'm missing? What would be the best way to implement this?
Many thanks for you answers
Update : Data estimation
So the data payload I estimate consists of :
Speed (km/ph) : ok so this will be max 3 decimal numbers, so one short int should be enough here (2 bytes)
bearing : so this will be a standard bearing, let's assume between 0-360 so another short int should be fine (2 bytes)
Velocity : ok, so also a short (2 bytes)
Long : well this needs to be a 32 bit float so it's going to take 4 bytes
Lat : same as above 4 bytes
It's possible with some hackery I could combine speed, volcity and bearing into one short to only take 2 bytes. But let's assume I'm probably going to need 14 bytes, in best case 9.

nRF24L01+ with power amplifiers? Cheap on eBay...

In fact, if they are always close enough to a neighbour you could scrap the amplifiers and go for the non-amplified version and run a self-healing mesh.

Looked at Zigbee?

RFM69 or https://talk2.wisen.com.au/product-talk2-whisper-node-avr/?
Just need to do some calculation to see how load the whole network will be. Need to consider messages clashing with each other... keeping the communication as short-as-possible might be the answer.

You will need to synch the time between devices so that they know when its time to talk.  The recipient can not send a reply.

Please add an estimation of the amount of data (my guess is four integers, 8 bytes, plus possible time stamp, 4 bytes, sequence number, 1 byte, etc). Also do the basic bandwidth requirements. A simple approach is to have a beacon that marks the start of the broadcast and each node transmits according to a time slot (based on their network id). You also need to deal with dropped data.

@Mikael Patel
thanks, I have included a rough estimate in terms of data size of the payload.

@Talk2 - the whisper solution looks quite good, what kind of calculations would I need to do about the whole network to avoid clashing are there some examples online?

@jqpat7 - Thanks I looked at zigbee but the range is limited to 50m, which is too small

The nRF24L01+ solution would give the coverage and it is easy to use to implement a broadcast protocol with high bit-rate (e.g. 1-2 Mbps). The Cosa NRF24L01P device driver allows for some of the functionality required. https://github.com/mikaelpatel/Cosa/blob/master/libraries/NRF24L01P/NRF24L01P.h

I think you also need to add estimates for the amount of SRAM and the data accuracy required. Even with aggressive message filtering the amount of data required for even a small number of neighboring nodes might be much higher than available on the smaller AVR based Arduino boards.

Re Message Payload : What about an extra byte for an identifier for the transmitter, this will be necessary when the nodes are two close to each other to be differentiated by LatLong.  You only have around 5ms to collate the data broadcast it receive and store it, so you may want to look at optimised solutions rather than just high bandwidth solutions.

In terms of Radio, the RFM69 is a good option for range, speed and reliability at low cost. A board like this one https://talk2.wisen.com.au/product-talk2-whisper-node-avr/ would have all ready to go, just add your sensors.
The link can run on 433MHz, 868MHz or 915MHz band, which cover 99% of unlicensed/open frequencies worldwide.

For the protocol/software you need to reduce the message as much as possible. As you mentioned, you could have 9 bytes for the payload if you "share" some bytes, which is the correct approach in this tight network. Add some 2 extra bytes for "operation/command", "sender" and "receiver". Additional to that, you need to consider the bytes added by the radio itself, like Preamble, Sync-word, Network ID, Length, CRC, etc.

The biggest challenge in my opinion would be to not have the RF network flooded with messages, causing multiple radios to transmit at the same time and messages being lost.
Let's suppose you have a total of 20 bytes for all headers+payload per message. If your network is running at 80Kbits/sec (or 10KBytes/s), that would allow a maximum of 500 message/second (2ms per message) in a perfect scenario, without considering any kind of delay between messages.
Bring down to the real-world a 1/3 link utilization is a bit more realistic, giving you a bit over 150 messages of 20 bytes per second. In other words, if the network had an evenly message distribution a node would transmit a 2ms message followed by 6ms of silence.
Now, you can't count that 100 nodes would have perfect synchronization to send a 2ms message and stay quiet for exactly 998ms before sending a message again. There are so many variables which require you to have some sort of control.
One way of doing that is by using a pooling mechanism, where you have a "tick" or "clock" node, which is the only one allowed to talk without being asked. This node will be sending "pooling" requests, a small message with 1 or 2 bytes, containing a command and the destination address, for example: 0x99 0x0A, where 0x99 is the address of the node being polled and 0x0A is the command, like "send me the instrumentation readings, you have 2ms".
Now, instead of the node 0x99 start reading the sensors, it already have it all stored in memory and ready to go, sending the broadcast message to everyone interested. The node 0x99 will also start collecting the new sensor data and preparing the message, so as soon it'll be asked it's ready to go again.
This way you can control how noise the network is and also implement other commands to capture additional information if necessary, etc.
Another implementation would be similar to the old "Token-Ring", but I believe having a master would be more beneficial in this case.
Notes:

The RFM69 can go over 200Kbp/s, but only tests would tell the maximum reliable speed. I use 80Kbp/s to make maths easier.
Design your system so it would survive if a message is lost, like UDP packages, send it and "pray". Adding Ack and re-transmission is probably worst as it would slow down the whole cycle.
The radio also offers encryption, but it might take a few uS extra
If one node will be expected to receive every single message, bear in mind that it would have only a few milliseconds available to process the message and do whatever it needs to do before another message arrive. If you need to perform lots of processing/logs/control actuators you might need to delegate this task to other MCU(s)

Cheers,

Thanks for all the input. I really like your hardware, and think it's definitely the way to go. I am still struggling with the contention issue though. I like the master/slave, but I need all the nodes to have access to all the data from the other nodes. Also, the nodes in the pool will be swapped out fairly regularly, like one every two minutes or so, so it's highly likey the master will leave the pool and then one of the other nodes would need to take over it's responsibilities.

Understand... the only thing you need to keep in mind is that you're going to have very little time after receiving a message to do something. About a master leaving, can you control that or it would simply shut-down? If you can control, the master can send a "command" back to the last sending node to take over.


text:
Problems building an Arduino Micro with through-hole components
So I'm trying to build an Arduino Micro using a bread-board and through-hole components. I'm leaving out the voltage regulator and voltage selector (see schematic at the bottom for reference). I'm powering off of USB, so the +5V line is connected to VUSB.
I checked over the circuit many times, so I think it's okay. Below is a picture of me trying to use an Arduino Micro to load the bootloader on to the Atmega32U4:

I looked here and here as references for trying to load the bootloader, but every time I try it gives me an error. It seems like the MCU is not being recognized. Has anyone tried this before, and successfully done it? I'd like some pointers as to how to achieve this.
EDIT: I've moved the crystal (and 22 pF cap's) closer to pins 16 and 17. The steps I take are:

Upload "ArduinoISP" sketch to Arduino Micro (the "programmer").
Select "Arduino Micro" as the board to be programmed.
Select "Arduino as ISP (Atmega32U4)" as the programmer.
Burn bootloader.

Here is the verbose output (compilation and upload):
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Micro"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -carduino -PCOM5 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0xffffff (probably .reduced_core_tiny)
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Are you sure you aren't trying to build a radio receiver?

My page about uploading bootloaders may help you.

Where is "here and here" ?  2. Edit question and show what commands or sequence you used for bootloader transfer.   3. What do you get when you try to read the fuses?

@IgnacioVazquez-Abrams Well played sir!

@NickGammon
I'll have to check that out. It looks quite promising!

@jwpat7
Good catch! I edited the post. It should have the links now.
The sequence is the same as in the second link.
Let me try and load it again. I'll post the errors I get.

Loading the "ArduinoISP" program on to the programmer (the Arduino Micro on the left side of my picture) works without errors.
I then unplug it from my computer and hook it up as shown in the second link.
I select "Arduino/Genuino Micro" as the Board.
I select the port that the programmer (Arduino Micro) is connected to.
I select "ArduinoISP" as the programmer.
I press "Burn Bootloader".
I get the following:
avrdude: Error: Could not find USBtiny device (0x2341/0x49)
Error while burning bootaloader.

Regardless if related to your present problem or not, you should put the crystal and its capacitors right at the relevant pins.  The same goes for anything intended as a bypass capacitor.

I did some research online, and found that other people have had trouble programming with the "Arduino as ISP". So I decided to go with a dedicated AVR Programmer (I chose the USBtinyISP). [In the Arduino IDE] I was able to write, but AVRdude reported errors during reading. One thing I noticed from using the USBtinyISP is that the "target" (board being programmed) must be separately powered. So my initial problems were caused by either failing to separately power the target board, using a "finicky" programmer, or both!

I select "ArduinoISP" as the programmer. I press "Burn Bootloader". I get the following: avrdude: Error: Could not find USBtiny device (0x2341/0x49) Error while burning bootaloader.

You need to select Arduino as ISP from the Tools > Programmer menu. ArduinoISP is a dedicated in system programmer made by Arduino, confusing because the name of the sketch used with Arduino as ISP is ArduinoISP.
If you're using Windows you'll also likely encounter the issue that ATmega32U4 based boards can't be used for Arduino as ISP. The cause of this is explained at https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo as well as a solution. Unfortunately the solution described in that blog post no longer works as-is with recent versions of the Arduino IDE. I have updated the solution to work with recent Arduino IDE versions and added support for installation via Boards Manager here:
https://github.com/per1234/ATmega32U4asISP

I got the following message when trying the steps on the github page:
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Micro"
avrdude: Yikes!  Invalid device signature.
Double check connections and try again, or use -F to override
this check.
Error while burning bootloader.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

@MaxJacob, I'm imagining the Arduino Micro auto-resets when you start a download to it.  If that is the case you need to disable the auto-reset after you download ArduinoISP to the Micro.  The Micro should remain connected to your host computer (that runs Arduino IDE) when you click Tools, Burn Bootloader to copy the bootloader to your target system.  The IDE will send the Bootloader to the Micro, and the Micro will send it on to your target system.   Note, if you have other working Arduinos, use one to practice download/bootload process, in case your target system is just not working.

@jwpat7
I disabled auto-reset (placed 120 Ohm resistor between 5V and Reset) after uploading the Sketch, but I still get the same error when try to burn the bootloader. Sadly, I do not have any extra Arduinos around.

I want to zone in on why I'm having these issues. What is the simplest circuit necessary to burn the bootloader to the ATmega32U4 using an Arduino Micro (using "Arduino as ISP") as the programmer?

If you have the correct board selected then usually the "invalid device signature" error indicates a wiring problem. If you have verbose output during upload enabled in File > Preferences you can see the actual signature that was read. What was it? It's probably helpful if you would edit your question to add the steps you used to do the Burn Bootloader and full verbose output from the console to your question so that all the information is located in one place instead of spread out over multiple comment threads. I agree with Chris Stratton about the crystal being too far away.

@per1234
Good suggestion. I've edited the original post with more details.


text:
What to do after prototyping?
I want to make a USB gamepad, and I've heard that an Arduino would be great for this kind of project. But before I start to work on it, I want to make sure I understand some things. Here are my basic diagrams of what the project will look like during prototyping and after prototyping:

Do the diagrams look right? Am I understanding the process correctly? For me to properly build a final circuit, I would have to emulate all the necessary (the most important one being the USB) circuitry that an Arduino has around it's microprocessor.
And my final question is, how would I load my program on to the microprocessor (with and without the "Arduino-like" USB circuitry)?

Like this? https://www.conrad.nl/nl/kaart-esplora-atmega32u4-arduinodvar-a000095-95443.html?WT.mc_id=gshop&insert=8J&gclid=Cj0KEQjw4MK_BRC1n6KTtezikbIBEiQA872hYUi_UaiOFnbFnOmFQU15ifGYq0lB8XuAMTdqGbIiQFAaAjXb8P8HAQ&tid=211354628_36784275548_pla-219283182788_pla-095443&WT.srch=1

Yes, something like that. But I want to learn the process of making one, so I would like to build my own circuit. I want to know how to go from prototyping, to a full-blown circuit/PCB.

Please embed your images into your question, rather than posting links. Links can go down.

I think I found a possible answer to my second question here. So for loading my program, I would first have to "install" a boot-loader on the microprocessor. And then I would be able to load the program via [?]. Is this correct?

So you've got no experience and want to do one project that involves designing a PCB and programming a joystick? You should break it up in smaller projects or iterations.

You'll have to make your own board, with the required buttons, but you should really check out blogs/tutorials on creating such a thing.

Yes, your thinking is pretty much correct.
You can place an ATMega32U4 chip and the associated required circuitry within your own circuit design. The required circuitry is actually quite simple - a crystal for the CPU clock, a few capacitors (load capacitors for the crystal, and decoupling), two 22Ω termination resistors for the USB bus, and a 10KΩ pullup on the reset pin. That's about it (besides power of course).
As far as programming goes, you can either install a bootloader (butterfly - like the Leonardo etc) that works through the USB, or you can directly program the chip using ICSP. It's best to provide an ICSP header anyway (it's the SPI pins plus RESET basically), and if you have done that (which you'd need really to be able to get a bootloader on there) then you may as will skip the bootloader entirely and just program direct through the ICSP header. Of course, you'll need some kind of programmer (an Arduino can do the job at a pinch, but it's worth spending the $10 to get a cheap AVR programmer from eBay).

The ATmega32U4 (not 'RC) comes with DFU and crystal fuses preprogrammed, so all you need to make it USB-programmable is the external crystal and load capacitors.

@IgnacioVazquez-Abrams What do you mean by "'RC"?

An ordering code that starts with ATmega32U4RC, which indicates blank flash and fuses programmed for internal RC oscillator operation.


text:
Can I use the same Data Registry for both input and output pins?
This is for a class in which we are not allowed to use the Arduino Library (Not my choice or preference). I know to use DDRB for the B pins. This is the code that I have so far:
//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (condition to turn on light) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   if (condition to turn off the light) {
     *portDataB &= 0x7F
   }
}

I would like for the light to turn on when the input of PB4 is HIGH (from a button press). I just am not sure on what to put in the condition statements or the setup functions.
When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?
I am using the Arduino Mega ATmega2560 btw.
From the comments I have this:
//Global pointers
unsigned char *portDDRB = (unsigned char *) 0x24;
unsigned char *portDataB = (unsigned char *) 0x25;
unsigned char *portPinB = (unsigned char *) 0x23;

void setup () {
  //For the led output I know that I would do this
  *portDDRB |= 0x80;
}

void loop () {
   //And here the code would be like this to light up the light:
   if (portPinB & 0x10) {
     *portDataB |= 0x80;
   }
   // To Turn off the LED:
   else {
     *portDataB &= 0x7F
   }
}

You check if the PB4 bit is set in the PINB register, by bitwise and-ing it with all zeros except for the bit you are interrested in. So if( PINB & _BV(PINB4) ) or if( PINB & (1<<PINB4) ). PS by using setup and loop you are still using the Arduino library. PS2 you need to change DATAB to turn the led on, not DDRB

I guess those are the only two we get to use. What do I initialize PINB and PINB4 to? As for the DataB, thats what I have, just tired.

PINB is (kind of) an output register. You can only read from it. It reports the HIGH and LOW voltages on the B-register's pins.

I added to my Question does that look right? Is PINB included in the Arduino Library? If you make it an answer, you'll get the upvote btw.

yes, except you need to change the |= to =, or the bit will only be set, and never cleared.

PINB etc. are defined in <avr/io.h> which isn't part of the Arduino library.

Is the assignment to write unreadable and unportable code?

Actually the assignment is to write a function that debounces input. I don't know why the professor doesn't want us to use the Library becasue it is an embedded systems course. I think he wants us to know more about the system as opposed to the library. Personally, I would rather just want to know how to use the code.

I specifically meant the |= in *portDataB |= 0x7F. Since portDataB was 0x80; when you or it with 0x7F you get 0xFF, not 0x00.

Assuming the button is connected between GND and pin 10, without any pull-ups or pull-downs.
void setup () {
    //For the led output I know that I would do this
    DDRB = 0;             // set all pins on port B to INPUT
    DDRB |= _BV(DDB7);   // set PB7 to OUTPUT
    PORTB = 0;            // set all pins on port B to LOW
    PORTB |= _BV(PORTB4); // enable the pull-up resistor on PB4
}

void loop () {
    if( PINB & _BV(PINB4) )
    {
        // if bit PINB4 is set, the button is not pressed
        PORTB &= ~_BV(PORTB7); // turn off led
    }
    else
    {
        PORTB |= _BV(PORTB7); // turn off led
    }
}

Wait which |= were you telling me to change to =. Also I am good to use my portPinB in place of your PINB right?

You can use portPinB, but why would you?

The professor's "Blinky" example used it. So I figured that I would need to use it too. I'd rather be safe. He stated that if we use anything from the arduino library we would get a 0 for the entire assignment. I would rather be safe then sorry and declare/initialize everything myself.

It's part of libc. You could just ask him. He'd be more of an asshole if he didn't allow this. I find it quite odd of him to force you to use the Arduino IDE, but not use any other part of Arduino; well; except for the loop and setup; oh; and the initialization that Arduino does.

@kingcobra1986 PORTB etc come with the compiler, and are nothing to do with the Arduino API. If your "professor" thinks they are anything to do with Arduino then he is a fool.

When I set the DDRB to 0x80, is that just making the PB7 an output and the rest as input?

Clarification
I take that question to mean "When I assign the value to 0x80 to DDRB". For example:
DDRB = 0x80;

In the code above that question, you were not assigning, you were "or"ing the value.

Yes. Typically you would "or" in the value if you want to affect only one pin, eg.
DDRB |= 0x80;

The conventional way to make it an input again would be:
DDRB &= ~0x80;

That is, "and" in the negated bit pattern for that pin.
Remember, you have 3 registers (per port) where "x" is "A", "B", "C" etc.:

DDRx - data direction - a 1-bit is output, a 0-bit is input
PORTx - output value - a 1-bit is HIGH, a 0-bit is LOW
However, if the data direction is input, then a 1-bit is input-pullup, and a 0-bit is not input-pullup.
PINx - read the input from the port - a 1-bit is HIGH, a 0-bit is LOW
Note that writing a 1-bit to PINx toggles the output value of that port.

These remarks apply to the AVR chips, not the SAM ones.

I was responding to the sentence, not the code. If you set DDRB to 0x80 then it has that effect. I think the words "set a variable" are generally understood to mean "assign a value to a variable". That is, replace the old contents with the new ones.

I clarified my answer to show exactly what I was responding to.