text:
Control Android Camera using Arduino over Bluetooth
I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.
I have HC-05 Bluetooth Module and Arduino Nano/Arduino leonardo.

The Connection as shown in figure.
The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.

You'll need an Android APP to interface with the bluetooth and receive instructions to control the camera. Maybe the play store has something. If not, you'll have to learn Android programming.

Is there any code available which can control android mobile volume buttons from arduino??

What have volume buttons got to do with anything?

Volume buttons can also use for camera shutter, so if arduino can control volume buttons then it also use as camera shutter.

I think you don't understand how things work. An app may read the buttons and use them to do things like activate the shutter, but you cannot "control" a button from inside software. A button is an external physical thing.

Did you look on the play store for anything suitable? If you didn't find anything then chances are there is nothing. So you will have to learn Android programming. I am sure there are plenty of bluetooth examples, and plenty of camera examples. Your task will be to work out how to combine the two into a custom app. And this isn't the place for that, since it has nothing to do with Arduino.

Yes i already search on play store and there are nothing related to this. That's why i am asking here, Because i am not a android programmer.

I think those cheap BT shutter buttons act like a keyboard, and send the spacebar keycode (if I remember correctly)

I am trying out Camera Pro. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.
There are example sketch and detailed docs here.

Welcome to Stack Exchange. Link-only answers are generally considered not good because the link may disappear. Add some relevant info from the link to your question, please. Thank you and enjoy our site!

Programming Android is too much work (PITA, really). I like your solution even if I have to pay for it. I grow tired of downloading IDE updates every other week, dealing with API changes from one release to next one, and having to redesign apps to the latest fad ("material" any one?).


text:
Arduino connection to brainwave analyzing module
I want to connect a TGAM module (detecting brainwaves) to an Arduino Uno. I know little of electronics, can someone advise me? To which pin of the Arduino should I connect the TGAM? How to get the right electrical supply from the Arduino to the TGAM? Here is data about the TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
The R pin on the TGAM module is providing digital data as an asynchronous serial stream of bytes: http://developer.neurosky.com/docs/doku.php?id=thinkgear_communications_protocol

As per the datasheet you provided, it is quite straight forward.
It can be connected to RX (pin 0) and TX (pin 0) pins of the Arduino Uno.
But, the pins have to be crossed;
Arduino RX (0) <> TGAM T (TX)
Arduino TX (1) <> TGAM R (RX)
Arduino 3.3V <> TGAM + (VCC)
Arduino GND <> TGAM - (GND)
Good luck.

source: Stack Exchange

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

sort: votes


text:
Can an interrupt function call a regular function?
If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

Yes you may.
Yet keep the function in question short, you don't want to spend too much time in interruption.
Another way is to set up a variable state in the interruption, and call the function in question in the normal cycle when the variable is in the desired state.

Yes, you can. You just have to make sure your function is reentrant.
If it accesses no memory beyond its parameters and (non static) local
variables, you should be fine. If it accesses global variables, hardware
registers, or static locals, it is unlikely to be, and only detailed
analysis will tell you for sure.
Beware also of the library functions you call: some of them are not
themselves reentrant and should therefore be avoided. See for example
the manual of strtok(), which explicitly addresses the
reentrancy problem.

In addition, if the function is only called by the one ISR, and it will always run to completion (won't be interrupted and run another time before the previous call finishes), it doesn't need to be re-entrant.

@JRobert: The OP stated that the function would also be called from non-interrupt context. That other call would need to be inside a critical section if one wanted to ensure the function is never called while another call has not finished.

True enough, making my comment irrelevant here.

You can do that, but it will increase the complexity of your program.
Often when entering an interrupt service routine, the first thing you do is disabling interrupts - the make sure the callback completes reliably.
This is something you will have to consider if you want to use the same routine for a 'regular' scenario

You wrote: “the first thing you do is disabling interrupts”: on AVRs at least, you don't. The hardware does it right before executing the interrupt vector.

If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

The right answer is yes and no.
The issue here is reentrancy : whether a function can be interrupted while it's being called by another. Not all functions are re entrant so the safer assumption is that they are.
Another issue with calling a function from within the isr is overhead.
The typical solutions are:

Make sure that the function called from the isr is re entrant.
The simplest way to assure that is to a. Limit your calling of that from the isr. Or b. Create two versions of the same function. And call them separately.

Btw, I routinely call functions from within isr. In my case through function pointers.

You left out not at the end of  “Not all functions are re entrant so the safer assumption is that they are.”

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


text:
SD.begin() causes SD card to pull 20mA in idle mode. Seem high?
I'm working on a project that uses an Atmega328p as the primary controller. I am using the Arduino libraries for programming.
I currently have an SD card in the project. I've done quite a bit of studying on current consumption of SD card and it turns out they're quite power hungry during read/write operations. However, when an SD card is not being interacted with, I believe it should go into an idle mode in which the power consumption is much less.
Now I've noticed that when I start using the Arduino SD library, specifically SD.begin(), the current consumed is approximately 20mA. This is a continuous 20mA without any read/write operations being used. Simply selecting SD.begin().
So I've got a few questions:
- Does this seem high for an SD card that is essentially doing nothing?
- What exactly does SD.begin do? I assume it configures some pins but does it do anything else? If it's just set up, shouldn't it 'set up' and be done? Why the continuous high current?

Current consumption depends entirely on the card used. Some (e.g., sandisk) will enter a sleep mode automatically. Some need to be placed into sleep mode. The SD library isn't clever enough to do that sort of thing.

So I'm really try to narrow down this high current draw between two things: the SD card or bad wiring/configuration of the Atmega328p. Given the fact that high current is only drawn after SD.begin() is called seems fishy to me. If were truly the SD card being power hungry in idle state, shouldn't it be pulling high current even without an SD.begin() call?

Not if the card starts in a low power state. SD.begin() would configure it ready for use.  Personally I always have a P-channel FET arrangement controlling the power to the SD card so I can turn it on and off at will.

It doesn't just set up some pins. It initializes the SD card with a series of command/response transactions where it determines stuff like the card supply voltage, block size, etc. Then, assuming there's a FAT file system, it must read the boot record and get stuff like the location of the root directory, sector size, etc. Only after this, and the method returns true, is it then ready to serve up files. That said, it should go  to sleep when idle, i.e. no reads/writes. I doubt the SD library does any stuff in the background, so is the current draw consistent even after begin() returns?

@TisteAndii Correct. I've completely stripped the project down to the barebones: #include <SD.h> void setup() {SD.begin(8);} void loop() {} and the 20mA draw still persists. It seems rather odd that this is happening. I had used the adafruit SD breakout board and did not experience this issue (https://www.adafruit.com/products/254?gclid=CjwKEAjw8ZzHBRCUwrrV59XinXUSJADSTE5k_iQcTM9kAJkN-TSNhhhlH9Nq5sMnh_l0TbCozVun7xoCgyzw_wcB). I don't believe there is any fancy power down circuit in the breakout board either.

How are you powering the SD card, now that you no longer use the adafruit breakout?  SD cards don't like 5volt.

Oh, totally missed what you said about the breakout. If the same card has worked well before with the Adafruit breakout and SD library, then the cause of your problem now is most likely hardware. Like Gerben said, 5V is not good at all, for supply or signals. You need a 1.8 - 3.3V source able to supply up to 200mA. Arduino 5V supply + LM1117 regulator would be okay. Level shifting's also required between the Arduino and SD card.

You should look here and see if it helps. Basically:

Ensure that SD.begin() returns true because the card won't sleep if not properly initialized.
I don't know if it's been fixed but the SD library may still have a bug that prevents it from letting SD cards sleep. So try the SdFat library instead.
Try another SD card, from a reliable source.
Connect external pullups or use the Arduino's internal pull-ups with the MOSI, SCK and SS pins so they don't float.


text:
How to reset Arduino with ESP shield?
I'm working on the wifi uploading to Arduino over ESP shield (eg. ESP-12). When uploading over USB Arduino IDE resets the boards first (using DTR) and then interacts with the bootloader. How can i control ESP's GPIOs to reset Arduino board with ESP?

Have you considered using Esp-Link ( https://github.com/jeelabs/esp-link ) on your ESP-12? It comes with the "reset" function, built-in (I had succesfully used it).

Which firmware do you have installed on the shield? If you're using the AT firmware then please post the results of AT+GMR.

You may probably send something from ESP to Arduino (through serial), that the Arduino will process and issue a software reset by itself?

@SMFSW - a commanded reset only works if whatever is currently loaded is both non-broken and intended to recognize that command.

@Chris you're totally right, i put aside the part that arduino is reflashed at this point. Two options then, find out more about the communication of the arduino core software, there may be some builtin commands. Other option with a gpio would be to bypass the reset button of the arduino board with that output from ESP (driven logic low on avr microntroller reset pin).

There are no "built in commands" of the "arduino core software" and in fact that anything is able to run at all depends entirely on the "sketch" loaded.


text:
What shift register would I need for input OR output?
Background:
A few days ago I received a 23LC1024 1Mbit SRAM chip, which works like a charm.
However, before I ordered that one, I ordered a LP621024D-70LL which also is a 1 Mbit SRAM but in DIP32 format, meaning LOTS of pins.
Now I made a breadboard setup with 3 shift registers 74HC595 to be able to set the address (tested with LEDs but should work).
However, when trying use a shift register for the data which can be read or write, I don't think I can use a 74HC595 since it is only for output. However, I also don't think a 74HC165 (shift in register) would work (if I had one).
Questions:

What kind of shift register would I need, one that can do both input and output? I read about I2C registers but that seems to be a bit of overkill.
I only have 74HC595 shift registers for setting the address, would that slow down SRAM? I mean are there faster registers? Not that I want to buy it, but just curious.

Here is a picture of a working LP621024D-70LL ... too bad the chip is barely visible , on the left are 2 74HC595s and right are also 2 (right one not used), these 3 shift registers take care of the address (17 bits -> 3 bytes). The SRAM itself is hidden under the center of the cables.

Would any of   74LS194, 74LS195, 74LS395, CD4035B be relevant?

since you already have input, use an 74HC165  8-bit parallel-in/serial out shift register. They are cheap.
another cheap option with I/O is an expander like the PCF8574, which are almost cheap

Are you sure that a 74HC165 would work? Because since I now do not have any multiple-input-ic I use 8 pins which I have to set in Write mode for writing a byte, and Read mode for reading a byte. I have the 'feeling' I would need a 74HC595 for writing and a 74HC165 for reading but of course that is not possible simultaneously.

The 75HC595 has an Output Enable pin. Use that to disable the outputs of the 595 when you want to read from the 165. You don't care about what the 165 does while you're writing with the 595, it's high impedance.

Personally though I'd use an MCP23017 or MCP23S17 (depending on what bus I was using elsewhere at the same time).

I think I will try a MCP23017 or the other ... just to try :-) ... however, I already know why using a 32DIP is not a good idea (I will post a picture)

From the web page about the 23LC1024:

The memory is accessed via a simple Serial Peripheral Interface (SPI) compatible serial bus.

Using the SPI hardware on your Uno will be a lot faster than using software-based shifting. See my page about SPI.

Yes and I can fully confirm it now. To give a bit of background: I ordered a 23LC1024 but these are like 4$ and this chip above was like 1,50$. But it seems it is not worth all the extra wiring and for my project I need faster memory anyway ... I was hoping it would both be more than fast enough. But even because of the wiring I probably will not use easily this SRAM chip anymore. But I learned a lot about timing measurements, SPI and shift registers.


text:
Working with multiplexers for constant voltage output
I'm working on creating a circuit where I'm trying to have the ability to switch multiple strands of LED rope on and off at a time using an Arduino and a multiplexer.
With my current configuration, I have the a circuit and a sketch that will cycle through the various LED rope strands, turning them on and off.
What I'm not sure how to do is modify my sketch / circuit so that I can turn ALL of the rope strands on and off, as well as individually.
Below is my current Arduino sketch:
//Mux control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux in "SIG" pin
int SIG_pin = 3;

int testValue = 255;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

}

void loop(){

  //Loop through and read all 16 values
  //Reports back Value at channel 6 is: 346
  for(int i = 0; i < 9 ; i ++){
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[10][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  analogWrite(testValue, SIG_pin);

  //return the value
  return 0;
}

I'm using two multiplexers to control multiple rope strands. Here's roughly what that looks like:

I'm still a bit new to electronics prototyping (coming from software development); so I'm not sure if what I want to do is possible with a multiplexer
Happy to start offer a bounty to a helpful answer.
Thank you

This is going to be difficult! You should have bought a digital LED strip. The analog one you got needs to be continously fed with PWM signals, and the MUXes can only route your PWM output to one color channel of one strand at a time. Are you using PNPs or MOSFETs? With MOSFETs, it may be possible to use their gate capacitance (or an extra cap) to hold the value while you rapidly cycle the MUX. Not sure you can do this fast enough to avoid visible blinking though.

Ah - that makes sense. Yeah, definitely should have gone with the digital LED strip :/ Wondering if something like this may do the trick... https://www.adafruit.com/products/1429

Looks good to me. Notice that you will need pullup resistors between that chip and each of your transistors.

I would think that for a small number of channels, cycling through them wouldn't produce flicker, but 16 or more channels is a lot for that technique, especially if you want a fair amount of control over the brightness as opposed to just on/off. Another board to look at that might help out is the SX1509, which is cheaper and I think more programmable than the TLC5947.

I advice using ht16k33 (you will use this one with digitalWrite)

Even I am new to this and I also find it a bit challenging with the available setup and desired output. Though it seems tough, I want you to just try out this code (it is a little modification to the one posted by you) and check whether it matches the expected result.
    //Mux control pins
#define s0 8;
#define s1 9;
#define s2 10;
#define s3 11;

//Mux in "SIG" pin
#define SIG_pin 3;

#define testValue 255;  //maximum value for analogWrite() function

void setup()
{
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
}

void loop()
{
  //Loop through and read all 16 values
  for(int i = 0; i < 16 ; i ++)
  {
    delay(1000);
    writeMux(i);
  }
}

int writeMux(int channel)
{
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]=
  {
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++)
  {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  for(int i_testValue = 0; i_testValue < testValue; i_testValue++)
  {
    analogWrite(i_testValue, SIG_pin);      //incresing intensity slowly with delay of 100ms
    delay(100);
  }

  //return the value
  return 0;
}

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


text:
How can I use delimiter/split serial input in a loop function?
How can I use delimiter/split serial input in a loop function? I want to use each word from the input and check a database, to check availability.
#include SoftwareSerial.h>
#define MAX_WORD_LENGTH 15

char messageArray[5][MAX_WORD_LENGTH + 1];
SoftwareSerial BT(10, 11);
String command = "";
char message[] = "";

void setup() {
  BT.begin(9600);
  Serial.begin(9600);
  while (BT.available()) {
    delay(10);
    char c = BT.read();
    command += c;
  }

  if (command.length() > 0) {
    Serial.println(command);
    char message[] = {command};
    for (int i = 0; i < 5; i++) {
      // you can 'reset' the array by writing a null to the first element of each
      messageArray[i][0] = '\0';
    }
    sscanf(message, "%s %s %s %s %s", messageArray[0], messageArray[1], messageArray[2], messageArray[3], messageArray[4]);
    for (int i = 0; i < 5; i++) {
      Serial.println(messageArray[i]);
      delay(1000);
    }
  }
}

void loop() {
  for (int i = 0; i < 5; i++) {
    // you can 'reset' the array by writing a null to the first element of each
    messageArray[i][0] = NULL;
  }
  command = "";
}

Exactly how would you like this to work? How does it work now? Any compiler warnings or errors?

You seem to have no clue about arrays on C. Maybe you should read some C array tutorials.

Also your understanding of serial communications is flawed.

You might like this new blog post of mine: https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/


text:
Arduino Video player?
I want to play video from SD card   by using arduino mega 2560 and TFT 3.2" touch screen is it possible ?
if yes please tell me.
thanks in adavance

No, it is not possible.

@Majenko is it possible to play video from mobile via USB cable

You mean watch a video on your phone? Sure. Plug the SD card into your phone and open the video.

No ,is it possible to play video from mobile  on arduino  display via USB cable

If you can't play it from a local card then what makes you think you can play it from a remote connection?

It is not possible to play video on an Arduino from any source. The closest you could get would be to cycle through a set of images somewhat slowly.

The easiest way to understand why this is not possible is to "do the numbers", i.e. calculate the max frame rate for the TFT and image read from SD when using an Arduino. Even simply trying to read a file without decompression and writing to the TFT with give a very low frame rate.

An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.
The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.
We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/
On the same link you'll find also the youtube links for a video guide.


text:
Does ADC conversion to a voltage rely on the actual value of the +5 V pin?
Questions:

Does the conversion of the ADC count to voltage depend on the actual voltage of the +5 V pin?
If yes, what is the accepted method of getting that voltage from the board?

Background/Detail:
I have a circuit in which I have an Arduino Nano (clone) running from a USB connector (from a hub). The job of the Arduino is to measure the voltage on a battery which will drive a second circuit switched on/off by the Nano. For reference it is a battery tester.

There is a Nokia 5110 screen which displays the voltage from the very simple sketch below.
void setup() {
  Serial.begin(9600);
  display.begin();
  // Init done

  // You can change the contrast around to adapt the display
  // for the best viewing!
  display.setContrast(50);

  // Text display tests
  display.setTextSize(1);
  display.setTextColor(BLACK);
}

void loop() {
  display.clearDisplay();   // Clears the screen and buffer
  display.setCursor(0,0);
  display.print("Vin=");
  int rawVIN = analogRead(VIN);
  float floatVin = (rawVIN*4.75)/1023.0;
  display.println(floatVin);
  Serial.println(rawVIN);
  display.display();
  delay(1000);
}

I measured the voltage of the battery using a DVM and it is 4.13 V, yet
the Nano reports 4.35 V.
I have a common ground between the battery and Arduino.
Because the connection to test the voltage can float, I have a pulldown resistor to stop wild fluctuations (>10 kΩ)

After some investigation I found that the +5 V was actually outputting 4.75 V and changed my sketch from
float v = (rawVIN*5.0)/1024.0;

to
float v = (rawVIN*4.75)/1024.0;

and the voltage reading on the Arduino was now correct. I did this not because I understand what I did, I did it because I had a hunch it might change the value to the correct one.

As a side not you should be dividing by 1024, not 1023. This is a mistake which gets repeated over an over again, presumably stemming from the mistake being in the Arduino examples. Source? The datasheet for the AVR.

@TomCarpenter I think this is a result of my fumbling around with the calculation and reading something after quite a long time of banging my head against the desk - I started with 1024 but as you see ended up with 1023 - I'll correct my question.

The ADC inside the Arduino does not measure voltage, but rather a
voltage ratio. Namely the ratio from the voltage at the analog input
to the voltage at the Vref pin.
In the default configuration, the Vref pin is internally tied to the
+5 V line. You can select to use instead an internal reference as
Vref:
analogReference(INTERNAL);

This reference  is about 1.1 V, and is is quite immune to
fluctuations on the +5 V. The problem is that you cannot measure
voltages higher than the reference.
For your battery tester, if you want some sort of “absolute”
measurement, you could use the internal reference and a voltage divider
to ensure the measured voltage is below 1.1 V.
Edit: Another option which does not require a voltage divider is to
use Vcc as a reference to measure both the analog input and the
internal 1.1 V “bandgap“ reference. Measuring the 1.1 V
against Vcc is an indirect way to measure Vcc. This is not supported by
the Arduino core library, but you can do it by programming directly the
control registers of the ADC:
// Return the supply voltage in volts.
float read_vcc()
{
    const float V_BAND_GAP = 1.1;     // typical
    ADMUX  = _BV(REFS0)    // ref = Vcc
           | 14;           // channel 14 is the bandgap reference
    ADCSRA |= _BV(ADSC);   // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
    return V_BAND_GAP * 1024 / ADC;
}

Beware that the very first reading after boot may be bogus.

Thanks for the prompt reply :) this makes perfect sense now and explains why by my code (fudge) adjustment I get the right answer. This combined with enrics answer give me all I need to continue.

A USB-powered Arduino Nano will have an ADC voltage reference which can't be relied on, due to the +/- 5% tolerance of the incoming USB voltage. On top of that, the Nano has an MBR0520 Schottky diode (D1) that will drop between 0.1 and 0.5 V depending on its own manufacturing tolerances, its temperature, and the current draw of your board.
What can you do about it?
The MCU on-board the Arduino Nano is an ATmega328P. The Nano's ADC can scale its analog voltage readings according to several available references (and you can choose the one that suits you better). You can do this through the analogReference (type) function, and chose among the following reference types:

DEFAULT: the default analog reference of 5 volts (on 5 V Arduino boards) or 3.3 volts (on 3.3 V Arduino boards)
INTERNAL: An built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on
  the Arduino Mega)
  [...]
EXTERNAL: the voltage applied to the AREF pin (0 to 5 V only) is used as the reference.

Source: analogReference
This is the ADC schematic for what's inside the ATmega328 so you can see what's going on there:

Source: ATmega328 datasheet
So the straightforward solution is building a weak voltage divider to get the voltage you want to measure below the INTERNAL 1.1 V reference, and then configure analogReference accordingly.
The voltage divider needs to be weak (high R values) so you don't draw too much current out of the battery, but not too weak as to be loaded by the ADC input impedance.
Bonus
However, if you need a voltage reference higher that the internal 1.1 V bandgap reference of the ATmega328 you're still out of luck. A option would be to use the 3.3 V LDO regulator output from the on-board FT232RL, which is available to you at pin 14 of the header, but I don't think it's reliable either. The FT232RL datasheet specifies it at 3.0 - 3.6 V (nominal 3.3 V)
So a universal solution would be to build an external voltage reference based on a cheap TL431. That could give you a reliable reference up to 4.0 - 4.25 V with a +/-1% accuracy.
The external voltage reference circuit would be something as easy as this, (and the TL431 is available in the breadboard friendly TO-92 package!):

Thanks for this comprehensive answer and all the alternatives I could take up - I will probably go simple and do a voltage divider to scale my input between 0 and 1.1. The hint about resisteor values was valuable to me - thanks

I have a page about the ADC converter on the Atmega328P. Somewhat down the page I describe voltage references. You can use the TL431 chip to provide assorted reference voltages, for example 4V:

By changing the resistors you can get other voltages (it looks like you want around 4.2V).
The output voltage is not influenced by the input voltage (5V in this case).
The linked page describes how you might choose resistor values.

Does the conversion of adc count to voltage depend on the actual voltage of the +5v pin?

yes and no: the adc module cares about Vref, which can be supply via Vdd, internally, or externally.

If yes what is the accepted method of getting that voltage from the board?

by configuring the adc module. the device datasheet should have registers / bits that need to be set up for that.


text:
Arduino Interrupt example not working
The example program is from here: https://www.arduino.cc/en/Reference/attachInterrupt
When I paste in the code and run it, the LED is on all the time (It's supposed to blink):
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {
  digitalWrite(ledPin, state);
}

void blink() {
  state = !state;
}

This is my setup:

I think you misunderstood this example: it is not expected to automatically blink!
The LED is suposed to change state at every change of level on pin 2. This supposes that you wired something (e.g. a push button) to pin 2 and that this will make pin 2 change level when something happens (e.g. you press the button or you release it).
On your diagram, there is nothing wired on pin 2, so what you observe is just normal.
If you want to see attachInterrupt in practice, then connect pin 2 to a button with the other button lead connected to GND.
Then you can observe what happens when you play with that button.

I didn't have a button but I connected an ultrasonic distance sensor and the LED starts to blink whenever the distance changes. Thank you :)

if you want to blink your LED by giving interrupt by push button then you can try this..
int pushButton = 2;
int LED = 13;
volatile bool flag = false;
volatile byte state = LOW;

void setup()
{
    pinMode(pushButton, INPUT_PULLUP);
    pinMode(LED,OUTPUT);
    attachInterrupt(digitalPinToInterrupt(pushButton), &setFlag, FALLING);
}

void loop()
{
    if (flag)
    {
        digitalWrite(LED, state);
        delay(100);
        state = !state;
    }
}

void setFlag()
{
    flag = true;
}

An error with the code you show:   setFlag is not defined.  Also, some of the closing braces aren't indented in the code as shown, and the last one isn't shown as part of the code block

@jwpat7 Sorry for the code I have edited this code now..check it. Up

And it will blink too fast to be visible.

@EdgarBonet  add some delay() then problem will be solved

your code is a little bit too complicated. in the "if (flag)" portion of the code, flip the LED via "digitalWrite(LED, !digitalRead(LED));" and then clear the flag. No delay needed.

@dannyf, without a delay(), the LED gets toggled every pass through loop(), ie the  “blink too fast to be visible” problem Edgar Bonet mentioned.  With the delay, it still toggles every pass through loop(), so blinks at a 10 Hz rate.  That's still too fast, but will be visible.  Of course, once it starts blinking it never stops -- flag starts out false, but once it's set it never gets unset.  A problem!

to expand on my comments to Prayuktibid's code,  here is what I would propose in the loop:
void loop()
{
    if (flag)
    {
        //blink the led
        digitalWrite(LED, !digitalRead(LED));   //digitalWrite(LED, state);
        //delay(100);
        //reset the flag
        flag = false;                           //state = !state;
    }
}

the rest remains unchanged.
here is how it works:

it works as you would expect, without resorting to delays.
edit: btw, the approach shown above (of setting a flag in the isr, processing that flag in the main loop, and resetting the flag after the processing) is a fairly standard way of utilizing interrupts - pretty much the #1 choice unless you have some special reasons to deviate from it.
edit2: to just follow up on that state above (about trying to process the flag in the main loop).
for something this simple, you can also do it in the isr, making the code much closer to your original code:
void loop()
{
        digitalWrite(LED, flag);                //digitalWrite(LED, state);
}

void setFlag()
{
    //flip the flag
    flag = !flag;                               //flag = true;
}

the code above produced the same waveform as the code posted earlier.
the lessons learned: there is more than one way to solve a problem, as long as you do it right, :)


text:
Is the DigitalWriteFast library still needed?
Yesterday I played with a SRAM 621024 SRAM 1 Mbit IC and since I use a lot of pins, digitalReads and digitalWrites are needed including shift registers (see Example
Since it took a long time for reading/writing one byte, I checked for faster ways and found some posts, one of them was using digitalWriteFast:
Library
However, it did not make any difference... is it possible that the (fast) digitalWrite is already implemented in the default Arduino IDE/library?
Update: I found out I made a stupid mistake and the library was not used.
Now I get different values:

Writing 397.880 us per byte
Reading 386.524 us per byte

Without the fast library:

Writing 502.152 us per byte
Reading 483.752 us per byte

Note, there is also a digitalReadFast, but this does not affect the speed.
I did some more testing and found out that a digitalReadFast/digitalWriteFast cost just about 8-12 us, a pinModeFast is 0 us (negligable), however a shiftOut for setting the address cost 120-124 us ... since 3 shifts are needed to set an address, this results in 360-372 us. Subtracting this from the measured times above, writing takes around 25-38 us and reading 15-27us. I possibly can maybe optimize the bit operations a little bit.
However, the end result for using this RAM chip with enough speed is to either change the shift register to a faster one or remove the shift registers at all. This would mean about 30 pins needed for the SRAM only. The conclusion is: better use a 3K256, 23LC1024 or similar variant.
(Note: I tried a ShiftOutFast file), which reduces a shiftout to 36 us but 3 times 36 is still over 100 us, too much to compare to a 3K256/23LC1024 solution.

If it made no difference then the chances are the bottleneck isn't the digital pin manipulation.

I didn't get a microsecond difference.

The time taken to use digitalWrite() pales into insignificance compared to the time taken to use shift registers.

Yes it seems so ... I already thought that shift registers would not be beneficially for a SRAM solution ... maybe when I have the Arduino Mega I will check direct pins (like 32 pins maximum). Than I don't need shift registers. If I ever will solder that solution, I doubt :-)

The current digitalWrite() still does quite a lot of stuff.

That's why I was surprised I did not see any difference.

Last time digitalWrite() changed was six years ago

I should point out that micros() has a 4 µs resolution, so a difference of less than 4 µs would not be measurable (if that is how you are measuring it).

@NickGammon Thanks for the info (although it does not make the conclusion much different)

a pinModeFast is 0 us (negligable) - it may in fact be 3 µs is my point. Unless you did a loop of 1000 of them, written in such a way that the compiler didn't optimize the loop away.

No not in this case, so negligible means 3 us (or less). Negligible is relative :-)

I just tried to time digitalWrite() against direct port access with
the following code:
void setup()
{
    uint16_t overhead, start, end;

    Serial.begin(9600);
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    overhead = 7;
    cli();
    start = TCNT1;
    digitalWrite(2, HIGH);
    end = TCNT1;
    sei();
    Serial.print("digitalWrite(): ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");

    // Time direct port access.
    overhead = 4;
    cli();
    start = TCNT1;
    PORTD &= ~_BV(PD2);
    end = TCNT1;
    sei();
    Serial.print("direct port access: ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");
}

void loop(){}

The result was:
digitalWrite(): 78 cycles
direct port access: 2 cycles

I used an old Arduino core (1.0.5), but that function has not changed
since. You can try with your current core and see.
PS: In this program, the correct value for overhead can only be
determined by examining the generated assembly. It's a count of the
cycles you are measuring but do not directly belong to the operation you
really want to measure.

WOW! That's a difference! Very interesting to know. Where does all that extra MPU cycle usage come from?

@EnricBlanco: Here is the link to the source code again. Look at the disassembly: saving registers to the stack and restoring them back (20 cycles) table lookups, tests... and 8 cycles of call overhead.

is there any related trick like this for the ESP8266?

@dandavis: I have no experience on that chip.


text:
How to implement elapsed millis as the timer for my motor spinning time?
I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.
I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.
So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.
This is my code that I have tried using elapsed millis. Any suggestion is welcome.
#include <elapsedMillis.h>
#include <Keypad.h>
#include <Wire.h>  // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
Servo myservo;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
elapsedMillis timeElapsed;

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
{
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{

  Serial.begin(9600);
  lcd.begin(20,4);
  myservo.attach(11);

   lcd.setCursor(0,0);
  lcd.print("S=");
  lcd.setCursor(0,1);
  lcd.print("T=");
  lcd.setCursor(0,2);
  lcd.print("S=");
  lcd.setCursor(0,3);
  lcd.print("T=");
  lcd.setCursor(10,0);
  lcd.print("S=");
  lcd.setCursor(10,1);
  lcd.print("T=");
  lcd.setCursor(10,2);
  lcd.print("RPM");

}

 void loop()

{

  int stage1speed = getTheNumber();
  lcd.setCursor(2,0);
  lcd.print(stage1speed);
  lcd.print("sv");
  int stage1time = getTheNumber();
  lcd.setCursor(2,1);
  lcd.print(stage1time);
  lcd.print("sec");

  int stage2speed = getTheNumber();
  lcd.setCursor(2,2);
  lcd.print(stage2speed);
  lcd.print("sv");
  int stage2time = getTheNumber();
  lcd.setCursor(2,3);
  lcd.print(stage2time);
   lcd.print("sec");

  int stage3speed = getTheNumber();
  lcd.setCursor(12,0);
  lcd.print(stage3speed);
  lcd.print("sv");
  int stage3time = getTheNumber();
  lcd.setCursor(12,1);
  lcd.print(stage3time);
  lcd.print("sec");

   if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
        && stage3time > 0 )

   {

    if(timeElapsed <= 1000*stage1time)

    {

     myservo.write(stage1speed);

     }

    if(timeElapsed <= 1000*stage2time)

    {

     myservo.write(stage2speed);

     }

    if(timeElapsed <= 1000*stage3time)

    {

     myservo.write(stage3speed);

     }
  }

}

int getTheNumber()
{
    char buffer[4];
    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key && i > 0)
        {
            // Null terminate
            buffer[i] =0;
           int value = atoi(buffer);  // Convert to an integer
            break;
        }

    }
    return atoi(buffer);
    }

delay() is only the tip of the iceberg. The problem with delay() is
that it is a blocking function: nothing else can be done during the
delay. If you want to control your motor and at the same time be
responsive to the user, you must avoid blocking your program. This means
not only getting rid of delay(), but also getting rid of any blocking
function.
Here your problem is on getTheNumber(). This function blocks until the
user is done typing the number. Try to rewrite it in a non-blocking
fashion. For example, it could return -1 on every call as long as the
user is not done typing the number. On the first call after the user is
done it would return the valid value. If you manage to write everything
non-blocking, then you loop() will restart very often, and the program
will work with no significant latency.
As for managing the servo stages, simplest thing  would be to write a
finite state machine. I would write it with four states: IDLE,
STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 →
IDLE would be time-based, using the elapsedMillis object to track the
time spent in each state. The transition IDLE → STAGE1 would be
triggered by the user input.
static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
switch (state) {
    case IDLE:
        if (userRequestedToStartAgain()) {
            myservo.write(stage1speed);
            state = STAGE1;
            timeElapsed = 0;
        }
        break;
    case STAGE1:
        if (timeElapsed >= stage1time) {
            myservo.write(stage2speed);
            state = STAGE2;
            timeElapsed = 0;
        }
        break;
    case STAGE2:
        if (timeElapsed >= stage2time) {
            myservo.write(stage3speed);
            state = STAGE3;
            timeElapsed = 0;
        }
        break;
    case STAGE3:
        if (timeElapsed >= stage3time) {
            myservo.write(idleValue);
            state = IDLE;
        }
        break;
}

Thank you sir for your suggestions... I really appreciate it.  I 'll give it a try based on your suggestions.thanks so much ..

Sir, I have to build userRequestedToStartAgain() function?? I don't understand that..care to elaborate it for me..

@rjadkins: You may consider that call to userRequestedToStartAgain() as pseudo-code. It means you have to decide when the cycle is supposed to start, presumably on the basis of some user input. Then you write the if (...) condition for the IDLE → STAGE1 transition.

how do I do that?? I'm very confused right now. Forgive me, sir, I'm new to Arduino programming and this finite state machine is new to me. I am trying to understand the state machine. The transition from state to state really confuses me. In a typical switch statement, I understand that we can choose the cases in the switch statement, however, trying to move case to case or state to state in the switch statement is really new to me. So the transition part is a bit hard for me. Please help me, sir, trying to understand this transition.

@rjadkins: Then you should probably take some time to study the subject. See this Wikipedia article for a general background on the concept of FSM, and Majenko's tutorial for an introduction of the FSM as an Arduino programming technique.

I don't know if I even have time Sir, this project is due soon.  I have been using delay() for this project without out realising  that delay() pause the whole programming, thus unable for other function to work. The delay() have made my program unable to read the rpm function whilst the motor spin when I use delay() as the timer.

Mr. Edgar Bonet, can you give a suggestion regarding the userRequestedToStartAgain() ?? I find it hard trying to understand the state machine.

@rjadkins: It could be something like userJustTyped('*') or similar.

I'm using a 4x3 keypad. How do I put it in the code??  is it just like this:  if (userJustTyped('') ? or   if (key== '')? so far i have tried the key=='*' , nothing happen. Forgive me, sir, I am totally having trouble understanding this.


text:
HC-SR04 distance measuring without delay?
I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.
  long duration;
  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that delayMicroseconds() pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.
class distSensor{
   int trigPin;
   int echoPin;
   int distance;

   //Will be used in timer
   unsigned long previousMillis;

   public:
   distSensor(int tPin,int ePin){
   trigPin = tPin;
   echoPin = ePin;

   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   previousMillis = 0;
 }

 int calculateDistance(){

  //records time since program start
  unsigned long currentMillis = millis();

  long duration;
  digitalWrite(trigPin, LOW);

  //check if the previous time the method was called is greater than the interval of 2
  if(currentMillis - previousMillis > 2){
    digitalWrite(trigPin, HIGH);
    previousMillis = currentMillis;
  }

  //check if distance between current time and previous time it was called is greater than interval of 10.
  if(currentMillis - previousMillis > 10){
      digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  }
  return distance;
 }
};

In the calculateDistance() method I am trying to do the same thing as the first code but without delay() and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

Trying to use multiple sound based distance sensors at the same time may be problematic.  If they should "hear" each other their operation my result in unexpected values.  Consider using optical distance sensors based on the parallax principle.

theyre faced perpendicular and in opposite directions, thats not the issue

Likely there are configurations (room corners) which may still confuse sodar and sonar sensors which are trying to sample at the same time.

pulseIn() also blocks, so that won't help; you need an interrupt.

You said that the distance read is 0 ; your code does not work because you trigger the sensor with delays of 2ms and 10ms, you should use delayMicroseconds of 2us and 10us. As these delays are in us, you dont need to avoid them, you can use delayMicroseconds in your codes. The pulseIn() function blocks for too long, this is the one you have to avoid with interrupt as dandavis said.

delay() causes the processor to do nothing but wait.  You need to switch to millis().
In your code, you need to "grab" the current time using millis() and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what millis() returns.  When your stored value and millis() match, it is time to execute the code that would normally come after the delay() call.
Here, Arduino Playground - How and Why to avoid delay(), delay() and millis() are discussed in detail.
So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.

` //check if the previous time the method was called is greater than the interval of 2
if(currentMillis - previousMillis > 2){
digitalWrite(trigPin, HIGH);
previousMillis = currentMillis;
}
//check if distance between current time and previous time it was called is greater than interval of 10.
if(currentMillis - previousMillis > 10){
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
} `
I have done that already but it still does not work. currentmillis is the time counted from program start,

That is a very difficult comment to read.   You need to consider overflow of the variable type used and of the type returned by the medthod call to millis().  I don't think you included that in your comment above.  Also, for the way you are describing events, you might also have to worry about using unsigned integers.  It may be simpler to check if millis() returns an expected value rather than finding the difference between what millis() returns and some variable.

enter code here
#define ECHO 5        // Pin received echo pulse
#define TRIGGER 6     // Pin sends shot pulse

int distance; // the distance in cms
unsigned long previousMicros = 0; // will sotre last time TRIGGER was updated
long OnTime = 10; //microseconds of on-time
long OffTime = 2; //microseconds of off-time
unsigned long previousMillis = 0; //will store last time viewTime was updated
int triggerState = LOW; // triggerState used to set it up
long duration;
void setup()
{
  Serial.begin(9600);
  pinMode(ECHO, INPUT);
  pinMode(TRIGGER, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the TRIGGER
  unsigned long currentMicros = micros();
  if((triggerState == LOW) && (currentMicros - previousMicros >= OffTime))
   {
     triggerState = HIGH; // turn it on
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }
   else if((triggerState == HIGH) && (currentMicros - previousMicros >= OnTime))
   {
     triggerState = LOW; // turn it off
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }

duration = pulseIn(ECHO,HIGH  );
Serial.println(distance);
distance = ((duration*0.034)/2);
Serial.print("distance: ");

}

this will run your code without delay but the problem is you will get a zero every time resulting from pulseIn() which from there on I dont know how to fix it yet

unsigned long currentMillis = micros();
digitalWrite(Trig, LOW);

if (currentMillis - previousMillis > 4) {
  digitalWrite(Trig, HIGH);
  previousMillis = currentMillis;
}

if (currentMillis - previousMillis > 12) {
  digitalWrite(Trig, LOW);
  previousMillis = currentMillis;
}

impulseTime = pulseIn(Echo, HIGH);
distance_sm = impulseTime / 58; // convert to centimeters
distance = distance_sm;


text:
Make action happen after time is passed using interrupts
I am trying to create a code which prints to the LCD a message once a certain time is passed.
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, INPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  lcd.setCursor(0, 1);
  char time_out[16];
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    digitalWrite(2, HIGH);
  }
}

void blink() {
  lcd.print("time passed");
}

The setup uses the Time lib to set a date. It also  sets pin 2 as an INPUT and sets it it LOW. The attachInterrupt checks if pin 2 (0), changes, then function blink should execute.
In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of pin 2 to HIGH.
This should indicate a change in its state and should and trigger blink, but it does not. Can anyone spot the mistake I made? Thanks in advance.

Check what actually happens if you write to a pin that is defined as input. This does not work as you are assuming.

Which board are you using ?

Since I don't have enough reputations to comment on your question I am going to drop my two cents here.
Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the attachInterrupt function. I am going to suppose that there is no need to use timers' interrupts as well.
Have a look at the following code:
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);
}

void loop() {
  char time_out[16];
  lcd.setCursor(0, 1);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    blink();
  }
}

void blink() {
  lcd.print("time passed");
}

You should know the following:
Commands inside void loop() is going to be executed for ever again and again. Especially lcd.print(time_out);. You had better refresh the LCD every 1 second.
After 6 seconds blink() is going to be executed many times (maybe forever) since it is inside the loop and if(totalSeconds > 7806) is going to be always true.
If you have any question let me know in the comment section.

To do what you want, pin 2 would need to be an output.  As an input you have no control over its state when you write it low.  It may be hanging there floating in a high state and when you write high to it and turn on the pullup that may or may not actually be a change of state.
Doing a print to the LCD may not work in an ISR.  Remember that during the ISR all other interrupts are disabled and depending on how your lcd library works it may not print anything from inside the ISR.
Even if it does print "time passed" upon being triggered by the line at the end of loop, a few microseconds later loop would repeat and that would be overwritten by the stuff that loop writes to the screen.  So even if it did work you'd never know.

Instead of having your ISR print something to the screen, have it turn on an led or something so you know it actually triggered.
Try this instead and see if it is closer to what you want: (uncompiled and untested as I don't have the libraries)
#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

boolean passed = false;

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10, 00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, OUTPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  if (passed) {
    lcd.setCursor(0, 1);
    lcd.print("time passed");
    while(1);  // freeze here time is up
  }
  else {
    lcd.setCursor(0, 1);
    char time_out[16];
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second()); //use %x to get hex
    lcd.print(time_out);

    int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
    lcd.print(totalSeconds);
    if (totalSeconds > 7806) {
      digitalWrite(2, HIGH);
    }
  }
}

void blink() {
  passed = true;
}


text:
Play sound with speaker inside interrupt while a timer runs
I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.
This is what I have so far:
void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
}

int makeSound() { // This function creates the sounds
  ...
}

int echo() { // This function gets the distance the sensor is measuring
  ...
}

void loop() {
  distanceCm = echo();
  if (distanceCm < 25) {
    Timer();
  }
}

int Timer() {
  half_hour_millis = millis();

  while (millis() < half_hour_millis + interval) {
    // Here goes the code that I haven't written and was hoping you could help me with
  }
}

// My interrupt function
void sensor() {
}

All the level changing on the interrupt pin is complete before the timer loop is started, so you can't interrupt the loop.  Sounds like thinking of your problem as three states: idle, armed, and triggered would be good.  Given the way you are polling distance measurement, I'm not sure that you need to use the interrupt if you get the transitions between those states right.

Indeed I don't, but I'm trying to get to know interrupts.

Andrew,
I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:
boolean timerRunning = false;
unsigned long start_millis;
unsigned long end_millis;

boolean tripped() //was int Start()
{
  dist = echo1();
  if (dist < 25 && dist > 0) {
    return true;
  else
    return false;
}

void loop()
{
  if(tripped())  //check for < 25cm
  {
    //if tripped and timer not running, start
    //keeping track of time
    if(!timerRunning)
    {
      timerRunning = true;
      start_millis = millis();
      end_millis = start_millis + half_hour;
    }
    //if timer already running, print millis
    else
    {
      Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                    // for time since timer started
    }
  }
  else  //not < 25cm, not tripped
  {
    //if not tripped and timer running, time for sound
    if(timerRunning)
    {
      timerRunning = false; //might as well stop timer
      alert();
    }
    //if timer not started and not tripped nothing to do
  }

  //finally, lets check time, if past half hour, stop tracking
  //elapsed time
  if(timerRunning)
  {
    if(millis > end_millis)
    {
      timerRunning = false;
    }
  }
}//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).
I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.
Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.
Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.
Hope this helps and good luck!

Exactly what I needed! and thanks for the lesson heh. Oh, and I'm aware of the limit of millis(), and 50 days will be more than enough, so no problem :)

I'm aware of the limit of millis(), and 50 days ... the 50 day "limit" is only a problem if programmed poorly. Otherwise, not an issue.

To avoid the rollover problem, just code the comparison correctly instead of incorrectly.  That is, delete end_millis = start_millis + half_hour; and replace if(millis > end_millis) [sic] with if(millis()-start_millis > half_hour) because that arithmetic works ok (assuming half_hour < 2³¹)


text:
exit status 1 expected primary-expression before 'int'
int temp=A0;
#include<stdlib.h>
#include <SoftwareSerial.h>

#define SSID "rab"
#define PASSWORD "rakesh1234"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=B8B8E4FC1K541QZQ&field1=";
SoftwareSerial monitor(0, 1); // RX, TX
SoftwareSerial mySerial(5, 6); // RX, TX
int p1=0,p2=0,p3=0;
int i=0;
int j=0;

void setup() {
  pinMode(A0,INPUT);
  Serial.begin(115200);
  monitor.begin(115200);
  mySerial.begin(9600);
  sendDebug("AT");
  delay(2000);
  if(Serial.find("OK")) {
    monitor.println("RECEIVED: OK");
    Serial.println("RECEIVED: OK");
  }
  connectWiFi();
}

unsigned char buf[50];

void loop() {
   while(!mySerial.available());
   if(mySerial.read() == '#') {
     for(int i=0;i<12;i++) {
       while(!mySerial.available());
       buf[i] = mySerial.read();
     }
     buf[3] =0;
     buf[7]=0;
     buf[11]=0;
     p1 = atoi((const char *)&buf[0]);
     p2 = atoi((const char *)&buf[4]);
     p3 = atoi((const char *)&buf[8]);
     delay(1000);
   }

   long int SensorValue=analogRead(temp);
   SensorValue=SensorValue*5000;
   SensorValue=SensorValue/1024;
   SensorValue=SensorValue/10;
   SensorValue=SensorValue*9;
   SensorValue=SensorValue/5;
   SensorValue=SensorValue+32;
   String tempF=String(p1);
   String tempFF=String(p2);
   String tempFFF=String(p3);
   String tempFFFF=String(SensorValue);

   for(int j=0;j>-1;j++) {
     **j= Serial.read(int p1, int p2, int p3);**
   }
   while(Serial.available()==j)
     updateTemp(tempF,tempFF,tempFFF,tempFFFF);
   while(1) {}
 }

 void updateTemp(String tempF1 ,String tempF2, String tempF3,  String tempF4) {
   String cmd = "AT+CIPSTART=\"TCP\",\"";
   cmd += "api.thingspeak.com";
   cmd += "\",80";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("Error")) {
     monitor.print("RECEIVED: Error");
     Serial.print("RECEIVED: ERROR");
     return;
   }
   cmd = GET;
   cmd += tempF1;
   cmd += "&field2=";
   cmd += tempF2;
   cmd +="&field3=";
   cmd +=tempF3;
   cmd +="&field4=";
   cmd +=tempF4;
   cmd += "\r\n";
   Serial.print("AT+CIPSEND=");
   Serial.println(cmd.length());
   if(Serial.find(">")) {
     monitor.print(">");
     monitor.print(cmd);
     Serial.print(cmd);
   } else {
     sendDebug("AT+CIPCLOSE");
   }
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
   } else {
     monitor.println("RECEIVED: Error");
   }
 }

 void sendDebug(String cmd) {
   monitor.print("SEND: ");
   monitor.println(cmd);
   Serial.println(cmd);
 }

 boolean connectWiFi() {
   Serial.println("AT+CWMODE=1");
   delay(2000);
   String cmd="AT+CWJAP=\"";
   cmd+=SSID;
   cmd+="\",\"";
   cmd+=PASSWORD;
   cmd+="\"";
   sendDebug(cmd);
   delay(1000);
   if(Serial.find("OK")) {
     monitor.println("RECEIVED: OK");
     return true;
   } else {
     monitor.println("RECEIVED: Error");
     return false;
   }
 }

This is my code. I am getting an error as "exit status 1
expected primary-expression before 'int'"
Please help me.
Thank you.

Please reformat your code properly so we can read it. Also, what line number does the error happen at?

You are doing Serial.read() wrong with:
Serial.read(int p1, int p2, int p3);

Serial.read() takes no parameters per https://www.arduino.cc/en/Serial/read
Maybe you want to try parseInt() instead?

Your problem is that your are using asterisks ("*")
   for(int j=0;j>-1;j++) {
     **j= Serial.read(int p1, int p2, int p3);**
   }

The asterisk in C/C++ is the pointer operator. You use to get the value pointed by a pointer.
The expression **j means that j is a pointer to a pointer that points something. That's is meaningless here.
Then, the last ** is readed as another pointer to a pointer, and the compiler is expecting a variable or expression that give the value for the pointer, but found "}", which is an error.
You probably tried to comment out that line of code after the compiler barks at the Serial.read(), which, as Dave X pointed out, is illegal, because Serial.read() takes no arguments.
And, the syntax function(int x) is only use for declaring a function, not for calling one.


text:
What are the problems with using an Arduino in a production environment?
I am thinking about making a real project using arduino to earn money.
What could be the objective reasons (from both a technical and a business perspective) to not use an Arduino in a real profitable project?

There's pro products using OEM arduinos; 3d printers, custom home automation installs, cosplay accessories, and quadcopter controls come to mind. If your product's markup can eat the higher labor and parts cost compared to a lower-level setup, or you need fewer than 100 of something, It can be a viable option no doubt.

We've had a complaint that this question should not have been put on hold because it is a useful question. I'm inclined to agree with that, however questions about "is it a good idea" are indeed likely to be opinion-based. If enough people vote to re-open the question then it will be re-opened by the system. You may want to re-word along the lines of "what are the problems with using an Arduino in a production environment?" and omit things like "is it a good idea?". One issue I can see is that the pushing in of connectors into the Arduino "pins" could be problematic if there is vibration.

Even better would be to describe the particular project you're thinking of and the particular Arduino board you're thinking of using in it and ask "what would be the problems with this project if used with this board."

I suggested an edit that would make the question more objective. I think this is a useful question, even in general. Many people say in general that Arduino is for proto-typing, not for production. We can collect the reasons in one Q&A-page.

My 2 cents... I did VTC but also upvoted the answers by Majenko and dannyf. The OP doesn't specify whether he's planning to use an Arduino in a mass produced product or using it in a one-off project. Both cases are commercial projects but the implications are quite different. Also, what might be worth knowing (and objective too) could be the actual problems encountered by someone who actually used Arduino in a commercial project or, alternatively, the reasons why someone who considered Arduino for a commercial project ended up ruling it out.

I want to know if there is anyone that has used Arduino boards in a real project?

I have seen it being done, quite a few times.

What are the problems that you have faced?

Pros:

quick to market;
low cost accessories;
large code base to drop from;
...

Cons:

only workable for certain applications -> high cost per mcu (vs. bare chips), no possibility of passing certification of any rigor, no respect from others / clients, ...
quite inflexible an eco-system: porting code to / from others can be problematic.
poor project management capabilities.
...

Each of those pros / cons can be addressed and may not be relevant for your particular application.

Add big or bulky boards and high power requirements to list of cons.  Also assembly time can be a problem (lots of through-hole pins to solder, to connect eg a Nano or Micro to a project's PCB)

As a rule, no it's not a great idea.
Arduino boards are a prototyping platform. They are designed to make trying ideas out easy, not for permanent installation in a device. That's not to say you can't permanently install it in something of your own making, but when it comes to making a professional product it's not good, for a number of reasons:

An Arduino board is expensive compared to a plain MCU.
It's not a professional image.
It's not (typically) rugged and reliable enough.
Manufacturing something around a board like an Arduino is expensive.

The most professional way of using an Arduino would be to use something like an Arduino Mini and directly mount it on a custom PCB. But since you are making a custom PCB anyway, why would you incur the extra expense of an Arduino board when it is far cheaper to just build the required components directly into your board design? Also, when bulk manufacturing, you need to have as much of the build automated (i.e., surface mount to be populated by a pick-and-place machine) in order to keep costs down, and having to manually mount an Arduino onto a board adds extra expense (you have to pay a person to do the job themselves).

No, you don't want to manufacture a commercial device with the ATMega328P. If it had to be a '328 then it wants to be the ATMega328-MU or at a pinch the ATMega328-AU. Through hole is very expensive to manufacture.

That is pretty much what the entirety of my post is saying. Don't use a dev board, design the required components into your own circuit.

i just think mentioning a specific google-able term like the uno-acting atmega328 allows more follow-up

I am not about to recommend a specific chip to use, and certainly I wouldn't recommend an ATMega.

The ATmega328P is available as a surface-mount chip.

@EdgarBonet No it isn't. The ATMega328-PU is a SPDIP. The -MU is a QFN, and the -AU is a TQFP. The letters are important.

Yes, it is. C.f. the datasheet. Every ATMega328P-XX, where “XX” is anything but “PU”, is surface-mount.

@EdgarBonet Oh, it seems I am looking at the wrong page. Yes, you are right, there is the 328-* and the 328P-* (idiotic Atmel and their crappy naming scheme). They even have the 328PB-* now.


text:
How to pull a pin low?
On the instructions for this motor driver, it says that motors can be put to sleep by "pulling a pin low".

SLP - Logic Input. When pulled LOW, outputs are disabled and power consumption is minimized.

I'm guess this means connect to ground? How could I trigger that via my Arduino board?

Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".
It helps if you understand how an IO port works. This may help you.

Thanks – I get that this makes the Arduino pin go low, but will it also "pull" the pin on the driver to ground?

Yes, that is what going LOW is. Did you read the tutorial I linked to?

Sometimes it also is needed to put a resistor from the pin to ground to pull it low, or put a resistor to +5V to pull it high. This happens in cases where a pin needs to be set before the sketch can set a pin to low or high.


text:
Multiple connections on the same pin
I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?
Arduino <> TGAM
Arduino RX (0) <> TGAM T (TX)
Arduino TX (1) <> TGAM R (RX)
Arduino 3.3V <> TGAM + (VCC)
Arduino GND <> TGAM - (GND)
Arduino <> HC-06
3.3v    <> VCC
GND     <> GND
TXD     <> RXD
RXD     <> TXD

if the tgam only uses RX and the BT only TX, that can work;

No, you cannot use one pin (or set of pins) for two functions like that.
To communicate with two serial devices you will need two serial ports. It's possible to (just about) emulate one in software using the SoftwareSerial library. It's not wonderful though - personally I would use a chip that has multiple UARTs in it.

Thank you for the answer. But what about the GND and 3.3v pins. Can I emulate those too?

No. They aren't IO pins, they are just voltage levels. Wire as many things to those as you like. The fact you are having to ask these questions shows you lack the fundamental knowledge to be working with electronics. You are trying to  run before you have even been born.

Would agree and would appreciate if you share with me a nice source for learning the fundamentals. And remember everyone has to go through the stage of being born.

For those who might need it in the future: https://www.arduino.cc/en/Tutorial/TwoPortReceive

http://www.explainthatstuff.com/electricity.html


text:
Arduino EEPROM retains old data after flashing with a new program
I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the eeprom_clear program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.
I did some digging and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?

I'm pretty sure Arduino IDE isn't uploading eeprom at all. And for example in Platform IO CLI, there is different command to upload eeprom data instead of flashing program memory.

The IDE isn't. The program is setting values in the EEPROM. I simply want to clear the EEPROM everytime a new program is uploaded.

Also posted at http://forum.arduino.cc/index.php?topic=469061

save the old built date to eeprom and on boot, if it's different than the current build, run your clear routine

Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.
It's controlled by the -U... flag to avrdude:
avrdude ... -Uflash:w:<hex file>

If you want to set the EEPROM to something specific you can use avrdude to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):
avrdude ... -Ueeprom:w:<hex file>

I do not want to program the EEPROM. I simply want to clear its contents whenever I re-flash the Uno with a new program. When you burn the Arduino bootloader this bit remains unchanged and hence whenever the IDE runs avrdude with an -e parameter it erases the flash and the eeprom. Am I right? If so, this does not seem to be the case with my Uno and I'm hoping to understand why.

It's all to do with what the bootloader is capable of. You're not programming the board, you're uploading firmware for the board to program itself - it's a very different scenario.

You could add a "reset to factory settings" button - if it's held in while the power is turned on (or the board reset, or programmed, etc) it wipes the EEPROM.

The -e parameter in avrdude should only erase the EEPROM if the fuse bit
Preserve EEPROM memory through the Chip Erase cycle; [EESAVE=0]
is not set. However it appears it is not possible to SET this fuse bit. (at least not with AVRDUDESS.


text:
Port is not available
I'm trying to connect my Arduino Galileo to Linux via Arduino IDE. Sometimes I'm able to do so, but other times I ge the following error 'Board at /dev/ttyACM0 is not available'. With dmesg I can see that the device is not recognized, a deeper look at this issue led me to find out that a ls on /dev/ttyACM0 shows this:
-rw-r--r-- 1 root root      296 Apr  8 20:14 /dev/ttyACM0

Here I notice that there's a missing 'c' before the permissions that is common to every other /dev/tty*. I would like to know the reason why and if this is the cause for my problem. This seems to be suspicious..or maybe I'm mistaken...please correct me if I'm wrong.

If "c" is missing then it's a regular file. Probably something tried to open it with the O_CREAT flag without the device being there, and that created the file. You may get some clue as to what it was if you cat the file.

@Majenko is there a way to 'revert' it?!

Delete the file, then plug the board in.

Well...it worked! Not sure why, but this /dev/ttyACMO always end up to be a regular file, and I have no clue of what is responsible for it


text:
Arduino Uno with UsbSerial Android library w/ baud rate over 9600?
I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.
Has anyone had success with baud rate over 9600 when talking to Android?
I am using the felHR85/UsbSerial library.

I have no enough reputations to make a comment so I will drop my two cents here.
Are you changing the baudrate at both sides?
I have been using the arduino's built-in UART library for a while using different baudrates with no problems. Your problem could be an issue related to the library you are using.

Yes sir, I set the same speed on both sides. On Arduino I use the default Serial library too. The issue probably lies on the Android side.

Seems like there is a bug in the library.


text:
Arduino State Machine code flow
New to FSM, can someone explain how the flow works? If I use a case scenario in a loop, how is an external change detected and brought back to the loop?
Is all of the code/inputs, etc to be included within the case statements?
Still having a few problems. I have modified my code to include some of the suggestions. You can see that I added some print statements to allow me to monitor execution, but I can't get it to obey, such as print "trigger" when the PIR sensor is HIGH. Anyone available to explain my error(s)? I added a void check() just to bypass the keypad (not connected).
//////////////////////////// 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;
int switchPIN = 3; // alarm on test
char keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// 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, CHANGE); // PIR as interrupt
  // Could make use of the interrupts by checking in the interrupt if the state is "Ready" and
  // then setting the state to "Alarm".
  Serial.println ("System Ready");

  keypadPIN = HIGH;
}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  Ready, //system acknowledges trigger
  Unarmed, //system unarmed via keypad entry setting keypadPIN = LOW
  JustActivated, //PIR-triggered interrupt
  Alarm // confirm system unarmed then goto unarmed state else start alarm
};
STATE systemState = Unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
void trigger() {
  systemState = JustActivated;
}

//////////////////////////// State Machine //////////////////////////
void loop() {
  check ();
  switch (systemState) {Serial.println("switch");
    case Ready:
      if (PIR_SensorPin == HIGH) {Serial.println("PIR_Sensor");
        Serial.println("triggered");
        systemState = Alarm;
      } else if (keypadPIN == LOW) {
        systemState = Unarmed;
      }
      break;
    case Unarmed:
      if (keypadPIN == HIGH) {Serial.println("keypadPIN=HIGH");
        // Serial.println("Unarmed");
        timeGettingArmed = millis();Serial.println(timeGettingArmed);
         systemState = JustActivated;
      }
      break;
    case JustActivated:Serial.println("JustActivated");
      if (timeGettingArmed + waitTime < millis()) {
        Serial.println("Ready");
        systemState = Ready;
      }
      break;
    case Alarm:
      if (keypadPIN == LOW) {Serial.println("keypadPIN=LOW");
        systemState = Unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("8656171435", "*** 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);
    Serial.println (alarm_count);
  }
  systemState = Ready;
}

void check() {
  if (switchPIN == HIGH) {
    keypadPIN = LOW; // Unarmed
  }
  else {
    keypadPIN = HIGH; // Ready/Armed
  }
}

generally, you don't detect the change in that type of setup: you move one state to the next in a manner that that state behaves correctly after considering the context. for a button click/dblclick() library, i used: ready,1stDown,1stUp,2ndDown,stale states, which vary from the short,click,dblclick outputs. when in one state, check if you need to change to another state, and if not, do nothing. usually it's nothing.

Maybe I wasn't clear. Are the inputs signaling an event change to change a state located within or outside of the case statements?

one case, if needed, sets the state to another case or does nothing

A "state" is just a variable. Anywhere that variable has scope can change the state.

@Majenko: shared mutable state that gets changed in multiple places is the root of all evil, and the reason why redux/flux is so popular. I (and many others) HIGHLY recommend that you only change state in the switch to avoid spaghetti flow as the project grows. It's an adjustment for sure, but i loved it. ;)

@dandavis Not always possible. Especially when you're using interrupts.

@dandavis That "non-state flag" could be argued to be a state in its own right.

I moved the gist of my comments to an answer to allow me to explain these concepts in more detail.

Thanks dandavis. I would like to send you my project for your review.

MCU State Flow

State ( Model )
User/Machine Output ( View )
User/Machine Interruption ( Events )
State Changers ( Controller )
goto 1.

Breakdown of how it works:
#1. State. You start with a known finite state, which is the overall mode of operation for that piece or pieces. For a switch()-driven machine, it's a number, typically named by an integer constant for better readability.
#2. Output. Based on the state, you make certain things happen. These adjustments can be done in the switch(), or in the loop() as they notice state changes. You can also write explicit sub-routines to call from the switch() to keep code tidy. You can read the state from any point in the program, even interrupts if needed.
#3. Events/Interrupts. Lying in wait, these parts spring into action when something happens that the program needs to know. Both human-origin (ex: button press) and machine-origin (ex: SD card error) fall into this group. They can set flags and publish notifications to the controller that something has happened, but they MUST NOT set the state directly. The last point cannot be under-emphasized. If you start "cheating" and updating state outside of the controller, you  create another point of failure and another stop along the debug/enhancement tour.
#4. State Changing switch() (Controller).  This is where the actions meet the state. Only here should you change state to a new one, based on outside flags set by events. If your switch() is at the top of loop(), and you return in each case, you can call loop() from other points in the code to fire a state change immediately, but i like to name it in a void() and call it from loop(). The switch code should be lightweight and never use delay(). Lastly, most of the time a case does nothing, because no outside condition has changed that merits reaction, and it breaks or returns right there. When something important does change, the code below that early-exit conditional performs as a state change event handler.

Why bother
It can be a bit much at first, and seem like it's not worth the 5-10 mins up-front to name constants and write out all the switch bolierplate. I'm a lazy coder, and I still use this because it saves me a ton of time at every point in time besides those first 10 minutes.
Since things can only change in one place, you know exactly where to debug. It's simple to dump the outside values a case examines to the serial (remove before "launch"), rather than finding that chunk of code in the ether. Doing it all in one place makes it trivial to log when and what with each state change. With minor additional code you can even undo state changes, which can be a boon for users. Such actions are not risky because every part of the outside code knows what to do.
It breaks up tedious chains of semi-related action into independent pieces. You won't need lots of nested if()s if you follow the above guidelines. Even if you're not a long-time developer, simply following this pattern and slopping/pasting all the other code together, your program will be better in the end and faster and easier to build along the way.

Thanks. Looks like your idea is proving out well. Gave me another tool.


text:
Liquid Crystal LCD Display Prints f in all rows and columns
The problem is that the Liquid Crystal LCD display only prints "f" on every row and every column.
When I tell it to print something, then the display prints "f" on every square(row, column) for a brief second, then each square shows three white bars stacked up parallel to each other (quite like an "=" sign except that there's one more bar on top").
I am also using a tmrpcm library, so I'm guessing that interrupts might have to do with this, but I have no idea how to solve the problem.
The link to the tmrpcm library is as follows: https://github.com/TMRh20/TMRpcm
Thank you so much. I need to get this done by tomorrow 8 A.M., so I'm pretty desperate.
#include <LiquidCrystal.h>
#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

volatile int pauseOnOff;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  else{
    Serial.println("success!");
  }

  tmrpcm.play("Closer.wav");

  lcd.begin(16, 2);

  lcd.print("hello, world!");
}

void loop(){

}

If the problem is “something to do with interrupts” you will need to show some code for the problem to be diagnosed.  Please edit your question to include a Minimal, Complete, and Verifiable example of code.   On the other hand, it may be a wiring problem.  In that case, edit your question to include a circuit diagram and parts list.

Thank you, but I can confirm that the wiring is not the problem by excluding the tmrpcm library and confirming that the display works correctly. Furthermore, I do not know how the tmrpcm library works...I've been studying for it for a few weeks but I still don't grasp how it works.

I don't know the source of the problem, but here are a few things that might help diagnose where the problem begins or what it is due to.
(a) To track execution progress, and detect which statement, if any, ruins LCD operation:  Create a routine to display current line number in code to LCD and Serial; make a macro ss to use for invoking that routine; invoke the macro before and after each line containing a tmrpcm action by calls like ss;.  See following example.
void shoLine(int line) {
  Serial.println(line);
  lcd.home ();     // Set cursor to 0,0
  lcd.print(line);
  lcd.print(' ');
  delay(200);  // /Delay long enough to see stuff appear
}
#define ss shoLine(__LINE__)

Note:  Move lcd.begin(16, 2); to be the first statement in setup() when using this method of debugging.
(b) If you find that the first few LCD calls are ok and then LCD output stops working, try turning off interrupts during LCD output.  That is, put a cli() or noInterrupts() call before an lcd.print(), and an sei() or interrupts() after it, and see if it then works.  If so, that might serve as a last-ditch workaround.  (I don't know whether LCD output routines use any interrupts; I doubt they do; but if they do, this method won't work.)
(c) If the LCD doesn't display correctly at all, even before the first tmrpcm action, it may be that the combination of tmrpcm with other code is using too much memory.  Carefully check the memory-usage reports when you compile your sketch.


text:
Slave SPI does not work
I am trying to use both an SRAM (23LC1024) and SD card reader on an SPI bus.
My connections (for SPI):

Arduino pin 11 (MOSI) -> SRAM pin 5 (SI/SIO0)
Arduino pin 12 (MISO) -> SRAM pin 2 (SO/SIO1)
Arduino pin 13 (SCK ) -> SRAM pin 6 (SCK)
Arduino pin 10        -> SRAM pin 1 (CS )

In this way, I can read data from the SRAM.
To connect the SD I connected:

SRAM pin 2 (SO/SIO1) -> SD MISO
SRAM pin 5 (SI/SIO0) -> SD MOSI
SRAM pin 6 (SCK    ) -> SD SCK
Arduino pin 9        -> SD CS

Currently the SD card works, but read-byte commands to the SRAM always gives the same (wrong) value.
If I remove the wire between SRAM pin 2 and SD MISO the SRAM gives correct values, but the SD card does not have a MISO connection and seems to always return the same data (but still functions).
I also tried to first make the connections from the Arduino to the SD and than to the SRAM (but same result, not working).
What am I doing wrong?
Update: The problem is solved, however I do not understand why. I reconnected all pins, removed the shield to access the SRAM directly which worked. Than I put the shield back on (and moving the pins back) ... maybe it was something stupid that one pin did not have good contact. I'm sorry for the inconvenience.
New question (related):
Now it works with the Data logger shield, but not with the (cheap) SD reader breakout cards.
However, my eventual solution needs more proto space than is available on the Data logger shield.... do I really need to use a complete shield (and later the Arduino Mega), and a Mega proto shield ... that will be a big box.
While for the data logger, I don't need the RTC neither.

It doesn't sound like you are doing anything wrong as such, it all sounds fine.
However SD cards, certainly some cheap ones, don't like to play nicely with other devices on a shared bus. Also some SD card adapters with level shifting don't play nicely.
By not playing nicely I mean tri-stating the MISO line in a timely fashion (or at all in some cases) which stops any data getting out of other devices, and can even cause damage in some cases.
You should check out the level shifting on the SD card adapter to see if it has tri-stating control of MISO (if it is shifting that line, not all do), try other brands of SD cards, and maybe add your own tri-state buffer to the SD card signals.

It is for this reason I always use an SD card on a dedicated SPI bus rather than sharing it.

Mine is very cheap so maybe that is the reason.
I'm new to electronics, but how should I check the level shifting of the adapter if it has tri-stating? I don't have an oscilloscope ... I have one other SD card. Also I have an SD protoshield, but that one is so huge, I definitely do not want to use it in a prototype.

You say it may not play nicely on a shared SPI bus, but afaik the Arduino has only one SPI bus ... so how I can prevent it sharing while having two SPI devices?

Without a scope you can guess and try.  It is the harder way to do this.  For example, in your case we can disconnect the MOSI pin from the SRAM and see if we then can talk to the SDCard.  To verify we can replace the SRAM's MOSI pin and disconnect the MOSI from the SDCard and verify we can talk to the SRAM.

Arduino's now are made with many different processors.  Some have more hardware (more SPI buses) than others.  Also, there are now many Arduino libraries some which might emulate a SPI bus.  However, such libraries usually run slower than hardware and such libraries usually place a heavy burden on the processor not leaving much time to do other things.

I work almost exclusively with PIC32. Some have 4 or more SPI buses. You need the schematic of your SD adapter.

I tried a shield (datalogging sheet) and have approximately the same problem there ... SD card works, but SRAM gives always a value (different than with the breakout SD card reader).

@st2000: I tried this, the SD works OR the SRAM works, but not both at the same time

@Majenko I just got in the world of Arduino, so I don't know if I already want to step over at such a short period (I don't like quitting so easily). But I will check if the Mega has more SPI busses ... I have one in order and need to use it anyway to have more UARTs.

I tried to use 2 resistors to the MISO line (for the tristate behavior), but it does not work, so I use the SD data shield which works ok.


text:
Arduino motor driver 3.7v
I am planning to build my own micro quadcopter, so I bought an Arduino 101 and 3.7v micro DC motor.
So the next step is finding a motor driver that can control these four motors, using PWM pins on the Arduino board. I spent a lot of time searching for it, but all I found was a 5v motor driver and other types of Arduino shields that can't work in my project. Has anyone my requirement (name of motor drive, micro-controller, circuit)?
Thanks in advance.

Build your own H bridge with suitable MOSFETs?

Majenko do you have any pdf about the circuit and the element that i need , because i'm still a student so i know a little bit about electronic components .Thanks !

https://www.google.co.uk/search?q=h-bridge+mosfet&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi7sdaU55fTAhXIvBoKHRnQDcEQ_AUICCgB&biw=1120&bih=619

@Majenko He doesn't need a H bridge unless he wants to fly the quad upside down (would be cool to make your quad flip and stay flipped :D ). All he needs are some big logic-level N-channel mosfets. For the components you can easily find information on google about how to connect them, just search for "arduino mosfet motor control", but make sure your mosfets are logic level (it's a must, these motors can draw some amps and you don't want your fets to catch on fire because of them not being fully switched).

@AndreiDragan That is very true. Imagine the acrobatics you could do though :)