body:
I have a stepper controller board that I need to pulse every 40 uS or so.

I also have I2C sensors and Serial writes to preform.

Currently I run an update call in a tight loop, but the I2C sensors and Serial writes cause considerable delays which makes the motors stutter and come to a halt.

I would like to use an ISR to call the motor update method periodically.

However I cannot for the life of me figure this timer stuff out.

Here's my current attempt:
<!-- language-all: lang-cpp -->

    void TC4_Handler() {
      Stepper::updateAll();
    }

    void setup() {

      // Timer stuff
      // Set up the generic clock (GCLK4) used to clock timers
      REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor 1: 48MHz/1=48MHz
                        GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
                         GCLK_GENCTRL_GENEN |         // Enable GCLK4
                         GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
                         GCLK_GENCTRL_ID(4);          // Select GCLK4
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      // Feed GCLK4 to TC4 and TC5
      REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TC4 and TC5
                         GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
                         GCLK_CLKCTRL_ID_TC4_TC5;     // Feed the GCLK4 to TC4 and TC5
      while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

      REG_TC4_COUNT16_CC0 = 0x000F;                      // Set the TC4 CC0 register as the TOP value in match frequency mode
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization

      //NVIC_DisableIRQ(TC4_IRQn);
      //NVIC_ClearPendingIRQ(TC4_IRQn);
      NVIC_SetPriority(TC4_IRQn, 0);    // Set the Nested Vector Interrupt Controller (NVIC) priority for TC4 to 0 (highest)
      NVIC_EnableIRQ(TC4_IRQn);         // Connect TC4 to Nested Vector Interrupt Controller (NVIC)

      REG_TC4_INTFLAG |= TC_INTFLAG_OVF;              // Clear the interrupt flags
      REG_TC4_INTENSET = TC_INTENSET_OVF;             // Enable TC4 interrupts
      // REG_TC4_INTENCLR = TC_INTENCLR_OVF;          // Disable TC4 interrupts

      REG_TC4_CTRLA |= TC_CTRLA_PRESCALER_DIV1024 |   // Set prescaler to 1024, 48MHz/1024 = 46.875kHz
                       TC_CTRLA_WAVEGEN_MFRQ |        // Put the timer TC4 into match frequency (MFRQ) mode
                       TC_CTRLA_ENABLE;               // Enable TC4
      while (TC4->COUNT16.STATUS.bit.SYNCBUSY);       // Wait for synchronization
      // ...
    }

title: Arduino Zero - Stepper control (interrupt)?

Answers: 1

body:
As `Stepper::updateAll();` isn't shown I don't know what it does.  For accurate timing it would make sense to use hardware-operated output-compare output pins like TIOAx and TIOBx, instead of running some code to drive the pins when an interrupt occurs.

If you need to control several wires per motor – such that a pulse on a single output line isn't enough – you might consider using a 74HC595 (or other shift register) to transfer the bits.  Thus, each time an output compare occurs, the  TIOAx and TIOBx line would pulse the ST_CLK (store-clock) line of the SR, to transfer bits from the shift chain flipflops to the output flipflops; then, at its leisure the interrupt routine can shift the next set of bits out to the '595, ready to be transferred at the correct moment, when the next output compare occurs.

During stepper acceleration or deceleration, the timer count-limit would also need to be updated within the ISR.


body:
This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.

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

    int tempPin = A0;
    int fan = 3;
    int led = 8;
    int temp;
    int tempreal;
    int tempMin = 20;
    int tempMax = 30;

    void setup()
    {
      Serial.begin(9600);
      pinMode(fan, OUTPUT);
      pinMode(led, OUTPUT);
      pinMode(tempPin, INPUT);
    }

    void loop()
    {
      temp = analogRead(tempPin);
      tempreal = temp * 0.48828125;
      delay(1);
      if(tempreal > tempMax)
      {
        digitalWrite(fan,HIGH);
        digitalWrite(led,LOW);
        delay(1);
      }
      else if (tempreal < tempMin)
      {
        digitalWrite(fan,LOW);
        digitalWrite(led,HIGH);
        delay(1);
      }
      else if (tempreal >  tempMin && tempreal <  tempMax)
      {
        digitalWrite(fan,LOW);
        digitalWrite(led,LOW);
        delay(1);
      }
    }

**Edit** by Edgar Bonet – The OP added in a comment to my answer:

“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:

![Example readings](https://i.stack.imgur.com/UmEHM.png)

title: Arithmetic mean for sensor

Answers: 5

body:
Seems too simple. am I missing something?

    --- arithmetic-mean.ino.orig 2017-04-27 19:37:01.386458500 +0200
    +++ arithmetic-mean.ino 2017-04-27 19:38:14.458114972 +0200
    @@ -16,8 +16,11 @@

     void loop()
     {
    -  temp = analogRead(tempPin);
    -  tempreal=temp * 0.48828125;
    +  temp = 0;
    +  for (int i = 0; i < 5; i++) {
    +    temp += analogRead(tempPin);
    +  }
    +  tempreal = temp * 0.48828125 / 5;
       delay(1);
       if(tempreal > tempMax)
       {

body:
A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.

You can achieve similar results via exponential smoothing.

Yn = (1−α) Yn−1 + α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.
[![enter image description here][1]][1]

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

the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.

body:
See Arduino Tutorials Smoothing
https://www.arduino.cc/en/tutorial/smoothing

Create an array to hold a series of readings. And a variable to hold the sum.

Incrementally cycle through the array, subtracting the oldest value from the sum and replacing it in the array with the current reading. Divide by the number of readings for the average.

Remember to allow for a delay in each reading as is appropriate for the sensor.

body:
You could use a moving average. It will update at each cycle whenever you take a new reading. Suppose you want to average over N readings:

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

    double moving_average(double old_average, double new_value) {
        double new_average = old_average;
        new_average -= old_average/N;
        new_average += new_value/N;
        return new_average;
    }

I edited the function above. I had typed one of arguments incorrectly.

body:
> My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work.

I had a similar problem. It turned out that I was reading writing and transmitting too fast. It means that since it seems that reading and writing can be interrupted during "their job", when you read a variable and in the same time someone is writing on that you're reading garbage. In my opinion this can be fixed by the application of "semaphores" or mutex or reducing the call of the reading. Randomly it would happen again but less frequently.

An idea can be found here
https://forum.arduino.cc/index.php?topic=132813.0

Best

Gian Maria


body:
I have this code:

    void setup() {
      pinMode(11, OUTPUT);
      TCCR2B = 0;
      TCNT2 = 0;
      TCCR2A = _BV(WGM21);
      TCCR2A |= _BV(COM2A0);
      OCR2A = 249;
    }

    void loop() {
      soundBuzzer();
    }

    void soundBuzzer() {
      TCCR2B |= _BV(CS21);
    }

    void silenceBuzzer() {
      TCCR2B &= ~_BV(CS21);
      TCNT2 = 0;
    }

(Got it from [here][1]).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

  [1]: http://forum.arduino.cc/index.php?topic=51457.msg368422#msg368422

title: Generate 1.7 Mhz with PWM in Uno?

Answers: 1

body:
Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:

<!-- language-all: lang-none -->

    period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency

    frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an _even_ number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:

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

    const uint8_t OUTPUT_PIN = 3;  // = OC2B
    const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

    void setup()
    {
        pinMode(OUTPUT_PIN, OUTPUT);
        TCCR2B = 0;           // stop timer
        TCNT2  = 0;           // reset timer
        TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
               | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
               | _BV(WGM21);  // ...ditto
        TCCR2B = _BV(WGM22);  // ...ditto
        OCR2A = PERIOD - 1;
        OCR2B = PERIOD/2 - 1;
    }

    void soundBuzzer() {
        TCCR2B |= _BV(CS20);  // F_CPU / 1
    }

    void silenceBuzzer() {
        TCCR2B &= ~_BV(CS20);
        TCNT2 = 0;
    }

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set `PERIOD` to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

**Edit**: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the [Trinket][] or the [Digispark][].

This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:

    64 MHz ÷ 38 = 1.684 MHz

[Trinket]: https://www.adafruit.com/product/1501
[Digispark]: http://digistump.com/products/1


body:
I have my Arduino uno setup with RC522 reader. I am able to dump the data that is held on my test card supplied with the reader but I wish to read the data blocks held within another card I have. The reader shows this as a Mifare classic but Does not dump the blocks.
This is with [miguelbalboa library][1]

    Card UID: EE 67 29 8D
    Card SAK: 08
    PICC type: MIFARE 1KB
    Sector Block   0  1  2  3   4  5  6  7   8  9 10 11  12 13 14 15  AccessBits
      15     63  PCD_Authenticate() failed: Timeout in communication.
      14     59  PCD_Authenticate() failed: Timeout in communication.
      13     55  PCD_Authenticate() failed: Timeout in communication.
      12     51  PCD_Authenticate() failed: Timeout in communication.
      11     47  PCD_Authenticate() failed: Timeout in communication.
      10     43  PCD_Authenticate() failed: Timeout in communication.
       9     39  PCD_Authenticate() failed: Timeout in communication.
       8     35  PCD_Authenticate() failed: Timeout in communication.
       7     31  PCD_Authenticate() failed: Timeout in communication.
       6     27  PCD_Authenticate() failed: Timeout in communication.
       5     23  PCD_Authenticate() failed: Timeout in communication.
       4     19  PCD_Authenticate() failed: Timeout in communication.
       3     15  PCD_Authenticate() failed: Timeout in communication.
       2     11  PCD_Authenticate() failed: Timeout in communication.
       1      7  PCD_Authenticate() failed: Timeout in communication.
       0      3  PCD_Authenticate() failed: Timeout in communication.

I have also tried using these examples [https://github.com/BoolLi/RC522_RFID_NFC_Utilities][2]

But they fail to compile for me. All I want to do is dump the data blocks from a university card I have for a project, I don't need to be able to write to the card yet.

  [1]: https://github.com/miguelbalboa/rfid
  [2]: https://github.com/BoolLi/RC522_RFID_NFC_Utilities

title: Arduino RFID Mifare Classic dump info

Answers: 0


body:
My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library.
I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works.
This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible.
Here is an example of a code that does not work due to the use of the SPI.h library.

Any help is greatly appreciated, this is extremely odd and problematic.

    #include <Time.h>
    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__
    #include <avr/power.h>
    #endif
    #include <SPI.h>
    #include <SD.h>

    Sd2Card card;
    SdVolume volume;
    SdFile root;

    const int chipSelect = 4;

    #define PIN            6
    #define NUMPIXELS      400

    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

    boolean stringComplete = false;  // whether the string is complete
    boolean readarray=false;
    String inString = "";
    int c=0;
    int cc=0;
    int led=0;
    int i=0;
    int j=0;
    int pixel_n=0;
    unsigned long start;
    unsigned long endd;

    //char* ledd[]={"", "", ""};
    int ledd[3]={0,0,0};

    File myFile;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
    pixels.begin();
    while (!Serial) {
      ; // wait for serial port to connect. Needed for Leonardo only
    }

    Serial.print("\nInitializing SD card...");

    // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
    if (!volume.init(card)) {
      Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
      return;
    }

    // print the type and size of the first FAT-type volume
    uint32_t volumesize;
    Serial.print("\nVolume type is FAT");
    Serial.println(volume.fatType(), DEC);
    Serial.println();

    Serial.println("Ok we're done");
    delay(2000);

    pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
    pixels.show(); // THIS EITHER

      Serial.begin(9600);
    }

    void loop(void) {

    }

title: LED strip and SD card

Answers: 1

body:
I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.

To add a tristate solution by using two resistors on the MISO line also did not work in my case.

See [my post][1] for the post I created regarding this probably similar problem.

  [1]: https://arduino.stackexchange.com/questions/36912/slave-spi-does-not-work


body:
This is my first library so feel free to burn me and vote this down :D
This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.

In the test sketch I use the `watchdog timer's interrupt vector` but I want to place this within the library. How can I do this?

I have tried to add this to the `init` method but that did not work out;
`powernap.h:26: error: expected unqualified-id before string constant
     ISR(WDT_vect) { `

Also; feel free to shoot at the rest of the library, I am here to learn.

**Test Sketch**

    #include "powernap.h"

    #define LED 0

    Napper napper = Napper();

    volatile boolean f_wdt = 1;

    ISR(WDT_vect) {
      f_wdt=1;
    }

    void setup() {
      delay(2000);
      napper.setup(8); // configure watchdog timer
    }

    void loop() { // blink
      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);
      delay(200);
      digitalWrite(LED, HIGH);
      delay(200);
      digitalWrite(LED, LOW);
      delay(200);

      napper.sleep(); // deep sleep
    }

**powernap.cpp**

    #include "powernap.h"

     #ifndef cbi
       #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
     #endif
     #ifndef sbi
       #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
     #endif

    Napper::Napper() {

    }

    void Napper::init(float initial) {
    // volatile boolean f_wdt = 1;

    // ISR(WDT_vect) {
    // f_wdt=1;
    // }
    }

    void Napper::setup(int cycle) {
     byte bb;
       int ww;
       if (cycle > 9 ) cycle=9;
     bb=cycle & 7;
     if (cycle > 7) bb|= (1<<5);
     bb|= (1<<WDCE);
     ww=bb;

     MCUSR &= ~(1<<WDRF);
     // start timed sequence
     WDTCR |= (1<<WDCE) | (1<<WDE);
     // set new watchdog timeout value
     WDTCR = bb;
     WDTCR |= _BV(WDIE);
    }

    void Napper::sleep() {
     cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

     set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
     sleep_enable();

     sleep_mode();                        // System sleeps here

     sleep_disable();                     // System continues execution here when watchdog timed out
     sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
    }

**powernap.h**

    #ifndef Fader_h
    #define Fader_h

    #if ARDUINO >= 100
      #include "Arduino.h"
    #else
      #include "WProgram.h"
      #include "pins_arduino.h"
      #include "WConstants.h"
    #endif

    #include <avr/sleep.h>
    #include <avr/wdt.h>
    #include <util/delay.h>

    class Napper {
     public:
      Napper();

      void init(float initial);
      void setup(int cycle);
      void sleep();

     private:
      int flag;

    };

    #endif

title: Interrupt handler in library

Answers: 2

body:
It is hard to help you improve your library or code if you don't tell others what your code pieces are trying to do.

In general, you will have a piece of code that sets up the whole thing, a piece of code that will be executed in the isr, and other helper code pieces, like getting status and clear status, as appropriate.

I often use a function pointer that the user can hook to the user handler so my isr portion of the code is fixed. Just hook to different functions in the user space and you are ready to go.

Obviously other ways exist, each with their pros and cons.

body:
To answer your actual question, you just have to define `ISR(WDT_vect)`
outside any function.

Now, for the general critique, let me start by quoting [Antoine de Saint
Exupéry][Exupery]: “It seems that perfection is attained not when there
is nothing more to add, but when there is nothing more to remove.”
There are quite a few things to remove from your code, like unused
variables, parameters or methods. I understand that you may be tempted
to leave useless stuff in there anticipating that you may need it in a
future, extended version. But please, don't do that. Try to keep clean
and lean any code that you post in public, and only add extra stuff when
you actually need it.

I would remove most of the `#include`s from powernap.h. If the compiler
needs one of these to understand your .h, then live it there. If it's
only needed to compile your library, then it belongs to your .cpp.

Also, there is no point in making your library dependent on the Arduino
core, as you are using no core functionality. By removing this
dependency, you can make your library more versatile, as it can be used
both for Arduino and non-Arduino projects.

The line `#ifndef Fader_h` looks weird. Standard practice is to use the
name of the .h file, capitalized. Don't depart from common practice
unless you have some reason to do so.

I would also add `static` to your methods, this way they can be used
without having to instantiate an object, like in
`Napper::setup(WDTO_4S);`.

You are using three different syntaxes for setting and clearing bits in
I/O registers. Your code will look more consistent if you choose one and
stick with it.

I almost forgot... you have to make sure the timed sequence is done
atomically, i.e. it's not interrupted.

Below is a version of the library that implements the suggestions above:

**powernap.h**

    #ifndef POWERNAP_H
    #define POWERNAP_H

    #include <stdint.h>

    class Napper {
        public:
            Napper() {}
            static void setup(uint8_t cycle);
            static void sleep();
    };

    #endif  // defined(POWERNAP_H)

**powernap.cpp**

    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    #include <util/atomic.h>
    #include "powernap.h"

    // This interrupt is used only as a wakeup source.
    EMPTY_INTERRUPT(WDT_vect);

    // Configure the watchdog as an interrupt source.
    // `cycle' should be an integer from 0 to 9, or one of the constants
    // WDTO_XXS from <avr/wdt.h>.
    void Napper::setup(uint8_t cycle) {
        uint8_t prescaler;         // prescaler bits in WDTCR
        if (cycle > 9) cycle = 9;  // largest supported value
        prescaler = cycle & 7;     // bits WDP2:WDP0 are right aligned in WDTCR
        if (cycle > 7) prescaler |= _BV(WDP3);

        MCUSR &= ~_BV(WDRF);  // clear this bit: it overrides WDE
        ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
            WDTCR |= _BV(WDCE)    // start timed sequence
                  |  _BV(WDE);
            WDTCR =  prescaler    // set new watchdog timeout value
                  |  _BV(WDIE);   // enable watchdog interrupt
        }
    }

    void Napper::sleep() {
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_mode();
    }

[Exupery]: https://en.wikipedia.org/wiki/Antoine_de_Saint-Exupéry


body:
I am trying to do a self-balancing bot as a school project, but I got stuck with the MPU6050.

I tried using the code by Jeff Rowberg (MPU_6050_raw) but it's reading only zeros.

I tried the MPU_6050_DMP and got stuck at "initializing DMP..." and no reading is shown.

I tried other code, but same thing happens, either reading zeros or getting stuck at "initializing DMP..".

And how can I make sure that the chip isn't broken?

title: MPU6050 doesn't work

Answers: 1

body:
The MPU-6050 is a 3.3V chip. When you are using a 5V Arduino board, you should take care that you don't put current into the SDA and SCL pins of the MPU-6050.

Start with a i2c scanner.
This one: [Arduino Playground I2C scanner][1]
Or this one: [Nick Gammon I2C scanner][2]
If the I2C scanner halts, then there is a hardware problem with the I2C bus. It might be a shortcut of SDA or SCL to GND, or the MPU-6050 module is not powered.

If the I2C scanner is working, then you know the address (0x68 or 0x69). With that address you can try the [Short example sketch][3] to read data from the chip.

If that is working, then you can try the Jeff Rowberg library.

  [1]: http://playground.arduino.cc/Main/I2cScanner
  [2]: http://www.gammon.com.au/forum/?id=10896&reply=6#reply6
  [3]: http://playground.arduino.cc/Main/MPU-6050#short


body:
I want to make 2 LEDs blink back and forth continuously, but they only do so once, and the second one is very dim.

code:

    int ledone = 12;
    int ledtwo = 10;
    int keepgoing = 1;

    void setup() {
    pinMode(ledone, OUTPUT);
    pinMode(ledtwo, OUTPUT);
    }

    void loop() {
     while (keepgoing == 1) {
      digitalWrite(ledone, HIGH);
      delay(80);
      digitalWrite(ledone, LOW);
      digitalWrite(ledtwo, HIGH);
      delay(80);
      digitalWrite(ledtwo, LOW);
      delay(500);
     }
    }

I am using an Arduino Uno and one 220 ohm resistor for each LED.

title: Broken Loop and dim LEDs

Answers: 1

body:
I think the problem is, that your delays are just too short, so you see the blinking not as blinking, but as a dim lit led.

Maybe you can try the following code:

    void loop() {
     while (keepgoing == 1) {
      digitalWrite(ledone, HIGH);
      digitalWrite(ledtwo, LOW);
      delay(500);
      digitalWrite(ledone, LOW);
      digitalWrite(ledtwo, HIGH);
      delay(500);
     }
    }

Is this working?


body:
I'm working on a project using a nodeMCU using a ICR14500(3.7V and 700mAh) battery and I'm experienced some issues when I try to estimate the total current consumption. Firstly I experienced some problems with the power supply (here is the previous question [NodeMCU powered with battery and use WiFi][1]) but this problem is now solved.

At this moment if I measure the current consumption connecting the amperimeter in serie between the battery and the nodeMCU input voltage pin I see a current consumption of 140mA continiously (ignoring the deep sleep mode) and I experienced some strange behaviours in my NodeMCU, even the code doesn't work. If I remove the amperimeter from my set up all works smooth and my source code works perfectly.

In order to validate my amperimeter I modified a usb cable and I added the amperimeter in the middle of the wire and I measured the current consumption powering me nodeMCU from the computer and I saw a current consumption of 80mA when the code is run and 14mA when the device is in deep sleep. This behaviour seems the expected one.

Are there any colateral effect measuring the battery current consumption which I haven't considered?

  [1]: https://arduino.stackexchange.com/questions/37583/nodemcu-powered-with-battery-and-use-wifi/37637#37637 "NodeMCU powered with battery and use WiFi"

title: NodeMCU power consumption measurement and DeepSleep

Answers: 2

body:
An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).

This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.

For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.

Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.

When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.

So how can you measure the current with the battery? Well, there's two options:

1. Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
2. Add a large electrolytic capacitor to the input of the NodeMCU *after* your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/98yhz.png)

<!-- End schematic -->

body:
The NodeMCU has an on-board voltage regulator, that needs excess voltage to supply the 3.3V. So if the voltage for the regulator is too low, the voltage for the ESP8266 may become too low too or it can’t draw enough current as it needs.  (During boot or wifi operation it’s drawing up to 200mA peak current). If that happens, it’ll be stuck in the boot process, in which it’s drawing the 140mA.

So, when you’re running from battery, be sure to power the 3.3V supply of the board, not the 5V input that goes through the regulator first.
When your battery is fully charged it’ll give 4.2V, which may just be enough for the regulator still. With the ampmeter in between it’ll definitely be too low.

Note that with the NodeMCU board you’ll never get the advertised 20μA deep sleep current of the ESP due to the onboard voltage regulator (unless you [modify the board](https://itooktheredpill.irgendwo.org/2017/reducing-nodemcu-power-consumption/)).


body:
I'm reading the two wire library in Arduino libraries and in the C++ source  code I found different methods which I don't know what they mean, in the following:

    // Initialize Class Variables //////////////////////////////////////////////////

    uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
    uint8_t TwoWire::rxBufferIndex = 0;
    uint8_t TwoWire::rxBufferLength = 0;

    uint8_t TwoWire::txAddress = 0;
    uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
    uint8_t TwoWire::txBufferIndex = 0;
    uint8_t TwoWire::txBufferLength = 0;

    uint8_t TwoWire::transmitting = 0;
    void (*TwoWire::user_onRequest)(void);
    void (*TwoWire::user_onReceive)(int);

    // Public Methods //////////////////////////////////////////////////////////////
    void TwoWire::begin(void)
    {
      rxBufferIndex = 0;
      rxBufferLength = 0;

      txBufferIndex = 0;
      txBufferLength = 0;

      twi_init();
    }

    void TwoWire::begin(uint8_t address)
    {
      twi_setAddress(address);
      twi_attachSlaveTxEvent(onRequestService);
      twi_attachSlaveRxEvent(onReceiveService);
      begin();
    }

    void TwoWire::begin(int address)
    {
      begin((uint8_t)address);
    }

My first question, regarding to class variables:

 1. Why has the author connected the variables to the class with scope-resolution operator "::"?
 2. I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

----------

My second question, regarding to public methods:

 1. There are three versions of the "begin" function, can someone explain why?
 2. Why is begin(); called inside the second function declaration?

title: Different questions regarding Arduino C++ library coding style

Answers: 1

body:
> Why they connect the variables to the class with scope-resolution operator "::"?

Those are *static* variables. They don't exist within an instantiated class instance since they are common to *all* class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

> I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

> There are three versions of the "begin" function, can someone explain why?

This is called *function overloading*. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

> Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other `begin()` function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the `begin()` function that takes no parameters.


body:
So in a previous post I asked if I could charge an [SD card breakout board](https://www.adafruit.com/product/254) with a [3.7V LiPo battery](https://www.adafruit.com/product/1578), and I got a positive response, so I did it.

The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:

When connected with the Arduino:

    Initializing SD card...Wiring is correct and a card is present.

    Card type: SDHC

    Volume type is FAT32

    Volume size (bytes): 2696937472
    Volume size (Kbytes): 2633728
    Volume size (Mbytes): 2572

    Files found on the card (name, date and size in bytes):
    SYSTEM~1/     2017-04-27 15:20:04
      WPSETT~1.DAT  2017-04-27 15:20:04 12
      INDEXE~1      2017-04-27 15:20:14 76
    TEST0.TXT     2000-01-01 01:00:00 49050
    TEST1.TXT     2000-01-01 01:00:00 60231
    TEST2.TXT     2000-01-01 01:00:00 1044
    TEST3.TXT     2000-01-01 01:00:00 34831
    TEST4.TXT     2000-01-01 01:00:00 189736
    TEST5.TXT     2000-01-01 01:00:00 12419

When connected to the battery:

    Initializing SD card...initialization failed. Things to check:
    * is a card inserted?
    * is your wiring correct?
    * did you change the chipSelect pin to match your shield or module?

or

    Initializing SD card...Wiring is correct and a card is present.

    Card type: SD1
    Could not find FAT16/FAT32 partition.
    Make sure you've formatted the card

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?

title: Powering SD breakout board with 3.7V battery

Answers: 1

body:
You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from.  That means connect together:

* An Ardino GND pin
* The GND pin of the SD card breakout board
* The negative (or ground) pin of the battery


body:
I'm using an ESP8266-01S Wi-Fi module on an Arduino UNO.

When I use ```AT+CIPSEND=4``` and then type ```test``` it successfully sends that message to my laptop. However, sometimes the module returns a ```busy s...``` after typing the message... Then the module board is "frozen" for a couple of seconds to a full minute before accepting other commands.

What's a way to make sure the message gets send without getting that ```busy s...``` response. Or how do I catch it and reset the board or something like that?

title: ESP8266 sometimes stuck on AT+CIPSEND with "busy s..."

Answers: 0


body: I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.

title: How to use ESP8266 for wireless communication?

Answers: 2

body:
I'm not very clear on what you are asking but I think you are saying how do you connect an ESP8266 to an Arduino so the Arduino has wireless(WIFI) access.

I'm sure there are tutorials out there so I won't go in to detail (also I don't know the details), but hopefully you will get some better terms to search with.

The basic idea is you connect the serial connection of the ESP8266 to the serial of the Arduino (via a level shifter and connect Tx to Rx).  You then write a series of AT commands to configure the ESP8266 so that what ever is receives over the serial it sends to a TCP endpoint via WIFI (and what it receives is sent to serial).

You can program the ESP via the Arduino IDE, so you could write a 'smarter' version that did all the setup for you, etc.  In fact since the ESP8266 is a faster processor with more RAM you could do a lot more on it.

If you are using an UNO or Nano you might want to look at the software serial library to let you keep the main serial port for debug messages.  If you are using a Mega then you can use one of the secondary serial ports.

body:
You follow the instructions from blynk.cc/getting-started which include quite simple steps:

> 1 create auth id
>
> 2 download and install blynk library
>
> 3 replace auth id in some example you can find from arduino ide
>
> 4 run code

More details from tutorial.


body:
Is my syntax "SoftwareSerial uno1(0,1); // RX, TX" is right to communicate with more than two Arduinos?. How can I communicate with three Unos via single Mega?

    #include <SoftwareSerial.h>
    SoftwareSerial uno1(0,1); // RX, TX
    SoftwareSerial uno2(0,1); // RX, TX
    SoftwareSerial uno3(0,1); // RX, TX

    float lt[24]={3530,1580,3880,2780,4040,11260,7935,6655,2100,5100,1450,2200,2200,5900,6180,4230,2405,3560,4535,12635,12085,3500,930,3430};
    float gt[24]={0,0,0,0,0,0,6320,5496.9,5948,4124.1,3848.4,3573,3022.2,3297.6,3298.2,3573,4123.2,0,0,0,0,0,0};
    float lbt[24]={3530,1580,3880,2780,4040,7960,7935,2655,900,1400,1450,1300,1000,3400,3680,1730,2405,3560,4535,9635,9885,3500,930,3430};
    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
    float lst[24]={0,0,0,0,0,3300,0,4000,1200,3700,0,900,1200,2500,2500,2500,0,0,0,3000,2200,0,0,0};
    float les1[24]={0,0,0,0,0,0,0,2000,1200,0,0,0,0,2500,2500,2500,0,0,0,0,1200,0,0,0};
    float les2[24]={0,0,0,0,0,3300,0,0,0,0,0,900,1200,0,0,0,0,0,0,2000,0,0,0,0};
    float les3[24]={0,0,0,0,0,0,0,2000,0,3700,0,0,0,0,0,0,0,0,0,1000,1000,0,0,0};
    float BatCap[24]={405.83,405.83,405.83,305.83,305.83,305.83,305.83,305.83,588.91,576.24,799.08,936.45,1050.87,811.05,570.85,493.19,590.53,637.47,397.47,397.47,397.47,397.47,397.47,397.47};

    float Pvpin=41,Batpin=42,Gridpin=43;

    void setup() {
    // DEFINING THE MODES OF LOADS, OBEVIOUSLY OUTPUT.
      pinMode(Pvpin,OUTPUT);
      pinMode(Batpin,OUTPUT);
      pinMode(Gridpin,OUTPUT);

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

    void loop()
    {
      for (int i=0;i<24;i++)
      {
       if (gt[i]>lt[i])
       {
           uno1.write( "100");
           uno2.write( "100");
           uno3.write( "100");
           digitalWrite(Pvpin,HIGH);
       }
       else if (gt[i]+BatCap[i]>lt[i])
       {
           uno1.write( "110");
           uno2.write( "110");
           uno3.write( "110");
           digitalWrite(Batpin,HIGH);
           digitalWrite(Pvpin,HIGH);
       }
       else
       {
           uno1.write( "001");
           uno2.write( "001");
           uno3.write( "001");
           digitalWrite(Gridpin,HIGH);
       }
      }
    }

title: Serial communication with more than two Arduinos

Answers: 1

body:
If you want to use 3 `SoftwareSerial` instances, then you need to use 3 different sets of pins. Hence, replace:

    SoftwareSerial uno1(0,1); // RX, TX
    SoftwareSerial uno2(0,1); // RX, TX
    SoftwareSerial uno3(0,1); // RX, TX

with something like:

    SoftwareSerial uno1(0,1); // RX, TX
    SoftwareSerial uno2(2,3); // RX, TX
    SoftwareSerial uno3(4,5); // RX, TX

Also, since `SoftwareSerial` and `Serial` (hardware) are interchangeable in code, you should take advantage of the hardware Serial of Arduino UNO:

    HardwareSerial uno1 = Serial;

Note that, on UNO, `HardwareSerial` uses pins 0 and 1, hence you should not use these for something else:

    HardwareSerial uno1 = Serial;
    SoftwareSerial uno2(2,3); // RX, TX
    SoftwareSerial uno3(4,5); // RX, TX


body:
We're complete beginners with Arduino and we're working on a project that moves a pointer based on a color sensor reading.

We used two servo motors each: one performs a specific task, the small servo works pretty fine. The problem is with the larger one.

We used this servo motor model: (towardpro MG996R), Arduino Uno and a color sensor. Because the motor is large we connect it to a 9 V power supply.

But when we run the code it just vibrates in place and the arm won't move :(

Is there anything else we need to add to the circuit like a resistor or some thing?

    #include <Servo.h>
    Servo largeServo;

    void setup() {
      largeServo.attach(6);
      largeServo.write(0);
    }

    void loop() {
      largeServo.write(0);
      delay (2000);
      largeServo.write(30);
      delay (2000);
      largeServo.write(60);
      delay (2000);
      largeServo.write(90);
      delay (2000);
    }

title: Servo jitter with Arduino

Answers: 3

body:
As already suggested in the comments you need a more powerful current source than your battery.

No device work purely on Voltage, they all operate on Power (watts) or, if you prefer, on a combination of Voltage and Current (ampere).

You are feeding 9V into your beefy motor, but the amount of current your battery can provide is pretty limited due to the battery internal resistance and limited capacity.

Replace the battery with a proper power source capable to deliver 10W or more (1+ ampere at 9 volts equals 9+ watts) and your motor will start to operate and it will also get warm while operating.

body:
According to (MG996R)'s datasheet
You must connect a 6 volts - 2.5 amps power supply for it's best performance (max. Torque)
Maximum voltage of this servomotor is 6 volts
And be careful, exceeding that voltage can be cause of some damage to it's control board
Try 6 volts 2.5 amps power supply and if doesn't work maybe your servomotor's control-board is damaged by over-voltage.

body:
To complement the other answers, also make sure that the Arduino itself is being powered properly!

I was attaching Arduino Uno to a nearly out of battery laptop via USB cable, resulting in a jittering servo. As soon as I've put the laptop on charge, the servo started working smoothly!


body: I heard that you can program any AVR Microcontroller by just using Arduino ISP Can I program ATUC256L4U by just hooking it up to Arduino ISP and Caps, Crystals and etc. Or do I need to do some more work like you know the fuses and all ?

title: Programming ATUC256L4U using only Arduino ISP

Answers: 0


body:
I'm really bad with this coding part of using two rotary encoders to control two stepper motors [using 28BYJ-48 stepper motor with the ULN2003 board].
This code works fine using one rotary encoder for one stepper motor using this off brainy-bits.com:

[![enter image description here][1]][1]
https://brainy-bits.com/blogs/tutorials/stepper-motor-rotary-encoder-p1

When I slightly modify the code for two encoders and two stepper motors I'm using this: However I'm not getting the results I expected. The two motors just don't respond.

<!-- language: cpp -->

    #include "Stepper.h"
    #define STEPS 32   // Number of steps for one revolution of Internal shaft
    // 2048 steps for one revolution of External shaft

    volatile boolean TurnDetected;  // need volatile for Interrupts
    volatile boolean rotationdirection;  // CW or CCW rotation

    const int PinCLK = 2; // Generating interrupts using CLK signal
    const int PinDT = 3;  // Reading DT signal
    const int PinSW = 4;  // Reading Push Button switch
    const int PinCLK2 = 46;
    const int PinDT2 = 47;
    const int PinSW2 = 48;

    int RotaryPosition = 0;  // To store Stepper Motor Position
    int RotaryPosition2 = 0;

    int PrevPosition;     // Previous Rotary position Value to check accuracy
    int PrevPosition2;
    int StepsToTake;      // How much to move Stepper
    int StepsToTake2;

    // Setup of proper sequencing for Motor Driver Pins
    // In1, In2, In3, In4 in the sequence 1-3-2-4
    Stepper small_stepper(STEPS, 8, 10, 9, 11);
    Stepper small_stepper2(STEPS, 40, 41, 42, 43);

    // Interrupt routine runs if CLK goes from HIGH to LOW
    void isr () {
      delay(4);  // delay for Debouncing
      if (digitalRead(PinCLK))
        rotationdirection = digitalRead(PinDT);
      else
        rotationdirection = !digitalRead(PinDT);
      TurnDetected = true;
      /////I added this
      delay(4);  // delay for Debouncing
      if (digitalRead(PinCLK2))
        rotationdirection = digitalRead(PinDT2);
      else
        rotationdirection = !digitalRead(PinDT2);
      TurnDetected = true;
    }
    /////up to here

    void setup () {
      pinMode(PinCLK, INPUT);
      pinMode(PinDT, INPUT);
      pinMode(PinSW, INPUT);
      digitalWrite(PinSW, HIGH); // Pull-Up resistor for switch
      attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
      pinMode(PinCLK2, INPUT);
      pinMode(PinDT2, INPUT);
      pinMode(PinSW2, INPUT);
      digitalWrite(PinSW2, HIGH); // Pull-Up resistor for switch
      attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
    }

    void loop () {
      small_stepper.setSpeed(600); //Max seems to be 700
      if (!(digitalRead(PinSW))) {   // check if button is pressed
        if (RotaryPosition == 0) {  // check if button was already pressed
        } else {
          small_stepper.step(-(RotaryPosition * 50));
          RotaryPosition = 0; // Reset position to ZERO
        }
      }

      // Runs if rotation was detected
      if (TurnDetected) {
        PrevPosition = RotaryPosition; // Save previous position in variable
        if (rotationdirection) {
          RotaryPosition = RotaryPosition - 1;
        } // decrase Position by 1
        else {
          RotaryPosition = RotaryPosition + 1;
        } // increase Position by 1

        TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

        // Which direction to move Stepper motor
        if ((PrevPosition + 1) == RotaryPosition) { // Move motor CW
          StepsToTake = 50;
          small_stepper.step(StepsToTake);
        }

        if ((RotaryPosition + 1) == PrevPosition) { // Move motor CCW
          StepsToTake = -50;
          small_stepper.step(StepsToTake);
          small_stepper2.setSpeed(600); //Max seems to be 700
          if (!(digitalRead(PinSW2))) {   // check if button is pressed
            if (RotaryPosition2 == 0) {  // check if button was already pressed
            } else {
              small_stepper2.step(-(RotaryPosition * 50));
              RotaryPosition2 = 0; // Reset position to ZERO
            }
          }

          // Runs if rotation was detected
          if (TurnDetected)
          {
            PrevPosition2 = RotaryPosition2; // Save previous position in variable
            if (rotationdirection) {
              RotaryPosition2 = RotaryPosition2 - 1;
            } // decrase Position by 1
            else {
              RotaryPosition2 = RotaryPosition2 + 1;
            } // increase Position by 1

            TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

            // Which direction to move Stepper motor
            if ((PrevPosition2 + 1) == RotaryPosition2) { // Move motor CW
              StepsToTake = 50;
              small_stepper2.step(StepsToTake);
            }

            if ((RotaryPosition2 + 1) == PrevPosition2) { // Move motor CCW
              StepsToTake = -50;
              small_stepper2.step(StepsToTake);
            }
          }
        }
      }
    }

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

title: Running two stepper motors with two rotary encoders

Answers: 1

body:
simple:

1) write a set of routines that drive your servo motor via interrupts: you will need to specify the on-time for each servo channel.

2) write a set of routines that read the rotary positions.

3) write a set of routines that convert the rotary positions into the on-time parameter.

4) integrate them all.

in  your loop, you will simply need to read one rotary position, convert it into the on-time for that channel, and update the on-time parameter. The servo routines will run in the background transparently to your code.


body:
Look at the trick in the last few lines of this code:

    #include <ESP8266WiFi.h>

    const char* ssid = "xxxxx";
    const char* password = "yyyyyyy";

    // Create an instance of the server
    // specify the port to listen on as an argument
    WiFiServer server(80);

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

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
         delay(500);
         Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

     int delays = 0;

     // Wait until the client sends some data
     Serial.println("new client");
     while(!client.available()){
        delay(1);
        delays++;  // First line of trick.
        if (delays > 10) {
           return;
        } // Trick ends.
      }
      ...// Handle some events.
    }

Code works ok without the trick (only `delay(1);` inside the loop), but the problem is it gets stucked there, if some responses are asked from browser so that tab is closed in between the requests.

One response is for favicon:

     if (req.indexOf("favicon.ico") != -1) {
        String s = "HTTP/1.1 404 WTF Favicon !!\r\n";
        client.print(s);
        client.flush();
        return;
     }
I had also one similar response starting with 200 OK for certain URLs and then a response of plain json text.

I would like to know why my server gets stucked on this `delay(1);`? Also, when the trick is needed, what is correct `delays` value?

Also I did add a `client.flush();` after every `client.print();`. May that affect anything?

title: WiFi connections being lost on connection reset

Answers: 1

body:
[WifiServer class has a bug](https://github.com/espressif/arduino-esp32/issues/167) that is now resolved. It causes a phenomenom described like follows:

> When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.


body:
I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):

      int readButtons(){
      rbuttonState = digitalRead(right);
      lbuttonState = digitalRead(left);
      sbuttonState = digitalRead(sel);
      obuttonState = digitalRead(off);
      nbuttonState = digitalRead(snooze);
      int ret = -1;
      if (rbuttonState != lastrButtonState){
            if (rbuttonState == HIGH) {
                ret = right;
              }
            }
         if (lbuttonState != lastlButtonState){
              if (lbuttonState == HIGH) {
                ret = left;
              }
            }
         if (sbuttonState != lastsButtonState){
              if (sbuttonState == HIGH) {
                ret = sel;
              }
            }
         if (obuttonState != lastoButtonState){
              if (obuttonState == HIGH) {
                ret = off;
              }
            }
         if (nbuttonState != lastnButtonState){
              if (nbuttonState == HIGH) {
                ret = snooze;
              }
            }
      }
      lastrButtonState = rbuttonState;
      lastlButtonState = lbuttonState;
      lastsButtonState = sbuttonState;
      lastoButtonState = obuttonState;
      lastnButtonState = nbuttonState;
      return ret;
    }

Yet I have the errors that

    Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

    Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
       lastrButtonState = rbuttonState;
       ^
    Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
       lastlButtonState = lbuttonState;
       ^
    Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
       lastsButtonState = sbuttonState;
       ^
    Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
       lastoButtonState = obuttonState;
       ^
    Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
       lastnButtonState = nbuttonState;
       ^
    Nixie_Clock_0:70: error: expected unqualified-id before 'return'
       return ret;
       ^
    Nixie_Clock_0:71: error: expected declaration before '}' token
     }
     ^
    exit status 1
    'lastrButtonState' does not name a type

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.
(The last line of code is line 72).
I am at a complete loss. Any help?

title: Two ints declared simultaneously, one "does not name a type"

Answers: 1

body:
the following code

 1. is properly indented
 2. is missing the declarations of the variables for the 'button states' and the 'prior button states'
 3. has additional text about a format error
 4. is properly indented
 5. has the code blocks properly separated by a single blank line

and now the code

    int readButtons()
    {
        rbuttonState = digitalRead(right);
        lbuttonState = digitalRead(left);
        sbuttonState = digitalRead(sel);
        obuttonState = digitalRead(off);
        nbuttonState = digitalRead(snooze);
        int ret = -1;

        if (rbuttonState != lastrButtonState)
        {
            if (rbuttonState == HIGH)
            {
                ret = right;
            }
        }

        if (lbuttonState != lastlButtonState)
        {
            if (lbuttonState == HIGH)
            {
                ret = left;
            }
        }

        if (sbuttonState != lastsButtonState)
        {
            if (sbuttonState == HIGH)
            {
                ret = sel;
            }
        }

        if (obuttonState != lastoButtonState)
        {
            if (obuttonState == HIGH)
            {
            ret = off;
            }
        }

        if (nbuttonState != lastnButtonState)
        {
            if (nbuttonState == HIGH)
            {
            ret = snooze;
            }
        }
    }  << extranious closing brace ends the actual function

        lastrButtonState = rbuttonState;
        lastlButtonState = lbuttonState;
        lastsButtonState = sbuttonState;
        lastoButtonState = obuttonState;
        lastnButtonState = nbuttonState;
        return ret;
    }


body:
I'm writing library for smart home arduino DIY project.
i want to use another library(not written by me).
here is the code:

boiler.cpp

    #include "Boiler.h"

    Boiler::Boiler(int pin)
    {
     _pin = pin;
     dev.setDevice(_pin);     // Set Device Output (on/off)
     turnOff();
    }

boiler.h

    #ifndef BOILER_H_
    #define BOILER_H_

    // include RF24 libs
    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>

    // SmartHome Lib Includes
    #include "Device.h"
    #include "TimerOne.h"
    #include "timeSet.h"

    class Boiler
    {

     private:

      RF24 radio(7, 8);
      RF24Network network(radio);
      RF24Mesh mesh(radio, network);

      int _pin ;

      void timerIsr();
      void DrawSCR();
     public:
      .
            .
            .

      Boiler (int pin );
      void turnOn();
      void turnOff();
    };

The problem is it's not compiling
the error I get is :
Boiler.h: 32:14: error: expected identifier before numeric constant
RF24 radio(7, 8)

What am i doing wrong?
Thanks,

title: Library using another library

Answers: 2

body:
I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file

    #include "RF24.h"
    #include "RF24Network.h"
    #include "RF24Mesh.h"
    #include <SPI.h>
    .
    .
    .
    #include "Boiler.h"

    RF24 radio(7, 8);         // Init RF24 Radio
    RF24Network network(radio);       // Init RF24 Network
    RF24Mesh mesh(radio, network);      // Init RF24 Mesh

    Boiler::Boiler(int pin ,float Rev , String Last )
    {
     _pin = pin;
     dev.setDevice(_pin);     // Set Device Output (on/off)
     turnOff();
    }

    void Boiler::init( char nodeID)
    {
     _nodeID = nodeID;
     // Connect to the mesh and set Node ID
     mesh.setNodeID(_nodeID);
     if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
     mesh.begin();

     // init LCD and print init data on LCD
     myGLCD.InitLCD(60);       // Init LCD 55 contrast
     myGLCD.setFont(SmallFont);     // Set small font
     myGLCD.clrScr();       // clr screen
     myGLCD.print("Boiler Device",0,0);   //Print init Data on screen
     myGLCD.print("Rev :" , 0 , 10);
     myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
     myGLCD.print(_last,0,40);
     myGLCD.update();       // Update display

     turnOff();
    }

and now it compiles ;-)

body:
> What am i doing wrong?

without seeing those includes, it is hard to tell.

I can say is that your original code, with the includes in boiler.h, is the right approach.

the revised code, which doesn't give you the error message, it not the right approach.

the issue is likely that the associated .h and .cpp files are incorrectly coded. unfortunately, without the actual code, it is hard to tell how and what the fixes should be.


body:
I'd made an LED driver, and fed both the LEDs and nano clone from 12V. The 12V switched power supply is of dubious quality. The nano itself read a pot, and wrote PWM values on three pins. It has run on-off for 2-3 months. Not long. Now it's dead - my PC does register the serial device on the nano, and the power LED comes on. Apart from that, there's nothing that works.

Before I replace it, I'd like to know if the most likely culprit was my feeding 12V into VIN. Overheating voltage regulator? The LEDs got a bit hot, ~40°, and the nano was in a box with no airflow.

title: Nano clone failure, how to prevent it from happening again?

Answers: 0


body:
I am attempting to use an arduino MEGA 2560 to control a digital potentiometer (AD5206), but I am getting some strange behavior. I have attached the CLK and MOSI pins (52 and 51, respectively) to an oscilloscope, and have run the following code:

    #include <SPI.h>
    void setup() {
        SPI.begin();
        SPI.transfer(5);
        delay(500);
    }

    void loop() {
        SPI.transfer(5);
        delay(500);
    }

When I look at the signal, the transfer in the setup() looks correct (5V x 00000011), but then the transfer in the loop() looks like it's shifted by -5V (-5V x 11111100). Has anyone ever run into this? Is it possible for the MEGA to output a negative voltage?

title: Mega SPI communication changing between setup and loop

Answers: 1

body:
No, there is no problem with SPI on the Mega. If there were it would have been noticed by now.

Instead it's either the way you are measuring it or your method of generating the SPI signals that are at fault (and since you won't show us your *real* code we can't help you with that).

This is a trace of your provided "code" with the delays reduced to allow easier fitting on a single trace:

[![enter image description here][1]][1]

Clock goes low when `SPI.begin()` is called. Then there are the successive transfers - the first being in `setup()` and the rest in `loop()`. As you can see they are all identical.

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


body:
I'm trying to parse the last character from the string of the reply from server and print them to serial monitor.

My arduino code:

    // This will send the request to the server
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
      delay(10);

      // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

My PHP page only shows the following though:

      Output: 1
      Watering: 1

I get the following output from my Serial Monitor:

      HTTP/1.1 200 OK
      Date: Fri, 28 Apr 2017 19:27:40 GMT
      Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1
      X-Powered-By: PHP/7.1.1
      Content-Length: 9
      Connection: close
      Content-Type: text/html; charset=UTF-8

      Output: 1
      Watering: 1

I want to get the value of Output(In this case it's a 1), and Watering(Also a 1), etc...

Preferably store them in an int.

I tried using startsWith,endsWith,etc. but to no avail :(

title: ESP8266 - Parsing last char from a string

Answers: 2

body:
I've converted the string to a char array and just checked if there is a 1 or a 0 at that region.

    // Read all the lines of the reply from server and print them to Serial
    String line;
    int value=0;
    while(client.available()){
      line += client.readStringUntil('\r');
    }
    //Serial.print(line);
    char charBuffer[line.length()+1];
    line.toCharArray(charBuffer, line.length()+1);
    for(int i=207;i<line.length()+1;i++)
    {
      if(charBuffer[i] == '1')
      {
        value = charBuffer[i];
      }
      if(charBuffer[i] == '0')
      {
        value = charBuffer[i];
      }
      Serial.print(charBuffer[i]);
      //delay(20);
    }

body:
If you have a String `s`, then `s.charAt(s.length() - 1)` give you that last char.

The function `length` gives you the number of chars in the string (not counting the '0' marker). The function `charAt` give you a single char at the position. The first char is at position 0.

For converting a single char digit `D` (0..9), you can use (`D` - '0').

Demo:

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      String s = "Watering: 1";
      char last = s.charAt(s.length() - 1);
      Serial.println(last);
      int value = (int) (last - '0');
      Serial.println(value);
    }

    void loop() {
    }


body:
Typically, when I connect my Arduino to a slave device through I2C or SPI, I'll control the slave using instructions coded in the firmware. The output data will be then printed to the Serial port and I'll use Python or MATLAB to read from the serial port and process the data later on.

    PC <- Arduino <--> Slave

Now say I want to control the I2C slave from my computer, i.e. write instructions to the I2C slave. How do I go about it? I thought of writing to the Arduino Serial port, making Arduino read it and hence configuring it but this doesn't seem efficient and I have been racking my head over this for a while.

title: Controlling I2C slave on Arduino with Python

Answers: 1

body:
Since you are using an arduino as a partial bridge to a PC, it appears that you already have a solution in hand.

There is a project on [Git][1] that is intended to perform this function that you could use for reference.  (Disclaimer -- I have not tested this code.)

The cheapest stand alone device that I found was a $15 breakout board from [Adafruit][2].

  [1]: https://gist.github.com/kraftb/8c0bbcc35a9778608d74
  [2]: https://www.adafruit.com/product/2264


body:
This may be a dumb question but I need some (preferably with wires already attached) and I'm unable to find any like this. Everything I find has male crimps and female surface mount. That doesn't work for very well with my project because I do not have room in my project box for another board. I'm already cramped just adding the headers that I was planning to solder these wires to.

Here is what I'm looking for in the 1.25mm variety:
[![2P 1.25mm Crimpable JST Male connectors][1]][1]

  [1]: https://i.stack.imgur.com/CzaKS.jpg

title: Do they make 2.54mm 2P Crimpable Micro JST Female connectors?

Answers: 1

body:
I've found this product listing on Amazon:

[2.54mm spacing JST extension cable.][1]

It resembles the connector you've shown only slightly, but may be the only option out there.

And to contest the above statement, one that looks more like your objective:

[Another 2.54mm spacing JST cable][2]

There may be others. I used "jst 2.54 mm 2 pin female cable" as the search terms specifically in Amazon, other sources may have similar results.

Firing up the old Google again, using the last set of search terms, I've found an eBay listing:

[eBay product listing][3]

with the source in china. The photo appears correct, although the listing is for two cables, one male, one female, there is a third photo with the circuit board mount type connector.

This particular listing calls them a 2.5 mm connector, close enough? Perhaps a translation error.

[![eBay listing photo][4]][4]

  [1]: https://www.amazon.com/Icstation-2-54mm-Female-Connector-Battery/dp/B01MQUJIYX/ref=sr_1_11?ie=UTF8&qid=1493427419&sr=8-11&keywords=jst 2.54 mm 2 pin female cable
  [2]: https://www.amazon.com/49cm-Long-Female-Connector-Cable/dp/B00HG7GNL0/ref=sr_1_16?ie=UTF8&qid=1493427419&sr=8-16&keywords=jst 2.54 mm 2 pin female cable
  [3]: http://www.ebay.com/itm/182174345865?rmvSB=true
  [4]: https://i.stack.imgur.com/bq3vE.jpg


body:
Cant seem to get this code to work with my arduino, and yes its all hooked up properally, even used leds to show that the button is being pressed, what am i doing wrong or dont know?

    const int digitalInPin3 = 8;     //switch
    int Occur = 0;
    int Switch = 0;

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

    void loop() {
    int Switch = digitalRead(digitalInPin3);

    if (Switch == 1){
      int Occur = 1;
    }

    else {
     int occur = 2;
    }

       Serial.print("\t Switch =");
       Serial.print(Switch);
       Serial.print("\t occur =");
       Serial.println(Occur);

      delay(1);
    }

title: Trying to print "occur = 1" in an if statement but it wont work

Answers: 2

body:
Remove the *int* from inside the if and else statement. The code would always show 0 because access of *occur*, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.

So change it to:

    if (Switch == 1){
     Occur = 1;
    }
    else {
     Occur = 2;
    }
This will work.

body:
The comments are right, as is the other answer.

Also, I see that both Switch and Occur are highlighted as if they are keywords.

I know for sure Switch is a reserved word.

Take all of these suggestions together.  Remove the int from inside the if.

I recommend you change the variable names entirely to something else.  And make them consistent.

Define them one time at the top then just modify them within the code.


body:
I have a problem. I want to make a car with a motor, front lights and rear lights. I want to run them at the same time but in different loops.

This is my code.

    const int red1 = 10;
    const int red2 = 11;
    const int blue1 = 12;
    const int blue2 = 13;
    const int front1 = 3;
    const int front2 = 4;
    const int back1 = 5;
    const int back2 = 6;
    const int enablePWMPin = 9;
    const int controlPinA = 8;
    const int controlPinB = 7;
    int buzzer = A0;

    void setup() {
      pinMode(red1, OUTPUT);
      pinMode(red2, OUTPUT);
      pinMode(blue1, OUTPUT);
      pinMode(blue2, OUTPUT);
      pinMode(front1, OUTPUT);
      pinMode(front2, OUTPUT);
      pinMode(back1, OUTPUT);
      pinMode(back2, OUTPUT);
      pinMode(enablePWMPin, OUTPUT);
      pinMode(controlPinA, OUTPUT);
      pinMode(controlPinB, OUTPUT);

      digitalWrite(enablePWMPin, LOW);
      digitalWrite(front1, LOW);
      digitalWrite(front2, LOW);
      digitalWrite(back1, LOW);
      digitalWrite(back2, LOW);
      digitalWrite(red1, LOW);
      digitalWrite(red2, LOW);
      digitalWrite(blue1, LOW);
      digitalWrite(blue2, LOW);
      noTone(buzzer);
    }

    void loop() {
      digitalWrite(enablePWMPin, HIGH);
      digitalWrite(controlPinA, HIGH);
      digitalWrite(controlPinB, LOW);
      delay(3000);
      digitalWrite(controlPinA, LOW);
      digitalWrite(controlPinB, HIGH);
      delay(3000);
    }

    void loop() {
      digitalWrite(red1, HIGH);
      digitalWrite(red2, HIGH);
      digitalWrite(blue1, LOW);
      digitalWrite(blue2, LOW);
      delay(250);
      digitalWrite(red1, LOW);
      digitalWrite(red2, LOW);
      digitalWrite(blue1, HIGH);
      digitalWrite(blue2, HIGH);
      delay(250);
    }

    void loop() {
      int directionA = digitalRead(controlPinA);
      int directionB = digitalRead(controlPinB);
      if (directionA == HIGH && directionB == LOW) {
        digitalWrite(front1, HIGH);
        digitalWrite(front2, HIGH);
        digitalWrite(back1, LOW);
        digitalWrite(back2, LOW);
      } else if (directionA == LOW && directionB == HIGH) {
        digitalWrite(back1, HIGH);
        digitalWrite(back2, HIGH);
        digitalWrite(front1, LOW);
        digitalWrite(front2, LOW);
      } else {
        digitalWrite(front1, LOW);
        digitalWrite(front2, LOW);
        digitalWrite(back1, LOW);
        digitalWrite(back2, LOW);
      }
    }

I'm using an Arduino Uno. Can I start all the loop() functions at the same time?

title: Can I make multiple loop() functions with Arduino Uno?

Answers: 5

body:
No you cannot.

Not only is it no proper C/C++ to have multiple identical functions, i.e. it will not compile (as jfpoilpret's comment suggests). It is also not in accordance with the idea of programm flow in the Arduino world - the [sketches](https://www.arduino.cc/en/Tutorial/BareMinimum) - where you have two methods on the highest (user accessible) level: `void setup()` and `void loop()`. `setup` is run exactly once at the beginning of your program. Following that `loop` is looped (hence the name) forever. You need to properly restructure your code to implement your intended program flow, i.e. call your own functions from `loop`. Read more on [www.arduino.cc](https://www.arduino.cc/en/Tutorial/BuiltInExamples) with tutorials worth studying.

body:
What are you trying to accomplish? Are these loops meant to run simultaneously (not possible)? Or one after the other? You could get pretty close to "simultaneous" if "real fast" is good enough. You'd need to

 - Give each loop function a new, unique name;
 - Split each of the first two loops at the delay()s for a total of 5 functions;
 - Use a timer library such as SimpleTimer to run each of the functions at the rate you need them to.
 - and from the only loop() function, keep calling SimpleTimer's '.run()' function to keep the whole thing going.

You could improve the speed of the individual functions by replacing the digitalRead() and digitalWrite() calls with direct reads and writes to port and bit you want read or set.

body:
>  I want to run them at the same time but in a different loop.

First of all, you can only do one thing at a time. So that's out.

Secondly, to run multiple loops sequentially (one at a time), it is fairly easy:

    void loop1(void) {...}
    void loop2(void) {...}
    ...

    void loop(void) {
      loop1(); //run loop1
      loop2(); //run loop2
      ...
      loopn(); //run loopn
    }

Whether it works will depend on how you have coded those loops.

body:
As the others have stated, no you can't have multiple loop functions. What you need to do is modify your approach so that each thing you are trying to do can be done sequentially without blocking (ie: remove the delay function usage). Expanding on some suggestions by JRobert, Here is how I would make these functions "run at the same time":

    void loop() {

        lights1();
        lights2();
        motor();

    }

    void lights1() {

      static unsigned long lastTime = 0;
      const long interval = 3000;
      static bool state = 0;

      unsigned long now = millis();

      if ( now - lastTime > interval && state == 0) {
        state = 1;
        lastTime = now;
        digitalWrite(enablePWMPin, HIGH);
        digitalWrite(controlPinA, HIGH);
        digitalWrite(controlPinB, LOW);
      }

      if ( now - lastTime > interval && state == 1) {
        state = 0;
        lastTime = now;
        digitalWrite(controlPinA, LOW);
        digitalWrite(controlPinB, HIGH);
      }
    }

    void lights2() {

      static unsigned long lastTime = 0;
      const long interval = 250;
      static bool state = 0;

      unsigned long now = millis();

      if ( now - lastTime > interval && state == 0) {
        state = 1;
        lastTime = now;
        digitalWrite(red1, HIGH);
        digitalWrite(red2, HIGH);
        digitalWrite(blue1, LOW);
        digitalWrite(blue2, LOW);
      }

      if ( now - lastTime > interval && state == 1) {
        state = 0;
        lastTime = now;
        digitalWrite(red1, LOW);
        digitalWrite(red2, LOW);
        digitalWrite(blue1, HIGH);
        digitalWrite(blue2, HIGH);
      }

    }

    void motor() {
      int directionA = digitalRead(controlPinA);
      int directionB = digitalRead(controlPinB);
      if (directionA == HIGH && directionB == LOW) {
        digitalWrite(front1, HIGH);
        digitalWrite(front2, HIGH);
        digitalWrite(back1, LOW);
        digitalWrite(back2, LOW);
      } else if (directionA == LOW && directionB == HIGH) {
        digitalWrite(back1, HIGH);
        digitalWrite(back2, HIGH);
        digitalWrite(front1, LOW);
        digitalWrite(front2, LOW);
      } else {
        digitalWrite(front1, LOW);
        digitalWrite(front2, LOW);
        digitalWrite(back1, LOW);
        digitalWrite(back2, LOW);
      }
    }

This approach will simulate running all three functions at the same time. Each function runs one at a time. But, since the delay has been removed from the light1/2 functions, they will end quickly during the 'waiting' period instead of pausing execution. This will allow the motor(s) to run and lights to blink all at the same time.

body:
To use multiple loops at the same time you need a **Arduino Due** Board.
It is the only board compatible with library `#include <Scheduler.h>`

See [Examples > Scheduler Library > Multiple Blinks][1]

    // Include Scheduler since we want to manage multiple tasks.
    #include <Scheduler.h>

    int led1 = 13;
    int led2 = 12;
    int led3 = 11;

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

      // Setup the 3 pins as OUTPUT
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);

      // Add "loop2" and "loop3" to scheduling.
      // "loop" is always started by default.
      Scheduler.startLoop(loop2);
      Scheduler.startLoop(loop3);
    }

    // Task no.1: blink LED with 1 second delay.
    void loop() {
      digitalWrite(led1, HIGH);

      // IMPORTANT:
      // When multiple tasks are running 'delay' passes control to
      // other tasks while waiting and guarantees they get executed.
      delay(1000);

      digitalWrite(led1, LOW);
      delay(1000);
    }

    // Task no.2: blink LED with 0.1 second delay.
    void loop2() {
      digitalWrite(led2, HIGH);
      delay(100);
      digitalWrite(led2, LOW);
      delay(100);
    }

    // Task no.3: accept commands from Serial port
    // '0' turns off LED
    // '1' turns on LED
    void loop3() {
      if (Serial.available()) {
        char c = Serial.read();
        if (c=='0') {
          digitalWrite(led3, LOW);
          Serial.println("Led turned off!");
        }
        if (c=='1') {
          digitalWrite(led3, HIGH);
          Serial.println("Led turned on!");
        }
      }

      // IMPORTANT:
      // We must call 'yield' at a regular basis to pass
      // control to other tasks.
      yield();
    }

  [1]: https://www.arduino.cc/en/Tutorial/MultipleBlinks