message:
PCM audio, PROGMEM sounds through speaker, multiple clips (using speaker_pcm)

I downloaded the PCM Audio speaker_pcm (see link below) and it worked easily with the supplied Mac startup chime. I also got my own sounds parsed properly via a combination of sox and wav2c incantations as described. However, when I tried to store and play two or more (very short e.g. 150ms, 8K) sound clips in sequence, I couldn't seem to get it to work. It only sounds like it is playing the last clip in order. I only modified the code (see below) from the original to address the multiple clips. My pointer dereferencing seems to be working (it plays the last clip in sequence), but it won't play a group of them. What am I doing wrong?

(You can download the 01.h 02.h 03.h files from my website, pete dot zelchenko dot com slash 2017 slash the file name. I can't post lots of links here. You can also create your own using the incantations about sox and wav2c in the documentation below, but it takes time. The three files are the words "one" "two" "three" and that's it.)

    /*
     * (PCM Audio speaker_pcm downloaded from http://playground.arduino.cc/Code/PCMAudio)
     *
     * speaker_pcm
     *
     * Plays 8-bit PCM audio on pin 11 using pulse-width modulation (PWM).
     * For Arduino with Atmega168 at 16 MHz.
     *
     * Uses two timers. The first changes the sample value 8000 times a second.
     * The second holds pin 11 high for 0-255 ticks out of a 256-tick cycle,
     * depending on sample value. The second timer repeats 62500 times per second
     * (16000000 / 256), much faster than the playback rate (8000 Hz), so
     * it almost sounds halfway decent, just really quiet on a PC speaker.
     *
     * Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
     * (analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
     * for the pulse width modulation, breaking PWM for pins 11 & 3.
     *
     * References:
     *     [links]
     *
     * Michael Smith <michael [at] hurts.ca>
     */

    #include <stdint.h>
    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <avr/pgmspace.h>

    #define SAMPLE_RATE 8000

        /*
         * The audio data needs to be unsigned, 8-bit, 8000 Hz, and small enough
         * to fit in flash. 10000-13000 samples is about the limit.
         *
         * sounddata.h should look like this:
         *     const int sounddata_length=10000;
         *     const unsigned char sounddata_data[] PROGMEM = { ..... };
         *
         * You can use wav2c from GBA CSS (OR use EncodeAudio? http://highlowtech.org/?p=1963):
         *     http://thieumsweb.free.fr/english/gbacss.html
         * Then add "PROGMEM" in the right place. I hacked it up to dump the samples
         * as unsigned rather than signed, but it shouldn't matter.
         *
         * [link deleted]
         * mplayer -ao pcm macstartup.mp3
         * sox audiodump.wav -v 1.32 -c 1 -r 8000 -u -1 macstartup-8000.wav
         * sox macstartup-8000.wav macstartup-cut.wav trim 0 10000s
         * wav2c macstartup-cut.wav sounddata.h sounddata
         *
         * (starfox) nb. under sox 12.18 (distributed in CentOS 5), i needed to run
         * the following command to convert my wav file to the appropriate format:
         * sox audiodump.wav -c 1 -r 8000 -u -b macstartup-8000.wav
         */

        //#include "sounddata.h"
        #include "toolow.h"
        #include "toohigh.h"

        #include "01.h"
        #include "02.h"
        #include "03.h"

        int      ledPin   = 13;
        int      speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

        volatile uint16_t sample;
        byte lastSample;

        int sounddata_length;

        /*int sounddata_length;
        signed char *sounddata_data[10000]; */

        void stopPlayback()
        {
            // Disable playback per-sample interrupt.
            TIMSK1 &= ~_BV(OCIE1A);

            // Disable the per-sample timer completely.
            TCCR1B &= ~_BV(CS10);

            // Disable the PWM timer.
            TCCR2B &= ~_BV(CS10);

            digitalWrite(speakerPin, LOW);
        }

        unsigned int sounddata_addr;

        // This is called at 8000 Hz to load the next sample.
        ISR(TIMER1_COMPA_vect) {
            if (sample >= sounddata_length) {
                if (sample == sounddata_length + lastSample) {
                    stopPlayback();
                }
                else {
                    if(speakerPin==11){
                        // Ramp down to zero to reduce the click at the end of playback.
                        OCR2A = sounddata_length + lastSample - sample;
                    } else {
                        OCR2B = sounddata_length + lastSample - sample;
                    }
                }
            }
            else {
                if(speakerPin==11){
                    OCR2A = pgm_read_byte(sounddata_addr + sample);
                } else {
                    OCR2B = pgm_read_byte(sounddata_addr + sample);
                }
            }

            ++sample;
        }

        void startPlayback(int clip)
        {

        signed char *sounddata_data[10000];

            switch (clip) {
              case   1:  sounddata_data[0] = &s_01_data[0]; sounddata_length = s_01_length; break;
              case   2:  sounddata_data[0] = &s_02_data[0]; sounddata_length = s_02_length; break;
              case   3:  sounddata_data[0] = &s_03_data[0]; sounddata_length = s_03_length; break;

            }

        sounddata_addr = sounddata_data[0];

            pinMode(speakerPin, OUTPUT);

            // Set up Timer 2 to do pulse width modulation on the speaker
            // pin.

        *  // Use internal clock (datasheet p.160)
            ASSR &= ~(_BV(EXCLK) | _BV(AS2));

            // Set fast PWM mode  (p.157)
            TCCR2A |= _BV(WGM21) | _BV(WGM20);
            TCCR2B &= ~_BV(WGM22);

            if(speakerPin==11){
                // Do non-inverting PWM on pin OC2A (p.155)
                // On the Arduino this is pin 11.
                TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
                TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
                // No prescaler (p.158)
                TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

                // Set initial pulse width to the first sample.
                OCR2A = pgm_read_byte(&sounddata_data[0]);
            } else {
                // Do non-inverting PWM on pin OC2B (p.155)
                // On the Arduino this is pin 3.
                TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
                TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
                // No prescaler (p.158)
                TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

                // Set initial pulse width to the first sample.
                OCR2B = pgm_read_byte(&sounddata_data[0]);
            }

            // Set up Timer 1 to send a sample every interrupt.
            cli();

            // Set CTC mode (Clear Timer on Compare Match) (p.133)
            // Have to set OCR1A *after*, otherwise it gets reset to 0!
            TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
            TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

            // No prescaler (p.134)
            TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set the compare register (OCR1A).
            // OCR1A is a 16-bit register, so we have to do this with
            // interrupts disabled to be safe.
            OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

            // Enable interrupt when TCNT1 == OCR1A (p.136)
            TIMSK1 |= _BV(OCIE1A);

            lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
            sample = 0;
            sei();
        }

        void setup()
        {
        // audio pins
            pinMode(ledPin, OUTPUT);
            digitalWrite(ledPin, HIGH);

            startPlayback(01);
            startPlayback(02);
            startPlayback(03);

        }

        void loop()
        {
          loop();
        }

body:
I think it's just a case of `startPlayback()` being asynchronous. It doesn't block; it doesn't wait for playback to finish. It just sets up the 8000 Hz timer interrupt and returns.

The original code calls `stopPlayback()` when it runs out of samples. You could change that block (under `if (sample >= sounddata_length)`) to have it cycle on to the next clip, rather than stopping.

(Note: I'm the original author of the PCM sample but it's been quite a while so take this with a grain of salt. Surprised it still works with newer boards. Have fun!)


sender: user

sender: assistant

body: The Mega2560 apparently has to use pin 10 instead of pin 11 for PCM output.  It would be better if this were defined in the main sketch instead of the library.


message:
Output of Hex of ino

I have a hex file of a sketch i.e. `sketchname.ino.hex`. Can I find out anything from that hex file ?  Can I see the output or anything ? Can I upload it on arduino ?

body:
> I have a hex file of a sketch i.e. sketchname.ino.hex. Can I find out anything from that hex file ?

That is a binary image of the compiled sketch in a hexadecimal notation. You *could* spend hours disassembling it if you understood the right tools to use.

> Can I see the output or anything ?

You can convert it back to a crude form of assembly language maybe, but that is all. Understanding what that means takes skill and knowledge.

> Can I upload it on arduino ?

Sure. It's a compiled program ready to be uploaded to an Arduino.

    avrdude -D -patmega328p -PCOM3 -b115200 -C/path/to/avrdude.conf -c arduino -Uflash:w:sketchname.ino.hex:i


message:
Comparing 2 char converted from a array

I wrote this little program to test converting and comparing 2 char with each other. With some help from [here][1] i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:

    char code[4] = {'1','2','3','4'};
    char strcode[5];
    char pass[4] = {'1','2','3','4'};
    char strpass[5];

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

    void loop()
    {
        memcpy(strcode, code, 5);
        strcode[4] = '\0';
        Serial.println(strcode);
        Serial.println("done");
        delay(1000);
        memcpy(strpass, pass, 5);
        strpass[4] = '\0';
        Serial.println(strpass);
        Serial.println("donepass");
        if (strpass == strcode)
        {
            Serial.println("yes");
        }
        else
        {
            Serial.println("no");
        }
    }

I get this in my serial monitor:

    1234
    done
    1234
    donepass
    no

Why is this not equal to each other?
  [1]: https://arduino.stackexchange.com/questions/39399/converting-array-to-char

body:
You cannot compare char arrays with `==`. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.

C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).

Comparing two char array variables with `==` is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.

There's various functions for doing that depending on how you want to compare.

    strcmp(a, b)
    strncmp(a, b, n)
    strcasecmp(a, b)
    strncasecmp(a, b, n)

All return 0 for `a == b`, a negative number for `a < b` and a positive for `a > b`.

The "n" variants (e.g., `strncmp`) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).

The "case" variants are *case insensitive* comparisons - that is "foo" matches with "Foo" and "foO".


message:
Access I2C sensor from Arduino Uno as slave

I connected Raspberry Pi 3 to an Arduino Uno through I2C. The Arduino Uno uses the I2C as slave.

When I connect [AM2320 sensor][1] (temperature and humidity) to the Arduino Uno, I am getting the response that the sensor is offline.

I tested the sensor on Raspberry Pi 3 and it is working fine. On the Raspberry Pi the address is 0x5c. On most libraries, the address is 0xb8. I have the same result when I tried these 2 addresses.

Do I have problem because Arduino Uno is working as slave?

  [1]: https://akizukidenshi.com/download/ds/aosong/AM2320.pdf

body:
Indeed, I2C slaves cannot communicate with one another.

There are some obscure capabilities for devices to switch role, but that is likely to introduce lots of complications.

You might look at using bit-banged (or "soft") I2C on other digital pins and move the peripheral's I2C lines there instead o the hardware I2C pins connected to the pi.  For example, a web search quickly found something that claims to do this at:

https://github.com/felias-fogg/SoftI2CMaster

No idea if that particular one will work for you, but there are others as well.

Or you can re-design your scheme so that the pi reads the sensor, and if necessary writes the values of interest to the Arduino.


body:
I had may be a bad connection but I can read the sensor AM2320 on Arduino-
Uno and send the value back to Raspberry Pi.

Arduino side:

<!-- language: c++ -->

    #include am2320
    #define SLAVE_ADDRESS 0x04
    Wire.begin(SLAVE_ADDRESS);
    AM2320 th;
    Wire.write( (int)(th.t * 10)); // th.t is for temperature which I send
    integer

Raspberry side:

<!-- language: lang-py -->

    import smbus
    bus = smbus.SMBus(1)
    address = 0x04
    number = bus.read_byte(address)

Raspberry Pi and Arduino Uno seems to work good together with and I2C sensor on Arduino side. Thanks for you time to help me and I will go to the link you propose.


body:
You can do it. A single device like the Arduino can be both a slave and a master.

It's explained in great detail by Nick Gammon in [http://www.gammon.com.au/i2c][1] in the paragraph *Communicating with other devices*

  [1]: http://www.gammon.com.au/i2c


message:
Wierd Issue with PWM pin

I'm trying to run two of my motors through PWM. Here's my code -

    #include <Servo.h>
    int Lm = 11;
    int Rm = 10;
    int incomingByte = 0;
    int pos = 0;
    Servo myservo;
    void setup() {
      pinMode(Rm, OUTPUT);
      pinMode(Lm, OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(2,OUTPUT);
      myservo.attach(3);
      Serial.begin(9600);

    }

    void loop() {
      blinkers();
      if (Serial.available() > 0) {
                    incomingByte = Serial.read();
      }
      if(incomingByte == 49){
        analogWrite(Rm, 128);
        analogWrite(Lm, 128);
      }
       else if(incomingByte == 48){
        analogWrite(Rm, 0);
        analogWrite(Lm, 0);
        myservo.write(0);
      }
      else if(incomingByte == 50){
        analogWrite(Rm, 0);
        analogWrite(Lm, 128);
        delay(500);
        analogWrite(Lm, 0);
      }
      else if(incomingByte == 51){
        analogWrite(Rm, 128);
        analogWrite(Lm, 0);
        delay(500);
        analogWrite(Rm, 0);
      }
      else if(incomingByte == 52){
        for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);
      }
    }
    }

    void blinkers(){
        digitalWrite(7, HIGH);
        digitalWrite(2, HIGH);
      delay(100);
      digitalWrite(7, LOW);
      digitalWrite(2, LOW);
      delay(100);
    }
Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use `digitalWrite` instead, both motors work fine.

I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -

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

    }

    void loop() {
      analogWrite(10, 128);
      delay(100);
      analogWrite(10, 0);
      delay(100);

    }
This code worked perfectly fine.

So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...

Can anyone tell why is this happening?

body:
It is a timer conflict.

The [Servo reference][1] says: "*...use of the library disables analogWrite() (PWM) functionality on pins 9 and 10...*"

This is a picture of the pinmapping of the Arduino Uno: [PighiXXX - Uno][2].
Pin 9 en 10 uses OC1A en OC1B for PWM, that is Timer1. You can't use PWM on them when the Servo is used.
Pin 11 uses OC2A for PWM, which is Timer2.

I suppose it will work if you choose another PWM pin for analogWrite. Timer0 is used for millis and therefor the PWM frequency will be different (pin 5 and 6). That is mentioned in the [analogWrite reference][3]. In most cases that is not a problem.
Pin 3 is a normal PWM pin.

This is a common problem. The documentation is not always clear about the use of timers and other parts of the microcontroller. Many times the source code has to be read to see what is used. In the end, you need more experienced Arduino users to spot the conflict.

  [1]: https://www.arduino.cc/en/Reference/Servo
  [2]: http://www.pighixxx.com/test/portfolio-items/uno/
  [3]: https://www.arduino.cc/en/Reference/AnalogWrite


message:
Arduino nano as HID Keyboard

I'm a bit of a noob in the Arduino area but I found an Arduino nano I bought a long time ago sitting on my shelf and collecting dust,
so I taught "why not make a project". I game a lot of racing games so I wanted to make a simple ignition button with it, but every time I tried to compile or verify it, it says

> *Keyboard not found. Does your sketch include the line #include "Keyboard.h*"

body:
Get yourself a Arduino Leonardo, Micro or Pro Micro (or Due, Zero, M0). Those can emulate a keyboard.
Start with reading the [Arduino Keyboard Mouse reference][1].

The Arduino Nano can not use the Arduino Keyboard Mouse library.

Since many years, there is a library called "[V-USB][2]" that requires some extra hardware and makes it possible for a ATmega328p microcontroller to act as an USB device. It is not something for a beginner.

A few years ago, Arduino has changed the way the USB is used. The [NicoHood HID library][3] makes use of the new possibilities. It makes it possible for example to have extended features for a USB keyboard, like the media keys.

For a normal keyboard and mouse, the Arduino Keyboard Mouse library will do. It will be perfect for a ignition button. But you have to buy one of those boards (Leonardo, and so on).

  [1]: https://www.arduino.cc/en/Reference/MouseKeyboard
  [2]: https://www.obdev.at/products/vusb/index.html
  [3]: https://github.com/NicoHood/HID


body:
The solution to get a board that has built in USB support is not preferred for someone who just wants to use the boards they already have.  It is possible to use a board that can communicate with your computer over serial, such as the Arduino Nano, to send data to a Python program which can then turn the input from the Arduino into keyboard presses, etc. using libraries.

For this approach, you would need to know python.
The libraries to use are:

pyserial - communication with Arduino

pynput - control the computer's keyboard

threading (comes with python) - allow pyserial and pynput to work simultaneously


message:
Extracting char array out of function

I have a array called Table1 witch contains '1','2','3','4'
I do not want to work with global variables
I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1

This is the program i wrote:

    void setup()

    {
      Serial.begin(9600);
    }

    void loop()
    {
      char tabel1[4] = {'1','2','3','4'};
      int i;
      for (i = 0; i <= 3; i++)
      {
        Serial.println(tabel1[i]);
      }

      tabel1 = Change(tabel1);

      for (i = 0; i <= 3; i++)
      {
        Serial.println(tabel1[i]);
      }
    }

    char Change(char tabel2)

    {
      tabel2[0] = 'n';
      tabel2[1] = 'b';
      return tabel2;

    }

This is the error i'm getting:

    In function 'void loop()':
    testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
    tabel1=Change(tabel1);
    ^
    In function 'char Change(char*)':
    30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
    return tabel2;
    ^
    exit status 1

    [Error] Exit with code=1

body:
You should read something about C arrays and how they work.

Anyway, if you use:

      Change(tabel1);

    // ...

    void Change(char * tabel)
    {
      tabel[0] = 'n';
      tabel[1] = 'b';
    }

It'll change passed array because it's passed as pointer to the first element of `tabel1`.


body:
In c an array's name is effectively a pointer to the start of the memory location where the array is stored. You have to be careful, if you pass an array to a function that function will have no knowledge of the array size. If there is a risk of the size being unknown you normally pass a second parameter, the size of the array. In this case we will assume the array passed to change is always at least 2 chars long and risk a crash if it isn't.

At the most simple level your change function becomes:

    void Change(char tabel[])
    {
      tabel[0] = 'n';
      tabel[1] = 'b';
    }

and the line to call it is:
`Change(tabel1);`

Notice how there is no return type or return value. We were passed a pointer to where the array is in memory. When we make changes to the values we are changing the original array directly. The old values are lost.

The function:

    void Change(char *tabel)
    {
      *tabel = 'n';
      *(tabel+1) = 'b';
    }

Is functionally identical to the one above only it is explicitly using a pointer rather than an array.

One thing you need to get used to in c is that an array is not a type of variable, it's a collection of variables. As such normal variable operations don't work on them.

e.g. `array1 = array2` does not set the contents of array 1 to being the same as array2. It sets the memory address where array1 is stored to being the same as the memory address that is used for array2. The original memory used to store array1 is no longer accessible by the program and is now unusable. This is a bad thing.<br>
Similarly `if (array1 == array2)` doesn't compare the contents of the two arrays, it compares their memory addresses.


message:
if-else statement not working

So I'm facing this problem a lot in my code where the program is not getting into the `if` `else` loop properly and just returning the same answer again and again.

    void loop() {

    double X_value = ((double)(analogRead(X_pin)-487))/540.00;
    double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

    double theta_rad = atan((double)Y_value/(double)X_value);
    double theta_deg = ((double) theta_rad)*180.00/3.1416;

    double temp = (double)abs(tan((double)theta_rad));
    if (temp == 0.00) {
    temp2 = 0.00;
    } else {
      double temp2 = min(temp,1.00/temp);
    }

    Serial.print("Theta = ");
    Serial.print(theta_deg);
    Serial.print("\n");
    Serial.print("temp 2 = ");
    Serial.print(temp2);
    Serial.print("\n");

    delay(1000);

    }

The answer keeps on coming 0 even when temp is non zero.

[![Screenshot of result][1]][1]

 If anyone knows the reason please help...

  [1]: https://i.stack.imgur.com/Lm3Cr.png "Screenshot of result"

body:
I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.<br>
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.

    void loop() {

    double X_value = ((double)(analogRead(X_pin)-487))/540.00;
    double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

    double theta_rad = atan((double)Y_value/(double)X_value);
    double theta_deg = ((double) theta_rad)*180.00/3.1416;

    double temp = (double)abs(tan((double)theta_rad));

    if (temp == 0.00) {
      temp2 = 0.00;
    } else {

    /* Bug here.                                                             */
    /* this temp2 is local to these {} and is lost as soon as we reach the } */
    /* at the end of the else.                                               */
    /* Remove the word double and it should work                             */

      double temp2 = min(temp,1.00/temp);
    }

    Serial.print("Theta = ");
    Serial.print(theta_deg);
    Serial.print("\n");
    Serial.print("temp 2 = ");
    Serial.print(temp2);
    Serial.print("\n");

    delay(1000);

    }

Personally I'd replace the entire if ... else with:

    double temp = abs(tan(theta_rad)); // removed redundant casts to double

    double temp2;
    if (temp > 1.0) // 1/temp will be smaller if temp > 1
      temp2 = 1.0/temp;
    else
      temp2 = temp;

It'll have exactly the same effect but avoids unnecessary floating point calculations


message:
Arduino not recognizing when a timer reaches 0

Alright, so I'm attempting to make a timer that will turn on a light after an hour. Currently I have it set to 5 seconds for testing. What is happening is whenever I start the program it won't recognize when the timer reaches 0.
Here is my code

    /*
    Hour Alarm
    An hour long alarm that allows breaks
    Created by: Jaxon Reid
    Last Edited: 19/5/2017

    Pins:
    Pin 13 = Led
    Pin 2 = Button
    */
    int secLeft=5;
    const int led=13;
    const int button=2;
    const int buttonIn=4;
    int buttonValue=0;
    // Declares the button to reset as 2 and the lightbulb on pin 13
    //the secLeft means the seconds until the light turns on and button value is for wether or not the button is pushed

    void setup() {
      Serial.begin(2400);
      Serial.print("On  ");
      pinMode(13,OUTPUT);
      pinMode(button,OUTPUT);
      pinMode(buttonIn,INPUT);
    }
    // makes the led pin an input and opens the channel for the debugger
    void loop() {
      int buttonValue=digitalRead(button);
      Serial.println("Checking time");
      if (secLeft<=0) {
        Serial.println("No time remaining");
        digitalWrite(13,HIGH);
        Serial.println("Light On");
        // If the time remaining is 0 then turn on the light
      }
      if (secLeft>0) {
        Serial.println("Time Remaining");
        digitalWrite(led,LOW);
        secLeft=(secLeft--);
        Serial.println(secLeft);
      }
      if (buttonValue==1) {
        int secLeft=5;
        Serial.println("Reset Timer");
        Serial.println(secLeft);
      }
      delay(1000);
    }

 Whenever I start it up it just starts reading

    On 5
    Checking time
    Time remaining
    5
    Checking time
    Time remaining
    4
    Checking time
    Time remaining
    3
    Checking time
    Time remaining
    2
    Checking time
    Time remaining
    1
    Checking time
    Time remaining
    0
    Checking time
    Time remaining
    -1
    Checking time
    Time remaining
    -2
etc...
So where did I go wrong is what I'm asking.
Thanks!

body:
    int secLeft=(secLeft2--);
    int secLeft2=(secLeft);

You are making 2 new variables there instead of using the existing ones.


body:
As per comment and Majenko's answer you are current creating local variables called `secLeft ` and `secLeft2` inside the `'if` block.  These take precedence over the ones you have defined globally.  Removing the `in` declarations from inside the `if` block will stop doing that and point you at the globally defined variables.

As to the rest of the code. If you have

    secLeft=(secLeft2--);
    secLeft2=(secLeft);

Then that translates to this sequence of instructions

   1. Assign `secLeft` with the value of `secLeft2`
   2. Decrement `secLeft2`
   3. Assign `secLeft2` with the value of `secLeft`

And in the end you do not change anything.

This is because you are using `post-decrement` on `secLeft2`  EG `secLeft2--`.  This is a feature of C style languages.

I am not sure what you are even trying to do at this point.


body:
Besides problems mentioned in other answers, your use of `button` and `buttonIn` variables is messed up.

With `button` equal to 2, the `pinMode(button,OUTPUT)` statement initializes pin 2 to be an output.  Pin 2 is low after reset and `pinMode()` doesn't change it.

When you say `int buttonValue=digitalRead(button);` the low value at pin 2 will be read into `buttonValue`.  In the sketch, `buttonValue` will never be anything but low.

To fix this problem, get rid of `buttonIn`, and in `setup()` use `pinMode(button,INPUT)` to set `button` to be an input, not an output.


message:
Listen for specific frequency

I’m trying to build a custom baby monitor for my wife who is deaf. It needs to detect loud noises and listen for a specific series of tones from a feeding pump our daughter uses.  It will then send a radio signal to the other room to trigger a bed shaker.

I do have a loop which samples the **MAX4466** microphone and uses a “peakToPeak” calculation to determine volume, which I can use to trigger for loud noises (pasted below).  However, **I cannot figure out how to determine the frequency of a noise sample.**  I’ve tried searching for other sketches and tutorials that would work, but haven’t found anything.  The feeding pump, when it has an error puts out a series of tones which alternates between 4.1 kHz and 2.1 kHz.   What I wanted to do is see if the first tone is sounding, and then if the second tone shows up within a couple seconds afterwards, then it would trigger sending the signal to the other device.

I’ve tried for two days now to find a way to determine the frequency, but haven’t figured it out.  Any help would be *greatly* appreciated.  The closest I was able to get was this: [Instructables - Arduino Frequency Detection][1], but when I use this script, the Arduino can no longer do `analogRead()` to get the status of various setting knobs and such I have on the device.

The script I use to get the sound level / loudness is:

      #define micPin 0                      // Microphone
      const int sampleWindow = 96;          // Sample window width in mS (50 mS = 20Hz)
      unsigned int sample;
        while (millis() - startMillis < sampleWindow) {
          sample = analogRead(micPin);
          // Check peakToPeak mins and maxs
            if (sample < 1024) {
              // toss out spurious readings
               if (sample > signalMax) { signalMax = sample; }          // save just the max levels
               else if (sample < signalMin) { signalMin = sample; }     // save just the min levels
            }
        }
        peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude

  [1]: http://www.instructables.com/id/Arduino-Frequency-Detection/

body:
With a microphone listening for one frequency in ambient audio you have to do far more than just count cycles or measure time between crossings.

You have to sample a burst of audio into a buffer at a minimum of double the rate of the highest frequency you are interested in. Then you need to analyse that audio sample to determine the amplitudes of the different frequencies within it. FFT (Fast Fourier Transform) is the most popular method of doing that, and there are integer maths based libraries and examples around on the internet suitable for running on an Arduino.


body:
You can use a [DFT(Discrete Fourier transform)][1] that just checks the component frequency magnitude at 4.1kHz and 2.1kHz. Below is some code that works for my Arduino UNO. When I put a signal generator on A0 with a 2.3V(peak to peak) sine wave, the result goes above 0.5 at the respective frequencies.

    float Single_Point_DFT(int16_t inputArray[], int startingIndex, int endingIndex, float sampleFreq, float freqToSampleFor){
      float N = endingIndex - startingIndex + 1; //N=number of samples
      float k = freqToSampleFor * N / sampleFreq;
      float radiansPerSample = 2.0 * 3.14159 * k / N;

      float RealSum = 0;
      float ImaginarySum = 0;
      for (int n = 0; n <= endingIndex - startingIndex; n++){
        float angle = n * radiansPerSample;
        float voltage = inputArray[startingIndex + n] * (5.0 / 1023.0);

        RealSum += voltage * cos(angle);
        ImaginarySum -= voltage * sin(angle);
      }

      return sqrt(RealSum*RealSum + ImaginarySum*ImaginarySum) / N;
    }

    const int analogInPin = A0;
    uint32_t startTime_uS;
    uint32_t endTime_uS;

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

    void loop() {
      int16_t values[128];

      while(1)
      {
        startTime_uS = micros();
        for(uint8_t n = 0; n<128; n++)
        {
          values[n] = analogRead(analogInPin);
        }
        endTime_uS = micros();

        float sampleFreq = 128.0*1000000.0/(endTime_uS - startTime_uS);
        float result = Single_Point_DFT(values, 0, 127, sampleFreq, 2100);
        Serial.print(result);
        Serial.print(", ");
        result = Single_Point_DFT(values, 0, 127, sampleFreq, 4100);
        Serial.println(result);
      }
    }

This calculation is pretty slow due to the float arithmetic and the sine/cosine calculations, But is is fast enough if the beeps last longer than a quarter of a second.

  [1]: https://en.wikipedia.org/wiki/Discrete_Fourier_transform


body:
As stated in previous answers, frequency measurement is unlikely to be
reliable because the microphone is going to pick up ambient noise, which
is a combination of many individual frequencies. You want instead to see
how much sound amplitude you have at the specific frequency of the
feeding pump. Fourier analysis seems like the natural tool for the job.

However, a Fourier transform is heavy math, and overkill for your
application. You are only interested in the Fourier amplitude at one
specific frequency. Computing that single amplitude is way easier and
faster than doing a full-fledged Fourier transform.

My preferred method for doing that is called [homodyne detection][]. It
is fast enough to be done _in real time_ by an Arduino Uno sampling at
9.6 kHz. Basically you multiply the input signal by both a sine and
a cosine at the target frequency, then you low-pass filter both
products. The two resulting signals are the real and the imaginary part
of the complex amplitude you are looking for.

Here is a small program of mine that does _almost_ exactly what you are
looking for: [homodyne.ino][]. It is set for one specific frequency
(1 kHz, but it's trivial to change), and you will have to adapt it
to be able to change the target frequency between 4.1 and 2.1 kHz.

[homodyne detection]: https://en.wikipedia.org/wiki/Homodyne_detection
[homodyne.ino]: https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6


body:
A few ways, fft, 1057, or sin multification. Fft is quite calculation and space intensive, even in interfere form. For the detection of a known frequency, 1057 can be very efficient.

Multification is iterative so space and mips efficient. But you will need to filter and it detects with a delay.

A more efficient way is hardware filtering followed by rectification .


message:
Sidestep one second log rate with NeoGPS when another sensor on the board need to log faster

The sample rate of an accelerometer, like an MPU6050, is much faster than the GPS log rate, different technology, different issues.
A common GPS Reciver has, approximatly, one second log rate.
In my specific case the accelerometer has a 100hz log rate.

With a previous code the gps log rate was slowing down the accelerometer log rate so i thought to introduce two counters:

 - one for the gps
 - one for the accelerometer

What i tried to do was:

      if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
      //Log accelerometer and gps data
      } else ((  if ((lastLog + LOG_RATE) <= micros()) {
      //Log only Accelerometer data
      }

----------

 **1. Is that a speed and memory efficient solution? Or better way exist*?**

**2. During a 60 seconds test the board return me only the accelerometer value, never the satellites informations, i think there are some dumb errors in my code**

----------

Thanks for your help :)

This is the void loop section

    void loop()
      {
        Wire.beginTransmission(MPU);
        Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
        Wire.endTransmission(false);
        Wire.requestFrom(MPU,14,true);   // request a total of 14 registers
        AcX=Wire.read()<<8;
        AcX|= Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
        AcY=Wire.read()<<8;
        AcY|=Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
        AcZ=Wire.read()<<8;
        AcZ|=Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
        GyX=Wire.read()<<8;
        GyX|=Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
        GyY=Wire.read()<<8 ;
        GyY|=Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
        GyZ=Wire.read()<<8;
        GyZ|=Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
        if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
        while (gps.available( gpsPort )) {
        fix = gps.read();  // get the entire fix structure, once per second

        if (logGPSData()) { // Log the GPS data
        SerialMonitor.println( F("GPS logged.") ); // Print a debug message
        } else {// If we failed to log GPS
        // Print an error, don't update lastLog
        SerialMonitor.println( F("Failed to log new GPS data.") );
          }
        }
       lastLogGPS=micros();
      }
      else{
        if ((lastLog + LOG_RATE) <= micros()) {

          printImuData(dataFile,lastLog, AcX, AcY, AcZ, GyX, GyY, GyZ);
          dataFile.flush();
          }
        lastLog=micros();
        }
      }

This the function that print only the accelerometer informations:

    static void printImuData(Print &printer, unsigned long lastLog,
            int16_t AcX, int16_t AcY, int16_t AcZ,
            int16_t GyX, int16_t GyY, int16_t GyZ)
    {//Printing the mpu6050 information

      printer.print("0");   printer.print(",");   //0 longitude
      printer.print("0");   printer.print(",");   //0 latitude
      printer.print("0");   printer.print(",");   //0 altitude
      printer.print("0");   printer.print(",");   //0 speed
      printer.print("0");   printer.print(",");   //0 course
      printer.print("0");   printer.print(",");   //0 date
      printer.print("0");   printer.print(",");   //0 time
      printer.print("0");   printer.print(",");   //0 satellites
      printer.print(lastLog); printer.print(",");
      printer.print(AcX);     printer.print(",");
      printer.print(AcY);     printer.print(",");
      printer.print(AcZ);     printer.print(",");
      printer.print(GyX);     printer.print(",");
      printer.print(GyY);     printer.print(",");
      printer.println(GyZ);

    }

And this is the part for the GPS informations:

    byte logGPSData()
    {
      if (dataFile.isOpen())
      { // Print longitude, latitude, altitude (in feet), speed (in mph), course
        // in (degrees), date, time, and number of satellites.

        if (fix.valid.location)
          dataFile.print(fix.longitude(), 6);
        dataFile.print(',');
        if (fix.valid.location)
          dataFile.print(fix.latitude(), 6);
        dataFile.print(',');
        if (fix.valid.altitude)
          dataFile.print(fix.altitude() * 3.2808, 1);
        dataFile.print(',');
        if (fix.valid.speed)
          dataFile.print(fix.speed_mph(), 1);
        dataFile.print(',');
        if (fix.valid.heading)
          dataFile.print(fix.heading(), 1);
        dataFile.print(',');

        if (fix.valid.date) {
          dataFile.print( fix.dateTime.full_year() );
          if (fix.dateTime.month < 10)
            dataFile.print( '0' );
          dataFile.print( fix.dateTime.month );
          if (fix.dateTime.date < 10)
            dataFile.print( '0' );
          dataFile.print( fix.dateTime.date );
        }
        dataFile.print(',');

        if (fix.valid.time) {
          if (fix.dateTime.hours < 10)
            dataFile.print( '0' );
          dataFile.print( fix.dateTime.hours );
          if (fix.dateTime.minutes < 10)
            dataFile.print( '0' );
          dataFile.print( fix.dateTime.minutes );
          if (fix.dateTime.seconds < 10)
            dataFile.print( '0' );
          dataFile.print( fix.dateTime.seconds );
        }
        dataFile.print(',');

        if (fix.valid.satellites)
          dataFile.print(fix.satellites);
      dataFile.print(',');
      dataFile.print(lastLogGPS);
        dataFile.print(',');
        dataFile.print(AcX);
        dataFile.print(',');
        dataFile.print(AcY);
        dataFile.print(',');
        dataFile.print(AcZ);
        dataFile.print(',');
        dataFile.print(GyX);
        dataFile.print(',');
        dataFile.print(GyY);
        dataFile.print(',');
        dataFile.print(GyZ);

        dataFile.println();
        dataFile.flush(); // make sure the file contains at least this much

        return 1; // Return success
      }

      return 0; // If we failed to open the file, return fail
    }

Here a pic of some data returned by Arduino
[![enter image description here][1]][1]

*I need to load easily the *.csv whith the recorded data on matlab so i have some constraints.

  [1]: https://i.stack.imgur.com/vTfCU.png

body:
Ok, I won't recreate your whole code, but here is a logic snippet that you can use.

Let's suppose that you have 2 sensors, `sensor1` and `sensor2`.

`sensor1` is read every 10 milliseconds and `sensor2` is read every 16 milliseconds.

Here is what you would do:

Make 2 global variables for your timers :

    unsigned long timer1 = 0;
    unsigned long timer2 = 0;

Then make 2 constants for the frequency, this example will set the frequency in milliseconds.

    const int frequency1 = 10;
    cosnt int frequency2 = 16;

Then in your void loop, you would do something like this:

    void loop () {
        if (timer1 + frequency1 >= millis()
            read(sensor1);
            timer1 = millis();
        }

        if (timer2 + frequency2 >= millis()
            read(sensor2);
            timer2 = millis();
        }
    }

 This method makes sure that your code isn't going to get *stuck* anywhere. I would also suggest to remove any `while` loops because of that danger that it might *freeze&* your code.


message:
Wi-Fi module 5 GHz

What is a Wi-Fi module for an Arduino that works on 5 GHz? The ESP8266 - doesn't support 5 GHz according to:

 - [Re: 802.11AC 5GHz][1]
 - [Why can't ESP8266 operate in 5 GHz since 802.11N is supported][2]
 - my own experiments.

  [1]: https://forum.sparkfun.com/viewtopic.php?f=13&t=42757#p187292
  [2]: http://www.esp8266.com/viewtopic.php?f=6&t=4032

body: I asked Microchip a while back if they planned to release a 5GHz WiFi module at any point in the near future. The answer was basically "No, there would be no benefit to it." For embedded systems there is no point in 5GHz since 2.4GHz is more than adequate and there are better long range solutions than WiFi (LoRa for instance).


message:
Nano-like Board - Programmer Not Responding

I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

 - [Semi-compatible nano-like board][1]
 - Drivers
 - Arduino IDE 1.8.3 freshly installed
 - Windows 10 64-bit
 - Also tried on Mac OSX with the same result

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:

    avrdude: stk500_recv(): programmer is not responding

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the **same COM port as what it's listed as in Device Manager**. Assuming that all of those are correct, I have tried a few things with no luck:

 - Reinstalling the IDE, drivers and restarting my computer.
 - Letting Windows find its own driver.
 - Pressing the 'reset' button just before hitting 'upload' in the IDE
 - Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?

**Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.**

  [1]: https://www.amazon.com/Nano-V3-ATmega168-Compatible-soldered/dp/B072HN77N1/ref=sr_1_31?s=electronics&ie=UTF8&qid=1497035619&sr=1-31&keywords=arduino nano

body:
That is a Chinese NANO clone, using the notorious CH340G chip.

`macOS` does **NOT** have a driver, and it is difficult, if not impossible to get a driver which 1. `macOS` will let you install, and 2. Actually works.

I do not know the state with current Windows.

In my experience, in addition to poor support the chips are unreliable and fail to respond.

You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.


body:
For issues like this, you have to narrow down the problems first. For example

 is the computer plus programmer combo able to program any avr? If so, the issue us with your target, including wiring.

If not, can the programmer able to program any chip? If so, the issue is with your pc plus programming software.

...

Going backwards and with solid logic, which means making zero assumption, you will narrow the issues down further.


message:
What is the meaning of the preceding character on several library defines?

I have been reviewing the code for several libraries,mostly by SparkFun, and looking at the defines for for instance the chip select pins for their hardware.

In the defines, rather than being a simple number or string, they have the following syntax:

    #define P_MOSI B,3

with others being preceded by a `D` instead.

I am surmising this may be a data type definition, but I don't recognise the syntax and am wondering

 1. What does the syntax mean?
 2. What is the effect of nominating the data type of a define?
 3. Is this Arduino specific syntax or general to C/C++?
 4. If I want to modify a value, is it as simple as changing the value after the comma?

body:
    #define P_MOSI  B,3

This is a C style macro definition. During the pre-processor phase of compilation where ever the text `P_MOSI` is encountered it will be replaced with the text `B,3`.

This is a purely textual replacement with no understanding of the semantic meaning of what is being replaced.  So the validity of the macro will depend on where it is being used.

I am not familiar with how this macro is being used in the library code you are looking at, but from what I have seen from a quick google this macro is used to define things on a per-chip architecture basis.  EG for an ATmega16 it is

    #define P_MOSI B,5

But for a AT90USB82 it is

    #define P_MOSI  B,2

So if you are trying to adapt a library to your processor you will need to change the macro to suit your architecture.

In general such defines are used to adapt the same code across multiple architectures.  For instance here is a snippet of something I found when googling

    #if (BUILD_FOR_MCP2515 == 1)
     #if defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) || defined(__AVR_ATmega644__)
      #define P_MOSI B,5
      #define P_MISO B,6
      #define P_SCK B,7
      #define SUPPORT_FOR_MCP2515__
     #elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__)
      #define P_MOSI  B,2
      #define P_MISO  B,3
      #define P_SCK   B,1
      #define SUPPORT_FOR_MCP2515__


body:
While we can't see how the macro is being used, it may be worth noting that, on Uno's built-in SPI interface, the MOSI signal is on port-B, bit 3.

Update:

> the architecture is broken down into ports and pins.

The AVR processors use memory-mapped, byte-wide I/O ports, where each bit mapped to a physical pin (actually to a multi-function pin-driver/receiver). The Arduino programming environment defines symbols such as `PORTB` to be the addresses of those ports. It further defines single-pin I/O functions (`digitalRead()`, `digitalWrite()` ) that "know" the mapping of pin numbers to ports and bits as implemented in each processor. Most people rely on the single-pin functions but the ability read and write the ports directly is there if you need it. And note that the Arduino pin numbers *do not match* the physical pin numbers of the pins at the exterior of the chip, but it does match the numbers silk-screened on the PCB. While this relieves you from having to deal with that mapping, it makes those low level details somewhat less visible.


body:
I looked into one of these libraries, namely the [SparkFun CAN-Bus
Arduino
Library](https://github.com/sparkfun/SparkFun_CAN-Bus_Arduino_Library).
The macro appears to be used inside other macros that require two
arguments, for example `RESET(P_MOSI);`. Given the following
definitions from the library:

    #define RESET(x) _XRS(x)
    #define _XRS(x,y) PORT(x) &= ~(1<<y)
    #define PORT(x) _port2(x)
    #define _port2(x) PORT ## x
    #define P_MOSI B,3

the call `RESET(P_MOSI);` expands to

    PORTB &= ~(1<<3);

`PORTB` is the name of an IO port of the MCU which controls the outputs
of the pins. It is actually a macro from
[avr-libc](http://www.nongnu.org/avr-libc/) that expands to something
like:

    (*(volatile uint8_t *)(0x05 + 0x20))

where `0x05` is the IO port number of the register (the number depends
on the particular AVR chip) and `0x20` is an offset needed to get the
memory-mapped address from the IO port number. When the compiler does
constant folding, `RESET(P_MOSI);` resolves to

    *(volatile uint8_t *)0x25 = 8;

which is then compiled into

    cbi 0x05, 3

a single assembly instruction (Clear Bit in Io port) that executes in
two CPU cycles and sets to zero the bit 3 of IO port 0x05.

The same end result could be achieved in a much simpler way:

    #define P_MOSI 11  // assuming digital 11 = PB3, as in the Uno
    #define RESET(x) digitalWrite(x, LOW)

However, the function `digitalWrite()` is very slow, mostly because it
has to map an Arduino pin number to a port address and a bit number, and
it does it at _run time_. The SparkFun approach, though somewhat
convoluted, is _way_ more efficient, because the mappings are performed
at _compile time_.


message:
Serial.read() always returns 255

So I'm trying to learn basic Android app dev. My master plan was to make an app using MIT App Inventor that would turn on an LED over Bluetooth using an Arduino. Once I verified that everything worked, I would write the entire app from scratch using Android Studio. This way, when I inevitably run into bugs with my written-from-scratch app, I could say with 100% certainty that the issue is in my Android code and not hardware/Arduino related.

So I'm having trouble right now. I have two separate LED circuits, a blue LED from port 13 and a green LED from pin 8. I verified that both circuits are working properly by using the Blink code, so I know the issue is definitely not with the LED circuits.

I'm using an HC 06 Bluetooth module. The pins are connected as follows:

HC 06 -> Arduino

RX -> TX

TX -> RX

5V -> 5V

GND -> GND

Here is the Arduino code:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    SoftwareSerial bluetooth(0,1);
    int ledblue = 13;
    int ledgreen = 8;
    int tx = 1;
    int rx = 0;
    int type;

    void setup() {
      Serial.begin(9600);
      //bluetooth.begin(9600);
      pinMode(ledblue, OUTPUT);
      pinMode(ledgreen, OUTPUT);
      pinMode(tx, OUTPUT);
      pinMode(rx, INPUT);
      allpinslow();
    }

    void loop() {
      int i = 0;
      int m = 0;
      delay(500);
      if (Serial.available() > 0) {
        while(Serial.available() > 0){
          type = Serial.read();
          Serial.println(type);
        }
        Check_Protocol(type);
      }
    }

    void allpinslow()
    {
      digitalWrite(ledgreen, LOW);
      digitalWrite(ledblue, LOW);
    }

    void Check_Protocol(int inStr) {
      int i = 0;
      int m = 0;
      if (inStr == '0') { //Led Off equals("2off")
        allpinslow();
      }
      if (inStr == '1') { //Led on
        digitalWrite(ledblue, HIGH);
      }
      if (inStr == '2'){
        digitalWrite(ledgreen,HIGH);
      }
    }

Here is the MIT App Inventor block code

[![MIT App Inventor block code][1]][1]

If I press the Green or Off button, the Serial Monitor spits out 255. If I press Red, nothing shows up on the serial monitor. I'm a bit dumbfounded on what is broken so I would greatly appreciate any help I can get.

  [1]: https://i.stack.imgur.com/C0Gcq.png "MIT App Inventor block code"

Edit: @Delta_G here is the modified code

    #include <SoftwareSerial.h>
    int ledblue = 13;
    int ledgreen = 8;
    SoftwareSerial mySerial(2,4); //RX, TX
    int type;

    void setup() {
      Serial.begin(9600);
      mySerial.begin(9600);
      pinMode(ledblue, OUTPUT);
      pinMode(ledgreen, OUTPUT);
      allpinslow();
    }

    void loop() {
      int i = 0;
      int m = 0;
      delay(500);
      if (mySerial.available()) {
        while(mySerial.available()){
          type = mySerial.read();
          Serial.println(type);
        }
        Check_Protocol(type);
        //Serial.println(inSerial);
      }
    }

    void allpinslow()
    {
      digitalWrite(ledblue, HIGH);
      digitalWrite(ledblue, LOW);
    }

    void Check_Protocol(int inStr) {
      int i = 0;
      int m = 0;
      if (inStr == '0') { //Led Off equals("2off")
        digitalWrite(ledblue, LOW);
        digitalWrite(ledgreen, LOW);
      }
      if (inStr == '1') { //Led on
        digitalWrite(ledblue, HIGH);
      }
      if (inStr == '2'){
        digitalWrite(ledgreen,HIGH);
      }
    }

body: If you are using Serial then you can't use pins 0 and 1 for something else as those are the hardware serialpins. Pick different pins for the Bluetooth.


body:
From reading the comments, I assume you are using an Arduino Uno,
and you have a PC (or Mac, or any type of computer) connected to its USB
port, and an Android device at the other end of the Bluetooth link.

I can't see what is wrong with your sketch. I will then only suggest two
methods for checking the low-level communication is working properly.
Once you know the communication is good, debugging should be easier.

## Test bypassing the microcontroller

**First**, load an empty sketch in the Arduino, **then** connect the
Bluetooth module as follows:

    HC 06   Arduino
    ───────────────
     GND ─── GND
      5V ─── 5V
      RX ─── RX
      TX ─── TX

It is important to load the empty sketch first: you do not want the
Arduino to access its hardware serial port. Now you can open your serial
monitor on the PC, set to 9600/8N1.

With this setup, the HC 06 will be using the USB/serial bridge of the
Arduino (the ATmega16U2), whereas the main microcontroller (the
ATmega328P) is just a bystander. Whatever the HC 06 outputs through its
TX should appear on your serial monitor. The data path is as follows:

    ┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
    │ Android │ ──────────→ │ HC 06 │ ───────┐ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
    └─────────┘             └───────┘        │ └──────┘ │   └──────┘       └────┘
                                             └──────────┘

Note the 328P disconnected from the serial link.

## Test with an echo sketch

Load the following sketch:

<!-- language: c++ -->

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

    void loop()
    {
        if (Serial.available())
            Serial.write(Serial.read());
    }

then connect the Bluetooth module as follows:

    HC 06   Arduino
    ───────────────
     GND ─── GND
      5V ─── 5V
      RX ─── TX
      TX ─── RX

With this setup, whatever the HC 06 outputs on its TX should appear on
your serial monitor **and** should be sent back through Bluetooth. The
data path is:

    ┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
    │ Android │ ──────────→ │ HC 06 │ ───────→ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
    │         │ ←────────── │       │ ←──────┐ └──────┘ │   └──────┘       └────┘
    └─────────┘             └───────┘        └─────┴────┘

Note that the output of the 328P is received by both the 16U2 and the
HC 06. Since the Android device seems to ignore whatever it receives
through Bluetooth, the setup should work fine for debugging you app too.


body: Update: It was a faulty Bluetooth module that was causing the issues. I bought a new one and everything works perfectly!


message:
Some questions about a RGB LED Strip project that Im planning to do

Good day all

So Im in the planning and research phase of a new project that I want to start for my car. I want to control a bunch of RGB LED strips independently from each other via a micro controller, preferably Arduino  of courese, with a breakout board or something. I am going to run this system off the car battery so the current shouldn't be an issue, I hope, but prolonged usage will most likely drain the battery quite quickly. The strips I want to control are of the following lengths:

 - 6 x 30cm Pieces
 - 3 x 2m Pieces

So I want to be able to control all of them individually as well as the colour and brightness individually. So here are my questions:

Is there a board that the arduino can talk to that has 27 PWM outputs?
Can one maybe use normal outputs and just HIGH Low them quickly in sequence and use an arduino MEGA?
What would the current draw be if all the colours are on full on all strips? Would  it rather be better to blink them in sequence,rather than full on, and lose some brightness to reduce current draw?
Could multiplexing here be an alternative to controlling them individually? Maybe get it so I switch all the Positive outs of the LEDs, and the connect the 3 colours together. So in that case I would have 3 + 9 outputs?
Would addressable LEDs actually work better?

If you could refer to me to similar projects so I can sniff around there that would be greatly appreciated. So far Im just trying to wrap my head around all the aspects of the project. And yes I know that I wil not be able to use this while Im on public roads, its just for show.... So not sure what the legal aspects there are... :P

body:
You could use chainable RGB drivers like these:

[![P9813][1]][1]

They are based on the P9813 chip and can be used with the [FastLed library][2].
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".

  [1]: https://i.stack.imgur.com/CRuWA.jpg
  [2]: https://github.com/FastLED/FastLED


message:
Measuring distance based on time

I have written a arduino sketch which is used to measure the distance travelled. Since `distance = speed * time` , I have initiated speed = 6. I have initiated `time = millis()` variable and it calculates the time in millis().

So, `distance` is calculated as `(speed*time) /1000` and we get distance for every second.

Now, as soon as the `distance==20`, I want to print `distance` and then delay for 5 seconds. So, as soon as `distance==20` implies `time = 4000` . If I delay for 5 seconds, time becomes 9000. But I want time to start from 4000 itself. So I have initiated another variable called `curTime = time - prevTime`.At the start, `prevTime = 0`. Code:

    int prevTime = 0;
    void loop(){
      unsigned long time = millis();
      unsigned long curTime = time - prevTime;
      int speed = 6;
      unsigned long distance = (speed * curTime)/1000;
      Serial.println(distance); // displays values of distance
      if(distance == 20){
        Serial.println(distance);
        delay(5000);
        prevTime = time;
      }
    }

So `prevTime = 4000` if distance == 20.
After this, time will be equal to 9000 and curTime will be 9000-4000 which equal 5000. So the distance will be 30 skipping all the values between 20 and 30. I don't want the distance to skip the values between 20 and 30. I have tried a lot but couldn't achieve it. Please help me fix this.

Thanks.

Link for code:

https://circuits.io/circuits/5260912-the-unnamed-circuit/edit

body:
When `distance == 20` you pause for 5 secs. So all calculations after that will be off by 5 secs. So, `prevTime` should equal 5000.

    unsigned long time = millis();
    unsigned long curTime = time - prevTime;    // 0 or 5000
    int speed = 6;
    unsigned long distance = (speed * curTime) / 1000; // calculating distance in meters for every milli second
    Serial.println(distance);
    // Only pause once
    if (distance == 20 && prevTime == 0) {
      delay(5000);
      prevTime = 5000;  // Adjust for the delay
    }


message:
Is Arduino Ethernet shield compatible with arduino due?

Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

body:
The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can *tolerate* connection to a 5v Arduino.

Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.

However, you should review the [the full schematics][1] and **make your own determination** that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.

It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

----------

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  *An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.*

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-Ethernet-Shield2-V2-sch.pdf


message:
Is there any way to use the serial port as an interruption source?

I have an sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.

By checking out the reference on [attachInterrupt()][1], I found only the ways to declare interruption pins, but nothing related to serial. What you can say about it?

Thanks in advance.

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt

body:
Here is a logic snippet you can use:

    unsigned long timer = 0;

    void loop(){
      readSensors();
      while(millis() - timer < 10000){
        if(stringFromSerial == magicWord){
          readSensors();
        }
      }
    }


body:
Use `millis()` for the timing of the temperature reading, then you can read from the serial in between time and won't need to use any interrupts.

<!-- language: c++ -->

    unsigned long last_measure = 0;

    const byte buffer_size = 16;
    char buffer[buffer_size] = "";
    byte buffer_i = 0;

    // setup() and other stuff

    void loop() {
        if (millis() - last_measure > 10000) { // read the temperature like in the "blink without delay" example
            last_measure = millis();
            int value = readSensor();
            Serial.println(value);
        }
        while (Serial.available()) {
            char c = Serial.read();
            if (c == '\n') { // end of line, which means we got the whole string
                if (strcmp(buffer, "magic") == 0) { // compare if it matches the magic word
                    int value = readSensor(); // read and print the temperature
                    Serial.println(value);
                }
                buffer_i = 0; // reset the index
                buffer[buffer_i] = 0;
            }
            else if (buffer_i < buffer_size-1) { // if the buffer is not full
                buffer[buffer_i++] = c; // add char to buffer
                buffer[buffer_i] = 0; // and null terminate the string
            }
        }
    }


body:
Thank you all, guys. I considered your ideas, and then I code this solution. It works fine, right now I'm reading my sensor once every 30 minutes (1,800,000 miliseconds) and whenever I send the magic word. I hope it is useful to you:

    void loop(){
    if ((millis() - timer < 1800000) && (Serial.available() > 0)){
        magicInput = Serial.readString();
        magicInput.trim(); //Cleans input from \n at the end, otherwise never equals magicInput
        if (magicInput.equals(magicWord)){     //Elegant form for "=="
          Serial.println();
          Serial.println("  === Your request ==="); //Shows requested measurement
          Serial.println(millis() - timer); //Time since last measurement
          measure(); //
        }
      }

      if (millis() - timer >= 1800000){
        Serial.println();
        Serial.println("===== Normal mode =====");  //Indicates that measurement was not requested by user
        Serial.println(millis() - timer); //Checks that 30 "exact" minutes have run
        mide();
        timer = millis();
      }
    }


message:
Global variables with C++ in multiple files

I'm not a C++ programmer (but I have used regular C code for implementing low-level machine language equivalent SW for some time), and after trying to modify an existing cC+ program to do what I need (and failing), I've decided to rewrite parts of the code in plain C code.

But to be able to use the data, I need to create some variables that have to be accessible to parts of the existing C++ code.

When I declare a global variable (`extern int variable name;`) outside the main program, the compile fails because the references to the global variable aren't within the scope of the cpp parts of the program.

I don't program with multiple files myself, so I was wondering if I need to globally declare the same variables as part of each cpp program that needs to have access to the variables? Is there a another/better way?

body:
When using multiple source files you need to use header files to share things between them.

myproject.h:

    #ifndef __myproject_h__
    #define __myproject_h__
    extern int aGlobalVariable;
    #endif

myNewCode.c

    #include "myproject.h"
    int aGlobalVariable;

modifiedOldCode.cpp

    #include "myproject.h"

This way the header file defines the variable as an extern in all of your c / cpp files so that it is visible to all of them but the variable is only actually declared and memory allocated for it in one place, in the .c file.

Similarly any functions that you want to be visible in both files should be declared in the headerfile (e.g. `void myfunction(int x);`) but the actual definitions should be somewhere in the .c or .cpp files.

The #ifndef and #define lines in the header as there so that if the header somehow gets included twice you don't get lots of redefinition errors.

There is nothing strange about c++ and globals, a global defined this way is global to everything, it doesn't matter what object you're in or how things are scoped. This can however have some strange effects since there is only ever one copy of a global while you can possibly have multiple instances of the c++ class that uses it. This can cause some consistency related issues if you aren't careful. Whether you need to worry about this or not depends very much on the nature of the code.


message:
Can't get constant reading with load cells

I'm really a newcomer to arduino and I'm trying to build a scale with four SEN-10245 load cells and a HX711. My issue is that I can't get constant readings in the serial monitor and I'm not sure if my coding is right or if I did the right setup.
I made the following setup, based on some examples I found online:

![setup on the board](https://i.stack.imgur.com/wLmd8.jpg)
![setup ](https://i.stack.imgur.com/BeC1p.jpg)
![hx711 and protoboard](https://i.stack.imgur.com/yopDg.jpg)

The code I'm using is as follows:

        #include <hx711.h>
        Hx711 scale(A1, A0);
        void setup() {
        Serial.begin(9600);
        }
         void loop() {
         Serial.println(scale.averageValue());
         delay(200);
        }

link for the library github: https://github.com/aguegu/ardulibs/tree/master/hx711

Please help me, i'm a total beginner.

body:
Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.

Making the wires much shorter would likely also help. That would be a good test to see if it helps.

The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.


message:
Getting more current through an LED array

I have an Arduino Uno controlling an array of 24 LEDs ([datasheet][2]).  I understand these LEDs are ultraviolet and have a forward current of 0.5A.  My power source (12V 2A) is wired to a switch which is then wired to the LED array and Arduino.  I should probably use a 12V 4A power source but was worried if too much current would go to the Arduino.  As per my attached diagram, the Arduino and LED array are in parallel.  I would like to get more current through my LEDs to increase their brightness.  What would be the best way to do this?

Updated: I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.  And then I tried a 1 Ohm resistor instead but the resistor burned out.  Unfortunately, I threw out the resistor and don't have a picture of it.  I believe the correct value should be ~47 Ohm so I have added that resistance as R11.  However, I haven't tested it yet as I want to make sure it's correct.  (12V - 6V) = 130mA * R >>> R = 46.15 Ohm.  I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V).  I measured the current through a multimeter to be 130mA.

[![Updated schematic with resistor values][1]][1]

  [1]: https://i.stack.imgur.com/Rkc4V.png
  [2]: http://www.mouser.com/ds/2/427/vlmu3500xxx120-968628.pdf

body:
The current a bipolar transistor configured as a [common emitter amplifier][1] will allow from its collector to its emitter is equal to its [beta][2] time the base to emitter current.

A beta of 100 is common for many transistors. Assuming this information is close enough to your transistor, we can choose a base series resistance suitable for the collector to emitter current desired.

For example if you were using a 5 volt microprocessor and the voltage drop across the base to emitter was the usual 0.7 volts for silicon semiconductors and you had a base series resistor of 10Kohms:

    V = I * R
    V = 5 - 0.7 = 4.3 volts
    R = 10000 ohms
    I = 4.3/10000 = 0.43mA
    I(ce) = Beta * 0.43mA
    I(ce) = 100 * 0.43mA = 43mA

You could pass up to 43mA from the collector to the emitter.  If that is not enough,you can lowered the base resistor to 1Kohms:

    R = 1000 ohms
    I = 4.3/1000 = 4.3mA
    I(ce) = Beta * 4.3mA
    I(ce) = 100 * 4.3mA = 430mA

And increase the current to 430mA.  You still need to verify that the processor can supply the current to control the transistor (4.3mA as calculated above) as well as pick a transistor of sufficient capacity to handle the load.

If a beta of about 100 is not enough, consider using a [Darlington transistor][3] arrangement. This type of "2 transistor" device has a gain of the product of each individual transistor's beta.  So, it is common for such a device to have a beta of 10000!  Using this device, you can use a much larger base resistor and still be able to switch more current.

  [1]: https://en.wikipedia.org/wiki/Common_emitter
  [2]: https://en.wikipedia.org/wiki/Bipolar_junction_transistor#Transistor_parameters:_alpha_.28.CE.B1.29_and_beta_.28.CE.B2.29
  [3]: https://en.wikipedia.org/wiki/Darlington_transistor


body:
> I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.

You should not have a resistor in the Arduino's supply line at all.

>And then I tried a 1 Ohm resistor instead but the resistor burned out.

If you really wanted to have one to share the heat load of the on-board regulator, it would need to be a `power resistor` of appropriate wattage rating.

>I believe the correct value should be ~47 Ohm so I have added that resistance as R11...I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V). I measured the current through a multimeter to be 130mA.

This is incorrect.

The Arduino's regulator needs something like 7 volts input to operate correctly.

The power drawn by the Arduino will not be fixed, it will depend on what it is doing, what I/Os are exerted against what loads, and other things like the LCD you apparently have.

Likely, if you want to use a power resistor you should design it to drop no more than half of the difference between the supply voltage and the regulator dropout voltage, under conditions of *maximum* load.  A fixed power resistor cannot be used to *replace* the *variable power resistor* that is a linear regulator; at most it can be used to offset some of the *fixed* part of the resistance and resulting thermal load.  But you still have to leave all of the variable part plus a healthy margin for the regulator to handle, or it won't be able to regulate.

It would be simpler to just put a heatsink on the regulator.


message:
Sending JSON message to web api via post. Why does HTTP 1.0 versus 1.1 make a difference?

I am sending a message to a web api call every xx seconds. I could not get it to work at all until I changed the header from HTTP 1.1 which is what I was using to HTTP 1.0. Then, it started working. Why would this affect things where I could not post and now I can?

This is what it was when it wasn't working:

    client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.1");

And the change that fixed it:

    client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.0");

Thanks!

body:
HTTP/1.1 requires you to provide the host name of the server. And it will keep the connection open for some time unless you explicitly opt out of this. Thus, the equivalent of the basic HTTP/1.0 request in HTTP/1.1 language is

    POST /the_uri HTTP/1.1
    Host: foo.example.com
    Connection: close


message:
Rounding up and Down

My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5.
Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.

Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.

Thanks in Advance!

body:
You can round in C by multiplying for the significance, adding +0.5, round down (equals as casting to an integer) and divide.

    float f_rounded = ((int) (f * 10.0 + 0.5) / 10.0);

28.6 will be:

    float f_rounded = ((int) (28.6 * 10.0 + 0.5) / 10.0)
                    = ((int) 286.5) / 10.0 = 286 / 10.0 = 28.6

In Python it is equal (except the cast operator is int(...)

Update: for negative numbers +0.5 should be -0.5

Credits for Edgar Bonet: using round works for both positive and negative numbers:

    float f_rounded = round(f * 10) / 10.0;


body:
As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do `Serial.print( value, 1);`

Without extra parameter, the default is choosen, which is 2 decimal digits: `Serial.print( value, 2);`

Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.


message:
How can I use the NRF24L01 modules without a library?

The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.

body:
You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).

However, for this, you need to understand the library, and therefore high likely the datasheet too.

You also can start without looking at a library, but your only documentation source is the datasheet itself.

A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.


message:
send sketch to arduino via wifi

I'm pretty new to arduino and need some help.

My task is to connect my UNO R3 to wifi AND then send data (sketch for blinking led) to it.
I successfully connected my arduino with my wifi, but how do I send the sketch?

I didn't find a tutorial for this. Do you know a good one or can you help me, please?

body: There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.


body:
You can't with a normal Arduino and WiFi shield.

However it is possible (if you are cunning) to do it with the ESP8266.

The basic idea is that you program an ESP8266 module to act like a transparent TCP/IP to UART bridge. Connect it to the TX and RX pins of the Arduino, listen on a port number of your choice, then when you connect to it (with telnet, netcat, socat, etc) all data is forwarded directly back and forth to the UART interface. If you monitor the connection state as well and use that to drive an equivalent of the DTR pin you can reset the Arduino automatically when you connect.

There is an example in the ESP8266 core that does it all apart from the connection monitoring, which is easy enough to add.

Then it's just a case of getting your computer to connect a virtual serial port with the remote socket on the ESP8266 and you have OTA programming for your choice of target board.

On Linux you can use `socat` for that:

    root@foo:~# while `true`; do echo "ready"; socat pty,link=/dev/ttyACM99,raw,wait-slave,user=youruser,group=dialout tcp:192.168.0.16:24; done

(yes, you have to run it as root).

Quite how you'd go about that on other operating systems I don't know. I think socat is available on OS X. Windows is anyone's guess though.


message:
Problem on multiple interrupts operation on Arduino Uno

I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two switches which are connected with Uno's interrupt pins, pins 2 and 3, and also taking multiple LEDs which are connected with other pins.

My logic is when I press switch1 (which is connected to pin 3) LEDs should be turned on by the interrupt service routine and when I press switch2 (which is connected to pin 2) LEDs should be turned off by the interrupt service routine.

My problem is that when I pressed switch1 LEDs are turned on but when I pressed switch2 LEDs are not turned off.

Here's my code:

<!-- language: lang-cpp -->

    int switch1 = 3;
    int switch2 = 2;
    int led1 = 13;
    int led2 = 12;
    int led3 = 11;
    int led4 = 10;
    int led5 = 9;
    int led6 = 8;
    int led7 = 7;
    volatile bool flag1 = false;
    volatile bool flag2 = false;
    //volatile byte state = LOW;

    void setup()
    {
      pinMode(switch1, INPUT_PULLUP);
      pinMode(switch2, INPUT_PULLUP);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(led7, OUTPUT);
      attachInterrupt(digitalPinToInterrupt(switch1), &setFlag1, CHANGE);
      attachInterrupt(digitalPinToInterrupt(switch2), &setFlag2, CHANGE);
    }

    void loop()
    {
      if (flag1)
      {
        off();
      }
      if (flag2)
      {
        blink1();
      }

    }

    void blink1()
    {
      attachInterrupt(digitalPinToInterrupt(switch2), setFlag2, CHANGE);
      digitalWrite(led1, HIGH);
      blink2();
    }

    void blink2()
    {
      digitalWrite(led2, HIGH);
      blink3();
    }

    void blink3()
    {
      digitalWrite(led3, HIGH);
      blink4();
    }

    void blink4()
    {
      digitalWrite(led4, HIGH);
      blink5();
    }

    void blink5()
    {
      while (1)
      {
        digitalWrite(led5, HIGH);
        delay(10);
        digitalWrite(led5, LOW);
        delay(10);
      }
    }

    void off()
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      digitalWrite(led5, LOW);
      attachInterrupt(digitalPinToInterrupt(switch1), setFlag1, CHANGE);
    }

    void setFlag1()
    {
      detachInterrupt(digitalPinToInterrupt(switch1));
      flag1 = true;
    }

    void setFlag2()
    {
      detachInterrupt(digitalPinToInterrupt(switch2));
      flag2 = true;
    }

body:
You are being way way too convoluted with this. You're overthinking it.

The code should be as simple as (LED stuff omitted):

    volatile bool running = false;
    const uint8_t switch1 =3;
    const uint8_t switch2 =2;

    void setup() {
        pinMode(switch1, INPUT_PULLUP);
        pinMode(switch2, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(switch1), turnOn, FALLING);
        attachInterrupt(digitalPinToInterrupt(switch2), turnOff, FALLING);
    }

    void loop() {
        if (running) {
            // Do something
        } else {
            // Do something else
        }
    }

    void turnOn() {
        running = true;
    }

    void turnOff() {
        running = false;
    }

Note that what goes in `loop()` should be *non-blocking*, or at least have a reasonably short duration, so that it is able to pick up the changed `running` variable.

However, for something like this, interrupts are pretty pointless.


message:
Running a function in the background continuously

I have a keypad which is connected to arduino (with one analog pin).In the arduino code, I have created a circular queue which stores the inputs by pressing on keypad. Now when a key is pressed on keypad, it is stored as the first element in the queue. If an another key is pressed, it is stored as second element in the queue until is queue is full.(The keypad pins are connected using a voltage divider for each pin, so each and every key pressed on keypad will be recognized by arduino based on voltage for the key. The keys and voltages are stored in an array, as follows):

    int keyboardPin = 0;    // analog pin to which keypad is connected
    int keyboardValue = 0; // Initial reading of analog pin 0 (A0) (it is zero as no key is pressed initially)
    char keypad[16] = {'1','2','3','4','5','6','7','8','9'};
    int treshold[16] = {590,568,548,426,415,404,334,326,320}; // Volatge values corresponding to each pin
    int front=0,rear=0,size=6; // implementing circular queue using array
    char cQueue[6];
    int speed = 6,timer=0;
    void setup(){
      cQueue[0] = '1'; // the first element of queue is '1' by default at the start
    }
    void loop(){
      keyboardValue = analogRead(keyboardPin); // Reading the value from A0 when key is pressed
      while(keyboardValue > 5) {  // Runs when a key is pressed
        for(int i=0;i<8;i++){
          if((treshold[i] - keyboardValue) == 0){
            Serial.println(keypad[i]); // Printing the key pressed
            enQueue(keypad[i]); // Storing the key pressed in the queue
            break;
          }
        break;
        } // end of for
      keyboardValue = 0;
      liftStops(cQueue[front+1]);// function to be run in background (front + 1) because  the key pressed by the user should be the argument of function
      break;
      } // end of while
    }        // end of loop
    int isFull(){  // to check if queue is full
      if( (f1 == r1 + 1) || (f1 == 0 && r1 == stops1-1)) {
      return 1;
    }
      return 0;
    }
    void enQueue(char element){  // adding key pressed to queue
      if(isFull()){
        Serial.println("Lift full");
      }else{
        r1 = (r1 + 1) % stops1;
        qlift1[r1] = element;
      }
    }
    int deQueue(){  // removing the front element of queue
      char element;
      element = qlift1[f1];
      f1 = (f1 + 1) % stops1;
      return(element);
    }

At the start of program, 1st element of queue is loaded with '1' (in setup function). When key is pressed, it is added as 2nd element of the queue.

There is a function which should run in the background as soon as a key is pressed. The function is:

    void liftStops(char keyPress){  // defined after the loop() function
      while(timer<100){
        distance = (speed*timer);
        motorClockwise();
        Serial.println(distance);
        if(keyPress == '1' && distance == 0){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '2' && distance == 30){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '3' && distance == 60){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '4' && distance == 90){
          motorStop();
          deQueue();
          return;
        }
        timer = timer+0.167;
        delay(200);
      }
    }

The element hold indicated by `front` variable in the queue is passed as a parameter to the `liftStops()` function. There is a motor in the circuit and the `motorClockwise()` rotates motor clockwise,`motorStop()` will stop the motor.

When the program is run for first time , if I press '2', it is stored as second element in the queue. The function `liftStops()` starts with '2' as its argument. Now the `liftStops()` function runs till `distance == 30` and motor stops. Now `deQueue()` function is called and the element indicated by front gets eliminated('1' gets eliminated in the above case). After this,if I press '3', `liftStops()` runs till `distance == 60` and the element indicated by front gets eliminated('2' in this case).

If I press a key when the `liftStops()` execution didn't finish, nothing is added to queue. I want the `liftStops()` function to run in background so that each and every key I press at any point of time gets stored in queue and the `liftStops()` function runs for every element in queue one after another.

Thanks.

body:
Typically this is done via an interrupt.

The use of an analog keyboard makes that more difficult or less convintional as the detection of a press in the analog sense is more difficult. One way to go is likely to scan the keyboard on a constant rate. But then detecting releases needs to be done creatively.


body:
Use loop function already provided for repetitive tasks

     void loop() {
     //this itself should be the function which you want keep running
     //check for keystrokes here and handle characters as they are
     //received. For handling characters, you can write a function outside
     //of the main loop which should return control to loop when task is
     //finished
     delay(200);
     }


body:
I wrote in a comment to your question:

> If you use `millis()` instead of `delay()` [...], then you won't need
> to run anything in the background.

and you answered:

> I have tried a lot using `millis()`, but I couldn't achieve the
> desired output.

From this, I assume the real problem is that you haven't tried hard
enough. The general approach is quite simple:

* Is there any work that has to be performed _right now_?
  * if yes, then just do it
  * if no, then don't do it

It works as long as you do not have any _blocking_ code in your program.
Especially no calls to `delay()`.

In your particular case, it would seem that `liftStops()` has work only
when:

* `timer` is less than 100
* _and_ it hasn't done useful work during the past 200 ms (that's
  the `delay(200)` in your code, and it's not _useful_ work).

You may try the following:

    void liftStops(char keyPress) {

        // Manage the execution timing.
        static uint32_t last_time;
        uint32_t now = millis();
        if (timer >= 100 || now - last_time < 200)
            return;  // nothing to do this time
        last_time = now;

        // Do the actual work.
        distance = (speed*timer);
        motorClockwise();
        Serial.println(distance);
        if(keyPress == '1' && distance == 0){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '2' && distance == 30){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '3' && distance == 60){
          motorStop();
          deQueue();
          return;
        }else if(keyPress == '4' && distance == 90){
          motorStop();
          deQueue();
          return;
        }
        timer = timer+0.167;
    }

Just make sure it is called often. I.e. you call it in `loop()` and you
make sure there is no blocking code elsewhere in your program.


body:
I have solved my problem using `attachInterrupt()` function.The `loop()` runs `liftStops()` continuously and if there is a keyPress, it is recorded by the interrupt.

    void setup(){
      attachInterrupt(digitalPinToInterrupt(3), floor1, CHANGE);
    }
    loop(){
      liftStops();
    }
    void liftStops(){
      if(qlift1[f1+1] != NULL){
        while(timer<100){
          distance = (speed*timer);
          motorClockwise();
          Serial.println(distance);
          if(qlift1[f1+1] == '1' && distance == 0){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }else if(qlift1[f1+1] == '2' && distance == 30){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }else if(qlift1[f1+1] == '3' && distance == 60){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }else if(qlift1[f1+1] == '4' && distance == 90){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }else if(qlift1[f1+1] == '5' && distance == 120){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }else if(qlift1[f1+1] == '6' && distance == 150){
            motorStop();
            deQueue();
            delay(5000);
            return;
          }
          timer = timer+0.167;
          delay(200);
        }
      }
    }
    void floor1(){
      keyboardValue = analogRead(keyboardPin);
      while(keyboardValue > 5) {  // Runs when a key is pressed
        for(int i=0;i<8;i++){
          if((treshold[i] - keyboardValue) == 0){
            Serial.println(keypad[i]); // Printing the key pressed
            enQueue(keypad[i]); // Storing the key pressed in the queue
            break;
          }
        break;
        } // end of for
      keyboardValue = 0;
      break;
      } // end of while
    }

If any key is pressed during `delay(5000)` even that gets recorded.


message:
Not able to get response from esp using Arduino uno

I am new to Arduino & ESP modules, here am trying to communicate with ESP-01 via Arduino UNO. I have gone through multiple websites for initial setup. But when i upload my code to UNO, ESP is not responding back.Below is the code i have used.

    #include<SoftwareSerial.h>
    SoftwareSerial ESP(0,1); // RX, TX
    //ESP RX-->1(UNO) TX-->0(UNO)

    void setup() {
    // Open serial communications and wait for port to open:

        Serial.begin(9600);
        while (!Serial) {
            ; // wait for serial port to connect. Needed for native USB port only
        }

       // Serial.println("Goodnight moon!");

        // set the data rate for the SoftwareSerial port
        ESP.begin(9600);

    }

    void loop() {
          ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
        while (ESP.available()) {
            char inData = ESP.read();
            Serial.println("Got reponse from ESP8266: ");
            Serial.write(inData);
        }

    }
[Source: Link of the url][1]

My observation on this is

 1. ESP is blinking blue light when i reset UNO
 2. UNO TX onboard LED is blinking
 3. when i am trying to do  `Serial.println("Goodnight moon!");` it is printing
 4. `Serial.println("Got reponse from ESP8266: ");         Serial.write(inData);` is not printing

My questions are:

 1. Is there any need to flash ESP with Firmware or is it default enabled.(i have 3 esp's with me all of them not responding with above code)
 2. If no need then what is the possible mistake i am doing.

Here is the screenshot [https://i.stack.imgur.com/mOklg.png][2]

Note: I haven't used breadboard for connection, directly connected UNO-TX -> ESP RX and UNO-RX -> ESP TX, 3.3v VCC and ground.In the above screenshot on upload nothing prints, only when i type something "Got reponse from ESP8266: " is printing

  [1]: https://arduino.stackexchange.com/questions/24807/esp8266-not-able-to-communicate-over-serial-connection-with-arduino-uno
  [2]: https://i.stack.imgur.com/mOklg.png

body:
There's a good chance your ESP and SoftwareSerial baud rates are not matched. The last handful of ESP-01s I bought came with default baud rates 115200. You may need to change yours to 9600 baud to use with SoftwareSerial. See [my answer to a similar question][1].

Update:

> tried all the available baud rates....!!Still the same issue..

Three possible issues come to mind:

 1. Your terminal program must be at the same baud rate you set the ESP to.

 2. SoftwareSerial is pretty much limited to a max of 9600 baud, although it can usually transmit successfully at 115200.

 3. The serial connections must be cross-wired - Rx->Tx and Tx->Rx.

I think you had addressed 3) when you were trying to use pins 0 & 1, at least, as I read your comments. Together, 1) and 2) mean you'll need to use SS at 115200 to change the ESP's baud rate to 9600, then change SS to 9600 to carry on any further.

Also try moving the `ESP.write("AT\r\n");` command to the setup() function. As your code is written, anytime the while loop finds no character waiting, the while loop will end and the loop() function will exit and restart, sending a new command to the ESP. Your code might never get a chance to print anything at all.

  [1]: https://arduino.stackexchange.com/questions/38289/at-command-is-not-responding-on-serial-monitor/38323#38323


body:
    SoftwareSerial ESP(0,1); // RX, TX
Pins 0 and 1 are hardware serial on the Uno, used with the Serial object, these pins are used to communicate with your computer (e.g. Serial Monitor) via the USB-serial chip on the Uno.

There is absolutely no reason you should ever use SoftwareSerial with pins 0 and 1. If you want to use software serial then connect the ESP8266 to pins other than 0 and 1. Otherwise don't use SoftwareSerial at all, but be aware that using Serial to communicate with the ESP8266 and with the computer is problematic and can also cause issues when you try to upload to your Uno.


body:
Hi all i found out the solution after a long struggle. issue was with the ch_pd as per the ESP [documentation][1] ch_pd has to be active high that means it has to get 3.3v, only then it will communicate.

  [1]: http://ecksteinimg.de/Datasheet/Ai-thinker ESP-01 EN.pdf

soon after that all my problems got cleared.thank you