text:
Simultaneous button reading?
I'm currently working on a project that requires that I simultanously check the state of two buttons. Each button HIGH state is assigned to one if loop. Here's the basic concept:
void loop() {
  S1_State = digitalRead(S1_Pin);
  S2_State = digitalRead(S2_Pin);
  ButtonPRESSED = false;

  P1_Time = random(2000, 5000);
  delay(P1_Time);
  digitalWrite(P1_Pin, HIGH);

  while(ButtonPRESSED == false) {
    if (S1_State == HIGH) {
       Serial.print("Player 1 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
    if (S2_State == HIGH) {
       Serial.print("Player 2 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }

The problem is that checking for the button states this way requires that the S1_State loop _has to be read before the S2_State loop_, thus giving player 1 an advantage. Although I'm not sure how pronounced this issue is in practice, it certainly was noticable when I was first trying this project out through python code on a Pi through similar means.
Is it possible check the conditions to both if loops simultanously? If not, are there other ways to circumvent this problem?

read through your code line by line ..... imagine that both the buttons are pressed at the same time ....... is that the expected behavior?

There is a very easy solution to your problem, and it's called "interrupts".
The processes inside loop method are executed synchronously, so always one read will be done before second one, and always one check will be done before a second one (even if they are inside one if statement)
Fortunately there is a way of simulating asynchronous behavior in ATmega. It's called "external interrupt". You can setup ATmega inside Arduino to stop processing loop method and instead immediately run a different method whenever a voltage on one of the pins change. You are "interrupting" execution of loop  hence the name "interrupt". In Arduino Uno this can be done (only) on pins 2 and 3.
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
I made a little model i Tinkercad

Whenever you push left button PIN2 of the Arduino gets shorted to ground.
Whenever you push right button PIN3 of the Arduino gets shorted to ground.
And now my source code
void setup()
{
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  interrupts();
  attachInterrupt(digitalPinToInterrupt(2), Player1ButtonPress, FALLING);
  attachInterrupt(digitalPinToInterrupt(3), Player2ButtonPress, FALLING);

  Serial.begin(9600);
}

void Player1ButtonPress() {
  Serial.println("Player 1 wins");
}

void Player2ButtonPress() {
  Serial.println("Player 2 wins");
}

void loop()
{
    //nothing here
}

And now some explanation.
In setup we first setup PIN2 and PIN3 as "input with pullup resistor". In our design this means that when button is not pressed those pins will have 5V on them, but as soon as the buttons are pressed voltages go down to 0V. Then we make sure that interrupts are turned on (they are on by default, but I like to show everyone who is reading the code that I will be using them) and then we do some attachInterrupt magic. We make that a "falling edge" (change from 5V to 0V) on PIN2 and PIN3 will immediately run methods Player1ButtonPress and Player2ButtonPress.
When I was playing with buttons they worked perfectly.

And a word about possible cheating. Keeping the button pressed does not create a "falling edge" (voltage on a pin is constantly 0) so if you only add some global variables with info when game starts and who won. Then add some conditions in the two methods responsible for interrupts. You can then use the loop method to start the game, and show result.

Does the interrupt handling give either player an advantage? What happens in the event of a tie?

@Craig The more I think about it the more I think that there still will be a tiny bias, because ATmega will analyze values of pins with 16MHz frequency so there still is possible that a "tie" will happen and one button will be chosen by processor to be a "winner" incorrectly. But this time the decision will take only 1 clock cycle (6 nano seconds). digitalRead take about 50 clock cycles, and we need two of them. So we gained 100 times more resolution and I think it's enough for a "game" to risk suck event. Nothing is perfect in electronics.

You can't connect a button to an interrupt this way, you have to take debouncing precautions: http://ohm.bu.edu/~pbohn/__Engineering_Reference/debouncing.pdf

The game win condition is achieved on first falling edge. Debouncing is unnecessary since every subsequent "bounce" will be counted as a button press after game has ended. Debouncing makes sense only if system has to wait for subsequent input.

Instead of using the high level digitalRead() function access the low level port registers. See this documentation.
A port register is one byte and each bit represents one of the digital inputs on the arduino.
Do something like this:
pin_status = PIND; //Input port D (pins 0-7)
button_1 = bitRead(pin_status, 2); // digital pin 2
button_2 = bitRead(pin_status, 3); // digital pin 3

The values are read simultaneously so it is possible to have a tie.

I think you want after a random time, a 'Start' LED to be lit, and whoever presses his/her button first wins.
There are some problems in your sketch:

It seems even when a button is pressed to early, the button is still taken into account. You should check for this 'cheating'. So check directly after the 'start' LED is lit, that no buttons are pressed. If so, that player loses.
Assuming the players are honest, you check for their buttons, which probably the first iteration it will not be pressed (that would be an immediate reaction speed). However, than you wait 5 seconds; probably both players pressed their buttons, and you check the button of the first player first. It will help, if you change the delay to 1 ms, or even remove it completely.

Untested proposal:
int playerXWon = 0; // No player won yet, 1 = player 1 wins, 2 = player 2 wins, 3 = draw

void loop()
{
   // Delay for a random time.
   P1_Time = random(2000, 5000);
   delay(P1_Time);

   CheatCheck();

   if (playerXWon == 0)
   {
      // Start
      digitalWrite(P1_Pin, HIGH);

      checkFirstPress();
   }
}

void CheatCheck()
{
   // Check if a player did not press its button too early.
   // (Btw, it does not matter if the player presses and release its button before the LED goes on.
   S1_State = digitalRead(S1_Pin);
   S2_State = digitalRead(S2_Pin);

   if (S1_State == HIGH)
   {
      else if (S2_State == HIGH)
      {
         PlayerWin(3);
      }
      else
      {
         PlayerWin(2);
      }
   }
   else
   {
      if (S2_State == HIGH)
      {
         PlayerWin(1);
      }
   }
}

void checkFirstPress()
{
   // Whoever presses first wins.
   while (playerXWon == 0)
   {
      S1_State = digitalRead(S1_Pin);
      S2_State = digitalRead(S2_Pin);

      if (S1_State == HIGH)
      {
         if (S2_State == HIGH)
         {
            PlayerWin(3);
         }
         else if (S1_State == HIGH)
         {
            PlayerWin(1);
         }
      }
      else if (S2_State == HIGH)
      {
         PlayerWin(2);
      }
   }
}

void playerWins(int player)
{
   switch (player)
   {
   case 1:
      Serial.print("Player 1 wins\n");
      break;

   case 2:
      Serial.print("Player 2 wins\n");
      break;

   case 3:
      Serial.print("Both players win\n");
      break;

    default:
       assert(NULL); // Programming error
       break;
   }

   playerXWon = player;

   digitalWrite(P1_Pin, LOW);
}

The cheating pevention will come later, I'm aware of that problem and will add it later. I wanted to tackle this first as it's more important and unlike the cheating prevention I don't know how to do it.

I'm not sure how much that approach would change things as it would most likely still require one button to be read after the other in whatever loop those 5 seconds take place in. Could you clarify what you mean by "change the delay"?

Actually, it's better to remove the delay. When it's removed, many times per ms the buttons are checked, so whoever presses the button first will win. Now it is only checked every 5 seconds, and probably both players press the button within this time easily.

I also split the big function in smaller functions.

Lot's of stuff here I haven't learned yet like switch functions and using void loops as functions, thanks for the pointers.

switch is an if statement to check multiple values easier (instead of if, else if, else.. ). A void function is just to take a fragment of the code and put it separately. This makes your programs much more clear and maintainable. Also you can reuse those fragments without copying them every time.

I was not sure about posting this as an answer, since it is basically some more considerations on the three existing answers (for reference, they are Michel Keijzers's one - using digitalRead -, Craig's one - read the PIND variable at once -, Filip Franik's one - use interrupts), but it became quite long and so a single comment could not fit all of this.
What you and the other answerers wrote is in theory correct. Checking the button of player 1 before player 2 gives an advantage to player one. What you lack is... How much advantage?
Mechanical actions (such as the pressing of a button) have a time duration that is around 50ms*.
Since I assume your application is a reaction time tester, human reaction times are around 250ms.
Moreover mechanical buttons have "bounces". Typical debounce times are in the range 20-100ms. You can avoid this by just checking the first edge.
A player gets an advantage if he is awarded as winner even if the button was pressed at the same time.

_* I tried to find a source for this, but I was not able to get some data. I tried with an online stopwatch and pressing the two spacebars (notebook and USB keyboard) roughly at the same time, obtaining results around 75ms. This is not a real value, so if someone has some measured values or estimations feel free to comment

Now, let's assume you properly coded your program so that you check for ties and avoid delays, since these will greatly affect the following measurements.
In the digitalRead case you are executing this series of actions:

Read status of pin 1 - 3.6us
Read status of pin 2 - 3.6us
Check the statuses and decide who won - some tens of instructions (about 1us)
Loop - a couple instructions (0.5us)

The 60 instructions comes from this thread (3.6us = 57.8 instructions @16MHz); as for the others it's a rough measurement. Let's assume that the function actually samples the pin at the very end of the function.
Now, since you are checking for ties, if both buttons get pressed during phases 3, 4 or 1 you will get a tie (since both buttons will be read as pressed). If both buttons get pressed during phase 2, button 2 will be marked as pressed and button 1 not, thus giving advantage to that player. The time when this happens is about 3.6us long. So you are giving a 3.6us advantage to button 2 player.
In the PIND case you are reading the buttons exactly at the same time. The advantage is thus 0.
In the interrupt case when both EXT0 and EXT1 interrupts are triggered at the same time EXT0 gets executed, since it is before in the ISR. Consequently the player pressing the button on EXT0 has one interrupt checking cycle of advantage. I admit I do not know how often the inputs are checked for the EXT interrupt, but I assume it performs a check every clock cycle (consequently the advantage is 62.5ns).

Now, let's sum up the advantage

digitalRead: 3.6us
PIND: 0
interrupt: 62.5ns

The solution is pretty obvious to me, and it is... Don't care! Even in the worst case scenario you are four order of magnitude faster than your phenomenon. You are giving one player a 4us advantage in a 250ms game (0.0016% of advantage). I'm pretty sure that the mechanical differences between the two buttons (maybe one is a bit stiffer, or has a slightly higher size, or has a slightly lower contact) affect the reading much more than this.
In the end, with this kind of setup you will reasonably be able to have an accuracy that is at most some tens of milliseconds. With other measurement setups (maybe optically based) you can go as low as 1ms. Adding 4us of advantage to one player will not influence the result.
Try to focus on the rest of the program, and for this problem use whichever solution you find more understandable.
NOTE: This is based on the assumption that a proper program is developed, with tie checks  and no delays and so on. The program as you wrote in the question is not ok from this point of view (as it is now it will stay in the loop forever; if you change Sx_State to digitalRead it will become roughly fair - something like 4us of advantage to player one and 3.8us of advantage to player two)

I have to concur with frarugi87 here. The few microseconds taken by
digitalRead() are completely inconsequential for your application. But
let me add that, even if your players were super-humans capable of
sub-millisecond reaction times, you are not giving an advantage to any
of them if you alternatively check button 1, then button 2,
then button 1, and so on. The reason is that, in the small time
window between reading button 1 and reading button 2, you give
an advantage to player 2: he will win if both buttons are pressed
simultaneously. In the following time window (between checking
button 2 and button 1) the same advantage goes to
player 1.
The net result is that the game has a tiny amount of randomness: if both
buttons are pressed simultaneously, the result is seemingly random. But
again, the chances of this happening are so tiny that it makes no sense
to worry about it.
Here is how I would determine the winner. I think this code makes clear
that we are alternatively checking button 1, then button 2,
then button 1...
int find_winner()
{
    for (;;) {
        if (digitalRead(S1_Pin) == HIGH)
            return 1;
        if (digitalRead(S2_Pin) == HIGH)
            return 2;
    }
}


text:
Burn bootloader into Arduino UNO from Arduino Duemilanove
I have been working with my Arduino UNO for 2-3 hours and after that it was not possible to load sketchs into the board since it returns a

"avrdude: stk500_recv(): programmer is not responding" error.

The internal led "L" of the board is permanently on.

After a little research I guess that the bootloader was corrupted at some point (I still don't understand when and how).
Q: Apart from this board I have an Arduino Duemilanove board and I would like to know if it is possible to use this Duemilanove board to burn the bootloader in the broken board, is this possible? in afirmative case, how?
Since all the examples over there shows how to do it with the same board and not with a different one.

https://www.arduino.cc/en/Tutorial/ArduinoISP

Yes, Nick Gammon has a page on doing that here  https://www.gammon.com.au/bootloader

Hey, a big ___ ____ to whomever downvoted this with no comment.  Nick has a great page written up, answers the question very directly, and has been in place for several years.

source: Stack Exchange

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

sort: votes


text:
Sending a digital signal from one Arduino to another to trigger an event
I am wanting to send a digital signal from one Arduino to another. The goal is for one Arduino send a HIGH signal to a pin on the receiving Arduino. While the pin is HIGH, do function
I initially successfully tested this by blinking the LED on pin 13 but then I tried to add the functionality I needed but I couldn't get the state to change of pin 12 to change.
The circuit is simple
GND <--> GND
pin 10 --> pin 12
I saw there is already a post with a similar title but it didn't help me.
Any ideas?

Host Arduino
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//DIGITAL SIGNAL PIN
int pin = 10;

void setup() {

 Serial.begin(9600);

  if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // list files
  printDirectory(SD.open("/"), 0);

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);

  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT); // timer int

  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

    pinMode(pin, OUTPUT);}

void loop() {

  digitalWrite(pin,LOW);
  Serial.print(digitalRead(pin));

  // Play one file, don't return until complete
  Serial.println(F("Playing track 001"));
  musicPlayer.playFullFile("track001.mp3");
  // Play another file in the background, REQUIRES interrupts!
  Serial.println(F("Playing track 002"));
  musicPlayer.startPlayingFile("track002.mp3");

  delay(100);
}

/// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

Slave Arduino
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//DIGITAL SIGNAL PIN
int inPin =  12 ;
int state;

void setup() {

  Serial.begin(9600);

 if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // list files
  printDirectory(SD.open("/"), 0);

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);

  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT); // timer int

  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);  // DREQ int

  pinMode(inPin, INPUT);
}

void loop() {

  state = digitalRead(inPin);
  Serial.println(digitalRead(state));

  if(state == HIGH){
    musicPlayer.playFullFile("track001.mp3");
    Serial.println(F("Playing track 001"));
    }
}

/// File listing helper
void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       Serial.println("/");
       printDirectory(entry, numTabs+1);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
     entry.close();
   }
}

please post the actual question .... you either have a problem with changing the state of pin 12 or changing the state of pin 10 .... which one is it? ..... it is unclear which one is the output

What has changed between the LED test working, and the actual functionality not working? For the LED experiment to have worked, the input pin of the receiving Arduino must have followed the output from the sender. Did any wiring change? Pinmode? If not, then the problem is in the new coding.

One method is to use interrupts with a state machine.  Here is a minimal example:
Master
#define pin 10 // connect to slave digital input pin
void setup(){
  pinMode(pin,OUTPUT);
  digitalWrite(pin,LOW);
}

void loop(){
if( // insert your condition to trigger the slave Arduino ){
 digitalWrite(pin,HIGH);
 delay(10); // short delay
 digitalWrite(pin,LOW);
 }
}

Slave
#define pin 2 // connect to master digital output "pin"
unsigned int state;
void setup(){
  pinMode(pin,INPUT);
  state=0;
  attachInterrupt(digitalPinToInterrupt(pin),isr,RISING) // trigger ISR on rising edge of master voltage signal
}

void loop(){
if(state==1){
  // your code here
  state=0;  // reset when done
 }
}

void isr() {
 state=1;
}

Digital interrupts can be done on the Arduino UNO with pins 2,3.  Don't forget to also connect a common electrical ground between Arduinos.

If you use SPI, you can't use pin 12 as GPIO. Pin 12 is SPI MISO.

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


text:
How come my switch is triggering with out pushing the button?
New here, sorry If my formatting is bad.
int button = 2;
int relay = 3;
int speaker = 4;

void setup()
{

  pinMode(button, INPUT_PULLUP);
  pinMode(relay, OUTPUT);
  pinMode(speaker, OUTPUT);

}

void loop()
{
  if(digitalRead(button) == 0)
  {
    digitalWrite(relay, HIGH);
    tone (speaker, 100, 300);
    delay (3000);
  }
  else
  {
    digitalWrite(relay, LOW);
  }
}

I want the relay to trigger and stay open only while the button is pressed.   However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.
If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

how is the speaker wired?

@Gerben, sorry, I had it right on the board but copied it wrong to here.

@Juraj, The red wire is in pin 4 and the black is in GND on POWER

is it a piezo speaker? because normal speaker should not be connected without resistor?

@juraj The piezo is a speaker, however that can't be the issue entirely as even if I don't plug in the speaker, just the code causes the error.

I can't see any red or black wires in your question.

I want the relay to trigger and stay open only while the button is
  pressed. However for some reason touching pin 2 triggers the relay and
  sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

If i remove the tone (speaker, 100, 300); it only triggers when the
  button connecting pin 2 to ground is pressed, but obviously doesn't
  play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.


text:
How do I send MIDI properly with ESP8266?
So, I've finally able to send and receive MIDI using Arduino.
My next thing to do was sending 5 pin MIDI to rtpMIDI, and vice versa, using ESP8266, but so far I can't even send MIDI correctly.
So far, I used this library, and it send midi without issues with Arduino Mega. But using Wemos D1, strange thing happens.

this is output of MIDI OX. Pretty sure I wasn't sending MIDI CC.
Here's the code so far :
#include <MIDI.h>

 // Created and binds the MIDI interface to the default hardware Serial port
 MIDI_CREATE_DEFAULT_INSTANCE();

 void setup()
 {
     MIDI.begin(MIDI_CHANNEL_OMNI);  // Listen to all incoming messages
 }

 void loop()
 {
     // Send note 42 with velocity 127 on channel 1
     MIDI.sendNoteOn(42, 127, 1);

     // Read incoming messages
     MIDI.read();
 }

UPDATE : Here goes the settings.

Any reason why this happens? Please help me. Thanks!
Schematics :
Basically I just change the Arduino to Wemos D1 Uno.

how is it wired? MIDI_CREATE_DEFAULT_INSTANCE will use Serial on pins labeled RX, TX on Wemos, but esp8266 outputs some boot log on this RX at start.

@Juraj I updated the screenshot. the old screenshot was me trying to send MIDI using TX1, but still not working. Above screenshot were me trying to run that program, with MIDI  OUT on pin D1 (TX)

Please show a schematic of your circuit.

@CL Edited the answer with schematics. I just realized the title was wrong! :( I'm trying to send MIDI from ESP8266 (Wemos D1 Uno) through serial, to MIDI cable.

Does the Wemos run at 5 V or 3.3 V?

Wemos io pin is 3.3 V only

@CL but I run the wemos with USB cable ... does that mean 5v?

just tested the exact same sketch and schematics using Arduino Mega, and it works.

I just realized that moved the cable from 5V to Vin works! Since I only use USB connection, I don't think it should make any problems. It may broke the MIDI receiver if I'm using external power supply tho ...

NOTE : Probably not the answer you're looking for, but it works for me.

Solution : Move the jumper from 5V to Vin.
Why? I don't know. It just works.

Please notice that this is Wemos D1 Uno, which has adaptor input, which can receive 9-24V.
If you're going to use the adaptor, IT MAY BROKE YOUR MIDI DEVICE!
As far as I know, Vin stands for Voltage Input, and everything from the adaptor is routed there. That means if you use 24v adaptor, Vin is 24v!

I'm only planning to use USB as power supply, so yeah. it works for me.
If you're going to use Vin with external power supply, please use voltage regulator to 5v. Better safe than sorry.

Anyway, since I'm planning to use 6N137 to receive MIDI also on this board, here goes :

Input voltages greater than 7 V must be avoided to preclude damage to
  the gate oxide of the input stage. This damage is not necessarily
  permanent, but will adversely affect the expected lifetime of the
  circuit. The gate oxide of AHC devices is only 200 Å thick. An input
  voltage of 7 V corresponds to a field strength over the gate oxide of
  350 kV/cm. Although breakdown of the oxide is expected only at input
  voltages above 10 V, electrons tunnel increasingly into the gate oxide
  at field strengths greater than 350 kV/cm, influencing characteristics
  of the transistors and causing failure.

Source : this question on electronics stackexchange.


text:
How do I properly receive MIDI with Arduino, with 6n138?
UPDATE : I still can't receive MIDI as of 2019/07/01.
Here goes so far : I'm trying to follow this schematics from instructables, using 6N138. To make it easier, I'm going to copy his schematics.

===================================
I'm using Arduino Mega. I tried to find specific topic about this and can't find any.
The target is actually send and receive MIDI, then replace the whole Arduino Mega to ESP8266 (probably the ESP-01, or Wemos D1), but I'm afraid it is too specific.
Here's the code so far on PasteBin
Here's my work so far.

The diodes were replaced with LED, because I don't have one Original guide here.
But that schematics on that thread also didn't work for some reason.

What is the Mega supposed to do? The ESP8266 can easily handle all of that on its own.

@tttapa I'm using the esp8266 only as the wifi module, mega for the rest

Define "the rest"?

@tttapa mega would receive the power, receive midi connection, send midi back, and doing everything esp8266 is only for wifi shield replacement.

The ESP8266 can easily handle MIDI connections, as well as receiving power. Using an extra microcontroller is just making everything more difficult, and is a waste of time and resources, in my eyes.

@tttapa yeah, but for now it is impossible to modify my thesis documentation. also since esp8266 has no other serial, I can't debug using serial monitor or similar and probably running blindly. that's why I consider mega at the first place. or you have another solution?

The ESP8266 has two serial ports. One of them can only transmit data. This is not a problem for debugging. On top of that, you can change the pins of the first serial port.

@tttapa but I only got the ESP01 module ... damn I should have think about this before. now I'm pretty much stuck :s

Then you should probably use the Mega. If you were to start from scratch, I would recommend a WeMos D1 mini, or similar, they are $3.50 from China, and break out all usable IO pins, and include a USB interface, so you can just plug it into your computer directly to program it, just like a normal Arduino. If you can get one in time, that would be a good solution, but you can start using the Mega for now. Either way, you'll have to program the ESP8266, you can't use AT commands for RTP-MIDI, AFAIK.

@tttapa for now I do have Wemos D1 Uno, which is kinda the same thing. But the problem is I can't change any specs, it must include mega and esp. I do have the esp with AT firmware that is compatible with this firmware. Idk what to do next ...

Please do not edit the question in a way that makes existing answers invalid or incomplete. "How to create 220 Ω from several 1 kΩ's?" and "Can I replace or omit the 1N914 in a MIDI input?" would be separate questions. (hint: 1/1/1/1/(1+1) in parallel; and see MIDI connectors / Diodes) And the diode is reversed.

How to connect 6N138 to Arduino :

Schematics :

Basically the above schematics and installation is already okay, but instead of 1k, I used 10k on 6N138 PIN 7 to GND.
VCC to 470 ohm is on PIN 6, also RX out, connected in series.

Just in case you want to use 6N137 :

Schematics :

Pin 5 of the MIDI DIN connector goes to pin 2 of the 6N137
Pin 4 of the MIDI DIN connector goes via 330 ohm resistor to pin 3 of the 6N137 (so the 6N137 pins and the resistor are connected in series)
You should also have a reverse connection protection diode between pins 2 and 3 of the 6N137 but I like living dangerously and rely on the diode inside the 6N137
Pin 8 and 7 are connected to VCC
Pin 6 is connected to RX
Pin 5 is connected to GND
4.7 kohm pullup resistor between pin 8 and 6 (VCC and signal out)

Adapted from this blog post.

How to test it :

I used Arduino Mega with this code.
I then attached the Arduino Mega to Hairless MIDI, then to loopMIDI.
Then I read the MIDI output using MIDIOX.

I might update it with H11L1 / PC900 later, if I have some time. Also, I'm going to put this thread in Indonesian in my blog later.

There are plenty of MIDI circuits and most of them are quite simple, mostly an optocoupler (6N137 or 6N138, although I had better luck with H11L1), some resistors and that's mostly it. I also added ferrite beads for EMI protection, but this is not absolutely necessary.
To test your circuit, use a lot of data (e.g. by pitchbend/aftertouch), and play notes meanwhile. If you hear stuck notes (meaning the MIDI Note Off command is missed), you know the circuit is not full proof.
Regarding libraries: the FortySeven Effects library is really easy to use. I used it in the beginning before I moved on to STM32 and having to write my own, but this is a good starting point.
For the schematics I based my circuit of can be found at H11L1 optocoupler.
The best way is to read the official MIDI documentation, see page MIDI 1.0 Specification, than search for
Download the Complete MIDI 1.0 Detailed Specification Document (1996)
(Please Register! It's Free!).

Do you have some example schematics? That would help alot. Thanks!

Note that there has been an addendum in 2014: Electrical Specification Update (CA-033)
It adds a specification for 3.3V systems.

@tttapa Thanks for that remark (didn't know about that addendum)

just realized nobody sells 6N137/6N138, H11L1, or everything else I found at arduino.cc that can be used as alternative.

@RinaldoJonathan I buy them from AliExpress, no problems at all.

@RinaldoJonathan 6N138: https://www.aliexpress.com/item/A6N138-6N138-DIP8/32843461925.html?spm=2114.search0204.3.1.3f891715EwEFhK&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=59100523-2f5e-4065-af82-6c1e5b4c5d08-0&algo_pvid=59100523-2f5e-4065-af82-6c1e5b4c5d08&priceBeautifyAB=0

@RinaldoJonathan 6N137: https://www.aliexpress.com/item/10PCS-6N137-DIP8-6N137-DIP-DIP-8-new-and-original-IC/32911564265.html?spm=2114.search0204.3.1.7ea619e7LGtwnu&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=0090b46e-5df5-4ac3-8601-67cdbb571f94-0&algo_pvid=0090b46e-5df5-4ac3-8601-67cdbb571f94&priceBeautifyAB=0

@RinaldoJonathan H11L1M: https://www.aliexpress.com/item/10pcs-lot-H11L1-DIP-6-H11L1M-Schmitt-trigger-output-at-a-high-speed-In-Stock/32892398601.html?spm=2114.search0204.3.1.36257b29TrA9ZE&ws_ab_test=searchweb0_0,searchweb201602_5_10065_10068_10130_10547_10059_10884_10887_10696_100031_10190_10084_10083_10103_10618_10307_10820_10301_10821_10303,searchweb201603_60,ppcSwitch_5_ppcChannel&algo_expid=2f5ebd94-33f1-4a10-9c0c-ebcf204e1f14-0&algo_pvid=2f5ebd94-33f1-4a10-9c0c-ebcf204e1f14&priceBeautifyAB=0

@Michel Keijzers bro I can buy them from tokopedia and it'll arrive in 3 days. but nobody sells them locally.

okay somehow I got 6n137, but again stuck with the schematics.

This is for 6n138 https://electronics.stackexchange.com/q/165255/140343

For 6n137 eg https://goo.gl/images/K71nAo

@MichelKeijzers I have bought H11L1. but it still not working :( I bought it because I see you also used that.

I'm still stuck with receiving MIDI. somehow, Arduino read the input high when nothing connected. But when MIDI cable connected, arduino didn't read it.  https://electronics.stackexchange.com/questions/400080/how-do-i-use-h11l1-correctly-to-receive-midi

I had some troubles with 6N137, but not with H11L1's. Make sure you use the correct resistor values (it matters for what I experienced). Also what helped me a lot was to buy a logic analyzer (about 5$), this way you can see the exact timings. If you need to see if the voltage is going up/down quickly enough you need a 'real' oscilloscope, but the H11L1 should be fast enough.

@MichelKeijzers mind checking my question there at Electronics Stackexchange to see what is actually wrong? I was very stuck ...

Most start at the midi site at playground.arduino.cc.  But there are numerous web sites across the Internet.  It is important to understand that the MIDI interface uses a current loop to send and receive data.  While the Arduino normally uses voltage levels to communicate.  As such, an electronic interface needs to be built or bought to convert between these two types of signals.  Some interface designs are simple and limited.  Others are complex and robust.

Thats a lot of read. I'll try to read them one by one. Thanks!

Use wikipedia as a reference (don't read it all, just what you need).  The playground.arduino.cc site is likely your best source.  The simple design isn't that simple and the complex not all that complex.  I was looking more for examples of simple (direct connections) and better (optically isolated) ways to convert voltage levels to current loops.

@RinaldoJonathan, your question has changed a lot.  On some bread boards the power doesn't connect from one end to the other.  In such a case you need to jumper the power bus together where they don't connect.  Or move the power wires to the side where you are powering your chip.

the other power line isn't used at all.

@RinaldoJonathan, that is not what I meant.  On some bread boards like yours, there are 4 power bus lines.  Two on each side.  Broken in the middle.  I see your bread board has uninterrupted blue and red lines.  So I think your bread board only has 2 power bus lines.  But it would not hurt to move where you supply power to the end of the board closest to where you use power just to check. Take a look at how the lines are painted on this bread board.

I use this library with Arduino Uno (where can change bootloader):
https://github.com/TheKikGen/USBMidiKliK
And after the device is recognized from windows how a Midi device, so not need any other program to interface em.
You can use your preferred sequencer program and your arduino interface is recognized how a midi interface.
The sketch is very simple:
    /**********************************************************************************

  KIKGEN MIDI USB
  A MIDI USB RELIABLE INTERFACE
  USB-MIDI simple converter Sketch for Arduino
       USB                           ATMEGA8U2                    ATMEGA 328P
  --------------         ------------------------------         ---------------
  IN Endpoint  o<--------o USBOUT | usbMidiKliK |  RX o<--------o (TX) MIDI IN
  OUT Endpoint o-------->o USBIN  |  firmware   |  TX o-------->o (RX) MIDI OUT

  The RX/TX on the Arduino must no be crossed, as the ATMEGA8U2 is directly connected
  to the RX and TX pins.  When PIN0 (RX) and PIN1 (TX) are configured as INPUT, we
  can talk directly with the ATMEGA8U2 managing the USB, making the Arduino transparent.

************************************************************************************/

void setup() {

  // Make Arduino transparent for serial communications from and to USB

  pinMode(0,INPUT); // Arduino RX - ATMEGA8U2 TX

  pinMode(1,INPUT); // Arduino TX - ATMEGA8U2 RX

}

void loop() {

}

And hardware schema is this:


text:
Arduino Nano, ESP8266-01 communication
In my last question I got the suggestion to get a voltage regulator to power my ESP8266, so I went out to buy one and in the end my ESP8266 turned on. Then I started wiring the Tx/Rx pins through the Logic Level Shifter and tried out this piece of code I found online
// Basic serial communication with ESP8266
// Uses serial monitor for communication with ESP8266
//
//  Pins
//  Arduino pin 2 (RX) to ESP8266 TX
//  Arduino pin 3 to voltage divider then to ESP8266 RX
//  Connect GND from the Arduiono to GND on the ESP8266
//  Pull ESP8266 CH_PD HIGH
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the ESP8266
//

#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup()
{
    Serial.begin(115200);     // communication with the host computer
    //while (!Serial)   { ; }

    // Start the software serial for communication with the ESP8266
    ESPserial.begin(115200);

    Serial.println("");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("Ready");
    Serial.println("");
}

void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
}

But I when I tried sending "AT" to the ESP via the Serial Monitor nothing happend.
This is my current wiring, I hope it's not to unclear:

Hopefully someone can help me :)

change baudrates in code and serial monitor and check again . Might be 9600.

@MITURAJ I already checked that, no luck

Make sure these connections are there:

Power to esp8266 is 3.3 V from NANO.
GND of NANO to GND of esp8266.
3)TX from esp8266 goes to RX of NANO.
4)TX from Nano goes to esp8266 via a resistive divider for 3.3V drop.
5)CH_PD, RST pins of esp8266 = 3.3 V

I think the problem is the baud rate, I ordered a USB to Serial converter to change it first

Is the blue color LED showing ON in your esp8266 ?

yea baudrate could be problem. USB-TTL converters along with puTTY is a good way to check your wifi module easily...before you use with arduino uno

Yup, it is constantly lit

constantly lit? oops then your firmware is corrupt. You need to reflash the esp8266!

is it the firmware or could it be that the nano is not supplying enough current?

Can be. Powering up using a separate 3.3 V supply is always the better choice. I usually use USB-TTL to power up.

I think I'll try flashing the firmware first, that's what my quick google search recommended

Some hardware troubleshooting -

Make sure that the 3.3 V power supply to the wifi module is supplying enough current to esp8266 as it consumes much current.
Make sure that TX from Nano is going to RX of esp8266 via a resistive divider for bringing down 5V out signals from nano to 3.3 V ( to be on safer side)
At power-on, check if BLUE LED of ESP8266 blinked 2-3 times quickly
and went OFF. Check if the RED LED lighted up and stays ON. If it
does, your ESP8266 chip is working fine. If the BLUE LED did n't
blink or if it stays ON, your firmware may be corrupt and you will
need to re-flash the firmware of ESP8266.
Make sure that the baudrate is correct.

Step 1: Turn On Your ESP8266 Module by Using Arduino Nano 3.3V Dc Output Pin. Remeber sometimes Arduino board is not delivering sufficient voltage to the ESP8266 module. You can use a 3.3 V ( Do not exceed input voltage from 3.3v) regulator ( AMS1117 ) to power this module. A voltage divider circuit is used to drop the Arduino 5V to ESP8266 3.3 V.
Step 2: Here is the schematic Diagram, in my code I used Digital pin 2 as a Tx and D3 as an RX.
Step 3: Open Arduino IDE and Paste the source code in the window just like shown in the picture.

Step 4: You are ready to send At Commands to Your ESP8266 Module. Remember you will see a Garbage value during Serial Communication.
AT – Will give OK on the serial monitor, if Not just unplug vcc Pin of ESP8266 Module for a moment and reconnect again.
Send AT+RST – Command to Restart module / Optional Command
Send AT+GMR – To get the firmware version
Send AT+CWMODE? – Set Module to a Dual Mode Sucha as Standalone + Access Point mode.
Send AT+CWLAP – Command to Search Nearby Wifi Access Point. Find your Wifi Name in the Search Result.
Send AT+CWJAP="Your Wifi Name","Your Wifi Password" – Command to Connect to WIFI.
Send AT+CIFSR – Command to Check Allocated Ip given by your Wifi to your ESP8266 Module/Optional Command.

There are several problems with this posting.  First, don't recommend using the Arduino's 3.3v output.  The poster is already beyond that, in using an external regulator.  Next, presenting code in a screen shot picture is absolutely unacceptable.  But even if you'd presented the code in textual format within your post, you can't just propose alternate code, you need to explain why it is better than that already being tried.

The problem is the ESP8266-01 as diagrammed is shorting the pins of the header.  Remember that the breadboard you are using connects all pins on each side, on a row by row basis.  The WiFi module has 8 pins with the pinout shared in other posts.  You must "float" the module and wire it to the breadboard with point to point wiring (hope that is clear).  Put simply... don't plug the WiFi module into the breadboard.  Can't be done.  Cheers!

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


text:
Autoranging ohmmeter
Note: Before i explain my issue i would like to note that I am a beginner in electronics. Please pay attention to that when providing solutions and explanations. Thank you.
I have succeeded at making an auto ranging Ohmmeter it is still ofcours experimental there for I would like to get some opinions and perhaps solutions to some of the issues I’m facing
How it works:
It is based on a simple voltage divider. After experimenting it seems that a voltage drop across the unknown resistor in a certain range (this case [3.135V, 0.99V] with a voltage source equal to 3.3V) gives the most precise results compared to other values.
This Ohmmeter has a very useful feature and that is auto ranging, it changes the range automatically when the voltage drop values are not in the previously mentioned interval ([3.135V, 0.99V]).
The accompanied image shows how the device works.
If the value of Rx is too small compared to (R1+R2+R3) the Arduino switches the analog reading from A0 to A1 if the problem still accurse the Arduino will change again to A2 meaning it is now measuring not the value of Rx but (Rx+R1+R2) in series after that the Arduino is programmed to do the subtraction accordingly.
This device presents some noticeable inconvenients  that need to be eliminated:

It depends on experimental values, so it is not certain if it’ll
function properly in different conditions.
For accurate (still not exact) measurements the value of Rx has to be greater than R1
It provides acceptable measurements compared to the actual value with an error that is not too big (less than 1% relative error) the precision was obtained by the use of some of the arduino functions (such as voltage reference) also I have chosen the voltage source to be 3.3V instead of 5V to reduce noise, now if one wishes to use a different microcontroller other than arduino will it still be possible to obtain the same precision.

I would like to know your professional opinion regarding these inconvenients and if you may solutions for them, I have accompanied the code for better understanding.
Thank you
#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analogPin0(A0, true);
ResponsiveAnalogRead analogPin1(A1, true);
ResponsiveAnalogRead analogPin2(A2, true);

int raw1= 0,raw2=0,raw3=0;
int Vin= 3.3;
float Vout1= 0,Vout2=0,Vout3=0;

float R1= 10000,R2=100000,R3=1000000;
float Rx= 0;
float buffer= 0;

void setup()
{
  analogReference(EXTERNAL);

Serial.begin(9600);
}

void loop()
{
  analogPin0.update();
  analogPin1.update();
  analogPin2.update();
raw1=analogPin0.getValue();
buffer= raw1 * Vin;
Vout1= (buffer)/1024.0;
if(Vout1<=3.135&&Vout1>=0.99) //firstif
{

buffer= (Vin/Vout1) -1;
Rx= (R1+R2+R3) * buffer;
Serial.print("Vout1: ");
Serial.println(Vout1);
Serial.print("Rx: ");
Serial.println(Rx);
delay(1000);
}
   else //else1 of first if
   {

   raw2=analogPin1.getValue();
   buffer= raw2 * Vin;
   Vout2= (buffer)/1024.0;
      if(Vout2<=3.135&&Vout2>=0.99) //second if of first else
      {
      buffer= (Vin/Vout2) -1;
      Rx= (R2+R3) * buffer;
      Rx=Rx-R1;
      Serial.print("Vout2: ");
      Serial.println(Vout2);
      Serial.print("Rx: ");
      Serial.println(Rx);
      delay(1000);
      }
      else
      {
      raw3=analogPin2.getValue();
      buffer= raw3 * Vin;
      Vout3= (buffer)/1024.0;
          if(Vout3<=3.135&&Vout3>=0.99)
          {
          buffer= (Vin/Vout3) -1;
          Rx= R3 * buffer;
          Rx=Rx-(R1+R2);
          Serial.print("Vout3: ");
          Serial.println(Vout3);
          Serial.print("Rx: ");
          Serial.println(Rx);
          delay(1000);
          }
       }
   }
}

======================================================

to jot here are the results as i have previously explained the ohmmeter worked pretty well at the beginning but when i turned it off Then back on the value measured changed, the error got much bigger i tried changing the caliber aka R1 from 220 to 100 but the results were the same, the error was still big
thank you

Make the variable Vin a float.
The range is limited by the number of analog inputs and the resistors are in series. It will be hard to adapt the circuit to measure a resistor of 10 ohm. It is possible to use digital pins to power resistors or not and use a single analog input.

The answer by @EdgarBonet seems to be a very nice solution for the lowered output voltage of a pin, when a low resistor value is used.
A arduino uno pin can output 20mA without problem, even up to 40mA if needed. So a safe value to measure low resistor values is 220 ohm, which could result in a maximum of 23mA.
Analog input A1 is used both as digital output to power the circuit and also as a analog input to measure how much the voltage has dropped.
This is a quick test:
// Using the idea in the answer by Edgar Bonet
//
// Allow that the voltage of a digital output is
// lowered by the low resistor value,
// to calculate the unknown resistor.
//
// With two resistors in series.
// A1 - 220 ohm - A0 - 10 ohm - GND
//
// The circuit is a voltage divider.
// A1 powers the voltage divider.
// A0 measures the output.

#define R1 220
#define N_SAMPLES 10

void setup() {
  Serial.begin(9600);
  pinMode(A1,OUTPUT);
  digitalWrite(A1, HIGH);
}

void loop() {

  // Pin A1 is already set as a digital output and set HIGH.
  // Using analogRead(A1) is to measure the real output
  // voltage. There is a voltage drop, because of the current.
  float Vin = averageRead(A1);
  Serial.print("Vin=");
  Serial.print(Vin);

  float Vout = averageRead(A0);
  Serial.print(" Vout=");
  Serial.print(Vout);

  if(Vin > 0.0 && Vout < Vin) {
    float Vt = Vout / Vin;
    float Rx = (Vt * R1) / (1 - Vt);
    Serial.print(" Rx=");
    Serial.println(Rx);
  }

  delay(500);
}

float averageRead(int analogPin) {
  int total = 0;
  for(int i=0; i<N_SAMPLES; i++) {
    total += analogRead(analogPin);
  }
  return float(total) / N_SAMPLES;
}

That is very nice. It is no problem when the unknown resistor is 10 ohm.
Because of the low resistor values, I did not add delays. With high resistor values, some delay is needed before measuring the analog values.
The next step is to find the best value by finding the value that is the most in the middle, as Edgar Bonet has explained in his answer.
// Autoranging by finding the value that is most in the middle.
// Using the answer by Edgar Bonet

#define N_SAMPLES 10          // the number of samples to average, maximum 30

// Four resistors to power the circuit (one at a time).
// A1 has a resistor of 220 ohm, A2 has 3k3, A3 47k, and A4 750k
// The other leg of the resistors are all connected to A0.
// The unknown resistor Rx is at pin A0 and GND.
const float R[4] = {220.0, 3300.0, 47000.0, 750000.0};
const int pinR[4] = {A1, A2, A3, A4};
const unsigned long wait[4] = {1, 2, 4, 10};  // delay, values guessed.
const int pinMeasure = A0;

void setup() {
  Serial.begin(9600);
  Serial.println("Autoranging");
}

void loop() {
  float Vin[4];    // Vin is the pin that powers the circuit
  float Vout[4];   // Vout is the voltage over the unknown resistor

  for(int i=0; i<4; i++) {
    // Power the circuit with this resistor
    pinMode(pinR[i], OUTPUT);
    digitalWrite(pinR[i], HIGH);

    // Vin is the pin that powers the circuit.
    // This is always low impedance, no need to wait.
    Vin[i]  = averageRead(pinR[i]);

    // Extra delay to wait for the voltage to become steady,
    // before reading the analog data.
    // Might be needed for the higest resistor values
    // Perhaps there is a cable to the unknown resistor
    // that has capacitance.
    delay(wait[i]);

    // The first 'analogread()' sets the multiplexer.
    // For a high impedance circuit, the first
    // 'analogread()' might be less acurate.
    // Read it a few times, and throw it away.
    averageRead(pinMeasure);

    // Everything is settled by now.
    // Read the analog input for real.
    Vout[i] = averageRead(pinMeasure);

    pinMode(pinR[i], INPUT);  // Make this pin high impedance
  }

  // Find the value for Vout that is the most in the middle.
  // For an Arduino Uno, the middle ADC value is 512.
  float diff = 2000.0; // set to value higher than possible as default
  int best = 0;        // index of the best resistor

  for(int i=0; i<4; i++) {
    float d = fabs(512.0 - Vout[i]); // difference for this resistor
    if(d < diff) {                   // closer to the middle?
      diff = d;                      // remember new difference
      best = i;                      // remember index best resistor
    }
  }

  if(Vin[best] <= 0.0) {
    Serial.println("Something wrong with the circuit");
  }
  else if(Vout[best] >= Vin[best]) {
    Serial.println("Rx not connected");
  }
  else {
    float Vt = Vout[best] / Vin[best];     // temporary precalculation
    float Rx = (Vt * R[best]) / (1 - Vt);  // calculate unknown resistor

    Serial.print(" Rx=");
    Serial.print(Rx);
    Serial.print(" ohm (with resistor ");
    Serial.print(R[best]);
    Serial.print(")");
    Serial.println();
  }

  delay(250);
}

float averageRead(int analogPin) {
  int total = 0;
  for(int i=0; i<N_SAMPLES; i++) {
    total += analogRead(analogPin);
  }
  total += N_SAMPLES / 2;  // see www.gammon.com.au/adc
  return(float(total) / float(N_SAMPLES));
}

I would like to add a capacitor from A0 to GND (parallel with the unknown resistor) to reduce noise. This capacitor should be 1nF or less. The delay in the code is large enough to wait for the voltage to settle with 1nF.
The increase of the resistors by 15 times is a large step. That makes it less accurate, but the arduino uno has only 6 analog inputs. By using 5 resistors with an increase of 6 times is better.
4 resistors 15x : 220, 3k3, 47k, 750k
5 resistors 6x  : 220, 1k2, 8k2, 47k, 270k
There are a few ways to do more:

When two resistors result in a output that is close to the middle, it is possible to average the results.
When the 5 resistors are used, it is for example possible to lower the value of the 8k2 resistor. When all higher values are turned on, the resulting resistor value becomes 6k8 instead of 8k2.
For high resistor values, the output voltage of a pin is not lowered, and digital outputs can be used as well.

An protection resistor for A0 might be needed. I think that a value of 470 ohm or 1k should be fine.
Many thanks to @EdgarBonet, I used his answer and added the average and the delay.

Update November 2018
@RekaiaDraoui
When using a breadboard, there can be contacts which are not perfect. That can cause a lot of troubles.
Are you using a circuit as this:

Wow this is pretty impressive i see what you did right there one small issue that still worries me, EdgarBonet previously mentioned "the pins have an output resistance that is about 25 Ω, which ends up being in series with the corresponding reference resistors. You can account for that by adjusting, in your code, the values of those references." i wonder why you didn't take this detail in consideration when you wrote this code?, thank you

I did! Not the 25 ohm, but I measure the actual voltage drop. Edgar Bonet wrote "That's why I suggest to use analog instead of digital pins" (to be able to measure the voltage drop of a pin). I measure the voltage of the pin that powers the circuit and the voltage over the unknown resistor. The analogRead of pin a1 could be 840 (instead of 1023) and the a0 could be 37. The actual voltage does not matter. With the two resistors, everything is relative. Because it is a voltage divider, the unknown resistor is measured relative to the 220 ohm resistor. The calculation is just two lines.

OH! true i missread both of your answers well thank you big time! i will improve it and post it here as an answer once im done if anybody was interested, thank you again

i have another question, i've tried ur circuit in a simulator bcz my pc decided to stop all of a sudden, anyway when i chose a high value reference resistor(say 100k) vin was equal to 1024 so 5v unlike a low value reference resistor(say 220)where vin was about 824  can you please explain to me why is that ?

Because of the output resistance of 25 ohm, that Edgar Bonet was talking about. The atmega328 can output 20mA (even up to 40mA), but with such high currents the pin is no longer Vcc (5.0v), but lower. With very small current, it has no problem to set a pin to Vcc (5.0v). That is what my sketch is for. To test the accuracy by actually measuring the output pin with a analog pin. Since the arduino uno has a digital pin and a analog pin combined for all analog inputs, it is possible to use that single pin. Did you choose reference resistors? You can set them apart by 15 times: 220, 3k3, 47k, 750k.

i have, that's what i've been saying and when i used high values like 100k or 1M vin would be vrey high (1024).you're saying that is bcz the current is very low ?

Yes. In the datasheet ( http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf ) at page 391, Figure 33-24 you can see that the output drops when it has to supply current. For example, it drops to 4.5V at 20mA.

You are welcome, and nice job! For high resistor values, I suggest that instead of delaying, you read Vin, then take many readings of Vout that you throw away, then the Vout readings that you want to keep. The reason is that you want the ADC input capacitor within the sample and hold circuit to get charged to the appropriate Vout voltage. AFAIK, this capacitor only has a chance to charge during a short time at the start of each ADC conversion, meaning that the first readings you take after switching the multiplexer from Vin could be corrupted by the cap not having completely settled.

@EdgarBonet Thanks. I want to keep the possibility to add a small capacitor (1nF or less) at A0, parallel with the unknown resistor, to reduce noise. I have rearranged the delay and do a dummy read before finally reading the analog input. I have also added 0.5 bit to the average function. The 10 samples for the average is a low amount, perhaps 50 can make it a little better, but then the 'total' must be a long.

@Jot was hoping you could help me more, i have tested your program and circuit it worked very well at the beginning but after some time the values changed completly and the error got much bigger i was hoping you could explain to me why and if possible tell me how yo fix. I have posted 2 images showing the different values measured i edited this information into my question  please check it out, thank you

@RekaiaDraoui, I have added an update to my answer.

@Jot i have removed the breadboard now it's measuring 12 ohms instead of 14ohms but the error is still big(ps: Rx=10ohms)

@RekaiaDraoui, the Arduino Uno can supply 20mA (40mA shortcut current), that limits the maximum current, and that is why the lowest resistor to A1 is 220 ohm. With this circuit it is not possible to measure 10 ohms accurate. To measure 10 ohms accurate, perhaps a opamp has to be added. EdgarBonet wrote about the limits, but I thought it did not have to be very accurate for low or high resistor values.

@Jot i chenged the breadbord now im getting acceptable readings(10.66/10.75....ohms)but im still concerned cuz i got good results using the first breadbord at first then you know what happened, anyway thank you so much for your help, i was wondering if you had a blog or a quora account if you welcome questions, thank you again

@RekaiaDraoui no, no blog or quora. For 10 ohms you might need soldered connections, but it is the limit, it will not be accurate.

As you probably already know, the standard setup for measuring a
resistance with an Arduino is to put the unknown resistor in series with
a known one between 5V and GND, and measure the voltage at the point
in-between them:
     5V
     │
     R₁
 A0 ─┤
     R
     │
    GND

where R is the unknown resistor and R1 is the known
reference. The resistance is then computed as:
const float R1 = ...;  // reference resistance

int reading = analogRead(A0);
float R = (float) reading / (1024 - reading) * R1;

First, it is worth noting that the reference voltage does not appear in
this calculation. You could, of course, do the calculation in terms of
voltage, but you should then notice that the reference voltage can be
simplified away. This is not surprising if you realize than the ADC of
the Arduino does not actually measure a voltage: it rather measures a
voltage ratio: the ratio of the input voltage to the reference
voltage. This ratio can then be easily related to the resistance ratio
R/R1. What all this implies is that you should not expect to
get better accuracy by using a 3.3 V reference rather than
5 V. Any inaccuracy in the voltage reference is irrelevant to the
measurement of the resistance.
Next, when measuring a physical quantity, you are almost always
interested in the relative rather than the absolute accuracy. From
the equation above, it can be easily shown that you get the best
relative resolution when the reading is near the middle of the ADC
range:
raw reading    │   64 │  128 │  256 │  512 │  768 │  896 │  960
───────────────┼──────┼──────┼──────┼──────┼──────┼──────┼──────
resolution (%) │ 1.67 │ 0.89 │ 0.52 │ 0.39 │ 0.52 │ 0.89 │ 1.67

This is consistent with your observations, and it means that the
reference resistor should ideally have a value that is of the same order
as the unknown resistor.
Now, for the autoranging, I would advise you against putting all your
reference resistors in series. With this setup, you always have the same
voltage across the unknown resistor, irrespective of what range you
choose. Reading a different input does not help. You may find out that
the voltage between R1 and R2 gives a better
reading (closer to mid-range), and you get a better accuracy on the
measurement of R+R1. However, when you subtract R1
you are immediately degrade the relative accuracy of the result. In
the end you cannot really improve the accuracy this way.
What I suggest is to put the reference resistors in parallel instead of
in series, and power each one from an analog pin:
     A1  A2  A3
     │   │   │
     R₁  R₂  R₃
 A0 ─┼───┴───┴── ...
     R
     │
    GND

You then use these analog pins in digital mode: all of then in INPUT
mode, except one which is set to OUTPUT HIGH. You can try all of
them in turn and select whichever gives a result closer to mid-range. Or
you can implement a smarter algorithm that finds the optimal one without
trying them all.
There is something to be aware of with this setup: the pins have an
output resistance that is about 25 Ω, which ends up being in series
with the corresponding reference resistors. You can account for that by
adjusting, in your code, the values of those references. But then that
output resistance is not very well known, and can vary with temperature.
This should only be an issue when you are in the low ranges though. You
can mitigate this problem by measuring the voltage at the pin that is
currently pulling up, and replacing 1024 in the equation for R by that
reading. That's why I suggest to use analog instead of digital pins.
Finally, there are a couple of limitations that you should be aware of
when measuring resistances with the Arduino ADC. At the low end of the
resistance range, you cannot use a reference resistor with a very low
value, because you have to make sure you do not pull more than about
20 mA from the pin that pulls up. Your smallest reference may then
end up being somewhere around 220 Ω, and you will loose significant
accuracy when you try to measure anything below 50 Ω. At the upper
end of the range, you should be aware that the ADC is meant to measure
voltage sources with an output resistance no larger than 10 kΩ,
otherwise you risk cross-talk between the ADC channels. Then your higher
reference should probably be 10 kΩ, and any measurement above
50 kΩ will give poor accuracy. Going past these limitations would
require extra electronics, like a good-quality op-amp to “condition” the
signal into something that the ADC can reliably measure.

The 50kΩ upper limit is on the safe side. I have no problem with 1M. That requires the average of a number of samples and sometimes an extra delay or a capacitor to gnd (to keep the voltage the same when the adc eats some charge). When for example only 5% accuracy is required for the very low and very high resistor values, then a lot is possible.

thank you for your answer it has served me alot, as a last question i have felt after reading your answer that my project doesn't seem to be well made and that is of course due to my lack of knowledge in this field now, do you think it is worth fixing or should i jump to another way? it doesn't metter how it works as long as it is eventually an autoranging ohmmeter, thank you @EdgarBonet

@RekaiaDraoui Your circuit has too many limitations. Use this circuit with turning on a resistor one at a time. Find in the sketch which value is the most in the middle and use that to calculate the unknown resistor.

I don't quite get your last question. Can you easily change the circuit, or is it something you have soldered?

@EdgarBonet yes i can easily change the circuit

@Jot thank you for orienting me, that's what i'm planning to do.

@EdgarBonet can you please tell me where did you get the values of the table from?

@RekaiaDraoui: I computed them. For example, for a reading of 256, R/R₁ = 256/(1024-256) = 0.33333. One ADC step above, at 257, it's R/R₁ = 257/(1024-257) = 0.33507. The difference between these two numbers is 0.52%.

@EdgarBonet actually it's 0.174%, if by difference you mean (0.33507-0.33333)*100

@RekaiaDraoui: No. When a difference is given in percent, it is always understood that it is a relative difference.

@EdgarBonet your results make much more sense now. Thank you very much for your help.


text:
Getting FFT arduino code to run over 9+ hours, utilizing micros()
I am a beginner in Arduino, coding, and electrical engineering (learning on my own time) and am working on creating an EEG. I've got the hardware down and have managed to get numerical data output from the analog (A0) of Arduino. The next step is transforming these numbers to outputting dominant frequency and I have managed to find a code that uses FFT to find the dominant frequency from the input of A0. The following is the code:
#include "arduinoFFT.h"

#define SAMPLES 128             //Must be a power of 2
#define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[SAMPLES];
double vImag[SAMPLES];

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

sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}

void loop() {

/*SAMPLING*/
for(int i=0; i<SAMPLES; i++)
{
    microseconds = micros();    //Overflows after around 70 minutes!

    vReal[i] = analogRead(0);
    vImag[i] = 0;

    while(micros() < (microseconds + sampling_period_us)){
    }
}

/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

/*PRINT RESULTS*/
Serial.println(peak);     //Print out what frequency is the most dominant.

for(int i=0; i<(SAMPLES/2); i++)
{
    /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

    //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    //Serial.print(" ");
    //Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
}

delay(1000);  //Repeat the process every second OR:
//while(1);       //Run code once

}
The problem I have is with the line microseconds = micros(). The comment state that this will overflow after 70 minutes and after some days of research, I sorta understand what is meant by this. However, I need this program to run over 9 hours, so I can log the dominant frequency of the brainwave throughout the night. Is that possible?

Hi, interesting project. How much memory is necessary?

I apologize, but I'm not sure what you mean by that. If I understand correctly, I am attempting to take the dominant frequency every ten minutes within the course of ~9 hours. That would mean the COM output would be displaying 54 different data or memorizing it. (6 data every hour * 9hours).

Chris Do, there is indeed a rollover problem when micros is used that way. When that happens, the samples are taken at full speed without interval. That will create bad data for the FFT.
The solution is in the Blink Without Delay example. The magic to avoid a rollover problem is the substraction with two unsigned long values.
The arduinoFFT library is in the Library Manager of the Arduino IDE.
The example "FFT_03.ino" uses micros in the wrong way.
The next sketch shows how to avoid the rollover problem:
// Use micros() without rollover problem for a fixed sample rate
// for a certain amount of samples.

#define SAMPLES 128

unsigned long previousMicros;
const unsigned long intervalMicros = 1000UL;   // 1000 Hz is 1000 us

float vReal[SAMPLES];
float vImag[SAMPLES];

void setup() {
}

void loop() {

  previousMicros = micros();  // set the previousMicros just before entering the for-statement
  for(int i=0; i<SAMPLES; i++) {

    // A while-statement to wait.
    // Note that the ';' at the end means 'do nothing'.
    while( micros() - previousMicros < intervalMicros);

    // The 'previousMicros' is increased with a fixed number, for a fixed sample rate.
    previousMicros += intervalMicros;  // for next interval

    vReal[i] = float(analogRead(0));
    vImag[i] = 0.0;
  }

  delay(1000);
}

Take the current value of micros and substract the previous value of micros. The result of that substraction is a valid number, even during a rollover. It is the only way that always works.
The line to calculate the sample period has too many things in it that can go wrong. These lines:
unsigned int sampling_period_us;
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));

In my example, I set the intervalMicros to a certain number. Could you do that as well? When everything works, you can try to calculate it.
Added: The answer by Edgar Bonet is exactly the same. That is no surprise because there is no other way.

Re “The example "FFT_03.ino" uses micros in the wrong way”: I wasn't aware that the OP copied the bad example from the library itself. Good catch! I just submitted a pull request to the author of arduinoFFT. Hopefully he will get this fixed upstream.

As long as you never compare timestamps, the rollover is not an
issue. The idiom you used:
while (micros() < previous_timestamp + period) ...

is comparing two timestamps. This is incorrect, and it fails whenever
micros() rolls over. However, subtracting timestamps to get a duration
does work fine across rollover events. And comparing durations does
always work. So the correct idiom is:
while (micros() - previous_timestamp < period) ...

Note also that the way you update microseconds is incorrect. You are
incrementing it by the period you want plus the time taken by the
CPU to execute some of the code in the loop. You should instead
increment it by the requested period and no more. Here is my take at
what you are trying to accomplish:
/* SAMPLING */
microseconds = micros();  // record initial time
for (int i = 0; i < SAMPLES; i++) {
    while (micros() - microseconds < sampling_period_us)
        ;  // wait for the right time to take the sample
    microseconds += sampling_period_us;  // update as per the period
    vReal[i] = analogRead(0);
    vImag[i] = 0;
}

Edgar bonet and jot, I greatly appreciate your answers. I believe I did come over the rollover topic while researching and saw the solution but never comprehended until now. Just to be clear however, the problem with using micros is that it will rollover (In other words, after approximately 4.26*10^9 microseconds, it will rollover back to 0 and restart counting upward again). The solution is to use interval because the numerical value of theinterval will be the same even if micros() rollover. Is that correct? I will try this approach. Thank you very much for your help!

@ChrisDo: That's correct. See also millis() overflow ... a bad thing?

Hey Edgar, after experimenting with the code that you provided for a few days, it seems that the output of the FFT gets very sporadic after a while. Compared to the original code that I found, the output of that original code would be something like 23, 22, 23, 24, 25, 26, 30, 27, 25.
With the code that you have provided, it would output something like 23, 22, 65, 102, 300, 450, 23, 34, 46, 89.
By any chance do you happen to know why this would be?

@ChrisDo: This is unrelated to the rollover issue. I have no idea why your data looks like that.


text:
How to use SPI to set/ read registers for a sensor (Avoiding need for Github Lib)
Ok so as some readers might have seen, my current project involves using MPU's. The idea is sending data via CAN bus to a controlling MCU to then send to a raspberry pi to perform the calculations required for my MATLAB/ Simulink model.
After a lot of searching i found this great post/ blog on how to set I2C registers.
Setting I2C Registers
With this, i was able to avoid using a library from Github. I do NOT think i am better than the people writing the libraries, just it's difficult to truly understand code/ a project with a downloaded library and it just stuffed at the top of a piece of butchered example code.
Using the above blog, i learnt how to control an MPU6050 myself in a very basic sense. I am now trying to use an MPU9250 for the sake of extra speed over SPI. However i am trying to understand how to set registers using the SPI interface. For example below for I2C you could write;
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

and then access the registers like below;
Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

my question, is how do you read and write to registers in a similar way via SPI. I've found lots of info on using SPI, but not configuring sensors etc with it in a nice, "SPI configuration for Dummies" type of thing. Is my googling just terrible?
EDIT - My goal is learn the theory behind making a basic library for a sensor, not to make my own SPI library. For example, make a library that can be used to control an MPU9250 using SPI commands to change registers. The last part is what i am struggling with. Interfacing with a sensor to change register values or read registers with SPI.
The link above is almost a crash course in how to use the wire library to interface with a sensor. How do you use the SPI library to change/ read register values.
EDIT2 - Is this the usual format for communicating with registers using SPI on arduino? Thanks
digitalWrite(SS, LOW);
SPI.transfer(0xF1);  // Read, Sensor 1...
SPI.transfer(0x02);  // ... RESA register
highByteA = SPI.transfer(0x00);  // Read High Byte of RESA
lowByteA = SPI.transfer(0x00);  // Read Low Byte of RESA
highByteB = SPI.transfer(0x00);  // Read High Byte of RESB
lowByteB = SPI.transfer(0x00);  // Read Low Byte of RESB
.
.
.
digitalWrite(SS, HIGH);

thanks

The Arduino IDE already has a SPI library, that you can use (like is also already has the Wire library for I2C). There are may tutorials, that explain, how to use it. And there is no general way to "configure sensores". It depends on the sensor. For the MPU it can be found in it's datasheet, though this is not a "... for Dummies" guide. I think you probably won't find such a guide, since the way "... for Dummies" is to use a premade library. But you might also learn much by looking at these premade libraries, that you don't want to use. Otherwise you just chose the hard tour.

This is what i like. Getting different perspectives. I am happy to use the SPI library, what i wanted to learn is almost how to make my own for each sensor. The link i put in explains the theory of communicating with the sensor to change parameters/ registers using I2C. (e.g measurement range or frequency). I will change my question to make it clearer what i am asking

Have you read page 36 of the datasheet (for example here https://cdn.sparkfun.com/assets/learn_tutorials/5/5/0/MPU9250REV1.0.pdf ) It explanes how it works. The first byte consists of a read/write bit and the address of the register, that you want to access. Next bytes are data (for example that should be written into the specified registers). Have you tried reading some registers that way?

forgive my ignorance. i did see that in the datasheet but my issue was trying to find how to actually write to or read from the register. I haven't figured out code tags in the comments, but i found some code from a post on arduino.cc that i overlooked because the OP hadn't found a working solution. It is at the bottom of my post.
is that the format to read to or write from a register for a sensor using SPI?

Do you have a logic analyzer? I was working on some similar things last year and it was infinitely helpful to be able to see what was actually happening on the wire.

no i don't have a logic analyzer, but might get one. i got it working in the end using the format above, it uses the same principle as i2c for writing to registers but just different names


text:
Arduino will not recognise USB ports on my Mac running Sierra
Arduino will not recognise USB ports on my Mac running Sierra
I am a teacher who helps teachers to use LilyPad. I used to be able to plug in my LilyPad Arduino and see the USB port. I have read all the answers and dowloaded the drivers from Spark fun and another driver from Github. Nothing is working and i am not technical enough to find the answer myself.  I have spent three hours today trawling through the answers to this problem and still cannot fix it myself. I am a luddite who needs a simple step by step remedy. Apple support had no idea when I rang them and told me it was an Arduino problem and to talk to them. you cant talk to anyone at Arduino you can only go to the forums. the forums tell you to read others answers before you post. I have. it's still not working. i need help. And not a lecture about being on a forum asking dumb questions.
I even mucked around in terminal and am hoping it's not a 'terminal" problem because I have no clue what i am doing. If you can explain in plain speak please respond. i have to teach this stuff in 4 days.

This is the message I get when I try to upload a sketch

LilyPad USB implements a atmega32u4 with built in USB. it doesn't have any FTDI or CH340 chips. so you don't need to install the mentioned driver files. the driver for this board installs with Arduino IDE itself. if you try to reset the board with onboard switch, the ports should vanish and reappear. try this and let me know what happens.

Tried pressing the reset button and nothing happened except the built in LED stopped flash and then returned as soon as I let the reset button go. Nothing changed in the ports. Thanks for answering. K

interestingly the usb ports appear when i plug in an Arduino uno. but not for lilypad.

I am a teacher who helps teachers to use LilyPad .... you should really call things by their correct names .... Arduino will not recognise USB ports on my Mac should be Arduino IDE will not recognise USB ports on my Mac

I spoke to a very clever friend who has had similar problems. The answer lay in downloading the FTDI helper package not just the driver.  If anyone else is having a similar problem the website is
https://www.ftdichip.com/Drivers/D2XX/MacOSX/D2xxHelper_v2.0.0.pkg
I downloaded it and now my lilypad and USB port is recognised by the Arduino software.
Just in time for Thursday.
Thanks to all who tried to help.
K

I had a problem getting my computer (Mac Pro, OS 1.12.1 Sierra) to recognize my Arduino Leonardo and Micro boards. Tried many different fixes, nothing worked. Finally used a different cable, and both boards worked fine. NB: I didn't suspect a cable problem, since I removed the cable from a working device. Just to make things weirder, the original device I removed the cable from worked just fine when I re-installed the (supposedly defective) cable.

The Lillypad uses the ATMega32U4 chip. This is the same as the Arduino Leonardo and the Arduino Micro, and suffers the same basic issue that they both suffer from.
Basically, the USB connection is driven by the main chip, not by an interface chip as in most other Arduino boards.  This gives you increased flexibility (e.g., using it as a keyboard or a mouse) and decreased cost (less components on the board), but at the additional cost of certain problems that you have to be prepared to resolve.
Because the main chip runs the USB connection that main chip must be working properly for there to even be a USB connection. With other boards that isn't the case - you can remove the main chip completely and the USB interface chip will still work.  So it is perfectly possible to "kill" the board by installing a sketch on it which stops the main chip from functioning. As soon as the main chip stops functioning the USB stops functioning - and if the sketch that is installed never starts working at all then you never see a USB connection.
Sometimes it is possible to get the USB port to appear for a short period (a few seconds) by pressing the reset switch, but you have to time it right (press reset and immediately select the port in the menu, then press upload, and press reset again just before the uploading itself starts).
The sure-fire fix, though, is to erase the entire chip (along with your installed "broken" sketch) and reinstall the bootloader using the IDE's tools.  You'll need either a hardware programmer (the USBASP is dirt cheap and easy to get on eBay) or another Arduino using the ArduinoISP sketch bundled with the IDE.
If you're going to do any serious work or teaching with any microcontroller-based system it's always good to have a hardware programmer available to help recover from problems, no matter what platform you're working with.  Remember: if there's a way to break it, kids will find it. And do it.

This is a brand new out of the box lilypad board with no sketches loaded on it at all. The ports do not appear when I plug in and select "tools".  This is the third one I have opened and there is nothing that works. I have tried bot USB ports. Nothing. So it isn't broken. It just won't work.

Hmm... That is most odd. I'd suspect your USB cable.  You should also check this answer: https://arduino.stackexchange.com/a/46122/4143

i checked it. it is beyond my skill set!. Thanks anyway. Three usb cords too!

try a computer with Linux or Windows

I had the same problem: my MacBook Air registered by Arduino Board in the USB Device Tree but it was not showing up in the Ports list of the Arduino IDE. It was resolved when I changed the Privacy and Security setting for Allow Accessories to Connect. When I changed the setting to "Automatically When Unlocked" the Arduino IDE was able to recognize my board.
Route to setting: Apple Logo on top Right -> System Settings -> Privacy and Security -> (scroll down to Security) Allow Accessories to Connect.


text:
Why is AREF connected to a capacitor in the Arduino Pro Mini Schematic?
I'm currently looking at the Arduino Pro Mini schematic and have noticed that the pin AREF (analogue reference) is connected to a 0.1uF capacitor as shown below:

I have done some research and read this great explanation into AREF and now understand its purpose as a voltage reference. What I do not understand however is the purpose of the capacitor. Is it as a means of stabilising the pin when an external voltage is applied, or something else?
A full schematic of the Arduino Pro Mini can be sourced from here.

That has clarified part of my question. I will rephrase my post.

On the datasheet for the Atmega328P, in the Analog-to-Digital Converter section, is the sentence:

The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

Also:

The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.

Thus the capacitor is there to reduce noise on the AREF pin.

An ideal capacitor presents an impedance of wC (radian frequency * capacitance -- ohms).  Of course ideal capacitors do not exist in real component selections or circuits and all include parasitic losses and inductance. The parasitic components depend on the type of the capacitor, lead length, connecting circuits, etc.  Oscilloscopes, network analyzers and spectrum analyzers serve to identify fundamental performance of voltage reference points.
The decoupling capacitor should be connected using short leads to a ground plane layer and the Aref pin.

Rather than provide a generic answer which may or may not assist the individual using the pin, I added information to guide selection of a capacitor.  Simply adding a 0.1uF capacitor may or may not resolve a specific noise condition and in fact may worsen the issue.


text:
Global Variable does not Change when Value is set within Boolean Function
I have a boolean function which contains a string. In my main project this string is extracted from a website using an ESP8266 which is compatible with the Arduino IDE. I need to convert this string to a char* type of which is to be used in the loop() section of the code. The issue which I have faced is related to the setting of the mPass global variable, which does not change when it is done in the restoreConfig() Boolean function, meaning it remains blank when called for in the loop.
I do understand that this problem is related to the fact that I am defining the mPass within the Boolean function, however I am unsure as to the process in which I can change the global variable without errors.
I have tried resolving this problem through moving the mqttpass, mqttpasslen and mPass variables out of the restoreConfig() function, however it creates significantly more problems than that which I have at the moment. As a result I have only presented the code without any adjustment below:
char* mPass = "";

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

void loop() {
  if (restoreConfig()) {
    Serial.println(mPass);
    Serial.println("ABOVE IS mPass IN LOOP");
  }
  delay(1000);
}

boolean restoreConfig() {
  String mqttpass = "DOGS";
  int mqttpasslen = mqttpass.length() + 1;
  char mPass[mqttpasslen];
  mqttpass.toCharArray(mPass, mqttpasslen);
  Serial.println(mPass);
  Serial.println("ABOVE IS mPass IN BOOLEAN");
  return true;
}

My current output from this is:
DOGS
ABOVE IS mPass IN BOOLEAN

ABOVE IS mPass IN LOOP

You have local variable mPass in the function restoreConfig. It 'shadows' the global variable.

Hi @Juraj, I do understand that this is the case and have since uncommented the local variable mPass, however now my output does not show anything but blank. If I attempt to move char mPass[mqttpasslen], then I have the issue that then mqttpasslen is undefined. Do you have any suggestions as to the way I can resolve this?

the global variable is only a pointer. change it to array to allocate space.


text:
How do I run a bipolar motor with an arduino uno?
At the risk of looking like a complete idiot on the internet, I'll preface with this; I'm incredibly new to this. I'm new even to coding, and not sure what questions I should be asking.
I'm trying to run a bipolar motor with an Arduino Uno. I'm fairly sure it should be as simple as set a pin to high, plug the motor into that pin and a ground and it should run. I did this a week ago, and it worked then.
Now I'm trying to essentially run a modified version of blink with this motor running instead of the LED. Running the code with pin 13 as my positive does still flash the LED. If I set my pin to high with the motor, the motor no longer runs. However, It does run when plugged into the 5V and ground. The motor also runs straight off of the two poles of a 9V battery.
I'm unsure what I'm doing wrong. Do I need to step up the voltage of my pins somehow?
Thanks in advance.
-Alec Rosso
Edit 1:Here's the code:
int motorPin1 = 13;
int interval= 5000;

void setup() {
pinMode(motorPin1, OUTPUT);
digitalWrite(motorPin1, HIGH);
}

void loop() {
digitalWrite(motorPin1, HIGH);
delay(interval);
digitalWrite(motorPin1, LOW);
delay(interval);
}

As far as voltage or current specifications, it says DC 12V.
Edit 2: it is not a stepper motor. The serial number is TS-32GZ370-950. It's apparently a "DC geared motor."
Final Edit: I've got it working using an L298. I used a 9-volt battery in addition to my arduino's 5 volts, and everything works like a dream. Thank you for your help.

@VE7JRO it's possible it's a duplicate, and it would make sense that i'd need a shield or something similar to run it. I'm going to try an L298 motor driver, but my limited expertise make this whole operation somewhat trial-and-error.

If you resolved the issue please "accept" the answer that helped you the most, or make your own answer describing how you solved it. This will help others to realize the problem has been solved.

"At the risk of looking like a complete idiot on the internet,"
Without getting personal - you cannot put 10 pounds of potatoes in 5 pounds bag.
AKA you cannot run 12V device with (5V output) Arduino   BECAUSE 12V device / motor requires far more current than Arduino can safely provide.
That is the short version - you probably moved the motor at very slow speed and lucked out before you let the smoke out from the Arduino chip.


text:
Arduino Uno ADCH register stuck at 255 when read from ISR
I'm working on a project that will essentially become an oscilloscope in the long run. I am following this guide. My code is uploaded here for more reference.
In my .ino file I have called functions to set up register such that I have a timer ISR called at a frequency of 100 KHz, and an ADC clock rate of 2 MHz. The ADC is also set so that the result is left shifted so ADCH contains an 8-bit result. In a separate .h file I have an ADC ISR that looks like this:
ISR(ADC_vect)
{
  // Read 8-bit conversion result from ADCH.
  uint8_t byte0 = ADCL;
  uint8_t byte1 = ADCH;

  data_byte = byte1;
  flag = true;
}

The loop() function is the following:
void loop()
{
  if (flag == true)
  {
    //Serial.println("ISR HIT");
    Serial.println(data_byte);
    flag = false;
  }
}

So, when the ISR is called the flag is set to true, and in the loop() function I am notified with an "ISR HIT" printed on the serial monitor, this operation is successful.
However, I also have a volatile global variable in my .ino function called data_byte (also declared as an extern in the .h file) that I set byte1 to. When byte1 is printed to the serial monitor the result is:
255
255
255

Any ideas on why the value of ADCH is stuck at 255? My hardware is simply a light sensor connected to pin A0, 3.3 V, and GND.

At 9600 baud sending "ISR HIT" can be done 120 times per second. You want to send it 100000 times per second.

You never set nor print data_byte. Or maybe you do in a version of the program you didn't publish. If we cannot see the code, there is no point in trying to guess what could be wrong.

@Jot Thank you! I did not take that into consideration. Ideally I would set the baud rate to ~800,000 bps (or higher) but right now I've just set it to 250,000 because my serial monitor on my computer isn't letting me go higher.

@EdgarBonet My apologies, I had removed that bit of code for debugging purposes. The updated code is in github and I've updated the code snippets in this question.

Your program works for me: connecting AREF to 5V and A0 to 3.3V gives a stream of numbers around 187. Please, show us the complete schematic of the circuit you are using.

@EdgarBonet Thank you for your comment, I figured out what was wrong from it. I assumed my setup used the internal 5 V reference, however I realize now that I need to apply voltage to AREF (I applied voltage from the 5 V pin), and now my setup works. If you would write it as an answer I would gladly accept, thank you so much!

It would seem the problem lies here:
// Set Register to all zeros since Vref
// will be set to internal voltge and
// analog pin A0 is used.
ADMUX = 0x00;

According to the datasheet, the bits REFS[1:0] of the ADMUX register
select the voltage reference as:

00: AREF, Internal V ref turned off
01: AVCC with external capacitor at AREF pin
10: Reserved
11: Internal 1.1V Voltage Reference with external capacitor at AREF pin

Settings those bits to zero means that you are now supposed to provide
your own reference through the AREF pin. If you want to use the 5 V
supply as a reference, you should set them to 01. This is confirmed by
the block schematic. Here is the part of that schematic relative to the
reference voltage:

When REFS0 is zero, the highlighted transistor does not conduct, hence
the only way to provide a voltage reference is through the AREF pin.

Answer accepted! Thank you again for such a through and well explained answer.