text:
Motor response is lagging
I've got a DC motor connected to an Arduino Nano, L298N H-Bridge and a 12v Power supply. I'm trying to make it respond to incoming MIDI data a bit quicker. Right now, it seems awfully slow, and lags in response to quick value changes. I'm using MIDI to send data into my Arduino, so my baud rate is limited to 31250.
The issue is mainly with my DAW (Ableton), as my motor responds quickly when I try to control it with a fader on my MIDI keyboard.
Note: I'm also using a potentiometer and a capacitive touch sensor in this code. I'll try to simplify it as much as I can so I can isolate the issue
Here's the code:
#include <SoftwareSerial.h> // MIDI Input
#include <CapacitiveSensor.h>
#include <MIDI.h> // MIDI Output
#define txPin 1
#define rxPin 4

SoftwareSerial midiSerial (rxPin, txPin);

const byte touchSend    = 2;//Send pin for Capacitance Sensing Circuit (Digital 7)
const byte motorPWM     = 3;
const byte motorDown    = 5;
const byte motorUp      = 6;
const byte touchReceive = 7; //Receive pin for Capacitance Sensing Circuit (Digital 8)
const byte wiper        = 7; //Position of fader relative to GND (Analog 0)

int incomingCommand;
int incomingNote;
int incomingVelocity;
byte motorSpeed = 75; // Raise if the fader is too slow (0-255)
byte minimumCp  = 200; // Raise if the fader is too sensitive (0-16383)
byte tolerance  = 10; // Raise if the fader is too shaky (0-1023)
double faderMax = 0; //Value read by fader's maximum position (0-1023)
double faderMin = 0; //Value read by fader's minimum position (0-1023)
bool touched = false; //Is the fader currently being touched?
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay    = 10;    // the debounce time; increase if the output flickers
int lastfaderValue    = 0;

byte ch1Vol = 224;
byte fullVel = 127;
byte ch_1 = 1;
byte Db_1 = 1;

CapacitiveSensor touch = CapacitiveSensor(touchReceive, touchSend);
MIDI_CREATE_DEFAULT_INSTANCE();

void setup() {
  touch.set_CS_AutocaL_Millis(0xFFFFFFFF);
  midiSerial.begin(31250);
  MIDI.begin(MIDI_CHANNEL_OMNI);
  while (!Serial);
  pinMode(motorDown, OUTPUT);
  pinMode(motorUp, OUTPUT);
  pinMode(motorPWM, OUTPUT);
  pinMode(rxPin, INPUT );
  pinMode(txPin, OUTPUT);
  analogWrite(motorPWM, motorSpeed);
  calibrateFader(); }

void calibrateFader() {
  digitalWrite(motorUp, HIGH);
  analogWrite(motorPWM, 100);
  delay(300);
  digitalWrite(motorUp, LOW);
  faderMax = analogRead(wiper) - tolerance;
  digitalWrite(motorDown, HIGH);
  analogWrite(motorPWM, 100);
  delay(300);
  digitalWrite(motorDown, LOW);
  faderMin = analogRead(wiper) + tolerance; }

void loop() {
  int faderPos = analogRead(wiper);
  int faderMIDI = faderPos / 8;
  int faderHiResMIDI = ((faderPos *16) - 8191);
  while ( midiSerial.available() > 0 ) {
    int commandByte = midiSerial.read();
    int noteByte = midiSerial.read();
    byte velocityByte = midiSerial.read();
    midiSerial.write( commandByte);
    midiSerial.write( noteByte);
    midiSerial.write( velocityByte);
    incomingCommand = commandByte;
    incomingNote = noteByte;
    incomingVelocity = velocityByte*8; }

 { int totalCp =  touch.capacitiveSensor(30);
 if ( (millis() - lastDebounceTime) > debounceDelay) {
    if (totalCp <= minimumCp) { touched = false; // Not Touching Fader
      if (incomingCommand == ch1Vol) { updateFader(incomingVelocity); } }
    if ((faderPos == lastfaderValue) && (totalCp > minimumCp)) { touched = true; // Touching Fader
      MIDI.sendNoteOn(Db_1, fullVel, ch_1);
      digitalWrite(motorDown, LOW);
      digitalWrite(motorUp, LOW); }
    if (((faderPos > lastfaderValue+1) or (faderPos < lastfaderValue-1)) && (totalCp > minimumCp)) { touched = true; // Moving Fader
      MIDI.sendPitchBend(faderHiResMIDI, ch_1);
      digitalWrite(motorDown, LOW);
      digitalWrite(motorUp, LOW); }
    lastfaderValue = faderPos;
    lastDebounceTime = millis(); //set the current time
} } }

void updateFader(int position) {     //Function to move fader to a specific position between 0-1023 if it's not already there
  if (position < analogRead(wiper) - tolerance && position > faderMin && !touched) {
    digitalWrite(motorDown, HIGH);
    while (position < analogRead(wiper) - tolerance && !touched) {}; //Loops until motor is done moving
    digitalWrite(motorDown, LOW); }
  else if (position > analogRead(wiper) + tolerance && position < faderMax && !touched) {
    digitalWrite(motorUp, HIGH);
    while (position > analogRead(wiper) + tolerance && !touched) {}; //Loops until motor is done moving
    digitalWrite(motorUp, LOW); } }

It probably because those while() {} (wait until...) codes that are blocking.

About what lack are we talking here exactly? Is it the delay between sending a command and the fader starting to move? Or is it the fader not reacting directly when it already received a command? From your code the former should be rather short (a bit more than 10ms I think), while the latter will be a bit greater than the time that the motor needs to drive the fader to its previously commanded position (because of the while loop).

There's a fundamental flaw in your serial reading code. Read: https://majenko.co.uk/blog/reading-serial-arduino

Good point. @zRockafellow You are checking for more than zero bytes being available, but then you read 3 bytes. You cannot be sure, that all these bytes where already received. Maybe just check for 3 bytes being available

I tried replacing the while() codes with if, but I found that the motor stopped responding to data completely. I'll try rewriting that section without any while loops.

@Majenko I changed the '0' to a '2' in the Serial reading code. This made my motor move a tiny bit after receiving data, and stop responding completely. Change the '2' back to '0' & I can move the motor freely again.

@chrisl The fader's not reacting directly when it receives a command. It's receiving a number between 0 and 127, and if I have any quick movements, the data coming into serial skips quite a bit of information to get to the new value, which makes my motor jump around as well

I'm wondering if simply getting a faster processor would do it? I'll try running this same code, but instead of using an Arduino Nano, I'll use a Mega. Or perhaps it's time to get a teensy

You have to just read the serial properly. Read one byte (the command byte) then use that to determine how many other bytes should be read, then read those in one at a time as they arrive. Only once all the bytes for a command have arrived do you act on it.

your code shows unclear thinking ... for instance, every if statement in updateFader contains && !touched ... just test that first on its own .... actually, you don't even have to test it because of touched = false; just before updateFader is called

I took out the boolean 'touched' part of the code entirely - Didn't make a difference to the functionality, but thanks for pointing that out. The motor still runs smoothest when I use the code "Serial.available > '0'". I've tried every combination of the number 0-3, and that one is definitely the smoothest

@Majenko, I'm not sure I understand what you mean. If it works best when reading the Serial as is, is that still not the proper way?


text:
How To Get Data From Arduino Uno Onto My Laptop Through The USB
I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?
My laptop runs Ubuntu 18.04 if that matters.
EDIT: I am not talking about the Serial monitor by the way

Chech the "serial" scetch and open "serial monitor" in the ArduinoIDE. You can write a program that reads data from the serial.

Check out the inbuilt examples. There are many options there. How do you plan to store the data on your computer once it gets there?

The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.
You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.
So:

Use Serial.print() etc to send data to the PC
Write your own PC software in your language of choice to process that data, or
Use some third party application to read and process the serial data

source: Stack Exchange

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

sort: votes


text:
My Serial plotter isn't working (arduino)
I'm trying to upload this code and it works properly but I can't see anything on my serial plotter
const int AnalogIn_Pin0=  A0;
const int AnalogIn_Pin1=A1;
const int Pwmout_PIN=11;
float AnalogIn_Val0=0;
float AnalogIn_Val1=0;
int Pwmout_Val=0;
float Error=0;
float ErrorInteg=0;
float Control=0;
float ControlFilt=0;
float kp=0.2;
float Pole =-10;
float Ki =0.01;
int deltaT=0.01;
int deltaT_ms=(int)deltaT*1000;

void setup() {
  pinMode (Pwmout_PIN,OUTPUT);
  Serial.begin (9600);
}

void loop() {
  AnalogIn_Val0=(float)constrain (analogRead(AnalogIn_Pin0),0,600);
  AnalogIn_Val1=0.97*AnalogIn_Val1+0.03*(float)analogRead(AnalogIn_Pin1);
  Error= (AnalogIn_Val0-AnalogIn_Val1);
  ErrorInteg=ErrorInteg+Error*deltaT;
  ControlFilt=kp*Error+Ki *ErrorInteg;
  Pwmout_Val= constrain (map ((int)ControlFilt,0,1023,0,255),0,220);
 analogWrite (Pwmout_PIN,Pwmout_Val);
 Serial.print(AnalogIn_Val0);
 Serial.print("");
 Serial.print(AnalogIn_Val1);
 Serial.print("");
 Serial.print( Pwmout_Val);
 delay (deltaT_ms);

}

works properly ... then why did you post your question?

you do not say what you actually see ..... maybe your plotter is defective

it's not plotting, the hardware works properly

It looks like that will just output a long string of numbers. No separators between fields, no separators between records (like: 5678298549328756238746524983759823462938746238974692387463298574369587234658723468734629375605237643724123046503453948765.... How is anything supposed to make sense of the data?

You must have each set of data point (or points) on a separate line and if you are plotting more that one value you need a space or a tab between each value.
So to have 3 lines on your plot, I think you want this:
 Serial.print(AnalogIn_Val0);
 Serial.print(' ');
 Serial.print(AnalogIn_Val1);
 Serial.print(' ');
 Serial.println(Pwmout_Val);

The output in the serial monitor should be something like this:
123 456 789
234 567 901
...

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


text:
Ultrasonic Sensor - JSN-SR04T 2.0
I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?

#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}
void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);

  delayMicroseconds(5);
 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance:
  distance = duration*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(100);
}

What is the approx depth of the water? That sensor seems to be good to about 20 ft. Also since you didnt post your code, or anything about how your using the sensor, its hard for anyone to give you an answer.

Sorry. Here is the code.

@ChadG the body of water im testing has a depth of 50 cm

According to the data sheet the minimum target distance is 20cm in the open air at a 343 m/s
The speed of sound in water is 1481 m/s so the minimum distance would be 20cm x 1481 / 343 = 86cm.

You cannot measure distances under 83cm in water.

Thanks. I'll try the sensor out in a 4 foot deep pool.


text:
Error Compiling any coding in Arduino IDE
I was using the example code of "Blink", and when I try to compile it, it pop out an error as below.
I tried to:

uninstall and installed back the Arduino IDE
installed different versions of Arduino IDE
update the u8glib library
installed different version of Arduino AVR boards

but still doesn't work.

Arduino: 1.8.9 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs
  -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\ASUS\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files
  (x86)\Arduino\hardware\tools\avr -tools
  C:\Users\ASUS\AppData\Local\Arduino15\packages -built-in-libraries
  C:\Program Files (x86)\Arduino\libraries -libraries
  C:\Users\ASUS\Documents\Arduino\libraries -fqbn=arduino:avr:uno
  -vid-pid=0X2341_0X0043 -ide-version=10809 -build-path C:\Users\ASUS\AppData\Local\Temp\arduino_build_109130 -warnings=none
  -build-cache C:\Users\ASUS\AppData\Local\Temp\arduino_cache_111506 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.arduinoOTA-1.2.1.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr
  -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose
  C:\Users\ASUS\Desktop\FSR\FSR.ino
Error compiling for board Arduino/Genuino Uno.

reinstall Arduino IDE. better try 1.8.10


text:
Code with if multible conditions
My project has 4 float switches, 2 valves and 3 pumps. I created a sketch and uploaded it. But my project keep all "OUTPUT" at "HIGH" all the time. I couldn't find what the problem, can you help?
This is my sketch:

#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS3231  rtc(SDA, SCL);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

void setup()
{
  rtc.begin();
  lcd.begin(16,2);
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  //rtc.setDOW(TUESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(1, 15, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 6, 2017);   // Month, Day, Year

 //Setup FLoat Switch Pins
  pinMode (x, INPUT);
  pinMode (y, INPUT);
  pinMode (z, INPUT);
  pinMode (w, INPUT);

 //Setup Irrigation Valves
  pinMode(WaterIn, OUTPUT);  //irrigation "in" valve
  pinMode(WaterOut, OUTPUT);  //irrigation "out" valve

//Setup Pumps
  pinMode(Pump1, OUTPUT);
  pinMode(Pump2, OUTPUT);
  pinMode(Pump3, OUTPUT);
}  // end of setup

void Calendar(){

 lcd.setCursor(0,0);
 lcd.print("Real Time Clock  ");
 lcd.setCursor(0,1);
 lcd.print("Time: ");
 lcd.print(rtc.getTimeStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Day: ");
 lcd.print(rtc.getDOWStr());
 lcd.print("           ");
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Temp: ");

 lcd.print(rtc.getTemp());
 lcd.print(" C");
 lcd.print("          ");
 delay(1000);
}  // end of setup

void Valves(){
    int pinToTurnHigh = 24;
    if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))  //Condition 1
    {
        pinToTurnHigh = WaterIn;
        pinToTurnHigh = Pump1;
        pinToTurnHigh = Pump2;
        pinToTurnHigh = Pump3;
    }
    if ((x == LOW) && (y == LOW) && (z == HIGH) && (w == HIGH))  //Condition 2
    {
       pinToTurnHigh = WaterOut;
    }
    resetAllPumpValve();
    digitalWrite(pinToTurnHigh, HIGH);
}  // end of setup

void resetAllPumpValve(){
     digitalWrite(WaterIn, LOW);
     digitalWrite(Pump1, LOW);
     digitalWrite(Pump2, LOW);
     digitalWrite(Pump3, LOW);
     digitalWrite(WaterOut, LOW);
}  // end of setup
void loop()
{
    Calendar();
    Valves();
    resetAllPumpValve();
}  // end of loop

use serial.print() to display debugging information on the serial console .... verify that the program flow is as you expect it to be

I'm new with arduino, can you make it clear? You mean replace lcd.print () to serial.print()?

No, rather, in addition to the lcd.print() commands. This way you can see on the serial monitor where your code is going during execution. delay() may also come in handy.

chrisl made an excellent analysis of your program and the problems
therein. I would just want to add a point about how to handle the
Calendar() function. You have been given the suggestion to look at the
Blink Without Delay Arduino tutorial, and I second that suggestion.
This is indeed the first thing you should do.
However, once you have studied that tutorial and you try to apply it to
your specific problem, you will notice that yours is somewhat harder
than blinking an LED. The reason it is harder is that you have to manage
a more complex system state. The LED has only two states, and it
periodically transitions between them as:

LOW → HIGH → LOW

Your display routine will instead have four states and make the following
transitions:

SHOW_TIME → SHOW_DATE → SHOW_DAY → SHOW_TEMP → SHOW_TIME

The relevant programming concept for dealing with this kind of system is
called a “finite state machine” and I suggest you also study this
finite state machine tutorial. This tutorial proposes a very
generic switch/case control structure for programming an FSM.
However, if there is some behavior common to all states (in your case:
the fact that each one lasts for exactly one second), you can factor that
behavior out of the switch/case construct.
Here is what I would propose as a non-blocking Calendar(). First, put
this near the top of the program, along with the other constants:
const LCD_DISPLAY_TIME = 1000;  // display each item for 1,000 ms

Then, is setup(), right after initializing the LCD:
lcd.setCursor(0, 0);
lcd.print("Real Time Clock ");

As a general rule, setup() is the right place for anything that only
needs to be done once, at the start of the program.
And finally, the Calendar() function to be called from loop():
void Calendar()
{
    // Do nothing unless it's time to refresh the display.
    static uint32_t last_change = -LCD_DISPLAY_TIME;
    if (millis() - last_change < LCD_DISPLAY_TIME) return;
    last_change += LCD_DISPLAY_TIME;

    // Switch to the next item: Time -> Date -> Day -> Temp -> Time
    lcd.setCursor(0, 1);
    static enum { SHOW_TEMP, SHOW_TIME, SHOW_DATE, SHOW_DAY } state;
    switch (state) {
    case SHOW_TEMP:
        lcd.print("Time: ");
        lcd.print(rtc.getTimeStr());
        state = SHOW_TIME;
        break;
    case SHOW_TIME:
        lcd.print("Date: ");
        lcd.print(rtc.getDateStr());
        state = SHOW_DATE;
        break;
    case SHOW_DATE:
        lcd.print("Day: ");
        lcd.print(rtc.getDOWStr());
        state = SHOW_DAY;
        break;
    case SHOW_DAY:
        lcd.print("Temp: ");
        lcd.print(rtc.getTemp());
        lcd.print(" C");
        state = SHOW_TEMP;
        break;
    }
    lcd.print("           ");  // pad
}

It is not clear, what the code actually should do (what behaviour you are trying to achieve), so I will only look into the obvious programming problems.

The following declarations at the global scope seem to be pin numbers:
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

But in the Valves() function yout treat them as they were representing the value of that pins. That is not the case. If you want to read the state of a pin, you cannot do
if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))

You are just comparing the pin number with HIGH, which is defined as 1. That cannot work. You have to actually read the pin using it's pin number, which looks like this:
if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)

And that can be shortened to:
if( digitalRead(x) && digitalRead(y) && digitalRead(z) && digitalRead(w) )

Inside of the mentioned if statements you set a variable multiple times without doing anything with it. Any consecutive write to this variable will overwrite the previous value. After the code block
pinToTurnHigh = WaterIn;
pinToTurnHigh = Pump1;
pinToTurnHigh = Pump2;
pinToTurnHigh = Pump3;

The variable pinToTurnHigh is 27 (Pump3). The values, that you assigned right before that line, are lost. You actually have to do something with the variable, or the first 3 lines of that block makes no sense.
In most cases it is not a good idea, to use variables with changing values to handle pin numbers, since that will make the code difficult to understand. The circuitry is mostly hardwired, it will not change. So there is no need to assign pin numbers to a changing variable. Instead you can directly do, what you need to do with a constant pin number. (Actually the code optimizer, that comes with the compiler, can optimize the not-changing pin-number variables out, so that you wrote them in your code, but the actually code might not have them.) Here it seems, that you want to write a HIGH value to all the mentioned pins. You can do that directly:
digitalWrite(WaterIn, HIGH);
digitalWrite(Pump1, HIGH);
digitalWrite(Pump2, HIGH);
digitalWrite(Pump3, HIGH);

Here it is important to understand, that digitalWrite() is only working on 1 single pin at a time. If you want to set multiple pins with it, you have to call it multiple times with the according pin numbers.
Now the timing of your code: The Calendar() function will block the rest of the code for about 4s, because you used that much of delay(). During that time the Arduino cannot react to anything. The switches will not do anything either (since the Arduino is busy waiting in the delay() instead of checking the switches). The code, that is called after the Calendar() function, contains no delay()s, so it will run very fast. In the Valves() function you first reset all the pumps and valves to LOW. Then you write HIGH to one pin (as mentioned above I assume, that you wanted to write them all on condition). After that the program will go back to the loop() function and execute the resetAllPumpValve() function again, which will set all the outputs to LOW.
All in all that means, that the Arduino is fiddling thumbs inside the Calendar() function, without doing anything else. Then he will reset, set and reset the pins again. Since there is not timing code in there, this will happen very fast. So the pins have to be LOW most of the time and being turned on about every 4s for a tiny amount of time (a low number of milliseconds, since that is about the time to execute digitalWrite() or it's siblings). The motors or values will hardly have time to move with that.
For solving this you might want to look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It shows a non-blocking coding style, that will only do something, if it is the time to do it. Much like when you bake a pizza. You will not sit in front of the oven and wait patiently, until the pizza is fully baked. You will put it into the oven and regularly (maybe every 5 min) look, if the pizza is ready to eat. In the meantime you would do other things. Thats what is done there by using the millis() function, that will return the number of milliseconds passed since the programs startup. You can look into the example and google about it to learn more. It has been covered numerous times throughout the internet.

That's it for now. To really help you with the logic of the program, you will first have to get these parts right.
Have fun while learning :-)

Outstanding analysis of the problems with that code. (voted) I got part-way through it and threw up my hands. I couldn't make much sense of what it was supposed to do, and saw so many problems that gave up trying to call them all out. You were very thorough and patient, and provided clear explanations. Huzzah!

I would add to Chrisl's answer by saying that, if you wanted to make the code more compact, you could represent the 4 boolean variables by a single byte,
e.g. w HIGH + x HIGH + y LOW + z LOW = 1100.
e.g. w HIGH + x HIGH + y LOW + z HIGH = 1101.
Then it would be easier to implement a switch statement instead of if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH) etc.
For example:
byte state;

void setup(){}

void loop(){
 // insert code to read state
 switch (state)
 {
     case 1:
         // insert code to be run if state = 0b0001;
     break;

     case 13:
         // insert code to be run if state = 0b1101;
     break;

     default: // code to be run if state doesn't match any cases
 }
 // insert other code
}

If you were willing to use the ATmega's digital 30-37 pins then you could use the AVR's port command PINC to read all of the HIGH/LOW states at once, using a single instruction.  I leave this as an exercise for you to try!

This is likely to make the program harder to read and understand. There are situations where your suggestion would make the program more readable, e.g. if all 16 cases have to be dealt with and there is no easy way to factor cases. But if there are only two or three cases to handle, if/else is likely to be both more compact and more readable.

Very true, but I wrote "if you wanted to make the code more compact", not necessarily readable.

I fixed the Calendar(), it works perfect.


text:
Getting my keypad to reset when wrong password is entered
I am working on a puzzle for my nephew. I currently have an arduino mega, SD card reader and keypad. Everything is wired correctly and I have it currently programmed so when you enter the right password than an audio file plays and a green LED lights up. Where I am struggling is I do not know how to program it so that when the wrong pass code is entered then my red LED light flashes and the code resets to position 0. I also noticed that my current password is 1,2,3 and when I add a random number between my pass code, say, 1,5,2,3 or even 1,3,2,2,3 then the audio file still plays and my green LED lights up. Any suggestions?
#include <Keypad.h>
#include <SD.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 53

TMRpcm tmrpcm;
char* password = "123";
int position = 0;
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte rowPins[ROWS] = { 8, 7, 6, 9 };
byte colPins[COLS] = { 5, 4, 3, 2 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int R = 12;
int G = 13;

void setup(){
  pinMode(R, OUTPUT);
  pinMode(G, OUTPUT);

  LockedPosition(true);
  tmrpcm.speakerPin = 46;
  if (!SD.begin(SD_ChipSelectPin)) {
    return;
  }
}

void loop()
{
  char key = keypad.getKey();
  if (key == '*' || key == '#')
  {
    position = 0;
    LockedPosition(true);
  }
  if (key == password[position])
  {
    position ++;
  }
  if (position == 3)
  {
    LockedPosition(false);
  }
  delay(100);
}

void LockedPosition(int locked)
{
  if (locked)
  {
    digitalWrite(R, HIGH);
    digitalWrite(G, LOW);
    position=0;
  }
  else
  {
    digitalWrite(R, LOW);
    digitalWrite(G, HIGH);
    tmrpcm.setVolume(6);
    tmrpcm.play("matt.wav"); ;
    delay(10000);
    digitalWrite(G,LOW);
  }
}

Define two Strings:
String password = "123";
String answer = "";

replace the loop function with:
void loop()
{
        char key = keypad.getKey(); // init. variable key keypad is non blocking
        while(key == NO_KEY)                 // we got no key press? -> do again
        {
                key = keypad.getKey();
                delay(100);
        }
        answer.concat(key);         //add key to answer
        if(answer.equals(password)) //password OK
        {
                LockedPosition(false);
                answer="";
        }
        else
        {
                LockedPosition(true);
        }

        if (answer.length() > password.length()) { // answer is different and bigger than password
                                                   // can't become the right answer
                answer = "";
        }

        if (key == '*' || key == '#')
        {
                LockedPosition(true);
                answer="";
        }

}

That should do the job.

Hi @JoB. Unfortunately I got no response from the keypad when I substituted my void loop() with the one posted above. Any reason why this may be?

Hi @MattGargiulo I have edited my answer. I missed that getKey is not waiting for a key (non blocking). Now it will wait for a key and then add it to the answer String. Hope that will work for you. I have worked with keypads before but I do not have a keypad here to test that code. So try this and report here if it does not work.

you are the man! Can i integrate your code with two different passwords. My ultimate goal is to set up a puzzle for my nephew where one combo gives 1 clue and a different combo gives another clue.

You have the part checking if the key equals the position in the password and if so you increment the position.  But if it is not equal then you don't do anything.  You should probably have an else there that resets the position to 0 and tells the user they entered the wrong password.

Thanks for the comment. Could provide an example code to correct this issue. I tried several different else statements but nothing seemed to work. For example: I tried:                                                                      if if (key == password[position])  { position ++;  }  if (position == 3)  { LockedPosition(false);  }  else{   digitalWrite(R,HIGH);   delay(250);   digitalWrite(R,LOW);   delay(250);   digitalWrite(R,HIGH);   position=0;  } delay(100); }

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


text:
Arduino Mega and gyroscope erroneous values
I have Arduino mega2560 and MPU6050.
I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.
I used this code:
#include<Wire.h>

const int MPU=0x68; //I2C address of MPU
int GyX,GyY,GyZ;
float pitch=0;
float roll=0;
float yaw=0;

float v_pitch;
float v_roll;
float v_yaw;
float a_pitch;
float a_roll;
float a_yaw;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU);
  Wire.write(0x43);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,6,true);
  GyX=Wire.read()<<8|Wire.read();
  GyY=Wire.read()<<8|Wire.read();
  GyZ=Wire.read()<<8|Wire.read();
  v_pitch=(GyX/131);
  if(v_pitch==-1) {
    v_pitch=0;
  }
  v_roll=(GyY/131);
  if(v_roll==1) {
    v_roll=0;
  }
  v_yaw=GyZ/131;
  a_pitch=(v_pitch*0.046);
  a_roll=(v_roll*0.046);
  a_yaw=(v_yaw*0.045);
  pitch= pitch + a_pitch; roll= roll + a_roll;
  yaw= yaw + a_yaw;
  Serial.print(" | pitch = ");
  Serial.print(pitch);
  Serial.print(" | roll = ");
  Serial.print(roll);
  Serial.print(" | yaw = ");
  Serial.println(yaw);
}

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

What is the 0.046? The mpu6050 uses 3.3v.

I dont know why its used by author. He said that eaxh 46ms the loop is reading a value.

@Jot no It is better to use 5v for more accurate results as I read on arduino forums.

Thanks for the explanation about the 46ms of the loop. The loop time can be measured with millis. The 5v depends on the sensor module that you have. Which arduino forums told you to destroy the sensor with 5v? Please add all the extra information to your question.

Please refer to this link https://www.addicore.com/GY-521-MPU6050-p/170.htm where it says the power supply is from 4.3 to 9V.

@jot and this site http://www.brokking.net/ymfc-32_main.html where the author used 5V from uno to mpu6050

Maybe you should stay away from bad websites. The arduino uno is not the same as the arduino mega. The mega has extra 10k pullup resistors for sda and scl. Use a module with level shifters or add a level shifter module for sda and scl. That might not be the solution to your problem, but at least it stops damaging the sensor via the i2c bus.

how to do it @Jot ?

@Jot I tried it with 3.3V and still not getting the correct values.

It is possible to use your sketch and get angle information. It is not very accurate and it drifts.
I started with your sketch, and improved it until I had the angle.
The Serial.println functions take time and they are printed too often. To measure the interval between the samples, I used millis.
This test is done with:

arduino M0 board (with 3.3v i2c bus)
gy-521 module with onboard voltage regulator, but no level shifter
vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.
// test with arduino M0 board
#include <Wire.h>

#define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

const int MPU = 0x68;   // I2C address of MPU

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

float pitch = 0.0;
float roll  = 0.0;
float yaw   = 0.0;

unsigned long previousMillisSample;
unsigned long previousMillisOutput;
const unsigned long intervalOutput = 500;  // half a second update to serial monitor

void setup() {
  SER.begin(9600);
  while(!SER);         // wait for serial monitor to open for Leonardo and M0
  SER.println("Angle from gyro");

  Wire.begin();

  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission();

  // get the values of the gyro and use them as offset
  GetXYZ(x_offset, y_offset, z_offset);
}

void loop() {

  int16_t GyX;
  int16_t GyY;
  int16_t GyZ;

  GetXYZ(GyX, GyY, GyZ);

  unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

  // remove offset
  GyX -= x_offset;
  GyY -= y_offset;
  GyZ -= z_offset;

  float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
  float v_roll  = float(GyY) / 131.0;
  float v_yaw   = float(GyZ) / 131.0;

  // calculate time in milliseconds between previous and current sample
  unsigned long t = currentMillisSample - previousMillisSample;

  // time in seconds as a float
  float float_t = float(t) / 1000.0;

  // adjust the number of degrees during the time
  float a_pitch = v_pitch * float_t;
  float a_roll  = v_roll  * float_t;
  float a_yaw   = v_yaw   * float_t;

  // remember the time in millis when the sample was taken for the next time
  previousMillisSample = currentMillisSample;

  pitch += a_pitch;
  roll  += a_roll;
  yaw   += a_yaw;

  // Once in a while, print the output
  if(millis() - previousMillisOutput >= intervalOutput) {
    previousMillisOutput = millis();

    SER.print("pitch = ");
    SER.print(pitch);
    SER.print(" | roll = ");
    SER.print(roll);
    SER.print(" | yaw = ");
    SER.println(yaw);
  }
}

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.

Once I get home (in 2 hours) I will try it. Your sketch drift 60degrees per 5min or mine ?

The changes I made was only to make it work (remove offset; less println; measure time between samples with millis; do float calculations with float variables). My sketch drifts up to 60 degrees per 5 minutes with a faster arduino m0 board.It drifts a lot more when I wildly move the sensor. For the arduino uno or mega, you have to change the define to: #define SER Serial

Can we reduce the drifts ? It would make the drone unstable even with correct PID values

@droidnation , this was only for fun and to learn about arduino. Now it is time to buy a mpu-9250 and use the ahrs filter: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide For a drone you need sensor fusion, that is a filter that combines the accelerometer and the gyro and a magnetometer. The kalman filter was used previously but today the ahrs is used.

so using MPU9250 would reduce the drifts right ?

@droidnation Maybe a little. The MPU9250 has less noise and a magnetometer. Less noise makes the results of the ahrs filter a lot better.


text:
How to code 4 relays to go off in intervals and not in sequence?
Code :
//FOR AEROPONIC SYSTEM WITH ROOM TEMPERATURE AND HUMIDITY SENSOR
//AND 4 GROW CHAMBERS WITH DIFFERENT SPRAYING TIME

// RELAY CONTROL
#define RELAY1_PIN 2
#define RELAY2_PIN 3
#define RELAY3_PIN 4
#define RELAY4_PIN 5

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 6
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//Variables
int chk;
float hum;
float temp;

void setup()
{
    Serial.begin(9600);
    Serial.println("SENSOR RUNNING");
    dht.begin();

    pinMode(RELAY1_PIN, OUTPUT);
    pinMode(RELAY2_PIN, OUTPUT);
    pinMode(RELAY3_PIN, OUTPUT);
    pinMode(RELAY4_PIN, OUTPUT);
}

void loop()
{
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t))
    {
        Serial.println("CONNECTION ERROR");
        return;
    }
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.println(" ");
    delay(2*1000);
    {
        // FOR RELAY
        digitalWrite(RELAY1_PIN, HIGH);
        delay(2*1000); // wait for 2 second ON
        digitalWrite(RELAY2_PIN, HIGH);
        delay(3*1000); // wait for 3 second ON
        digitalWrite(RELAY3_PIN, HIGH);
        delay(4*1000); // wait for 4 second ON
        digitalWrite(RELAY4_PIN, HIGH);
        delay(5*1000); // wait for 5 second ON

        digitalWrite(RELAY1_PIN, LOW);
        digitalWrite(RELAY2_PIN, LOW);
        digitalWrite(RELAY3_PIN, LOW);
        digitalWrite(RELAY4_PIN, LOW);
        delay(5*60*1000);
    }
}

This code doesn't do what I want. How do I make them independent?

Please post an actual question and not code. What do you want to actually achieve? I and many others will not bother to look at your code until we know what we need to answer. Clearly explaining your problem then asking a specific question will result likely in help.

Indent your code properly. As it is, there's no way it'll compile, and as you should be able to see, it's exceptionally difficult to follow the flow.

think about your title ... not in sequence requirement makes no sense ... what if in intervals happens to be in sequence ... do you want to prevent relay activation if that happens?

Although the question is far from clear, it looks like the answer may be for you to learn how to Blink Without Delay.

Here is some code that might help you; leaving out the temperature and humidity stuff:
// constants
// number or relays
const int relays = 4;

// pins for the relays
const int relayPins[] = {2, 3, 4, 5};

// relay cycle times
const unsigned long relayTimes[] = {
     5*60*1000, // 5 min
     60*60*1000, // 1 Hour
     2*60*60*1000, // 2 hours
     12*60*60*1000 // 12 hours
  };

// relay on durations
const unsigned long relayOntimes[] = {
    1000, // 1 second
    10*1000, // 10 seconds
    60*1000, // 1 minute
    60*60*1000 // 1 hour
  };

// timing for the relays
// storing the last time
unsigned long relayElapsed[] = {0, 0, 0, 0};

// state of each relay
int relaystate[] = {0, 0, 0, 0};

// helper function to process each relay
void relay_helper(unsigned long t, unsigned long &elapsed, int pin, int &state, unsigned long delta, unsigned long ontime)
{
  // depending on the state we do different things
  switch (state)
  {
  case 0: // state 0 is off, wait until time has passed
    if ((t-elapsed) > delta)
    {  // then
       state = 1; // set the state to on
       elapsed = t; // reset the time
       digitalWrite(pin, HIGH); // turn on
    }
    break;
  case 1: // state 1 is on, wait until time has passed
    if ((t-elapsed) > ontime)
    {  // then
       state = 0; // set the state to off
       elapsed = t; // reset the time
       digitalWrite(pin, LOW); // turn off
    }
    break;
  }
}

void setup()
{
  unsigned long start = millis();
  for(int i = 0; i < relays; i++) // for each pin
  {
    pinMode(relayPins[i], OUTPUT); // set it to output
    digitalWrite(relayPins[i], LOW); // and turn it off
    relayElapsed[i] = start;
  }
}

void loop()
{
  unsigned long tm = millis();
  for(int i = 0; i < relays; i++)
  {
    relay_helper(tm, relayElapsed[i], relayPins[i], relaystate[i], relayTimes[i], relayOnTimes[i]);
  }
  // do other loop stuff
}

The basic idea is that the only way to do thing simultaneously is to do things in sequence really fast, we can't use delay() because it is a busy loop, nothing else can happen during delay(), so we keep track of the time and when it is time to turn on the relay we turn it on, and when it is time to turn it off we turn if off.
Another option would be to write a class per relay:
class Relay
{
public:
  Relay(int pin, unsigned long delta, unsigned long ontime);
  ~Relay();

  process(unsigned long t);

private:
  unsigned long delta;
  unsigned long ontime;
  unsigned long last; // elapsed
  int pin;
};

Then one can create an array of these:
Relay[] relays = {
    Relay(2, 5*60000, 1000),
    Relay(3, 60*60000, 10000),
    Relay(4, 2*60*60000, 60000),
    Relay(5, 12*60*60000, 60*60000)
  };

put the code from setup into the constuctor, and the code from the helper into process, and finally call it in a loop in loop.
The first way shown is how one would do it without C++ classes, and the second way is with them!


text:
Help with usbasp pinout
I am having trouble figuring out the pinout of my 6 - pin USBasp Chinese clone that I got off eBay.
BEFORE YOU TELL ME TO LOOK AT THE PINOUT DIAGRAMS, I can tell you that my version of the usbasp has no way of telling which way is up and which ways is down. Images:

Did you look at the triangle on the side of the connector?

The pin labeled “Or this pin?” is pin number 1: look at the key on the left side of the connector.

Look at the following pinout diagram (from telecnatron.com):

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header.  The header shell will have a triangle marking pin 1.  Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell).  Each socket on the cable also will have a triangle marking pin 1.

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


text:
CS5211AGP wireless RF transmitter (433MHZ) address decoding problem
I am using CS5211AGP wireless RF transmitter to transmit some data and another side receive this data through nRf905 as receiver. But now problem is how can I decode RF transmitter address (because transmitter and receiver address must be same).
if any one working on this module then please suggest me how can I decode address.
Please show below image where you can see the connection of address and zone.

Now please say about what address should I set at receiver side for communication.
Thanks in advance.
Regards,
rajneesh

I don't think the nRf905 and CS5211AGP are compatible. They both use their own protocol.

I am looking at mine, wich address is 01212012, acording to a sticker in a side. I can see in mine jumpers as follows (starting from A0): -HLHL-HL-H-H where - means no jumper. Based on my sticker I can see that 0 is equivalent to NO-JUMPER, 1 is H and 2 is L. By watching yours I can tell that your code is 21111002.
The other 4 jumpers is what I don-t understand, but if I change any of them, my alarm no longer detects any change.
Hope this helps...
Regards.


text:
How to send a number to Arduino via Python over serial?
I call an API in Python and it gives as output as a single digit and an Arduino program receives this number over serial and displays it on a 7-segment display.
I wrote a different program in which Arduino sends the data and a Python program receives it. That worked but the following program is not working. What is the problem?
I am using Python 3 and Arduino Uno.
Python program:
import serial ,requests, json, time
arduino = serial.Serial('COM1', 9600, timeout=.1)
time.sleep(1)
response = requests.get("https://traffic.cit.api.here.com/traffic/6.1/flow.json?bbox=12.9808%2C77.5759%3B12.9803%2C77.5767&app_id=zbvY0tdRs089c3ZTKqWR&app_code=pxAtGksNBgVD9V5XF5nEzA",)
#CALLING API
response.content.decode("utf-8")
data = response.json()
text = str(data) #CONVERSION TO STRING
l = len(text)
for i in range(0,l): #Taking out the number
    if text[i] == 'J':
        j = text[i + 5]
        print (j)
        arduino.write(j) #writing over serial
        break

Arduino program:
int a=2;
int b=3;
int c=4;
int d=5;
int e=6;
int f=7;
int g=8;
int h=9;
int rx_byte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(a, OUTPUT);
  pinMode(b, OUTPUT);
  pinMode(c, OUTPUT);
  pinMode(d, OUTPUT);
  pinMode(e, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(h, OUTPUT);
  digitalWrite(h, 0);  // start with the "dot" off
}

void loop() {
  if (Serial.available() > 0) {
    rx_byte = Serial.read(); //reading serial
    switch (rx_byte) {
    case 0:
      zero();
      break;
    case 1:
      one();
      break;
    case 2:
      two();
      break;
    case 3:
      three();
      break;
    case 4:
      four();
      break;
    case 5:
      five();
      break;
    case 6:
      six();
      break;
    case 7:
      seven();
      break;
    case 8:
      eight();
      break;
    case 9:
      nine();
      break;
    }
  }
}

// write '9'

void eight() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void seven() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void six() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void five() {
  digitalWrite(a, 1);
  digitalWrite(b, 0);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}
void four() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);
}
void three() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 1);

}
void two() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 0);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 0);
  digitalWrite(g, 1);
}
void one() {
  digitalWrite(a, 0);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 0);
  digitalWrite(g, 0);

}
void zero() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 1);
  digitalWrite(e, 1);
  digitalWrite(f, 1);
  digitalWrite(g, 0);

}
void nine() {
  digitalWrite(a, 1);
  digitalWrite(b, 1);
  digitalWrite(c, 1);
  digitalWrite(d, 0);
  digitalWrite(e, 0);
  digitalWrite(f, 1);
  digitalWrite(g, 1);

}

I am quite new to programming. Please help.

The python code
j = text[i + 5]
print (j)
arduino.write(j)

Is sending a single text character between '0' and '9', ascii values 48 to 58.
The c code
rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case 0:

is looking for absolute values between 0 and 9.
There are two easy options to fix this, option 1 change the case statement to look for the correct values:
rx_byte = Serial.read(); //reading serial
switch (rx_byte) {
  case '0':

or option 2, rely on the fact that the ascii for the numbers is always 48 more than the number represented and subtract that:
rx_byte = Serial.read() - '0'; //reading serial
switch (rx_byte) {
  case 0:

-'0' and -48 would have exactly the same effect here only by using '0' it makes it clear we are offsetting by the ascii value of a 0 rather than by some other randomly created number. It also saves you having to remember what the correct value is for 0.
Generally since you are using the value in a case statement I'd recommend the first option, it's a little more intuitive and avoids an extra calculation that can look a little odd if you are new to programming.
The reason I mentioned the second option is that this is the method you would use if you wanted to use the rx_byte value as the index in an array for any reason.

I think you are sending ASCII values 0 - 9 over serial.  This is a bad idea, because they can be interpreted as control codes, always send printable characters.  So in this case send '0' to '9'.
Also you could make you code much smaller if you used arrays.
For instance
int pins[8] = {2,3,4,5,6,7,8,9};
int TheData [8][8] =
{
    {1,1,1,1,1,1,0,0}, // 0
    {0,1,1,0,0,0,0,0}, // 1
    // etc
};
void write (int number)
{
    for (int i = 0; i < 7; i++)
    {
       digitalWrite (pins[i], TheData[number][i]);
    }
}

I'll let you figure out how to reduce setup to less than 3 lines :)


text:
Upload with esptool fails with "espcomm_send_command: can't receive slip payload data"
Uploading a sketch to an ESP8266 board fails with:
error: failed reading byte
warning: espcomm_send_command: can't receive slip payload data
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

...or:
espcomm cmd: receiving 2 bytes of data
warning: espcomm cmd: no final C0
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

This is on OS X with a PL2303HXD USB-to-Serial cable, using the latest official Prolific signed OS X El Capitan-compatible drivers.

This is a known issue with the included esptool, and for the Arduino IDE there are quite a few blog posts to be found on this problem. But most are outdated, and are not applicable when using PlatformIO with some other IDE. So, February 2016:
Install esptool.py

git clone https://github.com/themadinventor/esptool/ (or download the ZIP file)
cd esptool
sudo python setup.py install

When using Arduino IDE

Open ~/Library/Arduino15/packages/esp8266/hardware/esp8266/2.0.0/platform.txt.
Find the line tools.esptool.upload.pattern and disable that by prefixing with a hash. Check that your version only mentions -ca 0x00000, not -ca 0x10000 as well (like in most outdated blog posts):
# tools.esptool.upload.pattern="{path}/{cmd}" {upload.verbose} -cd {upload.resetmethod} -cb {upload.speed} -cp "{serial.port}" -ca 0x00000 -cf "{build.path}/{build.project_name}.bin"

Add the following, referring to the esptool.py you installed above and also using different command line parameters:
# Fix for espcomm_send_command: cant receive slip payload data
tools.esptool.upload.pattern="/path/to/new/esptool.py" --port "{serial.port}" --baud {upload.speed} write_flash 0x00000 "{build.path}/{build.project_name}.bin"

Restart the IDE.

(One might be tempted to just change tools.esptool.path and tools.esptool.cmd instead, but beware that the command line parameters need changing as well.)
When using PlatformIO
You will find the same platform.txt file somewhere in ~/.platformio/packages/framework-arduinoespressif/platform.txt, but that file is not used for the upload. Instead:

In platformio.ini add:
# ...or whatever your port is named
upload_port = /dev/cu.usbserial
extra_script = /path/to/platformio_extra_script.py

Create a new file /path/to/platformio_extra_script.py:
# Custom settings, as referred to as "extra_script" in platformio.ini
#
# See http://docs.platformio.org/en/latest/projectconf.html#extra-script
# See https://github.com/platformio/platformio/issues/426

from SCons.Script import DefaultEnvironment

env = DefaultEnvironment()

# Must be full path, or use
# https://docs.python.org/2/library/os.path.html#os.path.expanduser

env.Replace(
    LOCAL_UPLOADER="/Users/arjan/path/to/new/esptool.py",
    LOCAL_UPLOADERFLAGS=[
        "--port", "$UPLOAD_PORT",
        "--baud", "$UPLOAD_SPEED",
        "write_flash", "0x00000",
    ],
    UPLOADCMD='$LOCAL_UPLOADER $LOCAL_UPLOADERFLAGS $SOURCE'
)

hey, it throws an error: java.io.IOException: Cannot run program /mypath/esptool.py error=2, No such file or directory

To avoid errors when programming boards that don't support QIO (e.g. NodeMCU from Amica), you also need -fm dio in the command line. So adjust that tools.esptool.upload.pattern line by adding -fm {build.flash_mode} right after write_flash (and before the 0x00000 address).

Did not work for me. Can I somehow find out if my controller is broken? Have 5 and all the other 4 work without this tweak.


text:
My Arduino keeps telling me the button is being pushed
My code is simple simple for the button.
There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.
Output:

Code:
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <Bounce2.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

int led = 13;
int led2 = 12;

Bounce debouncer1 = Bounce();

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int buzzer = 10;

Servo LockServo;

int ServoPos = 0;

void setup()
{
  debouncer1.attach(buttonPin);
  debouncer1.interval(5); // interval in ms

  pinMode(buzzer, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
  buttonState = digitalRead(buttonPin);
  LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
  pinMode(led, OUTPUT);
}

void loop()
{
  debouncer1.update();
  buttonState = debouncer1.read();
  if (buttonState == HIGH) {
    Serial.println("Button Pushed");
    // turn LED on:
    digitalWrite(led, HIGH);
    ServoPos = 0;
    LockServo.write(ServoPos);
  }
  else {
    digitalWrite(led, LOW);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    ServoPos = 0;
    LockServo.write(ServoPos);
    tone(buzzer, 20000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 15000);
    delay(500);
    noTone(buzzer);
    delay(15);
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }
  else {
    Serial.println(" Access denied");
    tone(buzzer, 10000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 30000);
    delay(500);
    noTone(buzzer);
    digitalWrite(led2, HIGH);
    delay(3000);
    noTone(buzzer);
    digitalWrite(led2, LOW);
  }
}

if (buttonState == HIGH) { means the button is NOT pressed when using pinMode(buttonPin, INPUT_PULLUP);

you are asking about a pushbutton problem, yet your code has a bunch of stuff for servos and MFRC522 .... please reduce the program to the code necessary to demonstrate the issue with the pushbutton

When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to HIGH. The connected button should have one side connected to your input pin, and the other to GND, so that when you press the button, the input pin is pulled to GND (that is, LOW).
So your comparison to trigger on a button press should be if (buttonState == LOW)


text:
ESP8266 Timing question / Do something in 2 seconds even
I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

The MC recieves the signal for trigger by the user on 09:25:18:312
It waits until it is exactly 09:25:19:000
It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!
Edit: Corrected Times.

The description isn't clear.  Where did time 09:25:18:312 come from?  If that's the time the request was issued, step 2 won't work out.  Why is step 2 included anyway?

Also, the time in step 2 is later than the time in step 1. You can't wait for something in the past, so that confuses it more.

Sorry that I didn't make that clear.  What I meant was, that there is a (fictional) time and I want the ESP to wait for a specific time. I correct the upper values. Sorry!

You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...
The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).
Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.
You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.

Probably yes. Is there a way to synch multiple RTC on different ESPs? As far as I know, the ESP-variant of the time.h library does not include the WiFi-Signal-lag.

Have a look at NTP implementation (Network time protocol) if you want to do that, but it might be better to have only one RTC and then calculate the average hop time between the master and slaves.

Indeed. the Arduino Core Library Time.h has a functions for synchronising time from an external time source: setSyncProvider(getTimeFunction) and setSyncInterval(interval) See: https://github.com/PaulStoffregen/Time


text:
2 analog sensors, pulse sensor and LM35 problem
I make a project in which I use two analog sensors. A pulse sensor and the LM35 temperature sensor. When I use them separated everything is normal,the codes are fine, when I combine them the lm35 is not precise, has an error margin of about 10 degrees but the pulse sensor seems to be ok. I read something about the analog to digital convertor that Arduino have and need a delay or something to trick the ADC.
I would be grateful if somebody help me to modify the code.
Thank you very much!

#include <LiquidCrystal.h>
#include <TonePlayer.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat

const int sensor=A5; // Assigning analog pin A5 to variable ‘sensor’ temperature
float tempc;
float vout; //temporary variable to hold sensor reading

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup() {

  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

  pinMode(sensor,INPUT); // Configuring pin A1 as input                             //   analogReference(EXTERNAL);

  lcd.begin(16, 2);
  lcd.clear();
}

//  Where the Magic Happens
void loop() {
  serialOutput();
  if (QS == true) { // A Heartbeat Was Found
    // BPM and IBI have been Determined
    // Quantified Self "QS" true when arduino finds a heartbeat
    serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
    QS = false; // reset the Quantified Self flag for next time

    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius

    Serial.print ("Temperatura: ");
    Serial.print(tempc);
    Serial.println(" C ");

  }
  delay(20); //  take a break
}

void interruptSetup() {
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput() {   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

void serialOutputWhenBeatHappens() {
 if (serialVisual == true) { //  Code to Make the Serial Monitor Visualizer Work

     Serial.print("Batai ");  //ASCII Art Madness
     Serial.print("BPM: ");
     Serial.println(BPM);
     lcd.print("Batai ");
     lcd.setCursor(6,0);
     lcd.print("BPM: ");
     lcd.setCursor(10,0);
     lcd.print(BPM);

     lcd.setCursor(0,1);
     lcd.print("Temp: ");
     lcd.setCursor(6,1);
     lcd.print(tempc);
     lcd.setCursor(11,1);
     lcd.print("C ");

     delay(300);
     lcd.clear();
   } else {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data ) {
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data ) {
   Serial.print(symbol);
   Serial.println(data);
}

ISR(TIMER2_COMPA_vect) { //triggered when Timer2 counts to 124

  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                              //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3) { // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T) { // T is the trough
      T = Signal; // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P) {       // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250) {                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ) {
        Pulse = true;                               // set the Pulse flag when we think there is a pulse
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        tone1.tone (1000);  // 1000 Hz

        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat) {                        // if this is the second beat, if secondBeat == TRUE
          secondBeat = false;                   // clear secondBeat flag
          for(int i=0; i<=9; i++) { // seed the running total to get a realisitic BPM at startup
            rate[i] = IBI;
          }
        }

        if(firstBeat) { // if it's the first time we found a beat, if firstBeat == TRUE
          firstBeat = false;                   // clear firstBeat flag
          secondBeat = true;                   // set the second beat flag
          sei();                               // enable interrupts again
          return;                              // IBI value is unreliable so discard it
        }
      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                    // clear the runningTotal variable

      for(int i=0; i<=8; i++) {                 // shift data in the rate array
          rate[i] = rate[i+1];                  // and drop the oldest IBI value
          runningTotal += rate[i];              // add up the 9 oldest IBI values
        }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true) {    // when the values are going down, the beat is over
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      tone1.noTone ();
      Pulse = false;                         // reset the Pulse flag so we can do it again
      amp = P - T;                           // get amplitude of the pulse wave
      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
      P = thresh;                            // reset these for next time
      T = thresh;
    }

  if (N > 2500) {                          // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }
  sei();                                   // enable interrupts when youre done!
}// end isr

When you use the sensors separately, are you still using this code you've posted? If not, how is the separate code - especially for the LM35 - different from the above?

I still use this code, my problem is that i don't know how to combine them correctly. the code only for LM35 is the next one. ` const int sensor=A5;
float tempc;
float vout;
void setup() {
Serial.begin(115200);
}
void loop() {
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in Degree Celsius
Serial.print ("Temperatura: ");
Serial.print(tempc);
Serial.println(" C ");
delay(1000);

} `

I have a couple of suggestions:
The combined code is very different from the simple LM35 code that works. I'd suggest you start with the combined code but comment out everything that doesn't directly apply to reading the LM35, and get that working correctly.
The interrupt service routine (ISR) is trying to do too much, and leaves the interrupts off during all of those calculation. Plus, its hard to debug code inside an ISR! ISRs should do the minimum work that they have to do. In this case, it looks like it needs to read & save the pulse sensor value and do the N, lastBeatTime, and sampleCounter calculation. Have it also set a flag every time it runs.
The main loop should check that flag, and if it is set, clear it and call another function to do everything you took out of the ISR. Debug this code, perhaps with the LM35 commented out.
Ideally your loop() function should be as simple as:
void loop(){
   Timers.run();
   maybeCalcHeartbeat();
   maybeDoOtherSubtask();
   ...
}

Then the rest of your code goes into "maybeDo" functions. A "maybeDo" just decides whether the time or conditions are right to do a particular thing; if so, the function does it; but in any case, it returns quickly:
void maybeCalcHeartbeat(void){
   if( !isrFlag )
      return;
   else {
      // everything you took out of the ISR goes here //

      isrFlag = false;
   }


text:
Connecting to WiFi on ESP32 using credentials from SD card
I'd like to use an SD card to provide the login credentials to an ESP32. I've already got the ESP32 reading the relative data from the SD card and storing it as a char array on the ESP, but when I use those arrays in the WiFi.begin function it never connects.
Is this something to do with the way arrays work or am I doing something else wrong?
Respective code:

if (dataFile) {
Serial.println("File is available");
while (dataFile.available()) {
  byte currbyte = dataFile.read();
  if (currbyte == 58) {
    reading = 1;    //Begin reading data
    i = 0;
  }
  while (reading == 1 and s == 0) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 1;
      reading = 0 ;
    }
    ssid[i] = char(currbyte);
    i++;
    //Serial.println(ssid);
  }
  while (reading == 1 and s == 1) {
    byte currbyte = dataFile.read();
    //Serial.print(currbyte);
    //Serial.println(char(currbyte));
    if (currbyte == 13) {
      s = 2;
      reading = 0 ;
    }
    password[i] = char(currbyte);
    i++;
    //Serial.println(password);
  }
}
dataFile.close();
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED and count < 20) {
Serial.println("Connecting to WiFi..");
delay(1000);
count++;}

Hi I've got the data of the SD card without issues, howeverI can't connect to wifi with that data stored as arrays

Alright, well I know that the code works if I manually enter the SSID and Password. A serial print of the arrays shows that they visually appear to be correct, and are being called correctly for the function

that makes it clear ... one way to debug this issue is to write the data back to the SD card and examine the result (i am assuming that you used a mac or a pc to write the data to the SD card) .... perhaps use a separate filename for each data field .... also, update your question with the info in your last comment

Writing the arrays for the SSID and password to a file on the SD card returns the correct results. So like I asked, is this something to do with arrays or is it something else I'm doing?

do not write an array to the SD card ... write the content of the array .... the SSID and password strings ... check that there are no hidden characters in the strings

I used
dataFile.println(ssid);
dataFile.println(password);
Which when I checked the file on my computer afterwards showed the exact correct string of ASCII characters

you add the '\13' to the SSID and password string instead of the terminating zero

Where exactly do I add that? In my wifi.begin or when I finish reading the SSID from the SD card?

ssid[i] = char(currbyte); runs for  13 too

you add the '\13' to the SSID and password string instead of the terminating zero, because ssid[i] = char(currbyte); runs for 13 too
use readBytesUntil()
  char ssid[33];
  int l = file.readBytesUntil('\n', ssid, sizeof(ssid));
  if (l > 0 && ssid[l-1] == '\r') {
    l--;
  }
  ssid[l] = 0;


text:
What is the best way to connect multiple Arduinos?
In my situation, I have a map divided into multiple parts, each part could have about 20 to 100 Arduinos that they should send information from time to time to the master. How could I do this?
Second problem. How could I use the other Arduinos to send the info from Arduino that are so far from the Master?
Example in part 1: Arduino X is 500 meters far away from the master. How could use the other to send the information?
Can I do this with NodeMcu or such equipment with built-in WiFi?

esp8266 arduino boards package supports WiFi mesh

This is a classical application for LoRa technology, not WiFi.  Designing a LoRa mesh is no simple task, though.
Check this post, or this other post

I think you should start with using Wifi modules and you use an esp-01 too instead of NodeMCU. Once you are familiar with esp-01's, you will find them as good as NodeMCU. Esp-01's only lack multiple pins when compared to NodeMCU.
And for communication between arduino and esp-01, use serial ports- 0 and 1.
Here is example code-
For Master Arduino
int temp;
int hum;

void setup(){
 Serial.begin(115200);
 delay(2000);
}
void loop() {

 temp = random(0,100);
 hum = random(100,200);
 Serial.print(temp);
 Serial.println('t');
 delay(2000);
 Serial.print(hum);
 Serial.println('h');
 delay(2000);
 Serial.flush();
}

For Slave Esp or any other slave arduino -
String inString = "";    // string to hold input

float temp = 0,hum = 0;

boolean newtemp=false, newhum=false;

void setup() {
  Serial.begin(115200);
  Serial.println("ESP 8266 - 01 Module is ready to receive codes from Master Arduino");
 }

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {

      if (inChar == 't')
      newtemp = true;

      if (inChar == 'h')
      newhum = true;

      inString += (char)inChar;
    }
    else {
      Serial.print("Input string: ");
      Serial.println(inString);
      if ( newtemp == true ) {
      temp = inString.toFloat();
      Serial.print("Received Temperature:");
      Serial.println(temp);
      newtemp = false;
      }
      if ( newhum == true ) {
      hum = inString.toFloat();
      Serial.print("Received Humidity:");
      Serial.println(hum);
      newhum = false;
      }
      inString = "";
    }
  }
}

Pin connections -
Master Arduino TX -- Slave board RX

You could use low radio frequency modules to get to the 500m. For example there are the so called xbee modules (XBee Pro 60mW PCB Antenna - Series 1). You can find cheaper ones, but from my experience they are a bit harder to understand and not reliable.
You can make a TCP-like connection, where before data is send, the "slave" asks the "master" whether he can catch data or not. If not, he'll just keep asking after a delay has passed till he gets through. Even though TCP is mostly used in WiFi 2.4G, you could still apply it to your project
If you want to use WiFi than you can make a connection between the "slave" and "master" by having some middle man chips in between that pass on the data, but you would need the middle man chips to be constantly powered on (or use a RTC to time the "wake time").


text:
Creating PPM signal from 4 integrers
I am currently building a MultiWii based drone, I have built the emisor-receptor that interface 4 analog signals(4 potentiometers to control the drone) and it works perfect, the receiver(arduino Nano, receives correctly the signal and parses it on 4 diferent integrers as expected (values between 1000 and 2000 because the MultiWii software expects that value range), but the problem is when I connect the receiver Nano to the MultiWii controller(Arduino UNO) the Arduino UNO receives incorrect values from the PPM signal(the four channels gets crazy unless the four potentiometers are turned full) so I think that the problem is the PPM generation process.
The problem is that I have taken code from internet to do that signal generation (because I don't know how to do it), and I don't know how to solve it.
Here I paste the NANO receiver to PPM code:

#define channel_number 4
#define sigPin 2
#define PPM_FrLen 27000
#define PPM_PulseLen 400

#include <SoftwareSerial.h>

int ppm[channel_number];

struct Received_data {
  byte ch1;
  byte ch2;
  byte ch3;
  byte ch4;
};

Received_data received_data;

String input;
int throttle, th;
int aileron, ail;
int elevator, el;
int rudder, rud;

unsigned long lastRecvTime = 0;
int boundLow;
int boundHigh;
const char delimiter = ',';

SoftwareSerial hc12(9, 10);

void setup()
{
  Serial.begin(9600);
  hc12.begin(9600);
  pinMode(13, OUTPUT);

  pinMode(sigPin, OUTPUT);
  digitalWrite(sigPin, 0);

  cli();
  TCCR1A = 0;
  TCCR1B = 0;

  OCR1A = 100;
  TCCR1B |= (1 << WGM12);
  TCCR1B |= (1 << CS11);
  TIMSK1 |= (1 << OCIE1A);
  sei();

  reset_received_Data();
}

void reset_received_Data()
{
  received_data.ch1 = 0;
  received_data.ch2 = 127;
  received_data.ch3 = 127;
  received_data.ch4 = 127;

  PPM_width_Values();
}

void PPM_width_Values()
{
  ppm[0] = map(received_data.ch1,   0, 255, 1000, 2000);
  ppm[1] = map(received_data.ch2,   0, 255, 1000, 2000);
  ppm[2] = map(received_data.ch3,   0, 255, 1000, 2000);
  ppm[3] = map(received_data.ch4,   0, 255, 1000, 2000);
}

void receive_the_data()
{
  if (hc12.available())
  {
    input = hc12.readStringUntil('\n');
    if (input.length() > 0)
    {
      //Serial.println(input);

      boundLow = input.indexOf(delimiter);
      ppm[0] = input.substring(0, boundLow).toInt();

      boundHigh = input.indexOf(delimiter, boundLow + 1);
      ppm[1] = input.substring(boundLow + 1, boundHigh).toInt();

      boundLow = input.indexOf(delimiter, boundHigh + 1);
      ppm[2] = input.substring(boundHigh + 1, boundLow).toInt();

      ppm[3] = input.substring(boundLow + 1).toInt();

      Serial.print(ppm[0]); Serial.print("   ");
      Serial.print(ppm[1]); Serial.print("   ");
      Serial.print(ppm[2]); Serial.print("   ");
      Serial.print(ppm[3]); Serial.print("\n");
      delay(10);
    }

  }
}

void loop()
{
  receive_the_data();
  digitalWrite(13, HIGH);

}

#define clockMultiplier 2

ISR(TIMER1_COMPA_vect) {
  static boolean state = true;

  TCNT1 = 0;

  if ( state ) {
    //end pulse
    PORTD = PORTD & ~B00000100;
    OCR1A = PPM_PulseLen * clockMultiplier;
    state = false;
  }
  else {
    //start pulse
    static byte cur_chan_numb;
    static unsigned int calc_rest;

    PORTD = PORTD | B00000100;
    state = true;

    if (cur_chan_numb >= channel_number) {
      cur_chan_numb = 0;
      calc_rest += PPM_PulseLen;
      OCR1A = (PPM_FrLen - calc_rest) * clockMultiplier;
      calc_rest = 0;
    }
    else {
      OCR1A = (ppm[cur_chan_numb] - PPM_PulseLen) * clockMultiplier;
      calc_rest += ppm[cur_chan_numb];
      cur_chan_numb++;
    }
  }
}

I don't understand, what the problem is. Please make clearer, from where to where you are sending data over which interface and what goes wrong with it. And why do you include the receiver code of the Nano (that you used for testing?), but not the sender code?

@chrisl I use an arduino nano as sender, an arduino nano as receiver and an arduino uno as flight controller, the send and receive process it correct because if I serial monitorize the data that nano receiver receives, it is correct. The problem is that that arduino nano after receive that data wirelessly, it must send the data over a wire in a PPM signal, and thats the problem, the PPM signal isn't sent correctly so I need help with the PPM signal generation.


text:
Problem reading an EEPROM chip using the I2C protocol
I am trying to read an EEPROM chip that supports the I2C protocol (cannot tell the IC model number as it is not printed). For sure it supports the I2C protocol, since I wrote a code to detect it using the I2C library and the device address I got it return is 0x51. Now I am trying to write a code that reads data from this IC chip. The code is as follows:
#include <Wire.h>

int addr = 0;

void setup() {
    Wire.begin(); // initialise the connection
    Serial.begin(9600);
    while (!Serial) {}
    delay(100);
}

void loop() {
  byte deviceAddress = 0x51;
  byte data = readData(addr, deviceAddress);
  Serial.print(data, HEX);
  Serial.print(" ");
  addr++;
  if(addr%16 == 0) {
     Serial.print('\n');
  }
  // check for 1Kbits first
  if (addr%128 == 0) {
     Serial.println("round complete");
     Serial.println();
     addr = 0;
  }
  delay(100);
}

byte readData(int address, int deviceAddress) {
  // sending device address
  Wire.beginTransmission(deviceAddress);
  Wire.write(address);
  Wire.endTransmission();
  Wire.requestFrom((short int)deviceAddress, 1);
  if(Wire.available()) {
    byte data = Wire.read();
    return data;
  }
  return 0xAA; // random data
}

The problem I am facing is, I get back the address (from which I want to read the data) as the data itself (For e.g. read(0) returns 0, read(1) returns 1 and so on). I even tried to debug the I2C communication using the logic analyzer (Saleae logic in this case). A screenshot is shown below.

The screenshot shows the logic for a read operation from a single address (0x78), but the story holds for each and every address i.e. I get back the address instead of the data from the address.
The output of the above code is as follows:

0 1 2 3 4 5 6 7 8 9 A B C D E F
  10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
  20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
  30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
  40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
  50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
  60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
  70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F
  round complete

Can you help me identifying what possibly I am doing wrong here?
Thanks.

How about using a 16-bit address? Here is a link to a driver that I have written for Cosa; https://github.com/mikaelpatel/Cosa/blob/master/libraries/AT24CXX/AT24CXX.hh

How many legs (pins) does the chip have?

I agree with Mikael too, you could try sending a 16-bit address. For example, send a zero first, then an address. In any case, can you be certain that the chip does not happen to have 0x00, 0x01, etc. inside its memory?

@MikaelPatel: I will give a try with 16-bit address and let you know what the results are.

@NickGammon: Just to make sure that the contents are not 0x00, 0x01, etc. I tried to perform a write operation to the chip. But the result for reading after a write, remains the same. Maybe I have to try using 16-bit addresses as you suggested as well.

@NickGammon: I tried using the 16 bit addresses, but to no success. The data I got in return is all zeroes. Maybe because now I am getting back the first 8 bits which I am writing, i.e. 0x00. I was also looking at the I2c library that you suggested in your blog. http://dsscircuits.com/articles/arduino-i2c-master-library. Can you help me in understanding, what exactly is registerAddress here? Its used in many functions of this library, for.e.g.I2c.write(address, registerAddress, *data, numberBytes). Thanks!

It depends on the device, but some have a register where writing something to it causes internal bits to be set. Honestly, trying to help write to / read from an unknown device is almost impossible. For $5 you could buy a chip that you know the part number of and can get the datasheet for.

Ahh OK. I was doing a reverse engineering project and the chip is in fact a COB. I have to then decap it somehow and see underneath. Thanks anyways.

You need to pass the address as two bytes, one by one.
Do not do:
Wire.write(address);

Rather, do:
Wire.write((uint8_t)(address >> 8)); // MSB
Wire.write((uint8_t)(address & 0xFF)); // LSB

In short, you should split
Wire.write(address);

into
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB

I am working on a similar project right now. I have searched through many different codes and libraries and found the following to work the best:
https://playground.arduino.cc/Code/I2CEEPROM
I am using the 24LC1025 who's datasheet can be found here:
http://www.microchip.com/datasheet/24LC1025
I am using the 1Mb version and it uses 0x51 and 0x50 becuase it has two pages. I suspect you will find your chip to at least be similar because of the I2C Address you listed. You may have a smaller version of the same chip that only uses the one address.

Without the specific chip info this will be difficult.
However, my experience with EEPROMs and I2C is that the first action is to write a command, then write the parameter(s) for that command, then read the response.
Often, there is a status register in the EEPROM that needs to be read (by writing a command, then reading the response) to determine if the EEPROM is ready to receive a different command, like writing to set the address for a read/or/write, then the actual read command.


text:
Arduino interrupt sleep mode/reset problem
I want to write a simple program that waits for an X amount of time (hours) then activates my components (LED and release mechanism) when time has elapsed. I have it so that once I press a button interrupt (pin2) it will put the Arduino in power-down sleep mode when I am not using the device.
What I want it to do next is when another button interrupt (pin3) is pushed, it will wake it up but instead of resuming where it left off in the loop, I want it to reset the program to the start of the loop. I am having trouble getting it to reset after it has woken. Is the code actually putting the Arduino in sleep mode? I'm not sure because after the if statement I make the variable false.
Here is my simple code so far:
#include <avr/interrupt.h>
#include <avr/sleep.h>
//Pin set up
int ledPin =12;
int wakePin = 3;
int sleepPin =2;
volatile boolean flag;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(sleepPin, INPUT_PULLUP);
  pinMode(wakePin, INPUT_PULLUP );
  attachInterrupt(0, sleepy, LOW);
  attachInterrupt(1,EMPTY,LOW);
}

void EMPTY(){
  detachInterrupt(1);
}

void sleepy(){
  flag = true;
}

void sleepNow() {
  digitalWrite(ledPin, LOW);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  attachInterrupt(1,EMPTY,LOW);
  sleep_mode();
}

void loop() {
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite (ledPin, LOW);
  delay(1000);
  digitalWrite(ledPin, HIGH);
  delay(1000);
  if (flag) {
    sleepNow();
  }
  flag = false;
}

Why does sleepNow() call detachInterupt(1)?

Here is my new code I got it to work on accident by using a boolean. But Now i need to get it to reset when waken.


text:
Which components to built remapping keyboard via USB in + out (remapped)
I know that it's fairly easy to change the emulate keyboard and mouse by Arduino. But I'm quite specific about the goal I would like to achieve hence I would appreciate if you could advise me which components (Arduino compatible) I am going to need to have such a built:
Physical usb keyboard --> Arduino via usb IN --> keys remapping (for example pressing q will return ctrl+3 or more advanced action) --> Arduino USB OUT (which I can directly plug in to my computer and receive modified keyboard commands).
To sum up I  just want Arduino to work as intermediary.
Will simple Arduino Uno + USB shield do the work?
Thank you a lot for your support!

The Due might be cheaper than a leonardo+usbHost shield, but I guess you would need a female usb to male micro-usb adapter. In any case, can't this be done on the target computer a lot cheaper and easier?

The thing is I wanted it to be stand-alone and easily transferable across different devices (on which one unfortunately cannot install any developer tools)

you should look into the maximum bandwidth a keyboard needs and then do some tests to see how much latency the arduino adds processing that much data. If its acceptable, you should be good to go (I imagine this will be the case). Oh and make sure whatever you buy has at least 1 usb host port, emphasis on host.

Thank you BrettAM. Yes, as you have guessed latency is not going to be an issue as even up to 500ms is totally ok as device is not going to be a prank or hidden hack, just to make my life easier with plenty of repeatable shortcut sequences. I'm aware of USB host requirement. After some research I learned that this will be much easier with arduino brother - Teensy. Plenty of interesting and easy to do projects on their website here --> http://www.pjrc.com/teensy/projects.html


text:
Connect multiple RFID-RC522 cards?
I have a project that requires 4 different RFID-RC522 readers.  The RFID-RC522 has the following pins:

SDA
SCK
MOSI
MISO
IRQ
GND
RST
3.3V

I have read that the SDA pin is used for selecting the active device, So I'm thinking that these devices can share data pins.  Is it possible to connect multiple RFID-RC522 readers to the same 3.3V, RST, GND, IRQ, MISO, MOSI and SCK pins if you use a different pin for each SDA?  If so, this would save me a lot of pins.  So far, I have only seen direction on how to connect one RFID-RC522 to an Arduino.
I'm using the MFRC522 library.  It appears to only support one reader because it only allows one SS pin to be identified in the constructor, and offers no way to change it later.  An I missing something or do I need another library?

possible duplicate of Use RFID-RC522 with other Pins

I am not asking how to redefine pins, I want to use one set of pins for multiple RFID cards.

The answer is still there.

@Magic-Mouse no, it is not. That doesn't state how to create different objects with different pins. To the OP: I'd suggest editing the library to replace the macro with a variable inside the class and just pass that in the class constructor. You're on the right track with the different chip select pins, but it seems like you might need to have an independent RST pin for each one, too. All of the SPI pins (SDA/SCK/MISO/MOSI) and power (3.3V/GND) 100% can be shared as long as the chip has a select pin.

@AnnonomusPenguin SDA is the SS/CS pin

Connect everyone to the MOSI / MISO / SCK and ground, then define every SDA all the way around. and set respectively high low depending on where you want to write.
How ever im not sure if you need to set high or low if you want to read. But since you got multiple you can play around with that your self. Feel free to add to this question with the result for future googlers.
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN           7          // Configurable, see typical pin layout above
#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

....

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

....

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card

I'm using the MFRC522 library.  It appears to only support one reader because it only allows one SS pin to be identified in the constructor, and offers no way to change it later.  An I missing something or do I need another library?

@Hoytman  works fine for me, though i only have one that i can test on but it compiles.

On my first couple of attempts, I could not get this to work.  Might have been my own code mistakes though.

I just saw that i made a copy paste error, try and set the variables as the corrected code.


text:
How to fix an IR remote signal
I am using the following code to send an IR signal:
#include <IRremote.h>
 IRsend irsend;

void setup() {

}

void loop() {

    unsigned int IRsignal[] = {86,88,86,88,174,86,88,88,86,88,86,86,88,86,88,86,88,174,86,88,174,86,88,2336,90,86,88,86,174,88,86,88,86,88,86,88,86,88,86,88,86,174,88,86,174,88,86,0};

    irsend.sendRaw(IRsignal, 48, 40);

    delay(3000);

}

However, when I attach an IR receiver to another Arduino and take a look at the signal that is produced by the code above, I see this:
Received:
OFF     ON
332 usec, 460 usec
1040 usec, 280 usec
2680 usec, 260 usec
820 usec, 80 usec
400 usec, 260 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    46, 104,
    28, 268,
    26, 82,
    8, 40,
    26, 0};

Received:

OFF     ON
39228 usec, 280 usec
1160 usec, 340 usec
2460 usec, 480 usec
440 usec, 500 usec
340 usec, 260 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    28, 116,
    34, 246,
    48, 44,
    50, 34,
    26, 0};

These numbers are not even close to the ones that are going in.  There are far few pulses recorded, the duration is very inconsistent (the original code is almost entirely made up of 880-860um pulses) and even close to the original values.  I must have made a serious mistake here.  What happened?
UPDATE ==========================
I multiplied all of the values in the array by 10 and attempted to play/read the values using another Adruino with an IR sensor.  I started to see better results.  each pulse time was close to 88, 86, or 174 but they are still off by up to 10%.  The related IR device is still unresponsive.  Is there any other way to improve this?
Received:

OFF     ON
29828 usec, 860 usec
900 usec, 820 usec
880 usec, 1700 usec
880 usec, 860 usec
880 usec, 840 usec
940 usec, 760 usec
840 usec, 880 usec
860 usec, 880 usec
860 usec, 860 usec
1740 usec, 840 usec
880 usec, 1700 usec
880 usec, 840 usec
6920 usec, 880 usec
860 usec, 860 usec
880 usec, 1680 usec
880 usec, 860 usec
900 usec, 820 usec
900 usec, 820 usec
880 usec, 840 usec
860 usec, 840 usec
960 usec, 740 usec
1760 usec, 880 usec
920 usec, 1620 usec
900 usec, 10680 usec
13580 usec, 8580 usec
8820 usec, 8680 usec
int IRsignal[] = {
// ON, OFF (in 10's of microseconds)
    86, 90,
    82, 88,
    170, 88,
    86, 88,
    84, 94,
    76, 84,
    88, 86,
    88, 86,
    86, 174,
    84, 88,
    170, 88,
    84, 692,
    88, 86,
    86, 88,
    168, 88,
    86, 90,
    82, 90,
    82, 88,
    84, 86,
    84, 96,
    74, 176,
    88, 92,
    162, 90,
    1068, 1358,
    858, 882,
    868, 0};

Possibly I have an out of date copy of IRremote.cpp, but in that file on my system IRsignal[] values are in microseconds, not tens of  microseconds.   Ie, sendRaw sends buf[i] values as-is to mark() and space(), which call delayMicroseconds() after enabling or disabling PWM.

Are you sure it's a 40kHz signal, and not 38kHz?

@Gerben - no idea what the kHz is, how can I tell?  Either way, the signal should still come across to the other Arduino as the same data set right?

@jwpat7 - so it might work if I put an extra zero on each value (x10?)

Most remotes and receivers use 38kHz. So if you send 40kHz to a 38kHz receiver, the signal might not be read entirely correct.

@Hoytman, I checked a current copy of IRremote.cpp and it uses microseconds in sendRaw buffer values.  Re 38 vs 40kHz, your rcvr part number (what is it?) dictates which you should use.  Eg, adafruit's TSOP38238 is tuned for 38kHz.  If you send 40kHz to a 38kHz receiver it could garble things up like you saw.  It's easy to try the other rates, of course