text:
Trying to understand interaction of interrupts, noInterrupts and delays
I'm having trouble understanding how to activate interrupts so that they operate only when they should. With this code, I seem to get erratic performance when I either attach or unattached interrupts, or when I try using noInterrupts.
What I am trying to accomplish is to deactivate the alarm function from running until a slight delay is initiated upon hitting an incorrect key. That would allow leaving the premises without triggering the interrupt. Does noInterrupt only affect the function in which it is placed??
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int PIR_SensorPin = 2;
int LED_OutPin = 11; //green
int Alarm_OutPin = 12; //red
int alarm_count = 0;
volatile boolean trigsensor = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (LED_OutPin, HIGH);
  }
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop()
{
  readKeypad(); // Serial.println ("at keypad");
  if (trigsensor == true) {
    alarm ();
  }
}

///////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  alarm();
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("trigsensor="); Serial.println (trigsensor);
  Serial.println ("at Alarm");
  if (away == true && trigsensor == true) {
    noInterrupts();////////////////////////////////
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW); delay (500);
      digitalWrite (LED_OutPin, HIGH); // delay (1000);
      //   digitalWrite (LED_OutPin, LOW); delay (1000);// End by turning off light
      Serial.println (alarm_count);
    }
  }
  trigsensor = false;
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW);
  trigsensor = false;
  away = false;
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  noInterrupts();
  Serial.println ("@ incorrect PIN ");
  //detachInterrupt(0); Serial.println ("interrupt off 1");
  trigsensor = false;
  away = true;
  digitalWrite (LED_OutPin, HIGH);
  delay(timeout);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); Serial.println ("interrupt on 2");
  alarm(); Serial.println ("here");
}

Well, yes, I think attaching and detaching interrupts isn't really something that you should do to often. It also won't really make your code very much more readable.
You may have a look at programming (embedded systems) in general. A technique I like to do is making a (non-blocking) state machine. In this way you don't even need interrupts (you can actually have interrupts if you want, though).
Also, it may be worth noting that making your code more readable and understandable is likely going to improve your "idea of what is going on" and thus improve it's reliability. This is commonly done by designing and applying "scope" to your code. You've done well on the keypad functions, giving them a sane name and reasoning. You could've put them in a class, but that's not where the errors are at.
Basically, your alarm has a few states:

Armed
Unarmed
Alarm!
Just activated

From these, you can form a state diagram.
Usually, "events" lead to the state of your system being changed.
For example:

simulate this circuit – Schematic created using CircuitLab
(Sorry for "abusing" the schematic editor (:  )
As you can see, events can be user interaction/sensors/timing, basically anything.
By designing your code in a state diagram, you get an idea of what you want your machine to do, at what moment. And what other states it can go to from there (and when/how).
Your code will become something along the lines of:
setup
enum STATE{
  armed,
  unarmed,
  justActivated,
  alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

loop
switch(systemState){
   case armed:
   if(breakinSensor.check() == HIGH){
      systemState = alarm;
   }else if(keyPad.check() == deactivated){
      systemState = unarmed;
   }
   break;
   case unarmed:
   if(armButton.check() == HIGH){
      timeGettingArmed = millis(); // Or you could just do a delay here.
      systemState = justActivated;
   }
   break;
   case justActivated:
   if(timeGettingArmed + waitTime < millis()){
     systemState = armed;
   }
   break;
   case alarm:
   if(keyPad.check() == deactivated){
     systemState = unarmed;
   }else{
     beep();
   }
   break;
}

Ofcourse you'll have to highly adapt this code to suit your needs, I doubt it will even compile. But it can also be a part of designing your program, try just writing it out in words (or explaining it to someone), before you program it.
*You could make use of the interrupts by checking in the interrupt if the state is "armed" and then setting the state to "alarm". This way you avoid the interrupt messing up any of your logic and having to disable it.
The cool thing of this "non-blocking" (if you don't use delays) state machine is that you can actually add more statemachines to it, and it will seem like the processor does everything at the same time. This is because it skips rather fast through the "i/o checks".

Your approach seems valid, but my issues to date are always getting sidetracked with trying to implement new techniques that I don't fully understand. The result is that I have been working on this project way too long. I will attempt your ideas on my next project.


text:
Running Multiple Languages on Arduino
This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

julialang.org refers to  “Julia’s LLVM-based just-in-time compiler”.   If you get LLVM bitcode from the compiler, it might be possible to put that through the AVR Backend To LLVM to get an assembly language or ELF file to download to an AVR.

Basically no, because you can't run either Julia or Python, let alone both together.
Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.

Thats a pretty straight forward answer lol! Thanks. I'm not surprised by Python because it's interpretted, but Julia compiles into machine code, so I thought that would at least work.

And basically correct one. There is ofcourse possibility to run interpreted langs on Arduino, even python ( http://stackoverflow.com/questions/8114916/is-there-a-way-to-compile-python-code-onto-an-arduino-uno ), there are some OS for it too and it can use external memory somehow, but Arduino is better used for other tasks, where you need small platform for some small things, which should be lightweigth and fast and usually solve just one or two tasks.  Cars, motocycles, bycicles and walks are also best fit for different tasks :)

What about Arduino DUE? It's an ARM based board.

source: Stack Exchange

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

sort: votes


text:
Initially my Arduino executes a series of PWM signals simultaneously, but after some iterations it adds around a second between PWM executions
I am using 2 adafruit PWM servo shield in order to generate 25 PWM signals. In particular I am using this shield: https://www.adafruit.com/products/1411
A python script sends the commands to the Arduino (Mega 2560) through pyserial. The commands are like "A0 P1 S500\n". Each argument separated by a space. The first chooses the shield, the second one the pin, and the third one the speed.
The code running in the Arduino is as follows:
#include <Adafruit_PWMServoDriver.h>

#define BUFFER_SIZE 200

// Init both adafruit boards
Adafruit_PWMServoDriver pwm0 = Adafruit_PWMServoDriver(0x40);
Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x41);

int read_command(char *buffer)
{

    static int pos = 0;
    int rpos;

    if (Serial.available() > 0) {
        Serial.println(Serial.available());
        char readch = Serial.read();

        switch (readch) {

            case '\n':
                rpos = pos;
                pos = 0; // Reset position index ready for next time
                Serial.println(buffer);
                return rpos;

            default:

                if (pos < BUFFER_SIZE -1) {
                    buffer[pos++] = readch;
                    buffer[pos] = '\0';
                } else {
                    Serial.println("666"); //buffer overflow
                }
        }
    }
    // no end line or char found, return -1
    return -1;

}

void parse_command(char* command)
{

    char* parameter;
    parameter = strtok(command, " ");
    long shield, pin, speed;

    while (parameter != NULL) {

        switch(parameter[0]) {

            case 'A':
                shield = strtol(parameter+1, NULL, 10);
                break;

            case 'P':
                pin = strtol(parameter+1, NULL, 10);
                break;

            case 'S':
                speed = strtol(parameter+1, NULL, 10);
                break;

        }
        parameter = strtok(NULL, " ");
    }

    for (int x=0; x < BUFFER_SIZE; x++)
        command[x] = '\0';

  if (shield == 0)
    pwm0.setPWM(pin, 0, speed);

  if (shield == 1)
    pwm1.setPWM(pin, 0, speed);

}

void setup()
{

  Serial.begin(9600);
  Serial.flush();

  pwm0.begin();
  pwm0.setPWMFreq(100);  //Max is 1600, Kevin was using 1000
  pwm1.begin();
  pwm1.setPWMFreq(100);

}

void loop()
{

  static char buffer[BUFFER_SIZE];

  if (read_command(buffer) > 0)
    parse_command(buffer);

}

As said, I am sending the commands from a Python script, where for example I have a function called "activate all", that will send 25 commands like "A0 P1 S500\n" (obviously with different values after the A and the P) to the serial port. I also have a function called "disable all", which is very similar to the previous command, but setting the S to 0 so like "A0 P1 S0\n".
So, as I start the serial communication, if I execute from Python "activate_all", I can how all the PWM signals are generated at the same time. I know it is actually 1 by 1, but it is fast enough to seem simultaneously to the human eye. If I then send a disable_all, I can see how all the PWM signals are set to 0 at the same time.
This works as expected for a while, but after some point, when I send an activate_all, it will indeed activate all of them, but it activates each PWM signal one by one, with a delay of around 1 second between activations (so you can clearly see them going one by one), and a very similar effect when disabling them all. From this point on, which seems slightly different each time, every time I want to activate more than one pwm signal at the same time, it will add this 1s delay between activations.
The only way I have to fix this is to send from the python a "flush()". which seems to be fix it. Doing flushes from the Arduino code, like when for example serial.available is 0, doesnt seem to fix it.
I don't know what exactly I am doing wrong. I guess the way I am handling the communication buffer is wrong, but I haven't seen where my mistake is.
A very similar code to the one pasted here was used in another project, in that case it was interfaced with Labview, and in that case everything seem fine.
In case you wonder about the code running in the Python script, it is like this:
import serial, time, json

class BZBoard:

    def __init__(self, port):

        self.ser = serial.Serial(port, 9600, timeout=120)
        time.sleep(2) # serial docs recommend a wait just after connection
        self.ser.flush(); self.ser.flushInput(); self.ser.flushOutput();

        self.motors = {
            just naming the pins
            }

    def __del__(self):

        self.disable_all()
        self.ser.close()
        del self.ser

    def close(self):

        self.disable_all()
        self.ser.close()
        del self.ser

    def activate_motor(self, motor_code, speed=300):
        ''' code as in A1 or C2 as marked in the actual board. See the dict motors'''

        shield, pin = self.motors[motor_code]
        command = "A%d P%d S%d\n" % ( shield, pin, speed )
        self.ser.write(command.encode())

    def activate_all(self, speed=300):

        for key in self.motors.keys():
            self.activate_motor(key, speed)

    def disable_motor(self, motor_code):

        shield, pin = self.motors[motor_code]
        command = "A%d P%d S0\n" % ( shield, pin )
        self.ser.write(command.encode())

    def disable_all(self):

        for key in self.motors.keys():
            self.disable_motor(key)

if __name__ == "__main__":

    board = BZBoard("/dev/ttyACM0")

So the user will do for example a lopp that repeats itself 20 times, where it will activate_all, wait 1 second, disable_all, wait 1 second. The first 10 iterations or so, everything will be fine and the PWM are generated all of them at the same time (with respect to the human eye), but after that, the PWM signals are generated 1 by 1, with a delay of 1s or so between them.

If you comment out all the Serial output (ie Serial.print() or  Serial.println()) does the problem still occur?

@jwpat7 yes. initially there was no serial output. I added it to debug

Your sketch generates greater output for each character of input, so unless you have pacing in your sending code, it will fall behind.  It's also possible that your sending code is filling up the transmit buffer that drip-feeds data through the slow serial link.  And it's not clear if you are claiming the response data or just letting it fill up an input buffer in the PC operating system.

@ChrisStratton by greater output you mean the PWM signals generated through Adafruit? I think also I have a lot of pacing. I have executed the same code with sleeps of 5 seconds, and the same problem appears. I don't understand what you mean about the transmit buffer, in particular when you say if I am claiming the response data or not. Could you help me with that? thanks for reading my question

There seems to be reason to think about filled buffers causing stalls and timeouts, but comments regarding 5-second sleeps between trials seem to rule that out.  To debug what's actually happening, you might blink an LED each time you receive a character, and another LED each time you call your parse_command() routine; and if you have an oscilloscope, look at the serial transmissions back and forth to see whether delay is due to something at the Arduino end vs at the host end.
That said, I think it would make sense to simplify the protocol by getting rid of your input buffer and just processing input as it comes.  For example, you could use the following letters as post-fix actions.
A  Select shield 1
B  Select shield 2
P  Set pin number, eg 11P selects pin 11
S  Set speed, eg 472S sets speed to 472
N  Send current speed to current pin, then increment pin number

For example, the command sequence for “disable_all” could look like:
0S0PANNNNNNNNNNNN 0PBNNNNNNNNNNNNN

This is easy to parse on the fly; declare int val=0 and any other needed variables before loop(), then within loop() say:
  char inc;   // For incoming character
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        board = 0;
        break;
      case 'B':
        board = 1;
        break;
      case 'P':
        pin = val;
        break;
      case 'S':
        speed = val;
        break;
      case 'N':
        if (PinNumberIsOk(board, pin))
          pwm[board].setPWM(pin, 0, speed);
        ++pin;
        break;
      default :
        ; // handle blanks, returns, whatever
      }
      val = 0;  // Set val to zero on any non-digit
    }

As another example, the sequence 4PA 11SN13SN17SN would send speeds 11, 13, and 17, respectively, to motors 4, 5, 6 on the first shield.

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


text:
RTL8170 Web Server - client unable to connect
RTL8170 is a new module, which is in many ways better than the old ESP8266 module. We are able to flash this module with Arduino using an Ameba Writer, and it should be able to support any code that is supported by the ESP (with some adjustments). It has been officially supported by Realtek's environment but it does not use all the GPIO (only 2). Luckily, pvvx developed an environment for Arduino IDE, which we can install and use through this tutorial: https://hackaday.io/project/19163/logs
I have uploaded a modified SimpleWebServerWiFi sketch from Ameba RTL8170 examples by both trying the official Realtek and pvvx's environments, and using LEDs to troubleshoot (I don't have an SPI/I2C LCD or a Serial-to-USB) I found the module being able to connect to my Samsung's hotspot but unable to communicate with the module because server.available() never turns true. When my module connects to my Samsung Note 4's hotspot, I see its IP (192.168.43.123) and fail to connect to it via a browser (on the phone or with a Windows laptop). Android port scanning apps indicate that the target IP address of the module has no open ports. Code below.
Update2: I've made adjustments to the code according to suggestions, but it still didn't respond. Updated code below:
   /*-----------------------------------------------------------------|
  |  Build using pvvx's enviroment: https://github.com/pvvx/RtlDuino  |
  |  Tutorial: https://hackaday.io/project/19163/logs                 |
  |=================================================================*/

#include <WiFi.h>

char ssid[] = "WiFi_SSID";      //  your network SSID (name)
char pass[] = "password";   // your network password
int keyIndex = 0;   // your network key Index number (needed only for WEP)
String currentLine = "";   // make a String to hold incoming data from the client

int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
  pinMode(1,OUTPUT);

  //Serial.begin(38400);      // initialize serial communication
  pinMode(LED_BUILTIN, OUTPUT);      // set the LED pin mode
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    //Serial.println("WiFi shield not present");
    while (true); // don't continue
  }
  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    //Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to Network named: ");
    //Serial.println(ssid);         // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 0.2 seconds for connection:
    delay(200);
  }

  server.begin();                   // start the web server on port 80

}

void loop() {

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,

    //Serial.println("new client");           // print a message out the serial port
    while (client.connected()) {            // loop while the client's connected

      if (client.available()) {             // if there's bytes to read from the client,

        char c = client.read();             // read a byte, then
        //Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {

            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Length: 88");
            client.println("Content-Type: text/html");
            client.println("Connection: Closed");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click here turn the BUILTIN_LED on
");
            client.print("Click here turn the BUILTIN_LED off
");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            //break;
          } else {    // if you got a newline, then clear currentLine:
            //digitalWrite(1,HIGH); // Doesn't turn ON
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          //digitalWrite(1,HIGH); // Turns ON
          currentLine += c;      // add it to the end of the currentLine
        }
        //digitalWrite(1,HIGH); // Turns ON
        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    //digitalWrite(1,HIGH); // Turns ON
    // close the connection:
    client.stop();
  }
}

Update 1:
I am still unable to fix the code. If no one can fix this code, please feel free to provide a totally new code.
P.S.: If this question keeps stagnating, I'll remove it and recreate it.
Any help is appreciated. Thank you!

Inside the while loop, where you give the link to click you have a break that prevents the handling of the answer from the client.
I would reconsider the use of that break and structure the code to not use it at all.

How would I correctly rewrite this code?

Could you please give a code snippet example? Thanks!

If you must use String, get its declaration out of loop(). You're only fragmenting your heap and reducing available RAM. Instead, declare it in the file scope and reserve sufficient space for a request line with the reserve() method in your setup().
Though response headers are supposed to be case-insensitive, it's still a good idea to follow the 'standard', spaces and all, like this for instance:
HTTP/1.1 200 OK
Content-Length: 88
Content-Type: text/html
Connection: Closed

Try sending all the fields above, especially the content length. And get rid of the break like mico said. There's no way your builtin LED will turn on or off if you keep breaking right after you respond to the client.

With these adjustments to the code, it still didn't respond

(Updated code above)


text:
How to send command from coordinator to router in Xbee?
I am using an XBee-PRO S2b module. I have sent data from the router Xbee to the coordinator Xbee.
Now I want to send a command packet from the coordinator to the router Xbee to set a pin high.
My coordinator is in API mode and the router is in AT mode.
Can anyone say how to do that?

In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s

it is using xbee s2 but i think it works under the same protocol.


text:
How do I check if a password is right? (keypad input)
Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it`s not working.
 while(i<=4,i++)
{
char key = keypad.getKey();

pass.append(key);
}
if(pass.evaluate())
{
  digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    delay(6000);
}

My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;)
But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.
edit:
the full code:
#include <Password.h>
Password pass = Password( "1331" );

#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int i = 0;

const byte rows = 4; //four rows
const byte cols = 4; //four columns
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}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
keypad.waitForKey();
digitalWrite(buzzer,HIGH);
  delay(125);
  digitalWrite(buzzer, LOW);
  delay(6000);

}

void loop() {

  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    while(i<4,i++)
    {
    char key = keypad.getKey();
    //keypad.waitForKey(); not sure if i should use that

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }

  }
      }

Please post a minimal, complete, verifiable example.

You might want to add some delay, or wait till the button is released. Otherwise, when you press for example 1, it will keep appending 1s till it reaches 4.

Without knowing how the pass.* works, it will be impossible to pinpoint the problem.
'key' gets an ASCII value. Is that would you are expecting?
Does pass.* reset (start over) once 4 digits?
Just a guess, but I believe that *.waitForKey() does not consume the key.
The algorithm only gets the key four times; then, it checks.

Password pass = Password( "1331" ); that`s how pass. works.

Could you just write me another algorithm to check for the password? I think this one is not good.

There's nothing wrong with the excerpt you posted. The problem is with code you haven't posted. As I requested, please provide a minimal, complete, verifiable example of your code, and then someone may be able to help. We don't know how you have your equipment connected, what libraries you're using and so on, so we cannot test our code or be sure it will work for you.

This is completely the wrong way of doing a loop. Since Arduino uses C++ I made this test program:
#include <stdio.h>

int main (void)
  {
  printf ("starting\n");
  int i = 0;
  while(i<=4,i++)
     {
     printf ("%i\n", i);
     }
  printf ("done\n");
  return 0;
  }

This prints:
starting
done

Note that the loop is executed zero times. This is because you used the "comma operator".
From https://en.wikipedia.org/wiki/Comma_operator you can see:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In other words, your loop adds one to i and checks if it is zero (before adding one). Thus the loop terminates immediately.
A better construct would be:
for (i = 0; i < 4; i++)
   {
   // whatever
   }

That is the standard C/C++ way of doing a loop a fixed number of times.

Also, most keypad libraries return NO_KEY if the user hasn't pressed a key.
You should test if keypad.getKey() returns NO_KEY and if so do nothing.
All your code would have done (if it had executed 4 times) was get 4 times NO_KEY (in a few microseconds) which would not be the correct password.

This is classical indexing problem:
while with <= 4 actually runs five (5) rounds.
So, use < 4.

Ok. I didint have access to my pc so I wrote what I remembered of my code. Here is the full one

... Unless i starts at 1, which we can't tell because we have a snippet of code without context.

I wrote what I remembered of my code - please don't post "remembered" code. Wait until you are at your PC and post the actual code. Posting "remembered" code just wastes everyone's time.

Assuming i starts at zero, while(i<=4,i++) executes zero times, not 5 times.

In case anyone was wondering, heres the code I came up with and now it works.
#include <Keypad.h>
int sensor = 11;
int buzzer = 10;
int red = 12;
int i = 0;
String Pass = "1331";
String tempPass = "";

const byte rows = 4; //four rows
const byte cols = 4; //four columns
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}; //connect to the row pinouts of the keypad
byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

void setup() {
pinMode(sensor, INPUT);
pinMode (buzzer, OUTPUT);
StartingBuzz();
keypad.waitForKey();
digitalWrite(red,HIGH);
digitalWrite(buzzer,HIGH);
  delay(200);
  digitalWrite(buzzer, LOW);
  delay(60000);
}

void StartingBuzz()
{
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer, HIGH);
delay(125);
digitalWrite(buzzer, LOW);
delay(125);
digitalWrite(buzzer,HIGH);
delay(125);
digitalWrite(buzzer, LOW);
  }

void UnlockBuzz()
{
  delay(200);
       tone(buzzer,3250,200);
       delay(300);
       tone(buzzer,3500,200);
       delay(300);
       tone(buzzer,4000,200);
  }

void loop() {
  i=0;//resets the password-checking loop.
  tempPass = "";//resets the guessed password.
  char state = digitalRead(sensor);
  if (state == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    A:
    {
    while(i < 4)
    {
    char key = keypad.getKey();
    if(key != NO_KEY)
    {
      tempPass += key;
      i++;
      }
    }
    }
    if(Pass == tempPass)
    {
      digitalWrite(buzzer, LOW);
      digitalWrite(red, LOW);
      UnlockBuzz();
      keypad.waitForKey();
      digitalWrite(buzzer,HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      digitalWrite(red, HIGH);
      delay(60000);
    }
    else
    { tempPass = "";
       i=0;
      goto A;
      }

  }
}


text:
door protector arduino program
Please check the arduino program given below and help me to find out error.
The program is for following hardware.
GSM 800 module
Arduino Uno board
Limit switch(2)
We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.
We run this program & it run but it sends the massage repeatedly after some time.
Please help me to find out error..
my ARDUINO code is
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;
bool i = true;
bool j = true;
bool k = true;
bool l = true;
int buttonState1 = 0;
int buttonState2 = 0;
void setup() {

  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void loop() {
  buttonState1 = digitalRead(Main);
  if (buttonState1 == HIGH && i == true ) {
    digitalWrite(Main_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Main Door is closed");
    Serial.write(0x1A);
    delay(5000);
    i = false;
    j = true;
  }
  else
  { if (buttonState1 == LOW && j == true )

    { digitalWrite(Main_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91---------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Main Door is open");
      Serial.write(0x1A);
      delay(5000);
      i = true;
      j = false;
    }
  }

  buttonState2 = digitalRead(Store);
  if (buttonState2 == HIGH && k == true) {

    digitalWrite(Store_led, HIGH);
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(5000);
    k = false;
    l = true;
  }
  else
  { if (buttonState2 == LOW && l == true)
    {
      digitalWrite(Store_led, LOW);
      Serial.println("OK");
      delay(1000);
      Serial.print("AT+CMGF=1\r\n");
      delay(500);
      Serial.print("AT+CMGS=\"");
      Serial.print("+91------------------");
      Serial.print("\"\r\n");
      delay(5000);
      Serial.print("Store room is Open");
      Serial.write(0x1A);
      delay(5000);
      k = true;
      l = false;
    }
  }
}

it sends the massage repeatedly after some time Which message? How long is some time is it after a certain number of button presses? after 5 minutes of nothing happening?

it is not depends on time but when switch is close(Door closed)(NC) it not repeated but when switch is open(door open)(NO) it send message repeatedly

You should be ashamed of yourself.  Writing code with no comment is irresponsible enough, but asking others to look at it is downright rude.  -1, and closing for the nearest handy reason  because this gross disrespect doesn't deserve a answer.

@OlinLathrop Are you telling a grown man to be ashamed of himself? The code is readable enough. +1 to OP because this isn't a forum for shame.

I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.
const int Main = 7;
const int Store = 8;
const int Main_led =  13;
const int Store_led =  14;

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}

I want to send Same message on two numbers how should I done

You should probably post another question giving enough detail to answer it. I want to send Same message on two numbers What numbers? In what situation?


text:
Contoller for a stepper motor
I am currently implementing the following setup:
Arduino Mega 2650 -- DRV8834 -- Stepper motor
Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by AccelStepper, the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only discrete and not accurate enough for a nice speed control.
Therefore I want to do the following
Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor
whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.
How can I create a PWM from 100 to 3000Hz with an arduino?

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM
void loop(){
digitalWrite(pinSTEP, HIGH);
delayMicroseconds(T/2);
digitalWrite(pinSTEP, LOW);
delayMicroseconds(T/2);
}

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:
prescalar = 1 ---> PWM frequency is 31000 Hz
prescalar = 2 ---> PWM frequency is 4000 Hz
prescalar = 3 ---> PWM frequency is 490 Hz (default value)
prescalar = 4 ---> PWM frequency is 120 Hz
prescalar = 5 ---> PWM frequency is 30 Hz
prescalar = 6 ---> PWM frequency is <20 Hz

which is not sufficient for my application.
For more about this method:

http://usethearduino.blogspot.ch/2008/11/changing-pwm-frequency-on-arduino.html
http://forum.arduino.cc/index.php?topic=72092.0

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:
#include <TimerThree.h>
// TimerThree PWM Pins 2, 3, 5

#define pinPWM       2
#define pinM0        22
#define pinM1        24
#define pinSleepnot  28
#define pinDir       30

void setup(void){

  // Define output pins
  pinMode(pinM0, OUTPUT);
  digitalWrite(pinM0, HIGH);
  pinMode(pinM1, OUTPUT);
  digitalWrite(pinM1, LOW);
  pinMode(pinSleepnot, OUTPUT);
  digitalWrite(pinSleepnot, HIGH);
  pinMode(pinDir, OUTPUT);

  // Initialize serial communication
  Serial.begin(9600);

}

void loop(void){

  for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
    float T = 1 / frequency * 1000000;
    Serial.print("Frequency: ");
    Serial.println(frequency);
    Timer3.initialize(T);
    Timer3.pwm(pinPWM, 100);
    delay(5);
  }
}

Do you need to count steps?  Do you just use it for speed control or do you have an encoder?  If you only need to control speed, maybe a voltage to frequency converter would do the trick.  E.g. http://www.ti.com/product/LM331

Dive into the Mega 2560 PWM hardware. I am sure it can be run at some speed suitable to you. But you might need to do it yourself instead of relying on the Arduino libraries.

The premise of your question is based on misunderstanding, you can toggle digital pins a lot faster than 1 KHz.

I do not need to count steps. I have a position read out system for that.
I will have a look at the PWM hardware stuff. I had a look at that one already: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM but it seemed to me that the steps are quiet big between the discrete frequency levels, but perhaps i got it wrong.
The problem with the toggling is somehow that it will block the microcontrollers processor (please correct me if I am wrong) and I could not continue reading out my sensors at the same time.

@AngeloQ: which voltage to frequency converter would you have in mind? I had a look at the other comments and i think it is not working with that. (see my edits in the post)

How can I create a PWM from 100 to 3000Hz with an arduino?

Your question is really "How can I create a PWM from 100 to 3000Hz with an Atmega2560"?
The Atmega has various timers which can be configured in many ways. You can alter the prescaler (ratio of processor clocks to timer ticks) and the amount it counts up to. Certainly you can change the frequency and duty cycle.
I have a page about timers which may help you.

I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM ... is not feasible

Yes, don't do "bit banging" when you have 5 hardware timers.

One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM.

Adapt the prescaler and the timer configuration. Between them you have very fine control.

Thank you very much sir! Sometimes a solution is so easy that it hurts if you find it ;)

You might need to move away from the AccelStepper library, and 'roll your own', but as others have pointed out, the MCU certainly has the bandwidth to do this directly.  I understand that PWM resolution may not give smooth ramping, but I would probably look into using a timer interrupt.  The timer ISR would count steps and you would only need to adjust the timer compare register to change the step frequency.

I will have a look into this tomorrow. But the AccelStepper library is really not suitable. I thought the 1000 pps limit would be related to the hardware. I also tested the stepper with an oscilloscope and it worked at very high freuquencies quiet smooth. Thanks for the input!

If you want to see what people squeeze out of ATmegas in the way of stepper control,  look into open source 3D printer firmwares.   Beyond that there are various ARM parts easily pushing 6 if not 10 times the clock rate that could make things easier, where you aren't trying to maintain a legacy tradition.

the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.
Much faster if you use direct pin ops.
So maybe the code you used isn't well written or your Arduino is doing lots of other things?
edit:

I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.

I use the AccelStepper library. I will try to find a software work around :) Thanks for the input!

Please see my edits in the post. I think this method is not working for me. Do you have anything else in mind?


text:
Problem with shift register
I have a problem with the shift register 74HC595.
The sketch I use is able to enable a specific led (8 are connected).
When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).
However, for the led connected to pin 15 (other side of the ic, see layout) it behaves differently.
 When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.
This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?
The code to switch on a led:
void updateShiftRegister()
{
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  digitalWrite(latchPin, HIGH);
}

where leds are the indices of the leds (0..7).

Please edit your question to include a Minimal, Complete, and Verifiable example of code, instead of just a snippet.  Also, if  “led 0 to 7” refers to 8 different LEDs (0 1 2 3 4 5 6 7) you will need to specify which pin each of those 8 LEDs are connected to.  The question seems to say you have a ninth LED attached to Q0 on pin 15.

Showing the wiring (and also a photo of your breadboard circuit) may help invesitgae on this issue. Also, I'd be curious to see code that sets leds value and how leds variable was declared (unsigned Vs. signed may have surprising effect on your code).

Thanks for all remarks, however, what I try is finding another project (instruction) for using it and check if I have the same problem; if still do, I can post it (and make a minimal example

You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on.
You have to build a table similar to the following:
byte led[8] = {
0b00000001,
0b00000010,
0b00000100,
0b00001000,
0b00010000,
0b00100000,
0b01000000,
0b10000000
};

and later . . .
shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

where leds is a number 0..7

Or more cheaply shiftOut(dataPin, clockPin, LSBFIRST, bit(leds));

Nice. I knew there had to be an even quicker way for such a simple mapping.

Thanks ... my example uses the shiftOut, but I will find another example and check if it also gives problems and than post the layout/full code if needed.

Somehow it seems to work, after using another scheme (although it looked exactly equal). So I'm really not sure why the problem existed; now it seems to work ... wondering if I should remove the question since  there might be useful information for others (regarding the table and shiftOut function.


text:
Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?
I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.
Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?
I have tried that name and know it probably isn't that.  Still poking around.

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want.  For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.
/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.
Note, arithmetic done in a form like
timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.

You don't need "to compensate for a roll over condition".
See my answer: https://arduino.stackexchange.com/a/33577/10794

in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:
maximum unsigned long in c++

You will find the first link leads to:
http://www.cplusplus.com/reference/climits/
In that it says:
ULONG_MAX   Maximum value for an object of type unsigned long int

Did you try to do this?:
unsigned long maxUnsignedLong = 0UL - 1UL;

or:
const unsigned long ULONG_MAX = 0UL - 1UL;


text:
Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow
I encountered a strange behavior while running 2 way transmission tests  between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).
I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C_readAnything".
Master's code
Slave's code
I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my previous problem)
I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).
Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?
I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

The code had several issues.
receiveEvent, on the slave side, contained a millis if condition timer that made it time out. I moved the timer to the master side before calling Wire.requestFrom.
receiveEvent, on the slave side, was also confusing real data with incoming requestEvent. I added an if statement to compare the receiveEvent data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the Wire library)
I set the global variables used in events as volatile. The code is working too without this tho.
fixed Master code
fixed Slave code

The Slave I2C clock is 100kHz, the Master has 800kHz. Start with the most normal settings, that means also the Master at 100kHz. The return values are not tested in the Master. I think in this situation you should test them. In the Slave you could test the howMany and increment an error counter if it is not right. The I2C bus is not fault tolerant, that means it should always work 100%. If it is unreliable, you should fix it. How long are the wires ? When you connect a 3.3V board via I2C to a 5V board, did you use a level shifter ? Did you connect the GND's of both boards ?

Do you mean the remaining wrong data I'm filtering out with by testing howMany shouldn't be there? When I test it like you advise, I see it's half of the receiveEvent (not a continuous flow anymore, so it's good enough, the bus gets released after each transaction so multimaster is working too now). That's why I think it's confusing requestEvent with data. I'll understand more once I get my logic analyzer.

The Master sets I2C bus speed. The slave's code doesn't contain speed setting. 800 kHz works fine between 48 MHz Nano but too much with the Mega. The wires are less than 1 m long. I'm using a level shifter between the Nano and the Mega. All on same GND. I'll add a test on the data content in my final application for extra safety.

I don't care if 800kHz worked in the past. You have to fix a number of problems, therefor returning to 100kHz would be wise. If everything works fine, you could try higher clocks speeds. But you are not there yet. The I2C communication should work 100%, not 99%. When the howMany is only half of the receiveEvent okay, then your I2C communication is working 50%. You have to fix the problems to make it 100%. Start by using the default I2C clock speed of 100kHz en test the return values in the Master. Maybe you could also store the howMany in a variable when it was wrong and print that variable.

Same @100kHz. howMany = 0 for half of the receiveEvent. For these, Wire.read returns -1, meaning no data.

Thanks for testing. That is very weird. Normally, only a collision in a Multi-Master bus could cause that. The howMany is the number of valid bytes waiting in a buffer. When you read more than the amount of valid bytes, the Wire.read returns -1. I'm out of ideas. It could still be a hardware problem, do you have pullup resistors ? My best guess is that it is a problem in the Wire library for the Zero. I can find a number of issues with the Wire library for Arduino Zero / Feather M0 / Arduino M0 (all ATSAMD21G).

I made some more tests. Pullups are there, around 2 kOhm. I made a first test with 10 transfers, without howMany. The data was randomly wrong in the serial print, but all good on the logic analyzer! code and result Then I made another test with 10000 transfers, with howMany. Any single transfer was good in both the serial print and the logic analyzer. code and result. I'm confused about the 1st result!

It means to me that the Wire library is sometimes triggering receiveEvent when there isn't any incoming data. It's not a big issue tho since there's no wrong data or collision on the bus.

You need to test it at 100kHz. If you can do the same at 100kHz then I suggest to assume that it is a bug in the library and you should work around it. Perhaps the receiveEvent is sometimes accidently called when the I2C transaction has just started. When the Master requests data, the Master should send a NAK at the end, but it doesn't. I read that when writing a register in a Slave followed by reading that register, sometimes a short delay (1ms) is needed between the Wire.endTransmission and Wire.requestFrom. That means there are already three things to improve for the SAMD21 Wire library.

It's behaving the same at 100 kHz. I only see NACK at the end of the reads, before the stop with the logic analyzer. The howMany workaround made it possible to transmit with 100% success. Thanks for all your advises. Adding the other tests you suggested plus retry on collisions made it possible to use the code for multi-master 2 way transmission.

Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.
The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent and in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.
With your sketch, you have to open the serial monitor for both the Master and Slave.
You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.

I simplified the code to test with a single byte 2 way transfer @100 kHz, using volatiles in events like you advised. I'm still seeing the same behavior (after opening monitor on both of course). Transferring one way only is working properly.
Adding more tests sounds to me that it would only hide that fake data is flowing between the devices (like the filtering I did in my initial code). I have to avoid disabling interrups because my final application relies on them (PID motor control and encoder reading...)

Result on slave:
"Arduino connected
...
ÿ
ÿ
m
ÿ
ÿ
ÿ
..."
(should get "m" only; same behavior on master side)
Master     /
Slave     /
One way only Master

I figured out what didn't work in the simplified test. The millis delay in requestEvent was causing it to timeout. I put this delay before requestFrom in the master instead. I have to test the "howMany" parameter in the receiveEvent so it doesn't confuse incoming data with a requestEvent. This should be handled by the wire library in my opinion.  Fixed code


text:
Right way to convert 120VAC to 5V?
I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.
Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.
I found this (Enclosed AC DC Converter) and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?
Thanks for your help in advance.

I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.
Short Answer, No
If you read the datasheet for the Particle Photon, it recommends no less than a 1A power supply. Unfortunately, the datasheet for the AC/DC Converter you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.
How to Make This Work
Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!
Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like this one may be right for you (not to plug for Adafruit, though they are a great learning resource).
Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.
Bonus Points
You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.
EDIT:
Easiest Solution
Just install one of these at the receptacle you intend to use.

Where did you get the 1A value from? The recommended conditions table on the datasheet you have linked mentions Avg Operating Current to be 80-100mA.  1A is mentioned in absolute maximum ratings, which I think defines a safe limit.

Under the "Power" section of the linked documentation, it says typical operating current is 80mA (still above the AC/DC the OP asked about), but the author recommends, "[...] the power source should be sufficient enough to source 1A of current to be on the safe side." Given the OP is asking this question, I doubt the OP is likely to calculate their exact power needs, so going with the manufacturer recommendation seems wise. Also, with WiFi, peak current goes as high as ~400mA.

You've also got options like these DC 5V 2A Switching Power Supply Board Converter Transformer since anyway you have to put your mains relay in an enclosed box.

Thanks for the response. I didn't even look at how many amps this gives off. After looking at the Particle Photon data sheet it says that it operates at a peak of 430mA so you are right this wouldn't work. Im not trying to use a usb block because I want to keep the size down. Also this is more of an exercise for me to learn more about how things work. Unfortunately, Im teaching myself via internet resources so I'm bound to make stupid mistakes.

As someone who does this semi-regularly, I'd simply gut an off-the-shelf component and throw it in my enclosure. There are times when it's worth reengineering something, but this really isn't one of those times. If it is to you, I'd recommend going full-on and building a transformer-rectifier-SMPS system. That will really teach you something.

Also, the USB power brick can be in your enclosure too.


text:
How to communicate with GPS SIM900a without Serial Monitor
I am fairly new to Arduino. I was working on a project where I use a GSM SIM900a modem interfaced with an Arduino. The AT commands are sent via the Arduino to the GSM Modem. The problem, however, is that the commands are only sent when I open the Serial Monitor. I have an IR proximity sensor and I would like the AT commands to be sent when the sensor detects an object. I am putting the code for the GSM modem below (I have not yet put in the code for the IR sensor).I want to know how to send the AT commands when the Arduino is hooked up to a battery and not to a PC
#include <SoftwareSerial.h>
SoftwareSerial myGsm(7,8);
float temp;
int tempPin = 0;
void setup()
{
 myGsm.begin(9600);
 Serial.begin(9600);
 delay(500);

myGsm.println("AT+CIPSHUT");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CIPMUX=0");
 delay(2000);
 printSerialData();

 myGsm.println("AT+CGATT=1");
 delay(1000);
 printSerialData();

 myGsm.println("AT+CSTT=\"bsnlnet\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks
 delay(5000);
 printSerialData();

 myGsm.println();
 myGsm.println("AT+CIICR");
 delay(6000);
 printSerialData();

 myGsm.println("AT+CIFSR"); //init the HTTP request
 delay(2000);
 printSerialData();

 myGsm.println("AT+CIPSTART=\"TCP\",\"122.178.80.228\",\"350\"");
 delay(5000);
 printSerialData();
 delay(5000);

 myGsm.println("AT+CIPSEND");
 delay(2000);
 printSerialData();

sendtemp();
delay(3000);
myGsm.println("AT+CIPCLOSE");
printSerialData();

myGsm.println("AT+CIPSHUT");
delay(1000);
printSerialData();
}

void loop()
{
}

void printSerialData()
{
 while(myGsm.available()!=0)
 Serial.write(myGsm.read());
}

void sendtemp()
{
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
  Serial.print("TEMPERATURE = ");
  Serial.print(temp);
  Serial.print("*C");
  Serial.println();
  delay(5000);
 myGsm.println(temp);
 delay(3000);
 printSerialData();
 myGsm.write(0x1A);
 delay(3000);
   printSerialData();

}

Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)

This saved my a*s a few hours before my final year university presentations.


text:
ESP8266 ASyncTCP class example
I am new to ESP programming on Arduino, as before I was developing on eLua. There were some memory problems in Lua, so I decided to move to Arduino.
After looking at some examples, I found a library called AsyncTCP and I was very glad because it provides callbacks for events just like Lua. But I was very disappointed when I found no example of an async TCP server. Instead there is an AsyncWeb Server but I don't want to use an HTTP server: I want a simple telnet server. Does someone have a working example?

There are examples in the ESP8266 library
https://github.com/me-no-dev/ESPAsyncTCP/tree/master/examples

If there are no examples provided with the library then you will have to make do with the example you have :(
If you think about what a web server does it is really just a glorified Telnet server without proper security.  When the web server comes up it creates a waiting socket on port 80, you want port ?? (too long ago).  It sits there waiting for text messages from clients, which is what you want to do.  Every time it receives a message it sends it to a handler.
I don't know how experienced a programmer you are, but you should be able to pick up enough from the webserver code to write your own telnet server.  However with you being new to Arduino you may be much better doing it as a synchronous application to start with.
Another approach is to find a the source for a telnet server and see if you can port that to the ESP.

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


text:
Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino
The error message, generated from Sublime, in its entirety...
Compiling KCT_Swimv4l...
Creating C:\Users\ken\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
'"avr-g++"' is not recognized as an internal or external command,
operable program or batch file.
[Stino - Error 1]

This is initial install of "Arduino-like IDE".
I used the following installation procedure:

Install Sublime Text 3
From Sublime, View --> Show Console
From a web browser, open  https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter.
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
from Arduino --> Preferences --> Select Arduino Application Folder.

Same problem with any sketch.
System Configuration:
-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0
github info on Stino was not helpful.
Has anyone encountered this problem and found a solution for it?
If not, I can open an issue there.

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --> Show Console
From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --> Preferences --> Select Arduino Application Folder
On Compile, error msg is now different:
  Compiling KCT_Swimv4l...
  Creating C:\Users\kct\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
  cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
  cc1plus.exe: error: unrecognized command line option "-flto"
  [Stino - Error 1]

unrecognized command line option "-std=gnu++11" - sounds like the compiler you installed is too old. It looks like it is from 2010. Right now it is 2017.

@Nick Gammon This was recommendation from answer posted.
Yes, this winavr copy is from 2010, as specified in answer, and the current year is now 2017.  I wondered about that.
Now that I have a starting point, I now see that there is a newer copy at https://sourceforge.net/projects/winavr/, and I will try that out.

@Nick_Gammon  Nope, same copy.  Perhaps you can suggest a direction to pursue.

The avr-g++ that ships with the Arduino IDE would be more recent. For example with IDE 1.6.9 I find: avr-g++.exe (GCC) 4.8.1. That accepts -std=gnu++11 on the command-line.

I found a whole lot of binaries (.exe files) in arduino-1.6.9\hardware\tools\avr\bin where arduino-1.6.9 is my install folder.

Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.
Update
I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)

I have updated problem description to show last actions taken in response to suggestion.
Now get different error msgs.


text:
Using a MOSFET module to control DC LED PWM
I've seen some similar questions here for using MOSFET to control 12V LEDs
But apparently the only MOSFET currently available to us is a 2-MOSFET high power trigger module, details in the link below.
https://www.elecrow.com/high-power-mosfet-trigger-switch-drive-module.html
How do we connect this to the Arduino to send the PWM trigger (I get confused by the three holes) and how do we connect the DC power to this??? I get confused with the power connections.

Did the picture with labels that tell you what connects where not help you?

The three TRIG/PWM pins are connected to the same electrical point. The same goes for the three GND pins.
You can either solder:

A 2-pin 0.2 inch screw terminal (the very same kind of those blue connectors already in the board) to the pair of big holes closer to the edge, or
A 2-pin 0.1 inch header to the 2 holes in the centre of the 4-hole row (the smaller ones).

These will be the control input you should be connecting your Arduino to.
The DC power supply for the load that will be switched by the MOSFETS has to be connected between the VIN+ and VIN- terminals. Note that VIN- is connected internally to GND.
Your load has to be connected between the OUT+ and OUT- terminals.
That's all you need to know. In case you're in doubt, I've drawn this schematic for you (see below)

simulate this circuit – Schematic created using CircuitLab
IMPORTANT ADDITIONAL NOTES:

No flyback diodes are present in the board. If you try to switch an inductive load (a motor, a solenoid, etc.) with this board you have a high risk of damaging the MOSFETs and rend it useless.
You need at least a 5V control signal for switching high current loads with this board. Although a 3.3V control may seem able to switch the MOSFET, its internal RdsON at 3.3V could easily be high enough to produce excessive power dissipation and blow up the MOSFET. See these curves from the AOD4184 datasheet:

it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --> ask the manufactuer to be sure.
whether it works for you will depend on the load, driving signal and the mosfet used -> you should ask the seller for a schematic, or buy one and reverse engineer it.

I'm afraid that's wrong.


text:
OVF in serial monitor instead of data
I am currently working with two Arduinos and I'm trying to synchronize them. I want to get data from four LIS3DH accelerometers. The LIS3DH accelerometers are connected to the Arduino using I2C interface. I have managed to get the Arduinos to synchronize using SPI but when I get the third set of data it keeps on showing OVF rather than the values. My code is below can someone please help me out?
Thanks
// SPI Master
#include <Wire.h>
#include <SPI.h>
#include "SPI_anything.h"
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>

//#define LIS3DH_CLK 13
//#define LIS3DH_MISO 12
//#define LIS3DH_MOSI 11
//#define LIS3DH_CS  10

// I2C
Adafruit_LIS3DH lisch1 = Adafruit_LIS3DH();
Adafruit_LIS3DH lisch2 = Adafruit_LIS3DH();
// Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();
struct event3;

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using
// programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup() {
#ifndef ESP8266
  while (!Serial)
    ; // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  Serial.println("LIS3DH test!");

  if (!lisch1.begin(0x19)) { // change this to 0x19 for alternative i2c address
                             // - Voltage SDO

    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH1 found!");
  if (!lisch2.begin(0x18)) { // change this to 0x18 for alternative i2c address
                             // - Ground SDO
    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH2 found!");

  lisch1.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!
  lisch2.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

  Serial.print("Range = ");
  Serial.print(2 << lisch1.getRange());
  Serial.print("Range = ");
  Serial.print(2 << lisch2.getRange());
  Serial.println("G");
}

void loop() {

  lisch1.read(); // get X Y and Z data at once

  /* Or....get a new sensor event, normalized */
  sensors_event_t event;

  lisch1.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);

  lisch2.read(); // get X Y and Z data at once
  lisch2.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);

  struct event;

  SPI_readAnything(event);
  //  sensors_event_t event;

  //  lisch3.getEvent(&event);
  Serial.print(" \t "); Serial.print(float2s(event.acceleration.x,6);
  Serial.print(" \t "); Serial.print(event.acceleration.y);
  Serial.print(" \t "); Serial.print(event.acceleration.z);
  Serial.println ();

  delay(500);
}

/ SPI Slave

#include <Wire.h>
#include <SPI.h>
#include "SPI_anything.h"
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>

#define LIS3DH_CLK 13
#define LIS3DH_MISO 12
#define LIS3DH_MOSI 11
#define LIS3DH_CS 10

    // I2C
    Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using
// programming port to program the Zero!
#define Serial SerialUSB
#endif

void setup() {
#ifndef ESP8266
  while (!Serial)
    ; // will pause Zero, Leonardo, etc until serial console opens
#endif

  Serial.begin(9600); // start serial for output

  SPI.begin();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

  Serial.println("LIS3DH3 test!");

  if (!lisch3.begin(0x19)) { // change this to 0x19 for alternative i2c address
                             // - Voltage SDO

    Serial.println("Couldnt start");
    while (1)
      ;
  }
  Serial.println("LIS3DH3 found!");

  lisch3.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

  Serial.print("Range = ");
  Serial.print(2 << lisch3.getRange());

  Serial.println("G");
}

void loop() {

  lisch3.read(); // get X Y and Z data at once

  /* Or....get a new sensor event, normalized */
  sensors_event_t event;

  lisch3.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print(" \t ");
  Serial.print(event.acceleration.x);
  Serial.print(" \t ");
  Serial.print(event.acceleration.y);
  Serial.print(" \t ");
  Serial.print(event.acceleration.z);
  Serial.println();

  digitalWrite(SS, LOW); // SS is pin 10
  SPI_writeAnything(event);
  digitalWrite(SS, HIGH);
  //  delay (1000);  // for testing

  delay(100);
}

OVF means overflow, you probably exceeded the range of the data type you're using. Try /1000; /10000000000 etc to your variable until you don't get the OVF or use a datatype with a bigger range.


text:
How to get response of issued AT command for ES266 on Arduino programatically?
I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.
Goal: After issuing AT commands programatically, knowing whether these run successfully or not.
Microcontroller: Arduino Uno
#include<string.h>
#include<SoftwareSerial.h>

#define OK "OK"
#define SERVER_PORT 1234
#define RX_PIN 2
#define TX_PIN 3

SoftwareSerial ESP(RX_PIN, TX_PIN);

void setup() {
  Serial.begin(115200);
  Serial.println("First serial");
  while(!Serial);
  ESP.begin(115200);
  Serial.println("Second serial");
  while(!ESP);
  //Enabling multiple connections
  ESP.println("AT+CIPMUX=1\r\n");
  while (!ESP.available());
  String muxResponse = ESP.readString();
  Serial.print("muxR:");
  Serial.println(muxResponse);
}

void loop() {
  if (ESP.available()) {
    String val = ESP.readString();
    Serial.println(val);
  }
}

After running the above code I get the response in the Serial Monitor like:
muxR:AT+CIPMUX=1

busy p../

OK

I'm getting special characters too.

You could try lowering the baud rate to see if the problem goes away:  ESP.begin(9600);  then increase in increments. I guess you are using some sort of level shifting between the Uno and the ESP8266 device.

Ok. I'm just using arduino uno R2, ESP8266 and breadboard, nothing else.

@6v6gt I changed the baud rate of ESP8266 to 9600 by AT+CIOBAUD=9600. Baud successfully changed but getting same response. Getting this busy p.. :(

busy p../ error not going even after factory reset (AT+RESTORE).

Maybe you find something here. I's a similar case: http://arduino.stackexchange.com/questions/18575/send-at-commands-to-esp8266-from-arduino-uno-via-a-softwareserial-port

I recently found out that ESP pins are probably tolerant to 6V, BUT I would still use a level shifter.  Also there is some issue when using SoftwareSerial to communicate between an Uno and ESP where something doesn't work at high baud rates, normally 9600 does work.  Personally I would put a delay(50); and the end of loop() but I have no evidence that it makes a difference :)

I believe busy is a response you should expect and it literally means the ESP is still busy doing the last command.

There is a nice library that hides the AT commands behind standard Arduino networking API: WiFiEsp

change
AT+CIPMUX=1\r\n

to
AT+CIPMUX=1

Explain that, what was the mistake and how your answer correct it. As it, it solve the problem at hand without educating the OP.


text:
fatal error ESP8266WiFi.h: No such file or directory
I want to turn my ESP8266 into an access point so that I can connect directly to it.
I use the following sketch, but when I select
GENERIC module ESP8266 from menu, the libraries ESP8266WiFi.h and ESP8266WebServer.h become available but I was unable to upload the sketch.
Also when I select board as Arduino Uno (Which i have really) and then what to upload then the above two files becomes unavailable and says fatal error no such file... no idea what to do next.
#include <ESP8266wifi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include<WiFi.h>
#include<SoftwareSerial.h>
SoftwareSerial esp(2,3);
IPAddress local_IP(192,168,4,22);
IPAddress gateway(192,168,4,9);
IPAddress subnet(255,255,255,0);
 String ssid="Wisal";
 String pass="12345678";
 ESP8266WebServer server(80);
 boolean isAccessPointCreated=false;
void setup(){
  esp.begin(115200);
  Serial.begin(115200);

  WiFi.mode(WIFI_AP);
  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

  Serial.print("Setting soft-AP ... ");
  Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!");
  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());

}

void loop(){
  while(esp.available()>0){
    char a = esp.read();
      if(a == '\0')
        continue;
      if(a != '\r' && a != '\n' && (a < 32))
        continue;
      Serial.print(a);
   }
}

Are you trying upload to an Uno or an ESP8266? The hardware package and libraries you're referring to are for use directly on an ESP8266, not an Uno using an ESP8266 for WiFi communications.

i upload the sketch to arduino uno and the esp8266 is connected to my arduino uno.

The ESP8266 core for Arduino that you're trying to use is for programming ESP8266 directly. You are trying to program an Uno with an ESP8266 connected to it for use as a WiFi module. For that application the ESP8266 core is of no use. For your application it's most common to run the AT firmware on the ESP8266 and communicate via serial. If you're doing that I recommend the WiFiEsp library:
https://github.com/bportaluri/WiFiEsp
Since you're uploading to the Uno you should have Arduino/Genuino Uno selected in the Tools > Board menu.

There are two ways to use an ESP8266.
Method 1
You seem to say you are using it as a slave to your UNO.  You program you Uno from the IDE.  The program will have code in it to send 'AT' commands to the ESP and this will make the ESP handle all the WIFI stuff.
Method 2
You remove you Uno and use the ESP as the main processor.  This means you get to program the ESP with C++ like code through the IDE, just as if it was an UNO.  HOWEVER you will need to install the ESP package from the board manager and there are certain limitations.  You also have access to less IO ports, but you can connect the Uno (over serial or I2C) and use it as a slave (which you program through the IDE separately).

You have imported ESP8266wifi.h and not ESP8266WiFi.h

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


text:
Any resources you know with regards to remotely reading data from arduino?
I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.
Please let me know if you can't understand my question.

Just letting you know: I can't understand your question.

You can use the Bluetooth on the board, a Bluetooth dongle for your laptop if the laptop does not have bluetooth or you can buy a wifi shield.
The 101 has Bluetooth LE on the board.
You will find there is a Bluetooth -> Serial USB software, so the application on the laptop can still work the same way as when using the usb.
Here are the Bluetooth examples for the 101 on arduino.cc
https://www.arduino.cc/en/Reference/CurieBLE
and the user guide for the 101
https://www.arduino.cc/en/Guide/Arduino101


text:
Max current of Vin and 5V pin on Arduino Nano
What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

It's hard to say. The maximum the on-board regulator can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

The voltage of your supply
The ambient temperature around the board
The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.
Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).
However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).
The VIN current will be the same as the 5V pin current + the board current.

Oops. Silly me, should have read better.

@gerben It happens...

What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

it depends on the power dissipation limits (and to a less extent the current limit) on the regulator. the power dissipation is determined by the load your arduino and its loads draw, and the voltage dropout on the regulator.
the other part of the thermal limit is the thermal resistance of the package and ambient temperature.
Most of them use el cheapo 1117 regulators in sot223 that has a limit of 1amp + a thermal limit of 100c/w. so max power dissipation should be less than 1w. That means a practical limit of 0.5amp under the most aggressive conditions (2v dropout, or 7v input).
at 9v input, max of 0.25amp.
at 12v input, a max of 0.15amp.
...


text:
Radio Issues with RF69HW
I am working through this tutorial on using the RF69HW. The RF69HW datasheet can be found here. I am using an Eegoo Uno R3 and yes I am aware that the Arduino is a 5v and the RF69HW is a 3.3v board. I am using some voltage dividers to get the voltage to 3.3v via the circuit shown below, at end of question.
I would use a level shifter but I only realized this mistake today and I am trying to get this working ASAP. The radio does not appear to be working. In fact the program seems to get caught on it. I introduced:
radio.sendACK();
Serial.print(" - ACK sent");

After the button has been pressed. This is the output I get:
Listening at 915 Mhz...
Button pressed!

So it gets to the line before it where the button is pressed but then gets stuck attempting to sendACK. I don't know what to make of this. Any help getting these two to communicate is appreciated. Code and pictures below.
Here is the code I am using as the sender:
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY,NODEID,NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;
void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE=LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed=true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('[');Serial.print(radio.SENDERID);Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
    Serial.println();
    if(LEDSTATE==LOW) LEDSTATE=HIGH;
    else LEDSTATE=LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

And the receiver:
#include <SPIFlash.h>
#include <SPI.h>
#include <LowPower.h>
#include <RFM69.h>
#include <RFM69_ATC.h>
#include <RFM69_OTA.h>
#include <RFM69registers.h>

//*********************************************************************************************
// *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
//*********************************************************
//This part of the code simply sets up the parameters we want the chip to use
// these parameters allow you to have multiple networks, channels, and encryption keys
#define NETWORKID     100  //the same on all nodes that talk to each other
#define RECEIVER      1    //unique ID of the gateway/receiver
#define SENDER        2    // you could for example, have multiple senders
#define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
//Select your frequency by uncommenting
#define FREQUENCY     RF69_915MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
//*********************************************************************************************
#define SERIAL_BAUD   9600

//This part defines the LED pin and button pin
#define LED             9 //LED on D9
#define BUTTON_INT      1 //user button on interrupt 1 (D3)
#define BUTTON_PIN      3 //user button on interrupt 1 (D3)
#define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

RFM69 radio;

// the setup contains the start-up procedure and some useful serial data
void setup() {
  Serial.begin(SERIAL_BAUD);
  radio.initialize(FREQUENCY, NODEID, NETWORKID);
#ifdef IS_RFM69HW
  radio.setHighPower(); //only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  char buff[50];
  sprintf(buff, "\nListening at %d Mhz...", FREQUENCY == RF69_433MHZ ? 433 : FREQUENCY == RF69_868MHZ ? 868 : 915);
  Serial.println(buff);
  Serial.flush();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(BUTTON_INT, handleButton, FALLING);
  pinMode(RX_TOGGLE_PIN, OUTPUT);
}

//******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
#define FLAG_INTERRUPT 0x01
volatile int mainEventFlags = 0;
boolean buttonPressed = false;

void handleButton() {
  mainEventFlags |= FLAG_INTERRUPT;
}

byte LEDSTATE = LOW; //LOW=0

void loop() {
  //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
  if (mainEventFlags & FLAG_INTERRUPT) {
    LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
    mainEventFlags &= ~FLAG_INTERRUPT;
    if (!digitalRead(BUTTON_PIN)) {
      buttonPressed = true;
    }
  }
  if (buttonPressed) {
    Serial.println("Button pressed!");
    buttonPressed = false;
    radio.sendACK();
    Serial.print(" - ACK sent");
    if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
      delay(100);
  }
  //check if something was received (could be an interrupt from the radio)
  if (radio.receiveDone()) {
    //print message received to serial
    Serial.print('['); Serial.print(radio.SENDERID); Serial.print("] ");
    Serial.print((char*)radio.DATA);
    Serial.print("   [RX_RSSI:"); Serial.print(radio.RSSI); Serial.print("]");
    Serial.println();
    if (LEDSTATE == LOW) LEDSTATE = HIGH;
    else LEDSTATE = LOW;
    digitalWrite(LED, LEDSTATE);
    digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
    //check if sender wanted an ACK
    if (radio.ACKRequested()) {
      radio.sendACK();
      Serial.print(" - ACK sent");
    }
  }
  radio.receiveDone(); //put radio in RX mode
  Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
}

Here is a link to project pictures: imgur.com/a/sFW88
Here is my circuit diagram:

Please edit your question and add circuit diagrams.  Did you implement both 3.3-to-5V and 5V-to-3.3V interfaces, or just the latter?

@jwpat7 Here is a circuit diagram. I apologize, I know its not great. First attempt doing this online. I only implemented the latter with 1k and 2k resistors.

The circuit diagram shows several resistive voltage divider circuits, each made up of a 1KΩ in series with 2KΩ.
When 5 V goes into the top of such a divider, about 3.3 V appears at the resistor junction.  (And 0 V in gives 0 V out.) This is suitable for a 5 V output pin connected to a 3.3 V input pin.
For connecting RF69HW 3.3 outputs (eg MISO) to 5 V Uno inputs, ideally one would step up 3.3 V to 5 V.  Instead, MISO goes to the resistor junction of what resembles a resistive voltage divider but in fact is not.
Consider a low output on MISO; then the 1K-2K junction goes to zero; so the Uno reads 0 on D12, as it should.
Now consider a high output on MISO.  The 1K-2K junction goes to 3.3 V, driving about 1.65 mA to ground through the 2KΩ resistor.  Presumably the SPI library uses pin 12, MISO, as an input, so current through the 1KΩ resistor is specified to be at most 10 μA (per Table 29-14 in ATmega328 datasheet) and is quite likely to be at most a few nanoAmps.  In any case, the voltage at pin 12 will be quite close to 3.3 V, which will register as a high input.  (Figure 31-72 in ATmega328 datasheet shows a 2.6 V threshold when Vcc is 5 V.)
This is more of a long comment than an answer, because although the MISO circuitry is problematic, it appears that it should work anyway.