text:
How to use a rotary encoder on NodeMCU with Arduino code?
I have a standard 5 ping rotary encoder (3 pins for encoder, 2 pins for button).
I'm trying to get a working code that manages to read the rotary encoder.
I began with the code I found here: http://bildr.org/2012/08/rotary-encoder-arduino/
My problem is that the interrup method never being called.
I read that all the GPIO pins on NodeMCU support interrupts (except D16).
Here's my code:
volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

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

  pinMode(D0, INPUT);
  pinMode(D3, INPUT);

  digitalWrite(D0, HIGH); //turn pullup resistor on
  digitalWrite(D3, HIGH); //turn pullup resistor on

  attachInterrupt(D0, handleInterrupt, CHANGE);
  attachInterrupt(D3, handleInterrupt, CHANGE);
}

void handleInterrupt() {
  int MSB = digitalRead(D0); //MSB = most significant bit
  int LSB = digitalRead(D3); //LSB = least significant bit

  int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded; //store this value for next time
}

void loop() {
    Serial.print("Encoder: ");
    Serial.println(encoderValue);
    delay(1000);
}

My initial thought is that if this code is where the problem is then you would be better off in the Arudino SE. You  did not provide a schematic though- do you have pullup resistors on the A/B pins and is the common grounded?

Check that interrupts are working with some simpler code, eg. use void handleInterrupt() {    encoderValue ++; } instead of the more complex handler code. Then you will either know interrupts are happening, or their is a bug in the handler.

@SpehroPefhany I have the same wiring as in the blog article I linked. So I found that I need a debounce circuit to make this work flawlessly.

Different RotaryEncoders work in different ways. Mine connects the two outputs sequentially to the Gnd or + inputs, depending on the rotation direction. The resultant phase changes need to be detected and decoded by the processor.
I took your code and ran it on a LoLin NodeMCU using my 5-pin RotaryEncoder.
I connected (NodeMCU to RotaryEncoder):

D0 to Clk;
D3 to DT;
GND to GND; and
3V to +.

I ran the code, and it worked: the printed value went up when I rotated it in one direction, and down when it rotated in the other. The "bounce" was terrible though - getting just a single increment or decrement for one "detent" was difficult; I typically got 2-4.
Because of my encoder, I was able to remove the two digitalWrite(..., HIGH); lines and it continued to work. Perhaps that's what your problem is? Did you connect the + input? You mention the two switch pins: perhaps there's only one switch pin, that connects to the Gnd pin?

EDIT: The code!
So I went away and wrote a RotaryEncoder polling library, rather than the interrupt code that the original question was based on. The idea is that you can poll a rotary encoder (relatively) infrequently, and stil "catch" the transitions as it rotates. Of course this won't work if you poll it too slowly - your mileage may vary!
But here are three files:

The header and library source for the RotaryEncoder module; and
An example usage of the module.

RotaryEncoder.h:
//
// RotaryEncoder.h
//
// This library manages a Keyes KY-040 Rotary Encoder by sampling the
// appropriate pins when requested. It is NOT interrupt driven, so you'll need
// to sample often.
//
// The encoder has five pins in a 0.1" row, so you can directly plug it into
// an Arduino's data-pin sockets. The sequence of pins matches the order of
// parameters in the constructor - use ascending (or descending) numbers for
// ease.
//
// If you pass in NoPin for gnd, vcc, or sw (the switch), then that parameter
// is ignored. You'll need to organise those pins yourself! Of course, NoPin is
// not valid for dt or clk.
//

#ifndef RotaryEncoder_h
#define RotaryEncoder_h

class RotaryEncoder {

public: // Typedefs and enums

   typedef byte Pin;

   typedef signed char OptPin;

   enum Pins : OptPin {
      NoPin = -1
   }; // Pins

public: // Methods

   // Define which pins to use for the various functions.
   // If Optional Pins are "NoPin", then they won't be initialised
   RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk);

   // Start RotaryEncoder with optional maxBias (call Rebias() periodically)
   void Begin(byte maxBias=1);

   // Returns true if switch is currently pressed
   bool Switch() const;

   // Returns 0 for no change, +ve for clockwise, -ve for counter-clockwise
   int Get();

   // Call this periodically to reduce the bias
   void Rebias(int delta=1);

private: // Variables

   const OptPin gndPin;

   const OptPin vccPin;

   const OptPin swPin;

   const Pin dtPin;

   const Pin clkPin;

   byte maxBias;

   byte bias;

   bool clk;

   bool dt;

}; // RotaryEncoder

#endif // RotaryEncoder_h

RotaryEncoder.cpp:
//
// RotaryEncoder.cpp
//

#include <Arduino.h>
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(OptPin gnd, OptPin vcc, OptPin sw, Pin dt, Pin clk) :
               gndPin(gnd),
               vccPin(vcc),
               swPin(sw),
               dtPin(dt),
               clkPin(clk),
               maxBias(1),
               bias(1),
               clk(false),
               dt(false) {
} // RotaryEncoder::RotaryEncoder(gnd, vcc, sw, dt, clk)

void RotaryEncoder::Begin(byte maxBias) {
   this->maxBias = maxBias;
   if (gndPin!=NoPin) {
      pinMode(gndPin, OUTPUT); // Let's power the device,
      digitalWrite(gndPin, LOW);  // Power -ve with 0
   } // if
   if (vccPin!=NoPin) {
      pinMode(vccPin, OUTPUT); // ,with both - and +
      digitalWrite(vccPin, HIGH); // Power +ve with 1
   } // if
   if (swPin!=NoPin) {
      pinMode(swPin, INPUT_PULLUP); // They pushed it!
   } // if
   pinMode(dtPin,  INPUT); // One half
   pinMode(clkPin, INPUT); // The other half
} // RotaryEncoder::Begin(maxBias)

bool RotaryEncoder::Switch() const {
   return swPin!=NoPin ?
          digitalRead(swPin)==LOW :
          false;
} // RotaryEncoder::Switch()

int RotaryEncoder::Get() {
   bool clkNew = digitalRead(clkPin);
   if (clk!=clkNew) {
      clk = clkNew; // Clock's changed; sample data
      bool dtNew = digitalRead(dtPin);
      if (dt!=dtNew) {
         dt = dtNew; // Data's changed; remember it!
         if (clk) {  // Only pay attention to Clk Low-High
            int temp = bias;
            bias = maxBias;
            if (dt) {
               return -temp;
            } // if
            else {
               return +temp;
            } // else
         } // if
      } // if
   } // if
   return 0;
} // RotaryEncoder::Get()

void RotaryEncoder::Rebias(int delta) {
   if (bias<=1) {
       return;
   } // if
   bias -= bias>delta ? delta : bias-1;
} // RotaryEncoder::Rebias()

RotaryBlinker.ino:
//
// RotaryBlinker
//
// This example changes how fast the built-in LED blinks by using the
// RotaryEncoder library.
// It starts with an intermediate value (80h).
// * If you rotate it left, it slows down (then it jumps to the fastest).
// * If you rotate it right, it speeds up (then it jumps to the slowest).
// The jumps are because there is no logic to handle wrap-around - an exercise
// for the reader!
//
// Also note that a bias feature has been included. The faster you turn the knob, the
// exponentially quicker the rate changes. This is done by setting a fast rate on
// every detent, then when the millisecond has changed it re-biases the knob lower.
//
// To handle the knob correctly, it needs to INCREASE the time interval when
// dialling LOWER - hence you'll see a negative number in the code.
//
// It also checks for the switch. If it's pressed, it simply turns the LED full on.
//

#include <RotaryEncoder.h>

// Choose pins that are convenient for the RotaryEncoder's pins
#if defined(ESP8266)

const byte LED = D5;                   // No built-in LED! Choose... this one!
const unsigned baud = 115200;
const RotaryEncoder::OptPin GND = -1; // Use GND pin
const RotaryEncoder::OptPin VCC = -1; // Use V+ pin
const RotaryEncoder::OptPin SW  =  D4; // Switch
const RotaryEncoder::Pin    DT  =  D3; // Data
const RotaryEncoder::Pin    CLK =  D2; // Clock

#elif defined(ADifferentBoard) // Put the board's definition here

// And then change these assignments
const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#else // Arduino Uno default

const byte LED = LED_BUILTIN;
const unsigned baud = 57600;
const RotaryEncoder::OptPin GND =  8; // Need 0V
const RotaryEncoder::OptPin VCC =  9; // Need +V
const RotaryEncoder::OptPin SW  = 10; // Switch
const RotaryEncoder::Pin    DT  = 11; // Data
const RotaryEncoder::Pin    CLK = 12; // Clock

#endif // Boards

// Tell library which pin does what. Note Optional Pins can be -1
RotaryEncoder encoder(GND, VCC, SW, DT, CLK);

// Setup the board for these definitions
void setup() {
    Serial.begin(baud);
    pinMode(LED, OUTPUT); // Want to see it working

    encoder.Begin(10); // Start, with a re-bias of 10
} // setup()

bool ledON = false;  // Current LED state
byte repeat = 0x80;  // How quickly to restart, in ms
byte count = repeat; // Count down 'til next time!

unsigned last = 0;   // Last time millis() was recorded

void loop() {
    // Have switch override pulsing - turn it hard ON
    if (encoder.Switch()) { // Hard override!
        ledON = false; // Pretend LED is now OFF
        digitalWrite(LED, HIGH);
    } // if
    else {
        int value = encoder.Get(); // Returns positive for clockwise turn
        repeat += -value;   // We want to INCREASE time to slow down blinking
        if (value!=0) {     // Did it change?
            Serial.print(value);    // Print latest value
            Serial.print('=');
            Serial.println(repeat); // Print new result
        } // if
    } // else

    // Is it time to blink the LED again?
    unsigned latest = millis();
    if (last!=latest) {
        last = latest;
        encoder.Rebias();    // Re-bias encoder, to decelerate rotation
        if (--count==0) {    // Reached zero yet?
            ledON = !ledON;  // Yes! Toggle LED
            digitalWrite(LED, ledON ? HIGH : LOW);
            count = repeat;  // Count for next time
       } // if
    } // if
} // loop()

So I wired everything together again and now I have the same effect as you described. The bounce is really bad. So it seems the code is okay. The hardware needs more attention. Can you suggest a good debounce circuit?

Actually, the easiest way to debounce the device is to not interrogate it so often. Using interrupts on every single change is just asking for trouble... I don't know the rest of your code, but does it loop reasonably quickly? Rather than read the results of the interrupt, could you simply poll the device? A rotation, even a fast one, gives pulses in the order of 10s of milliseconds, so if you could poll the encoder as to its current status every 5-10 ms, you'd get debounce for free.

One more question though : the device I'm building is an IoT device. What if I'm rotating the encoder while I'm downloading/uploading something to the Internet? That takes hundreds of milliseconds. Not easy to create a code that loops quick enough. How would you accomplish that?

Agreed: that's the problem with switch bounce. You've got three options: remove the bounce in hardware (add capacitors - difficult for a Rotary Encoder); don't interrogate as often; or get each and every bounce, but ignore those that happen "too quickly". One technique is, on every switch, to get the current value of micros(). Compare that to the last saved value, and if too recent, simply ignore it. Otherwise, remember the new time as the last time, and process the change. The problem is that micros() may not update quickly enough...

Fix to make the code inc/dec on every step instead of every second step:

Comment out this line in cpp
if (clk) {  // Only pay attention to Clk Low-High

2.Change the next conditional to:
if (dt^clk)

did you try a different pin? (D2, D1) should work..
Seems like D0 does not have interrupt
https://opensprinkler.com/wp-content/uploads/2016/03/NODEmcuPinOut.png
also there is a rotary encoder library so try using that
..
The library i use is able to work without interrupts
Encoder by Paul Stoffregen available from Arduino Library Manager or
https://www.pjrc.com/teensy/td_libs_Encoder.html

Which library is that?

See the link above


text:
"Exit(0);" caused uninterruptible uninterruptible loop on 32u4 board
I bought this 32u4 board on Amazon (https://www.amazon.it/gp/product/B019SXN84E/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1) that should be recognised as an Arduino Leonardo by the Arduino IDE.
At first it totally worked as I was only trying to emulate keyboard and mouse USB input. I was searching for a code line that could stop the void loop(), so I tried using "exit(0);", as it was suggested in an other topic here. Now since that moment the board is stuck in a loop.
It continuously repeat the loop, while the red led is always on. I tried to upload a different code, but the IDE gives me alternatively two error messages:

"processing.app.debug.RunnerException
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:159)
at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
at processing.app.SketchController.upload(SketchController.java:707)
at processing.app.SketchController.exportApplet(SketchController.java:680)
at processing.app.Editor$DefaultExportHandler.run(Editor.java:2176)
at java.lang.Thread.run(Thread.java:745)
Caused by: processing.app.SerialException: Error touching serial port 'COM3'.
at processing.app.Serial.touchForCDCReset(Serial.java:87)
at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:143)
... 5 more
Caused by: jssc.SerialPortException: Port name - COM3; Method name - openPort(); Exception type - Port busy.
at jssc.SerialPort.openPort(SerialPort.java:164)
at processing.app.Serial.touchForCDCReset(Serial.java:81)
... 6 more";
"Forcing reset using 1200bps open/close on port COM3". (Even waiting for hours didn't solve the "forcing")

I already tried uninstalling drivers, uninstalling the IDE and changing COM port. Nothing worked. Unfortunately the reset button is missing on this board.
Is possible to restore the board or is totally lost?
Thanks in advance!

My question is different from the one there (What happens when I call exit() from my program?) because I used that code and I need to solve a loop problem, it's not just a theorical question. I'm also using a different type of board.

You could try manually resetting the board before an upload, by pressing the reset button.

SparkFun bootloader can be activated by pressing reset twice. So it's not waiting 8s in bootloader after every reset.

Possible duplicate of What happens when I call exit() from my program?

And if you have another Arduino, you can use it as an Arduino ISP programmer for burning Bootloader (this also cleans up sketch).

This isn't really a duplicate of what happens when calling exit() from an Uno, as the consequences are different.  On an Uno, entry into the bootloader is a hardware operation, but on a 32u4 based board it is typically a software one.  Apparently calling exit() breaks the latter.  It cannot break the former.

Majenko's answer is probably the solution. Thanks to everyone for the help ^^

exit(0) basically shuts the board down. That includes the USB connection, which is managed by software. All functions stop - interrupts are disabled, etc.
You need to do a manual reset of the board when it's time to program. For that you need a reset button. If there isn't one on the board then just connect one between the RESET and GND pins.  Press it just before programming (LED should glow for something like 8 seconds) and upload your new sketch.
exit(0) is only safe to use on boards with a UART interface (such as the Uno). Other boards you should use while(1); or for(;;);

Thanks for the answer. I didn't know about that.
I will try to reset the board manually in that way.

source: Stack Exchange

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

sort: votes


text:
amblone error :85: error: 'TCCR3B' was not declared in this scope - no fullscreen vlc support
getting the following error when trying to upload Amblone code to my Arduino One board:
Arduino: 1.6.12 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Users\pha\Desktop\amblone\amblone.pde: In function 'void setup()':

amblone:85: error: 'TCCR3B' was not declared in this scope

   TCCR3B = TCCR0B & 0b11111000 | 0x2;

   ^

amblone:86: error: 'TCCR4B' was not declared in this scope

   TCCR4B = TCCR0B & 0b11111000 | 0x2;

   ^

exit status 1
'TCCR3B' was not declared in this scope

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe1
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Code:
void setup()   {
  // initialize the serial communication
  Serial.begin(256000); // opens serial port, sets data rate to 256000 bps

  TCCR0B = TCCR0B & 0b11111000 | 0x2;
  TCCR1B = TCCR0B & 0b11111000 | 0x2;
  TCCR2B = TCCR0B & 0b11111000 | 0x2;
  TCCR3B = TCCR0B & 0b11111000 | 0x2;
  TCCR4B = TCCR0B & 0b11111000 | 0x2;

  State = S_WAIT_FOR_SF;
}

The full code please.

Amblone doesn't work on an Uno. As stated in the requirements list, you require a Mega.

Thanks to @Majenko, I realised I was uploading code to wrong arduino board as mine was Mega not Uno.
I was also not getting colour changes (Amblone) when playing a file on VLC player full screen - downgraded version and it works again now.

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


text:
Unable to connect esp8266 12 module with arduino uno
Here is what I am doing
Arduino(UNO)--------Esp8266
3.3 v -- vcc
TX      -- RX
RX      -- TX
3.3 v  -- EN(ch_pd)
GND     -- GND

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND?
What's the difference between the blinking and a still LED on Esp8266?
I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.

http://arduino.stackexchange.com/q/16917/972

The UNO runs on 5V and the ESP on 3.3V. When you send data to the ESP, you're sending it over 5V. When the ESP sends data to the UNO, it uses 3.3V. So, these voltages don't match. I suggest using a logic level converter to change the voltages of communication between the UNO and the ESP.

When you are using Arduino board just as USB --> RS232 converter to send AT commands from PC to ESP8266 you have to connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.


text:
Male header pins on Arduino Uno
On my board, there are 12 (2 groups of 6, each group consistent of 3 rows of 2 pins) weird male header pins. What are these, and how would you use them?

These are the In System Programming (ISP) pins. They are used to program the microcontroller without using the bootloader.
The bootloader is a program already loaded into the flash of the microcontroller that allows the program to be loaded into the microcontroller through the Tx & Rx serial lines and hence not requiring a programming device.
Using the ISP can be useful when:

The bootloader program doesn't exist in the microcontroller such as on a new chip.
The bootloader is corrupted.
Your program is just that little bit too big and you wish to gain the couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

The standard connection for the ISP is a 100 mil 6-pin header (2x3).

There are two ISP headers on the Arduino Uno because there are actually 2 microcontrollers on the board. There is the main microcontroller (aka the ATmega328P) which is used to execute the program you load into the Arduino board. The second microcontroller (ATmega16U2 or ATmega8U2) is used as a USB interface - converting the USB signals into serial data that is connected to the ATmega328P's UART (ie. Tx & Rx).

The following document details the ISP and gives descriptions of the pins used on the ISP header and how to interface them with the microcontroller etc.:
[PDF] AVR: In-System Programming - Atmel

EDIT: As Majenko correctly points out, the 2x3 ISP header closest to the ATmega328P can also be used to connect sensors and controllers that communicate using the Serial Peripheral Interface (SPI).
More information on the Serial Peripheral Interface and the SPI Library can be found at: https://www.arduino.cc/en/Reference/SPI

The 2x3 by the 328P still needs a slave select or chip select supplied by another pin.

The one by the USB connector is ICSP for the USB interface chip. The other is ICSP for the main chip and doubles as the (now standard) SPI interface for shields.

https://www.arduino.cc/en/Reference/SPI

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


text:
Switching methods/functions with a button
I am trying to program a basic counter using 7segment display and a button.
What I am trying to achieve is the following:

Display 0 at the beginning.
When the button is pressed: Start Loop 0-9
Display 0 when the button is pressed the second time.

So basically the button should function as ON/OFF switch for the looping numbers function.
So far I have managed to change the mode from  displaying 0 to looping 0-9, but can't seem to get changing the mode back to displaying 0:
int buttonPin = 10; // Button connected to digital pin 10.
// variable for reading the pushbutton status
boolean buttonPressed = false;
int mode;

void setup() {
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);

    pinMode(1, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(13, OUTPUT);
}

void displayZero() {
    //while (buttonState == true){
    // Displays 0.
    digitalWrite(11,1);
    //button();
    delay(1000);
    //}
}

void displayCounter() {
    // Displays 0.
    digitalWrite(4,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 1.
    digitalWrite(2,1);
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(8,1);
    delay(1000);

    //Displays 2.
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(6,0);
    digitalWrite(4,0);
    digitalWrite(9,1);
    digitalWrite(3,1);
    digitalWrite(11,0);
    delay(1000);

    //Displays 3.
    digitalWrite(4,1);
    digitalWrite(9,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 4.
    digitalWrite(2,1);
    digitalWrite(8,1);
    digitalWrite(3,0);
    delay(1000);

    //Displays 5.
    digitalWrite(6,1);
    digitalWrite(2,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 6.
    digitalWrite(4,0);
    delay(1000);

    //Displays 7.
    digitalWrite(3,1);
    digitalWrite(4,1);
    digitalWrite(6,0);
    digitalWrite(8,1);
    digitalWrite(11,1);
    delay(1000);

    //Displays 8.
    digitalWrite(3,0);
    digitalWrite(4,0);
    digitalWrite(8,0);
    digitalWrite(11,0);
    delay(1000);

    //Displays 9.
    digitalWrite(4,1);
    //button();
    delay(1000);
}

void loop() {
    // Check button status.
    int buttonStatus = digitalRead(buttonPin);

    if (buttonStatus == HIGH)
    {
        // Checks if button is pressed and changes buttonPressed from false to true.
        buttonPressed = true;

        // While button is pressed.
        while(buttonPressed == true) {
            // Calls displayCounter method 10 times.
            for (int i=0; i<10; i++) {
                displayCounter();
                delay(30);
                buttonPressed == false;
            }
        }
    }
    else if (buttonStatus == LOW)
        displayZero();
}

You try to set pin 10 in INPUT then OUTPUT mode, hence it will not receive any input from your button. Also, based on your circuit, you may need to use INPUT_PULLUP instead of mere INPUT, otherwise you may have a dangling input signal.

In your loop() function, the statement buttonPressed == false; doesn't do anything; it is simply an expression that evaluates to 0 or false (because buttonPressed is equal to true). Your while() loop will never end which is why you can't stop the counter by pressing the button again.
You probably meant buttonPressed = false;, which is an assignment statement setting the value of buttonPressed.  But doing that within the while loop makes the loop contents iterate once which it would do anyway, so there is no need for the surrounding while statement. The for() statement will still be executed once, without the while (the loop contents will be iterated 10 times in that one execution).
So you can reduce your loop() function to:
void loop() {

// Check button status.
   int buttonStatus = digitalRead(buttonPin);

   if (buttonStatus == HIGH)
   {
      // Calls displayCounter method 10 times.
      for (int i=0; i<10; i++){
         displayCounter();
         delay(30);
      }
   }
   else
      displayZero();
}

which will check the button state on each call to loop() and either run the counter or zero it, once, depending on the state.
You'll need another refinement, that of debouncing the button. Push buttons (and some other kinds of switches don't have a clean 0 -> 1 (or vice versa) transition but take some amount of time during which their state appears to bounce between 0 and 1 before finally settling to the new state. Read Nick Gammon's excellent article about contact bounce to see why and what to do about it.

Not sure but this should work
const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

const int nums[10][7] = //declaring array
{
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,0,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,0,0,1,1}  //9
};

//=======================================================================

#define button 9 //defining button that is connected to pin 9

//=======================================================================

void setup() {
  for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
  {
    pinMode(i, OUTPUT);
  }

  pinMode(button, INPUT); //set button as an input
}

//=======================================================================

void loop() {
  while(digitalRead(button) == LOW) //wait until user click the button
  {
    number(0); //display 0 when waiting
  }

  bool state = false; // create a status varible

  for(int i=0; i<10 && state == false; i++) //run the numbers from 0-9
  {

    number(i); //display the number

    for(int j=0; j<100 && state == false; j++)
    {

      if(digitalRead(button) == HIGH) //if the button is clicked, then cancel the loop ans go back to displaying 0
      {
        state = true;
      }

      delay(10); //this delay while execute a 1000 times so there is actualy a 1sec delay

    }
  }
}

//=======================================================================

void number(int num) //num is the number to display
{
  for(int i=0; i<7; i++)
  {
    digitalWrite(segment[i], nums[num][i]);
  }
}

Good starting answer, however there are few problems - you are displaying the current number 1000 times. This is not needed and takes a lot of time too. The call to number(i) should be just before the 'j' loop. Also you don't need millisecond granularity so the 'j' loop could be 0 to 10 and the delay could be 100 ms (or slightly less to adjust for the execution time of the extra commands). The user will probably not notice the difference, but then the timing would be closer to 1 second.

done, still prefer to have the delay low for better input resolution. espacially if he clicks fast. 100 ms is a liitle too much. also tried to keep it simple and not use any ISRs

Only one more thing - since you are iterating 100 times the digitalRead will be called 100 times - this will introduce extra delay so the numbers are going to be displayed more than one second. This could probably be adjusted in real life by timing and decreasing the loop maximum from 100, or decreasing the delay(10) accordingly.

Thanks for the answer, howeverm I didn't get it to work with my breadboard coupling. The way I have set my wires and display is, instead of turning the LEDs ON, it turns all the other LEDs OFF to display a certain number.

Apart from apparent issues in the details, the approach of using a lookup table here is far more sound than what Daniel was trying to do.  However, it looks like Daniel has a common anode display (drive segment low to illuminate), while this assumes common cathode (drive segment high).  Therefore, Daniel either needs to swap the 1's and 0's in the table, or change the output line to use the opposite of the table contents, ie !nums[num][i]

Also the table really shouldn't be of type int as that is just wasteful (16 bits to store just 1 with meaning) when a char (8 bits) would suffice, and this is a target without a lot of memory.   Most real implementations would actually make it a bitmap, using 1 bit to per bit of meaning, but that is conceptually more complicated.


text:
Uploading Error: no programmer has been specified
Whenever I upload a code I get this error:
avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

I am able to upload from other PCs, but ever since I got the newest IDE, it stopped working. I even tried downgrading to 1.6.8, and still i get this error... Any help? Thanks,
Sean

Check what programmer you have selected in the IDE.

This issue occurs when using Arduino IDE 1.6.8 or older with Arduino AVR Boards 1.6.12 or 1.6.14. There are two solutions:

Upgrade your Arduino IDE to 1.6.9 or newer by downloading and
installing the appropriate file from
https://www.arduino.cc/en/Main/Software.
Downgrade your Arduino AVR Boards version to 1.6.11 or older(or 1.6.13) via
Tools > Board > Boards Manager...

I submitted a pull request to fix this backwards compatibility issue and it was merged by the Arduino developers so this issue will no longer occur with Arduino AVR Boards 1.6.15 and up. It explains the cause of the issue:
https://github.com/arduino/Arduino/pull/5427


text:
Arduino uno board not detected when connected via USB no matter what OS
I was working with Arduino in Win 8.1, when suddenly it stopped work. I tried to reinstall the drivers and IDE several times, but it didn't solved.
In Win 8.1, when I plug the arduino, I get the pop up message:
USB Device Not Recognized in Windows
Also, when I try to upload a sketch, I get this error in Arduino IDE:
avrdude: ser_open(): can't open device "\\.\com5": the system cannot find the file specified

I switched to Linux (Debian Jessie 64 bits), but it also doesn't get recognized, and I getting the same error, only the port Is different.
I am guessing is a problem with avr, but I don't know what can I do about it.
Other  symptoms:

In both systems the port tool in IDE is grey, so I can't choose a port.
When I press the reset button in Arduino, nothing happens.
The led L (13) is constantly shinning. It never blinks or stops.

Solutions I tried:

Reinstall drivers
Modify the preferences.txt file to change the COM port
Fall back to a previous IDE version
Change the usb cable

See Have I bricked my Arduino Uno? Problems with uploading to board

If the port selector in the IDE is greyed out, and the OS is throwing an error, it's likely the Board is damaged. Either The firmware on the serial device or the chip is fried somehow. What's happening is that the usb part is failing, so the Com port part never works.

By chip you mean the atmega?

The FTDI or USB Atmega in charge of the usb to serial. If it's atmega based, then it's possibly you tried to program that one and everything messed up at that point.

Yeah... It seems right.

Arduino is most probably aproaching the wrong com. You can set a new com. in the IDE of arduino under settings. Change it to the available com. It might be required to find out in Windows/ system configuration for the available coms  Maybe something there is wrong.

I am not sure, where I would set the new COM. The port tool is grey. Are you talking about this?

I can not help with the Windows details because I have a Dutch version Windows 8 operational


text:
Get an additional analog pin?
I have the following board:

As far as I can tell, there's only a single analog pin (A0). But I need at least 2 additional (for 3 total).
Is there some way to fake analog input on GPIO pins?

No. Get a SPI ADC.

What do you need to connect to the analog pins?  You can "bitbang" an ADC with some additional components, but it isn't trivial to do. Better go with an external ADC or use a different sensor that has a digital output instead of analog.

The ESP8266 only has one ADC pin. You can:

Use an analog MUX to switch that pin between different signals
Connect an external I2C ADC chip
Connect an external SPI ADC chip
Connect the ESP8266 to another MCU (such as an Arduino) and get that to do analog readings.


text:
Issue with photoresistor - the analogRead stays pretty much the same?
UPDATE: If I could I'd downvote myself. I'm a web developer and as I see that my job will be eaten, I'm trying to expand my skill set. Sometimes I wish I had a second pair of eyes or https://en.wikipedia.org/wiki/Rubber_duck_debugging

Previously I was asking which sensor use to measure the light: Which sensor to detect light?
Here is a short video showcasing my issue: https://www.youtube.com/watch?v=VGs_Ax_wlbg
Super simple .INO sketch from https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module
int sensorPin = A5; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  sensorValue = analogRead(sensorPin);
  digitalWrite(ledPin, HIGH);
  delay(sensorValue);
  digitalWrite(ledPin, LOW);
  delay(sensorValue);
  Serial.println(sensorValue, DEC);
}

I'm worried that my sensor readings are pretty much the same - in shade, brighten up by green laser...
Am I doing it right?
Are values from the sensor in the expected range?
Alternatively: is there any more sensitive sensor I should buy that will tell me more reliably if the there is green laser light pointing at it?

It helps if you plug the sensor into ANALOG 5, not into DIGITAL 5 ...

:) It helps... Thank you for being second pair of eyes and sanity check here!

Could you place a filter on the sensor to block out the non green light?
What are the values you are getting and what do you think they should be?

***** ITS ANALOG 5 not DIGITAL 5 *****
Also try doing this:
delay(sensorValue*10);

The times 10 will help show the differences between each value.

It looks like he is using an LDR breakout. Those probably already have a resistor.

True, my bad. There is a 10k k smd tinynynynyny resistor on it. No external resistor needed.

OMG! ANALOG... So silly, that's why I need second pair of eyes (and some common sense)...


text:
why does function affect my ISR?
I am currently running this piece of code:
main.ino
#include "speed_profile.h"

void setup() {
  // put your setup code here, to run once:
  output_pin_setup();
  cli();
  timer1_setup();
  sei();
}

void loop()
{
      //int motor_steps = 23400;//-9600; //23400 -  100%
      // Accelration to use.
      //int motor_acceleration = 500;//500;
      // Deceleration to use.
      //int motor_deceleration = 500;//500;
      // Speed to use.
      //int motor_speed = 1000; // 1000
      init_tipper_position();
      compute_speed_profile(23400, 500, 500, 1000);
}

Speed_profile.cpp
#include "speed_profile.h"

volatile speed_profile profile;

ros::NodeHandle_<ArduinoHardware, 1, 2, 125, 125> nh;
//ros::NodeHandle nh;

std_msgs::Int16 status_step_count;
std_msgs::Int16 status_tipper_availability;
ros::Publisher chatter_status("tipper_status", &status_step_count);
ros::Publisher chatter_availabilty("tipper_availability", &status_tipper_availability);

volatile bool global_state = false;
int received_data = 0;

void call_back_control( const std_msgs::Empty & msg)
{
  global_state = true;
  // For HMI
  received_data  = (100 *23400.0)/100.0; // Converts input to motor_steps.
}

ros::Subscriber<std_msgs::Empty> sub_control("tipper_control", &call_back_control );

void output_pin_setup()
{
  pinMode(en_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(slot_sensor_pin,INPUT_PULLUP);
  nh.initNode();
  nh.advertise(chatter_status);
  nh.advertise(chatter_availabilty);
  nh.subscribe(sub_control);
  //nh.subscribe(sub_command);
  profile.current_step_position = 0;
  delay(10);
  nh.getHardware()->setBaud(57600);
}

void init_tipper_position()
{
  //digitalWrite(en_pin, HIGH);
  //delay(1);

  //digitalWrite(dir_pin, LOW);
  //delay(1);

  while(!(PINB & (1 << 2)))
  {
    //PORTB ^= _BV(PB3);
    //delayMicroseconds(100);
  }

  //digitalWrite(en_pin, LOW);

}
void timer1_setup()
{
  // Tells what part of speed ramp we are in.
  profile.run_state = STOP;

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;  // reset the timer

  // Timer/Counter 1 in mode 4 CTC (Not running).
  TCCR1B = (1 << WGM12);

  // Timer/Counter 1 Output Compare A Match Interrupt enable.
  TIMSK1 = (1 << OCIE1A);
}

void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
{
  unsigned int steps_to_speed;  // Steps required to achieve the the speed desired
  unsigned int acceleration_step_limit; // If desired speed is not achieved, will this variable contain step_limit to when to stop accelerating.
  // If moving only 1 step.
  if (motor_steps == 1)
  {
    // Move one step
    profile.accel_count = -1;
    // in DECEL state.
    profile.run_state = DECEL;
    // Just a short delay so main() can act on 'running'.
    profile.first_step_delay = 1000;
    OCR1A = 10;
    // Run Timer/Counter 1 with prescaler = 8.
    TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));
  }
  else if (motor_steps != 0)
  {
    // Set max speed limit, by calc min_delay to use in timer.
    // min_delay = (alpha / tt)/ w
    profile.min_time_delay = A_T_x100 / motor_speed;

    // Set accelration by calc the first (c0) step delay .
    // first_step_delay = 1/tt * sqrt(2*alpha/accel)
    // first_step_delay = ( tfreq*0.676/100 )*100 * sqrt( (2*alpha*10000000000) / (accel*100) )/10000
    profile.first_step_delay = (T1_FREQ_148 * sqrt(A_SQ / motor_accel)) / 100;

    // Find out after how many steps does the speed hit the max speed limit.
    // steps_to_speed = speed^2 / (2*alpha*accel)
    steps_to_speed = (long)motor_speed * motor_speed / (long)(((long)A_x20000 * motor_accel) / 100);
    // If we hit max speed limit before 0,5 step it will round to 0.
    // But in practice we need to move atleast 1 step to get any speed at all.
    if (steps_to_speed == 0)
    {
      steps_to_speed = 1;
    }

    // Find out after how many steps we must start deceleration.
    // n1 = (n1+n2)decel / (accel + decel)
    acceleration_step_limit = ((long)motor_steps * motor_decel) / (motor_accel + motor_decel);
    // We must accelrate at least 1 step before we can start deceleration.
    if (acceleration_step_limit == 0)
    {
      acceleration_step_limit = 1;
    }

    // Use the limit we hit first to calc decel.
    if (acceleration_step_limit <= steps_to_speed)
    {
      profile.decel_length = -(motor_steps - acceleration_step_limit); //---
    }
    else
    {
      profile.decel_length = -((long)steps_to_speed * motor_accel) / motor_decel; //--
    }
    // We must decelrate at least 1 step to stop.
    if (profile.decel_length == 0)
    {
      profile.decel_length = -1;
    }

    // Find step to start decleration.
    profile.decel_start = motor_steps + profile.decel_length;

    // If the maximum speed is so low that we dont need to go via accelration state.
    if (profile.first_step_delay <= profile.min_time_delay)
    {
      profile.first_step_delay = profile.min_time_delay;
      profile.run_state = RUN;
    }
    else
    {
      profile.run_state = ACCEL;
    }

    // Reset counter.
    profile.accel_count = 0;
    //profile.step_counter = steps_to_speed;
  }
}

void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed)
{
  while (global_state == false)
  {
    //do nothing
    status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
    status_tipper_availability.data = 1;

    chatter_status.publish( &status_step_count);
    chatter_availabilty.publish(&status_tipper_availability);
    nh.spinOnce();
  }

  digitalWrite(en_pin, HIGH);
  delay(1);

  signed int move_steps;
  //if (motor_steps < 0)
  if(received_data > profile.current_step_position) // Compares whether received percentage (converted to motor_steps) is greater or smaller than current_step_position.
  {
    profile.dir = CCW;
    move_steps =  received_data - profile.current_step_position;
    digitalWrite(dir_pin, HIGH);
  }
  else
  {
    profile.dir = CW;
    move_steps =  profile.current_step_position - received_data;
    digitalWrite(dir_pin, LOW);
  }

  delay(1);
  // received_data = percentage converted to a step number received from tipper_control topic

  computation_of_speed_profile(move_steps, motor_accel, motor_decel, motor_speed); // function should be called with the correct motor_steps value

  OCR1A = 10;
  // Set Timer/Counter to divide clock by 8
  TCCR1B |= ((0 << CS12) | (1 << CS11) | (0 << CS10));

  while (global_state == true)
  {
    status_step_count.data = ((float)(profile.current_step_position / 23400.0)) * 100.0; //map(profile.current_step_position,0,23400,0,100); // could be expensive -- Nice flowing is only available with float
    status_tipper_availability.data = profile.run_state;

    chatter_availabilty.publish(&status_tipper_availability);
    chatter_status.publish( &status_step_count);
    nh.spinOnce();
  }
}

ISR(TIMER1_COMPA_vect)
{
  // Holds next delay period.
  unsigned int new_first_step_delay;

  // Remember the last step delay used when accelrating.
  static int last_accel_delay;

  // Counting steps when moving.
  static unsigned int step_count = 0;

  // Keep track of remainder from new_step-delay calculation to incrase accurancy
  static unsigned int rest = 0;
  OCR1A = profile.first_step_delay;
  switch (profile.run_state)
  {

    case STOP:
      step_count = 0;
      global_state = false;
      rest = 0;
      TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10)); // Stop the timer,  No clock source
      break;

    case ACCEL:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3);  // Toggles the step_pin
      step_count++;

      if (profile.dir == CCW)
      {
        profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }

      profile.accel_count++;
      new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
      rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);

      // Chech if we should start decelration.
      if (step_count >= profile.decel_start)
      {
        profile.accel_count = profile.decel_length;
        profile.run_state = DECEL;
      }

      // Chech if we hitted max speed.
      else if (new_first_step_delay <= profile.min_time_delay)
      {
        last_accel_delay = new_first_step_delay;
        new_first_step_delay = profile.min_time_delay;
        rest = 0;
        profile.run_state = RUN;
      }
      break;
    case RUN:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3); // Toggles the step_pin
      step_count++;

      if (profile.dir == CCW)
      {
        profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }
      new_first_step_delay = profile.min_time_delay;
      // Chech if we should start decelration.
      if (step_count >= profile.decel_start)
      {
        profile.accel_count = profile.decel_length;
        // Start decelration with same delay as accel ended with.
        new_first_step_delay = last_accel_delay;
        profile.run_state = DECEL;
      }
      break;
    case DECEL:
      //digitalWrite(step_pin, !digitalRead(step_pin));
      PORTB ^= _BV(PB3); // Toggles the step_pin
      step_count++;
      if (profile.dir == CCW)
      {
         profile.current_step_position++;
      }
      else
      {
        profile.current_step_position--;
      }
      profile.accel_count++;
      new_first_step_delay = profile.first_step_delay - (((2 * (long)profile.first_step_delay) + rest) / (4 * profile.accel_count + 1));
      rest = ((2 * (long)profile.first_step_delay) + rest) % (4 * profile.accel_count + 1);
      // Check if we at last step

      if (profile.accel_count >= 0)
      {
        digitalWrite(en_pin, !digitalRead(en_pin));
        //PORTB &= ~_BV(PB3);
        profile.run_state = STOP;
      }
      break;

  }

  profile.first_step_delay = new_first_step_delay;

}

And the Speed_profile.h
/*
 * Contains the class concerning with calculating the proper speed profile
 * for accelerating and decelerating the stepper motor.
 *
 */

#ifndef speed_profile_h
#define speed_profile_h

#include <Arduino.h>
#include <ros.h>
#include <std_msgs/Int16.h>
#include <std_msgs/Empty.h>

// Timer/Counter 1 running on 3,686MHz / 8 = 460,75kHz (2,17uS). (T1-FREQ 460750)
//#define T1_FREQ 460750
#define T1_FREQ 1382400

//! Number of (full)steps per round on stepper motor in use.
#define FSPR 1600

// Maths constants. To simplify maths when calculating in compute_speed_profile().
#define ALPHA (2*3.14159/FSPR)                    // 2*pi/spr
#define A_T_x100 ((long)(ALPHA*T1_FREQ*100))     // (ALPHA / T1_FREQ)*100
#define T1_FREQ_148 ((int)((T1_FREQ*0.676)/100)) // divided by 100 and scaled by 0.676
#define A_SQ (long)(ALPHA*2*10000000000)         // ALPHA*2*10000000000
#define A_x20000 (int)(ALPHA*20000)              // ALPHA*20000

// Speed ramp states
#define STOP  0
#define ACCEL 1
#define DECEL 2
#define RUN   3

// Pin numbering
#define en_pin 13
#define dir_pin 12
#define step_pin 11
#define slot_sensor_pin 10

// Motor direction
#define CW  0
#define CCW 1

typedef struct
{
  unsigned char run_state : 3; // Determining the state of the speed profile
  unsigned char dir: 1; // Determining the direction the motor has to move - Start being CCW
  unsigned int first_step_delay; // Period time for the next timer_delay, determines the acceleration rate.
  unsigned int decel_start; //  Determines at which step the deceleration should begin.
  signed int decel_length; // Set the deceleration length
  signed int min_time_delay; //minium time required time_delay for achieving the wanted speed.
  signed int accel_count; // counter used when computing step_delay for acceleration/decelleration.
  volatile signed int current_step_position; // contains the current step_position

}speed_profile;

void compute_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
void computation_of_speed_profile(signed int motor_steps, unsigned int motor_accel, unsigned int motor_decel, unsigned int motor_speed);
void init_tipper_position();
void timer1_setup(void);
void output_pin_setup(void);
#endif

The problems is with the ISR. The function init_tipper_position seem to be causing a timing problem that makes is impossible the ISR to go through all its states. I changed some parts of the code based on @EdgarBonet 's answer, which seem have helped a bit. The problem here is that the program stalls when the it reaches the state STOP. This is not a issue at all if the prior function is executed..?? why am I having this issue?

What does "the ISR stalls at its last state" mean? Which is the "last state" and how exactly does it "stall"?

@brhans It stalls  by the global state doesn't go further on from the state DECEL to STOP where the clock source for the timer1 is being removed, and thereby disables the occurrence of the ISR.

Could you please edit the question and remove all the duplicate stuff?

Rewrote the post, which now basically include the full code.

Can you please stop making multiple posts of what is basically the same issue? You have another question why is function being skipped? where you are speculating that init_tipper_position is being "skipped" or "ignored". The compiler just doesn't ignore functions in a whim. With thread after thread of yours (some now migrated from EE.SE) it is very hard to keep up with you. As soon as someone starts answering you throw all the same code into a new thread with a new idea about what the problem is.

You should try chatting with Carlton Banks - he seems to have exactly the same issues that you do.

Lamda / CB, Nick's comment about throwing in all the same code each time is worth heeding.  I find the code you've been posting awkward reading because of its formatting and presentation.  More people may look for the problem if it's less painful to read.  Perhaps ask on codereview.stackexchange for some advice on better formatting and presentation.

This isn't the sort of approach you should use in an ISR.  You need to get into the ISR, and get out of it ASAP.  Set a flag, and read the flag in your code to decide what needs to be done.  There should be very little in the way of decisions and branching in an ISR.  Most certainly, there should be zero floating point math in your ISR, especially on a platform that doesn't have a floating point processor (actually, my preference is to avoid floating point math wherever possible in an embedded system, but I might be a bit extreme.
Start from scratch, rebuilding your ISR to do only what needs to be done, and use main to do the rest of it (or "loop" or some such on an Arduino).
Having spent no real time on an Arduino, interrupts just don't seem all that convenient to use to me.  If the Arduino environment doesn't let you use interrupts the right way, you should consider programming the AVR wit AVR compilers.

The ISR could be changed i agree, It is basically an implementation taken from an Atmel application note.  and basically is only one of states performed for each ISR, meaning it might not be that critical. According to the application note  http://www.atmel.com/images/doc8017.pdf

will it spent 200µs in the Accel state and Decel state, and 35 µs in Run state, approx. measured. I've tried moving things outside the ISR and computed it there, but that often result in different values, or using non updated values even if I use volatile variables or static, which is why i choose to do it as such. the implementation can be found on github

you should consider programming the AVR wit AVR compilers - the Arduino IDE uses avr-g++ which is a perfectly fine tool. It also lets you generate your own interrupt routines if you want to.

I'm not very familiar with the details of the Arduino infrastructure either, but I think your fundamental problem is the fact that you are doing GPIO (i.e., digitalRead() and digitalWrite()) both in your ISR and in your main loop().
Since these functions manipulate global hardware and use various "shadow" variables to keep track of their state, it's very unlikely that they are "reentrant". A reentrant function is written without global/static variables (and a few other restrictions), such that one call to it can be interrupted and another call made to it without interfering with the first one.
The Arduino environment was never intended for projects in which issues such as reentrancy should arise; such projects should be using using a "real" RTOS or equivalent. Yes, you can shoehorn such project into the Arduino environment, but only if you already know exactly what you're doing.

The digitalRead and digitalWrite are performed in two different places. When init_tipper_position()  is called, is the ISR not activated yet, meaning the Timer1 has been setup to be in (CTC-mode), and a compare match interrupt is being enabled, but at no value has been given to OCR1A. Its only in the next function where it is being given a value.

There are no “shadow variables” in digitalRead() nor digitalWrite(), and digitalWrite() toggles the pin atomically (i.e. with interrupts disabled), precisely to avoid the kind of reentrancy problems you are afraid of.

What alternatives do i have for instead of using digitalRead and digitalWrite

@Lamda: Direct port access, but that won't help unless your problem is genuinely cause by digitalRead() or digitalWrite().

I have nothing else to go by. Everything works as it should be if I remove the while(digitalRead()..). I completely agrees that it does not make any sense that this should be the cause.  It could maybe a compiler optimisation? as I am currently running low on memory on the board?

@EdgarBonet: OK, I'll concede that point, provisionally. I was able to find the source code for wiring_digital, which does show that the actual port update is done inside a critical section. However, there is a lot of other stuff going on first that is not protected, such as program memory table lookups to determine pin parameters such as port number, bit mask and whether there's an associated PWM function. If there is a possibility of PWM, the timer register is twiddled unconditionally.

... I was not able to drill down into the details well enough to satisfy myself that there were no non-reentrant side-effects from all of this activity. I'll just have to take your word for it.

@EdgarBonet My bug was intermittent. After running some tests for a few hours, you may be correct about digitalRead being okay in an ISR so my previous comment was deleted.

I narrowed the search space to be inside the init_tipper_position

I see nothing wrong with this function, except that it takes some time
to execute, and makes compute_speed_profile() start later. So I am
guessing yours is a timing problem: your code may be sensitive to the
value held by the timer when compute_speed_profile() starts. It is
just a wild guess, as you did not show all your code, and the real
problem may be somewhere we cannot see.
Did you completely initialize Timer 1 before using it? I see no mention
of TCCR1A in the part you showed us. You should be aware that the
Arduino core library initializes this timer to provide 8-bit PWM. It is
likely that you will need to undo that initialization, e.g., at the very
beginning of your program:
TCCR1A = 0;  // undo the initialization done by...
TCCR1B = 0;  // ...the Arduino core library
TCNT1  = 0;  // reset the timer

This is the default state set by the hardware at boot, and the Atmel
application note you are using as a reference may well assume this state
has not been tampered with.
Also, I did not check your algorithm, but since your are stopping and
restarting the timer, it may make sense to also reset it (TCNT1 = 0;).

I am sure i understand why timer1_setup() starts later due to init_tipper_position is timer1_setup() not executed prior to init_tipper_position?

timer1_setup() is responsible for the initialisation of the timer.  But as you i don't touch TCCR1A as it by default is 0.  I stop and restart the timer, by removing the clock source, in the State STOP.
TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10));
And global_state becomes false, which makes the code loop in the while(global_state == false) until it becomes true, where it gets a clock source.

Which can be seen in the function compute_speed_profile

@Lamda: Sorry, I meant compute_speed_profile(). I edited the answer accordingly. It is an error not to set TCCR1A.

I might have been to fast to conclude whether it worked or not. I added TCCR1A in the timer1 setup, and the ISR stalls now in the state STOP...


text:
Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino
I am working on a project where I need to calculate distance traveled by a robot. The mouse is connected to the arduino uno processor and I received some sample code from the arduino website to get started.
The problem is that the mouse gives difference distances depending on how fast or slow the it moves. (The same way you can move your pc mouse from side to side, fast and slow, and watch it cover different distances across the screen). Is there anyway to get get around this mouse setting? If not,  is there a more accurate sensor that can be used to accomplish the task? I'm having a hard time finding one.
Here is a link to the datasheet: http://www.alldatasheet.com/datasheet-pdf/pdf/333273/PIXART/PAW3402.html

Mouse acceleration is part of the OS, not the mouse. Are you really having this problem, or are you just predicting this problem?

If you could point out in the specifications you linked to where the mouse has the feature / ability to tell how fast it is moving I would appreciate it.  And will change my answer to accommodate.

Assuming under normal conditions a relative pointing device such as a optical mouse always reports relative position changes with out regard to speed.  If true, then consider that the speed of the robot is faster than the mouse can process.  Also, consider that the mouse's optics is out of focus with respect to the surface it is supposedly taking its positioning cues from.  Lastly, consider the surface may not be ideal for an optical mouse.  Attempt the same experiment using a sheet of paper or a "not-shiny" wood surface.
All surfaces have to be flat.  For example, a ceramic tile floor will likely not work as the surface will come in and out of focus during travel.  Make sure the elevation of the robot with respect to the surface is constant.  Inspect the wheels to make sure they are perfectly round and rotating around their center point.
Check and make sure you are not suffering from a integer calculation or type size problem.  Examine your code and make sure you are handling all cases including the expected maximum and minimum values properly.  And that your variables are large enough to handle these expected values.

It seems that the speed of the robot is faster than the mouse can process

on page 9 of the data sheet, bytes 2 and 3 give the detail of how fast the mouse is moving in the X and Y directions

@Jay, agreed.  I knew this was going to be tricky to explain.  I believe your Question describes an artifact of the driver, not the mouse.  That is, using most drivers, if you move the mouse 1 inch slowly the driver will move the cursor a much shorter distance across the screen then if you moved the mouse the same distance quickly.  I suspect, if you sum up all the mouse reports for both actions, the total will be nearly identical.

What you can do is use a hall effect (magnetic) sensor. If you connect a small magnet yo your shaft and connect the sensor in a way that the magnet will pass the sensor at every rotation, you can count the number of rotation that the shaft doesn thus calculating the distance.
It's a simple math equation:
distance = rotation * circonference of the wheels
For circonference, here is the equation:
circonfernce = diameter * PI


text:
Is it possible to print client IP or MAC address from Arduino WiFi web server?
For a school project I want to make a little project with the Arduino Uno. I want to make a project that does something when a client connects to the WiFi shield.
My first thought was to print out the IP address or MAC address of the client but I can't find the codes for it. It is possible for me to print out the host IP? I have searched on the web for some time but only the ethernet shield will appear. Is my question even possible with an WiFi shield or do I have to get an ethernet shield?
Kind regards.

Which WiFi shield? There's two different official ones, plus a handful of third party ones.

It looks like Arduino only thought to provide access to that kind of information for UDP packets. They couldn't be bothered to do it for TCP connections. How **** is that?

***** Assuming it is an ESP8266 based WI-FI shield: *****
Wifi shield > PC
Open serial monitor. Baud rate 155200. Also check COM ports.
Test AT commands by typing AT.
If it responds OK, you're good.
Type AT+CIFSR for IP adress.
Full list of AT commands in this link:
http://www.pridopia.co.uk/pi-doc/ESP8266ATCommandsSet.pdf

You're assuming an ESP8266 based WiFi shield. If it's an official Arduino WiFi shield of either version then it most certainly won't be that.

I edited to have a disclaimer in the anwser. Thanks

Isn't it local address anyways? Question looks like he wanted the IP of the other side. But I'm not sure if he's using AP mode and he wants assigned IP for the client or he wants connected TCP socket client IP.


text:
connecting ESP8266 to mega 2056
im trying to connect wifi module to my MEGA 2560 board.
i set up the board as the picture bellow

and my program is as follows
#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(18,19); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  pinMode(10,OUTPUT);
  digitalWrite(10,LOW);

  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"mySSID\",\"myPassword\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.find("pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

     digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // build string that is send back to device that is requesting pin toggle
     String content;
     content = "Pin ";
     content += pinNumber;
     content += " is ";

     if(digitalRead(pinNumber))
     {
       content += "ON";
     }
     else
     {
       content += "OFF";
     }

     sendHTTPResponse(connectionId,content);

     // make close command
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendCommand(closeCommand,1000,DEBUG); // close connection
    }
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

but i always recieve the following error
Arduino: 1.6.12 (Windows 7), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 228,949 bytes (52%) of program storage space. Maximum is 434,160 bytes.
Global variables use 32,796 bytes (40%) of dynamic memory, leaving 49,124 bytes for local variables. Maximum is 81,920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

any idea where i went wrong ?

It looks you may have badly configured your Arduino IDE: you wrote a sketch for Arduino MEGA, but the console output you show looks as if you want to upload it to the ESP8266. That sounds weird. Please show us your IDE configuration (target board) for MEGA upload.

Do not use SoftwareSerial on a hardware serial port. It is pointless.
Do use a voltage divider to convert the Arduino's 5V TX to the required 3.3V the ESP8266 needs.
Do not try and program the Arduino as if it were an ESP8266 - it won't work.

I think you are getting a little confused here...

thanks! what should i edit ? it already has a 3.3 output. i changed the board to MEGA 2560 i don`t receive this error but i get some warnings and still not working

how do you know its 3.3V. there are high odds that you might have fried you esp

Connect your ESP directly to your PC. Test AT commands first. They will tell you if your good to go or not. Just open your serial monitor and set the baud rate to 115200. Select carriage return and type in AT. If it responds OK. Then your code is the problem. If it doesn't return OK, then your ESP or circuit is the problem.

thanks! but i cant connect esp directly to my PC. is there any way around this so i can test it with this setup'

do youn have an FTDI breakout?

sorry i don't have it . thats why i can't connect it. if its the only way i can order it. but is there any other way?

I would say that depends a lot on whether or not your ESP8266 is pre-loaded with the Espressif AT firmware. Flashing an ESP from a Arduino/MEGA is probably hard, if not impossible. If it is pre-loaded, it should respond to AT commands. As an in-between test, set the baudrate to 74880, and see if you get anything from the ESP when it's turned on, the ESP bootloader always prints info on the serial port at 74880 baud when turned on.


text:
Is possible to set a pin faster than digitalWrite?
I am currently using arduino library to logically set my digital pins high or low, but I just realized how slowly it actually sets those pins, which is especially problem as i am doing this in a ISR routine. Can't this be done faster by actually acessing the direct port, and setting the current pin?
How do I convert something like this
  digitalWrite(11, !digitalRead(11));

To something faster?
I am using a Arduino UNO..

Yes, it is possible
The atmel chip at the core of the arduinos can set or clear individual pin output levels in a single operation. There are special instructions to do so SBI and CBI- you just need to figure out what C compiles down to those instructions.
Each pin is represented by one bit of a port byte, for pin 11 it's bit 3 on port B.  So you can toggle it with
PORTB ^= _BV(PB3);

or set it with
PORTB |= _BV(PB3);

or clear it with
PORTB &= ~_BV(PB3);

Probably the last two will compile to a single SBI/CBI instruction while the toggle one may or may not, depending on the code and how the compiler optimises it.

hmm.. I just tested it with an logic level analyzer and can't see the signal togglin anymore..  It seem high.. it is a 24mHz logic level analyzer, so it should be fast enough to see the toggling?

I wrote the answer from memory, you may want to check that 1) that is the correct pin, and 2) I have the correct syntax.  Also, if the Arduino is doing nothing else, just toggling, then 24mHz will be nowhere near fast enough.

sorry I meant 24 MHz

Also, I just edited the answer, I originally used PINB but it should be PORTB because the pin is configured as an output, not an input.

but pin11 is used as an output?

but it seemed to have worked...??

Normally you just read from the PINB register, but it has an alternate function, in that it will toggle the pin if you write a 1 to that bit. From the datasheet: Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port.

Yes there is!
You can directly manipulate the port. The Arduino website has a pretty good explanation for it here.
Togelling a pin as asked by you can be simply done by something like this:
  PORTB ^= _BV(PINNUMBER)

A simplified way is the digitalWriteFast library.

This library consists of a complex header file that translates digitalWriteFast, pinModeFast, digitalReadFast into the corresponding PORT commands. It provides syntax that is as novice-friendly as the arduino's pin manipulation commands but an order of magnitude faster.

Since pin 11 on the ATmega328P is PB3:
PINB |= _BV(PB3);

The fastest way may be to use assembly from your C++ code:
asm volatile("SBI %[IOREG], %[BIT] \n\t"::[IOREG] "I" (&PINB), [BIT] "I" (PB3));

This forces a 1 to the bit for pin 11 (bit 3 on port B of the ATmega328), which, as per the Atmel datasheet, will simply toggle output (1 to 0 or 0 to 1) on that pin (provided it was initially setup as output).
As far as I remember the assemby instruction SBI used above cannot be generated by g++ (the C++ compiler used by Arduino IDE), hence you have to code it yourself.
You won't be able to achive a better performance as this single assembly instruction takes exactly 2 clock cycles to execute (ie 125 ns on an Arduino UNO).

You remember wrong. The answer from Ignacio Vazquez-Abrams compiles into the same assembly instruction.

Then that's very good news! Is that a change of latest arduino toolchain?

Seems gcc does that since at least 2002, but I don't know how much the Arduino toolchain is lagging behind gcc.

Yes that can be done by manipulating the ports directly. Here is the link to Arduino https://www.arduino.cc/en/Reference/PortManipulation

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. Feel free to add a more complete answer that directly answers the question.

The Arduino GPIO library has been developed to allow high performance digital pin access. Most access functions are compiled to a single instruction and execute in 1-2 clock cycles. The library functions are more than 10 times faster than the Arduino digital pin functions. In some cases as much as 100 times faster.
Additional support classes are available for Shift Register Input/Output, and Software Serial. These also demonstrate how the GPIO template class may be used to construct additional libraries.
This library supports boards based on SAM3X8E, ATmega168, ATmega328P, ATmega32U4, ATmega1280, ATmega2560, ATtinyX4 and ATtinyX5.
The classical blink sketch looks like this:
GPIO<BOARD::D13> led;

void setup()
{
  led.output();
}

void loop()
{
  led = HIGH;
  delay(1000);
  led = LOW;
  delay(1000);
}

Please see github for benchmarks and further documentation and examples.


text:
arduino pro mini analog pins read different values
i need to read a voltage with an arduino pro mini using the analog pins.
I created this simple test code:
int sensorValue;
float voltage;

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

void loop() {
  sensorValue = analogRead(A0);
  voltage= sensorValue * (5.0 / 1023.0);
  Serial.println(voltage);
}

my setup looks like this:

everything works so far. I get about 4,5v as a result. Now i want to port everything to an arduino pro mini. After i did that i only got 2,5v as a result. I also tried it with different pins and with an other arduino pro mini.
So what did i do wrong? Do i need an other pull-up resistor?

2.5 V is what you expect. Why would you read 4.5 V?

so you think my arduino nano is not working properly?

Or you used different resistors, or you used different code.

I made a circuit bellow for you. Note that the top resistor is 100 ohm and the bottom one is only 10 ohm. What I did is called a voltage divider. This way you can read voltages up to 50V. Simply connect the positive of your power source that you want to measure to the red wire and the ground of that same source to the black wire.
I also included a code that you could use:
Please notify me if any mistakes were spotted.
#define sensor A0 //defining sensor pin

float resistor1 = 100; //you can change it if you want, just make sure you also do it on the circuit
float resistor2 = 10;

float Vmax = (5*resistor1 + 5* resistor2)/resistor2;

void setup() {
  pinMode(sensor, INPUT); //declaring sensor as an output
  Serial.begin(9600);

  Serial.print("Do not input more then (V) : "); // print max input voltage
  Serial.print(Vmax);

  Serial.println(); //skip line
}

void loop() {
  float V = analogRead(sensor); //measuring analog values

  V = analogRead(sensor) * Vmax / 1024

  Serial.println(V); //printing voltage
}

Don't see mistakes, but here are a few suggestions: 1) Use higher valued resistors (but no more than 10 kΩ for R2) to avoid excessive current draw. Otherwise a 50 V source would blow up your 1/4 W resistors. 2) Declare the resistor values as float. 3) Write V = analogRead(sensor) * Vmax / 1024 instead of using map(). 4) Why divide the voltage by 100?

thats what i mean by mistakes! thanks though :)

That float int resistor1 and float int resistor2 works? If yes, what type is it in the end? float or int?

opps, its just float, my bad!


text:
Storing Long numbers in arduino like phone numbers...How?
I am using 20 x 4 LCD And 3 x4 keypad I want to enter and store 3 inputs in different variables the code I am using can store 3 inputs and display it right in serial monitor example I type 5 digits using keypad it will store and display correctly in LCD and serial monitor the right value however if its more than five it has negative output and very far to what inputted. Thank you for help .The code is...
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6,5);
#include <Keypad.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
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] = {19, 18, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad

int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

char entryStr[12];   // This can hold up to 4 digits
int i=0;

void setup()
{
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
}

void loop(){
    long n1, n2 , n3;

    lcd.setCursor(0,0);
    lcd.print("Enter n1:   ");

    lcd.setCursor(0,1);
    n1 = GetNumber();
    Serial.println ("n1: ");
    Serial.println (n1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter  n2:   ");

    lcd.setCursor(0,1);
    n2= GetNumber();
    Serial.println ("n2: ");
    Serial.println (n2);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter n3:   ");
    lcd.setCursor(0,1);
    n3 = GetNumber();
    Serial.println ("n3: ");
    Serial.println (n3);
}

int GetNumber()
{
    long num = 0;
    char key = kpd.getKey();
    while(key != '#')
    {
        switch (key)
        {
            case NO_KEY:
            break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            lcd.print(key);
            num = num * 10 + (key -'0');
            break;

            case '*':
            num = 0;
            lcd.clear();
            break;
        }
        key = kpd.getKey();
    }
    return num;
}

Phone numbers should be handled as strings. Otherwise 1, 01 and 000000001 will be the same.

int GetNumber()

should be changed to
long GetNumber()

It is because the function type is the type of value that returning. In this case you are returning a long so you have to change it. An int can handle a number from -32 768 to 32 767. A long on the other side can handle a number from -2,147,483,648 to 2,147,483,647.

thank you I followed what you advised it displayed the right value however if i tried to typed 091234 i can only see 91234 thank you very much I a newbie I appreciate your help a lot thanks

can be risky but use a char instead. the arduino sees your number as a litteral mathematical number. it will simplify your number by removing the 0s like when you do a calculation in math. please dont tell me you do 0003 x 0009 = 0027. using a char is like sending a complete word like HELLO then you can decompose it into multiple small bits such as H, E, L, L, O,. It also works with numbers like if your password was 0192, you can decompose it to 0_1_9_2

Thank you I'll try what you advices thank you again I appreciated your help and sharing your time thank you .

its char* btw. char is different then char* dont forget the *


text:
Arduino sound equalizer
I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.
And I need a little help on how I should do it cause Im a beginner.
Should I use pulsein() or analogin pin to measure the freqeuencies?
The input will be an audio cable.

You are probably asking too much from your poor Arduino Uno... To get some inspiration, you may want to take a look at this homodyne detection program, which is conceptually like a single-channel equalizer. You could try to extend it to handle multiple channels, but you will pretty quickly run out of processing power.

http://arduino.stackexchange.com/q/15828/972

You seem to be describing a spectral display.  A graphic equalizer might include one, but is actually a device with a set of sliders or similar controls that allow changing the response in various frequency bands, rather than merely displaying the spectrum as is.  That would be even harder with an arduino.

Ok to make it more clear sorry for this misundarstanding. I want for example to connect the audio cable and have for example 3 leds. And I want the 1st one to light in the range of 50-60hz the 2nd to 60-200 and so on. In "real" time.

There are three steps to doing what you want, and the Arduino is going to struggle with all of them.
First you need to sample a short block of audio into a buffer that is a power-of-two in size with at least double the number of samples that you want to have bars, and at double the frequency of the highest frequency band you are interested in.
Once you have that sample set you then need to perform a Fast Fourier Transform (FFT) on it. This is quite a heavy mathematical operation, but there are integer only implementations of it that work kind of OK on a little Arduino (though a floating point version running on a better chip with FPU, or a DSP version on a chip with a DSP, is more desirable).
Then the third step is to take the results of the FFT (or "buckets") and calculate the power magnitude of each one (basically the square root of the sum of the squares of the real and imaginary values of the bucket - just like Pythagoras with a triangle).
Finally you can plot those power values on your LED bars.

https://tushev.org/articles/arduino/9/measuring-frequency-with-arduino              This method that he is describing is not possible?

@user3247715 That is completely different. That allows you to measure the frequency of one discrete (square wave) signal. It does not allow you to differentiate the different frequencies present within a piece of music. For that you require FFT.

Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".
Here is its datasheet:
https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf
This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.
https://github.com/NicoHood/MSGEQ7
Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.
https://www.youtube.com/watch?v=InrQvtUuS2w

I know about it but I want to process the signal so I will get more im depth and understand better arduino amd how signals works.


text:
How to keep accurate millis() while using ADC_sleep mode?
millis() uses timer0 (linked to CPU clock) to count time, but ADC_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC_sleep mode.
With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC_sleep mode.
I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230.
How should I proceed to use ADC_sleep mode during ADC conversions but still keep millis() accurate?

Is this about SLEEP_MODE_ADC? And on what AVR/Arduino? A possible solution is to use Timer2 for the Arduino millis-ISR. See Cosa RTT for an example; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/RTT.hh (and files RTT.cpp, RTT_Config.hh)

Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, omillis() – compensate for those cycles. [Edit:  See better alternative, below]
In more detail:
• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
long lostcycles; ...; lostcycles += ADCcycles;
• Within each omillis() call, say return millis()+lostcycles/16000
• Or perhaps say return millis()+lostcycles>>14 to avoid wasting time on a division.  This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230”

That's incorrect [if using suggested approach].  Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. [As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.]
Note, the example code using SLEEP_MODE_ADC in the “Sleep during reading” section of ADC conversion on the Arduino on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion.  While SLEEP_MODE_ADC stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.
A better alternative:
As Gerben points out, it's slightly cleaner to update the count variable maintained by millis(), rather than using an intermediate routine.  For background, refer to his answer to an earlier question.  Here is an adaptation [untested] of the idea to the current case:
unsigned int lostcycles=0;
...;
void accountForADC() {
  enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
  extern volatile unsigned long timer0_millis;
  lostcycles += ADCcycles;
  while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++timer0_millis;       // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status
    lostcycles -= ms_cycles;
  }
}

After startup, on the tenth call to accountForADC() this code would add 1 to timer0_millis to account for a millisecond lost to ADC conversions. lostcycles -= ms_cycles would set lostcycles to 1280.  After another 9 calls we again add 1 to timer0_millis and reduce lostcycles; and so forth.

At the end keeping track of the number of conversions was my idea as well, thanks for confirmation (yours is cleaner than my idea)

@OlafM, thanks!  Note, I miscalculated the cycles to add -- 108 us is wrong units; I presume 13*128 = 1664 cycles is the number to use

You definitely can miss the overflow event if, along the lines of the OP's original idea, you do TCNT0 += 26; and that operation overflows.

@EdgarBonet, true!  Something the data sheet warns about.

My idea I was referring to one I had after writing, that is to subtract 0.1 ms times the number of conversions. This one keeping track of conversions*1664/16000 is more accurate.

@OlafM: Unless you reset the prescaler, the ADC conversion will take (1664 + some unknown number between 0 and 127) CPU cycles from ADSC to ADIF. C.f. the timing diagrams on section 24.4 of the datasheet.

If you don't want to have to change all millis call, you could actually increment the variable that is used by millis. Look at the bottom of my answer here.

@Gerben, thanks; I've edited that approach in at end of answer

@jwpat7 since timer0_millis is a 4-byte long, that is updated in an ISR, you need to update it atomically, or weird things may happen if the timer0 interrupt happens in the middle of your code changing the 4 bytes. In my code I temporarily disabled interrupts for this.

@Gerben, thanks for pointing that out... have edited answer accordingly

I won't tell you how to do what you ask as I don't really know how to do
it. But I have the gut feeling that it can be done. Only it would be
really, really hard, so this brings the question: is it worth it?
To avoid posting a pure opinion-based answer, I'll try to give you some
leads:

You can set the timer 0 with single-CPU-cycle resolution simply by
resetting its prescaler whenever you set a new value.
You can make very precise delays with the _delay_us() function. The
argument should be a compile-time constant. _delay_us(0.125) does
exactly what it says it does.
Beware of the prescaler of the ADC clock: it will induce some jitter
on the ADC timings unless you reset it as well. AFAIK, the only way to
reset that prescaler is to start the ADC conversion using some trigger
source in auto-trigger mode. This may cost you a timer.
If you miss the overflow event, you can just manually call the
relevant ISR (TIMER0_OVF_vect(), which you declare with
ISR(TIMER0_OVF_vect);). Sounds silly, but it works, with the only
caveat that it forcibly enables interrupts upon return.

To know how many tics exactly you are loosing, you could spend a few
evenings carefully studying the timings in the datasheet, or you could
try to calibrate against a stable frequency source. I would recommend
the latter.

I think you read the datasheet wrong. The conversion takes 13 ADC cycles (except for the first one), not 13.5.
Secondly; the conversion start at the next rising edge of the ADC clock, not directly. So because the prescaler is 128, it can take an additional 127 main clock cycles before the next ADC clock's rising edge. So that means and ADC conversion takes between 13 and 13.9921875 ADC clock cycles.
I'm also not sure how long it takes the uC to restart the CPU clock. So there might me more time "missed" here.
Though you must be aware that the crystal oscillator isn't that accurate to begin with.

In my mind I thought that the CPU clock would stop when the ADC actually starts, therefore the "from 0 to 127" cycles of delay was not considered. I see it's more complex than that.

The time to start a conversion is not fixed. From my page about timers we can see this:

Tip:
There is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

It looks like the prescaler can be reset by writing 0 to ADEN. According to the datasheet:

The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low.

If you do that however then you add to the conversion time, as it will now take 25 ADC clock cycles rather than 13.

As others have suggested, if accurate time is what you want, then an external clock chip could well be the answer. The chip and parts are likely to come to a dollar or so.
An alternative would be to get an external ADC chip, thus moving the problem of noise-reduction to a chip which is (hopefully) designed to cope with it.
Another possibility would be to put an external clock input to Timer 1 and run that asynchronously. As I read the data sheet, that timer will keep running in ADC sleep mode, and thus you could use that for timing. (That wouldn't help with millis() and micros() but you could write something similar that used Timer 1).
Edit - as Edgar Bonet pointed out, I misread the datasheet. It is Timer 2 that can do this, not Timer 1. And the pins to run the timer asynchronously are not on the PDIP chip on the Uno, and are not brought out to board pins on the Mega.

Only Timer 2 can run asynchronously, at lest on the Uno and the Mega. And you cannot use the asynchronous mode on those boards because the required pins (TOSC1/TOSC2) are not available.

Whoops! Misread the datasheet. Corrected my answer, thanks.


text:
How to multiply strings?
I want to have a line like this
Serial.println(count*"B");

So if count=6, it would print BBBBBB, etc.
Is there anything like this for arduino?

Nothing that will be more effective than a loop.

A loop that prints char by char, or a loop that builds a string, and is printed at the end of the loop?

That would depend on whether or not count has a reasonable limit.

For(let str = ‘a’; str.length<6; str+=‘a’){ Console.log(str) }

A more simple "noob" way could also be:
int count = 6

for(int i=0; i<count; i++)
{
  Serial.print("b");
}

Serial.println();

This is what I ended up doing (although made the for loop one line). I wasn't really looking to make my own method like the others have done, I was just hoping there'd be some kind of string * int syntax

You can write a helper function to do it, like this:
void printRepeat (Stream & device, const char * str, unsigned int count)
  {
  while (count-- > 0)
    device.print (str);
  }   // end of printRepeat

void setup()
  {
  Serial.begin (115200);
  printRepeat (Serial, "-", 20);
  Serial.println ();
  } // end of setup

void loop()
{
  printRepeat (Serial, "Hello, World! ", 5);
  Serial.println ();
  delay (500);
} // end of loop

The function printRepeat is passed a Stream argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.

Just for fun, here is a version of Nick Gammon's answer reformulated
with some C++ magic:
// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
    RepeatedString(const char * str, unsigned int count)
    : _str(str), _count(count) {}
    size_t printTo(Print& p) const
    {
        size_t sz = 0;
        for (unsigned int i = 0; i < _count; i++)
            sz += p.print(_str);
        return sz;
    }
private:
    const char * _str;
    unsigned int _count;
};

void setup()
{
    Serial.begin(115200);
    Serial.println(RepeatedString("-", 20));
}

void loop()
{
    Serial.println(RepeatedString("Hello, World! ", 5));
    delay(500);
}

You can .print() and .println() the RepeatedStrings on anything
that can print.

Nice! You can also overload "*" so that OP's exact syntax would work!