message:
LED strip and SD card

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) {

    }

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


sender: user

message:
Interrupt handler in library

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

sender: assistant

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


message:
MPU6050 doesn't work

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?

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


message:
Broken Loop and dim LEDs

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.

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?


message:
NodeMCU power consumption measurement and DeepSleep

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"

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/)).


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

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?

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.


message:
Powering SD breakout board with 3.7V battery

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?

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


message:
How to use ESP8266 for wireless communication?

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.

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.


message:
Serial communication with more than two Arduinos

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);
       }
      }
    }

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


message:
Servo jitter with Arduino

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);
    }

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!


message:
WiFi connections being lost on connection reset

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?

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.


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

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?

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;
    }


message:
Library using another library

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,

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.


message:
Mega SPI communication changing between setup and loop

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?

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


message:
ESP8266 - Parsing last char from a string

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 :(

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() {
    }


message:
Controlling I2C slave on Arduino with Python

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.

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


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

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

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


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

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);
    }

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.


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

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?

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


message:
Different ways (and the fastest) to compute sines (and cosines) in Arduino

I am using an Arduino Uno board to compute the angles of my system (robotic arm). The angles are actually 10 bit values (0 to 1023) from the ADC, using the full range of the ADC. I am only going to be operating in the 1st quadrant (0 to 90 deg), where both sines and cosines are positive, so there is no problem with negative numbers. My doubts can be expressed in 3 questions:

1. What are the different ways to compute these trigonometric functions on Arduino?

2. What is the fastest way to do the same?

3. There are the sin() and cos() functions in the Arduino IDE, but how does the Arduino actually calculate them (as in do they use look-up tables, or approximations etc.)? They seem like an obvious solution, but I would like to know their actual implementation before I try them out.

PS: I am open to both standard coding on the Arduino IDE and assembly coding, as well as any other options not mentioned. Also I have no problems with errors and approximations, which are inevitable for a digital system; however if possible it would be good to mention the extent of possible errors

body:
generally, look-up table > approximation -> calculation. ram > flash. integer > fixed point > floating point. pre-calclation > real time calculation. mirroring (sine to cosine or cosine to sine) vs. actual calculation / look-up....

each has its pluses and minuses.

you can make all sorts of combinations to see which works best for your application.

edit: I did a quick checking. using 8-bit integer output, calculating 1024 sin values with look-up table takes 0.6ms, and 133ms with floaters, or 200x slower.


body:
The two basic methods are mathematical calculation (with polynomials) and lookup tables.

The Arduino's math library (libm, part of avr-libc) uses the former. It is optimised for the AVR in that it is written with 100% assembly language, and as such is almost impossible to follow what it's doing (there's zero comments as well). Rest assured though it will be the most optimised pure-float implementation brains far superior to ours could come up with.

However the key there is *float*. Anything on the Arduino involving floating point is going to be heavyweight by comparison to pure integer, and since you are only requesting integers between 0 and 90 degrees a simple lookup table is by far the simplest and most efficient method.

A table of 91 values will give you everything from 0 to 90 inclusive. However if you make that a table of floating point values between 0.0 and 1.0 you still then have the inefficiency of working with floats (granted not as inefficient as calculating `sin` with floats), so storing a fixed point value instead would be far more efficient.

That may be as simple as storing the value multiplied by 1000, so you have between 0 and 1000 instead of between 0.0 and 1.0 (for instance sin(30) would be stored as 500 instead of 0.5). More efficient would be to store the values as, for instance, a Q16 value where each value (bit) represents 1/65536th of 1.0. These Q16 values (and the related Q15, Q1.15, etc) are more efficient to work with since you have powers-of-two which computers love to work with instead of powers-of-ten which they hate working with.

Don't forget as well that the `sin()` function expects radians, so you first have to convert your integer degrees into a floating point radians value, making the use of `sin()` even more inefficient compared to a lookup table that can work directly with the integer degrees value.

A combination of the two scenarios, though, is possible. *Linear interpolation* will allow you to get an approximation of a floating point angle between two integers. It's as simple as working out how far between two points in the lookup table you are and creating a weighted average based on that distance of the two values. For instance if you are at 23.6 degrees you take `(sintable[23] * (1-0.6)) + (sintable[24] * 0.6)`. Basically your sine wave becomes a series of discrete points joined together by straight lines.  You trade accuracy for speed.


body:
You could create a couple of functions that uses linear approximation to determine the sin() and cos() of a particular angle.

I am thinking something like this:
[![linear approximation][2]][2]
For each I have broken the graphical representation of sin() and cos() into 3 sections and have done a linear approximation of that section.

Your function would ideally first check that the range of the angel is between 0 and 90.
Then it would use an `ifelse` statement to determine what of the 3 sections it belongs and then does the corresponding linear calculation (ie `output = mX + c`)

  [1]: http://stackoverflow.com/a/2088589/6075112
  [2]: https://i.stack.imgur.com/4WuNU.gif


body:
I looked for other people that had approximated cos() and sin() and I came across this answer:

[dtb's answer to "Fast Sin/Cos using a pre computed translation array"][1]

Basically he computed that the math.sin() function from the math library was faster than using a look-up table of values. But from what I can tell, this was computed on a PC.

Arduino has a [math library][2] included that can calculate sin() and cos().

  [1]: https://stackoverflow.com/a/2088589/6075112
  [2]: https://www.arduino.cc/en/Reference/MathHeader


body: A lookup table will be the fastest way to find sines. And if you're comfortable computing with fixed-point numbers (integers whose binary-point is somewhere other than to the right of bit-0), your further calculations with the sines will be much faster as well. That table can then be a table of words, possibly in Flash to save RAM space. Note that in your math you may need to use longs for large intermediate results.


body:
There are some good answers here but I wanted to add a method which hasn't been mentioned yet, one very well suited to computing trigonometric functions on embedded systems, and that's the CORDIC technique
[Wiki Entry Here][1] It can compute trig functions using only shifts and adds and a small look-up table.

Here's a crude example in C. In effect, it implements the C libraries' atan2() function using CORDIC (i.e. find an angle given two orthogonal components.) It uses floating point, but can be adapted for use with fixed-point arithmetic.

    /*
     * Simple example of using the CORDIC algorithm.
     */

    #include <stdio.h>
    #include <math.h>

    #define CORDIC_TABLE_SIZE  16

    double cordic_table[CORDIC_TABLE_SIZE];

    void init_table(void);
    double angle(double I, double Q);

    /*
     * Given a sine and cosine component of an
     * angle, compute the angle using the CORIDC
     * algoritm.
     */
    double angle(double I, double Q)
    {
        int L;
        double K = 1;
        double angle_acc = 0;
        double tmp_I;

        if (I < 0) {
            /* rotate by an initial +/- 90 degrees */
            tmp_I = I;
            if (Q > 0.0) {
                I = Q;           /* subtract 90 degrees */
                Q = -tmp_I;
                angle_acc = -90;
            } else {
                I = -Q;          /* add 90 degrees */
                Q = tmp_I;
                angle_acc = 90;
            }
        } else {
            angle_acc = 0;
        }

        /* rotate using "1 + jK" factors */
        for (L = 0, K = 1; L <= CORDIC_TABLE_SIZE; L++) {
            tmp_I = I;
            if (Q >= 0.0) {
                /* angle is positive: do negative roation */
                I += Q * K;
                Q -= tmp_I * K;
                angle_acc -= cordic_table[L];
            } else {
                /* angle is negative: do positive rotation */
                I -= Q * K;
                Q += tmp_I * K;
                angle_acc += cordic_table[L];
            }
            K /= 2.0;
        }
        return -angle_acc;
    }

    void init_table(void)
    {
        int i;
        double K = 1;

        for (i = 0; i < CORDIC_TABLE_SIZE; i++) {
            cordic_table[i] = 180 * atan(K) / M_PI;
            K /= 2.0;
        }
    }
    int main(int argc, char **argv)
    {
        double I, Q, A, Ar, R, Ac;

        init_table();

        printf("# Angle,    CORDIC Angle,  Error\n");
        for (A = 0; A < 90.0; A += 0.5) {

            Ar = A * M_PI / 180; /* convert to radians for C's sin & cos fn's */

            R = 5;  // Arbitrary radius

            I = R * cos(Ar);
            Q = R * sin(Ar);

            Ac = angle(I, Q);
            printf("�, �,   .4e\n", A, Ac, Ac-A);
        }
        return 0;
    }

But try the native Arduino trig functions first - they might be fast enough anyway.

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


body:
I have been playing a bit with computing sines and cosines on the
Arduino using fixed-point polynomial approximations. Here are my
measurements of average execution time and worst case error, compared
with the standard `cos()` and `sin()` from avr-libc:

    function    max error   cycles   time
    -----------------------------------------
    cos_fix()   9.53e-5     108.25    6.77 µs
    sin_fix()   9.53e-5     110.25    6.89 µs
    cos()       2.98e-8     1720.8   107.5 µs
    sin()       2.98e-8     1725.1   107.8 µs

It's based on a 6th degree polynomial computed with only
4 multiplications. The multiplications themselves are done in
assembly, as I found that gcc implemented them inefficiently. The angles
are expressed as `uint16_t` in units of 1/65536 of a revolution, which
makes the arithmetic of angles naturally work modulo one revolution.

If you think this can suit your bill, here is the code: [Fixed-point
trigonometry](https://wiki.logre.eu/index.php/Trigonométrie_en_virgule_fixe).
Sorry, I still did not translate this page, which is in French, but you
can understand the equations, and the code (variable names, comments...)
is in English.

------------------------------------------------------------------------

**Edit**: Since the server seems to have vanished, here is some info on
the approximations I found.

I wanted to write angles in binary fixed-point, in units of quadrants
(or, equivalently, in turns). And I also wanted to use an even
polynomial, as these are more efficient to compute than arbitrary
polynomials. In other words, I wanted a polynomial P() such that

cos(π/2 x) ≈ P(x2)  for x ∈ [0,1]

I also required the approximation to be exact at both ends of the
interval, to ensure that cos(0) = 1 and
cos(π/2) = 0. These constraints led to the form

P(u) = (1 − u)(1 + uQ(u))

where Q() is an arbitrary polynomial.

Next, I searched for the best solution as a function of the degree of
Q() and found this:

            Q(u)             │ degree of P(x²) │ max error
    ─────────────────────────┼─────────────────┼──────────
              0              │         2       │  5.60e-2
           −0.224            │         4       │  9.20e-4
    −0.2335216 + 0.0190963 u │         6       │  9.20e-6

The choice among the solutions above is a speed/accuracy trade-off. The
third solution gives more accuracy than achievable with 16-bits, and
it's the one I chose for the 16-bit implementation.


body:
I had a simillar question to OP. I wanted to make a LUT table to calculate the first quadrant of the sine function as unsigned 16 bit integers starting from 0x8000 to 0xffff. And i ended up writing this for fun and profit. Note: This would work more efficiently if i used 'if' statements. Also it's not very accurate, but would be accurate enough for a sine wave in a sound synthesiser

    void sin_lut_ctor(){

    //Make a Look Up Table for 511 terms of the sine function.
    //Plugin in some polynomials to do some magic
    //and you get an aproximation for sines up to π/2.
    //

    //All sines yonder π/2 can be derived with math

    const uint16_t uLut_d = 0x0200; //maximum LUT depth for π/2 terms.
    uint16_t uLut_0[uLut_d];        //The LUT itself.
    //Put the 2 above before your void setup() as global variables.
    //This coefficients will only work for uLut_d = 511.

    uint16_t arna_poly_0 = 0x000a; // 11
    uint16_t arna_poly_1 = 0x0001; // 1
    uint16_t arna_poly_2 = 0x0007; // 7
    uint16_t arna_poly_3 = 0x0001; // 1   Precalculated Polynomials
    uint16_t arna_poly_4 = 0x0001; // 1
    uint16_t arna_poly_5 = 0x0007; // 7
    uint16_t arna_poly_6 = 0x0002; // 2
    uint16_t arna_poly_7 = 0x0001; // 1

    uint16_t Imm_UI_0 = 0x0001;              //  Itterator
    uint16_t Imm_UI_1 = 0x007c;              //  An incrementor that decreases in time

    uint16_t Imm_UI_2 = 0x0000;              //
    uint16_t Imm_UI_3 = 0x0000;              //
    uint16_t Imm_UI_4 = 0x0000;              //
    uint16_t Imm_UI_5 = 0x0000;              //
    uint16_t Imm_UI_6 = 0x0000;              //  Temporary variables
    uint16_t Imm_UI_7 = 0x0000;              //
    uint16_t Imm_UI_8 = 0x0000;              //
    uint16_t Imm_UI_9 = 0x0000;              //
    uint16_t Imm_UI_A = 0x0000;
    uint16_t Imm_UI_B = 0x0000;

    uint16_t Imm_UI_A = uLut_d - 0x0001;     //  510

    uLut_0[0x0000] = 0x8000;        //Assume that the middle point is 32768 (0x8000 hex)
    while (Imm_UI_0 < Imm_UI_A) //Construct a quarter of the sine table
      {
    Imm_UI_2++;                                   //Increase temporary variable by 1

    Imm_UI_B = Imm_UI_2 / arna_coeff_0;           //Divide it with the first coefficient (note: integer division)
    Imm_UI_3 += Imm_UI_B;                         //Increase the next temporary value if the first one has increased up to the 1st coefficient
    Imm_UI_1 -= Imm_UI_B;                         //Decrease the incrementor if this is the case
    Imm_UI_2 *= 0x001 - Imm_UI_B;                 //Set the first temporary variable back to 0

    Imm_UI_B = Imm_UI_3 / arna_poly_1;           //Do the same thing as before with the next set of temporary variables
    Imm_UI_4 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_3 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_4 / arna_poly_2;           //And again... and again... you get the idea.
    Imm_UI_5 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_4 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_5 / arna_poly_3;
    Imm_UI_6 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_5 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_6 / arna_poly_4;
    Imm_UI_7 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_6 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_7 / arna_poly_5;
    Imm_UI_8 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_7 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_8 / arna_poly_6;
    Imm_UI_9 += Imm_UI_B;
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_8 *= 0x0001 - Imm_UI_B;

    Imm_UI_B = Imm_UI_9 / arna_poly_7          //the last set won't need to increment a next variable so skip the step where you would increase it.
    Imm_UI_1 -= Imm_UI_B;
    Imm_UI_9 *= 1 - Imm_UI_B;

    uLut_0[Imm_UI_0] = (uLut_0[Imm_UI_0 - 0x0001] + Imm_UI_1); //Set the current value as the previous one increased by our incrementor
    Imm_UI_0++;              //Increase the itterator
      }
      uLut_0[Imm_UI_A] = 0xffff; //Lastly, set the last value to 0xffff

      //And there you have it. A sine table with only one if statement (a while loop)
    }

Now to get back the values, use this function.It accepts a value from 0x0000 to 0x0800 and returns the appropriate value from the LUT

    uint16_t lu_sin(uint16_t lu_val0)
    {
      //Get a value from 0x0000 to 0x0800. Return an appropriate sin(value)
      Imm_UI_0 = lu_val0/0x0200; //determine quadrant
      Imm_UI_1 = lu_val0%0x0200; //Get which value
      if (Imm_UI_0 == 0x0000)
      {
        return uLut_0[Imm_UI_1];
      }
      if (Imm_UI_0 == 0x0001)
      {
        return uLut_0[0x01ff - Imm_UI_1];
      }
      if (Imm_UI_0 == 0x0002)
      {
        return 0xffff - uLut_0[Imm_UI_1];
      }
      if (Imm_UI_0 == 0x0003)
      {
        return 0xffff - uLut_0[0x01ff - Imm_UI_1];
      }
    }// I'm using if statements here but similarly to the above code block,
     //you can do without. just with integer divisions and modulos

Remember, this is not the most efficient approach to this task, i just couldn't figure out how to make taylor series to give out results in the appropriate range.


body:
Just for the fun of it, and to prove it can be done, I finished an AVR assembly routine to calculate sin(x) results in 24 bits (3 bytes) with one bit of error.  The input angle is in degrees with one decimal digit, from 000 to 900 (0~90.0) for the first quadrant only.  It uses less than 210 AVR instructions and runs on average of 212 microseconds, varying from 211us (angle=001) to 213us (angle=899).

It took several days to do it all, more than 10 days (free hours) just thinking about the best algorithm for the calculation, considering the AVR microcontroller, no floating point, eliminating all possible divisions. What took more time was to make the right step-up values for integers, to have good precision it needs to step-up values of 1e-8 to binary integers 2^28 or more.  Once all the errors culprits of precision and rounding up were found, increased their calculation resolution by extra 2^8 or 2^16, the best results were met.  I first simulated all the calculations on Excel taking care of having all values as Int(x) or Round(x,0) to represent exactly the AVR core processing.

For example, in the algorithm the angle must be in Radians, the input is in Degrees to facilitate for the user.  To convert Degrees to Radians the trivial formula is rad=degrees*PI/180, it seems nice and easy, but it is not, PI is an infinite number - if using few digits it will create errors at the output, division by 180 requires AVR bit manipulation since it has no division instruction, and more than that, the result would require floating point since involves numbers far below integer 1. For example, Radian of 1° (degree) is 0.017453293. Since PI and 180 are constants, why not reverse this thing for simple multiplication?  PI/180 = 0.017453293, multiply it by 2^32 and it results as a constant 74961320 (0x0477D1A8), multiply this number by your angle in degrees, lets say 900 for 90° and shift it 4 bits right (÷16) to obtain 4216574250 (0xFB53D12A), that is the radians of the 90° with 2^28 expansion, fit in 4 bytes, without a single division (except the 4 bit shift right). In a way, the error included in such trick is smaller than 2^-27.

So, all further calculations need to remember it is 2^28 higher and taken care of it. You need to divide the on-the-go results by 16, 256 or even 65536 just to avoid it use unnecessary growing hunger bytes that would not help resolution.  That was a painstaking job, just finding the minimum quantity of bits in each calculation results, keeping the results precision around 24 bits. Each one of the several calculations where done in try/error with higher or lower bits count in the Excel flow, watching the overall quantity of error bits at the result in a graph showing 0-90° with a macro running the code 900 times, once per tenth of a degree. That "visual" Excel approach was a tool I created, helped a lot to find the best solution for every single part of the code.

For example, rounding up this particular calculation result 13248737.51 to 13248738 or just lose the "0.51" decimals, how much it will affect the final result precision for all the 900 input angles (00.1 ~ 90.0) tests?

I was able to keep the animal contained within 32 bits (4 bytes) on every calculation, and ended up with the magic to obtain precision within 23 bits of the result. When checking the whole 3 bytes of the result, the error is ±1 LSB, outstanding.

The user may grab one, two or three bytes from the result for its own requirements of precision.  Of course, if just one byte is enough I would recommend to use a single 256 bytes sin table and use AVR 'LPM' instruction to grab it.

Once I had the Excel sequence running smooth and neat, the final translation from Excel to AVR assembly took less than 2 hours, as usual you should think more first, work less later.

At that time I was able to squeeze yet more and reduce registers usage. The actual (not final) code uses around 205 instructions (~410 bytes), runs a sin(x) calculation in average of 212us, clock at 16MHz. At that speed it can calculate 4700+ sin(x) per second. Not being important, but it can run a precise sinewave up to 4700Hz with 23 bits of precision and resolution, without any lookup tables.

The base algorithm is based on Taylor series for sin(x), but modified a lot to fit my intentions with the AVR microcontroller and precision in mind.

Even that using a 2700 bytes table (900 entries * 3 bytes) would be speed attractive, what is the fun or learning experience on that?  Of course, CORDIC approach was also considered, maybe later, the point here is to squeeze Taylor into the AVR core and take water from a dry rock.

I wonder if Arduino "sin(78.9°)" can run Processing (C++) with 23 bits of precision in less than 212us and the necessary code smaller than 205 instructions. May be if C++ uses CORDIC.  Arduino sketches can import assembly code.

Makes no sense to post the code here, later I will edit this post to include a weblink to it, possibly on my blog at [this url][1]. The blog is mostly in portuguese.

This hobby-no-money venture was interesting, pushing the limits of the AVR engine of almost 16MIPS at 16MHz, without division instruction, multiplication only in 8x8 bits.  It allows to calculate sin(x), cos(x) [=sin(900-x)] and tan(x) [=sin(x)/sin(900-x)].

Above it all, this helped to keep my 63 years old brain polished and oiled. When teenagers say the 'old people' know sh*nothing about technology, I answer "think again, who do you think created the bases for everything you enjoy today?".

Cheers

  [1]: http://www.ustr.net/blog/xblog/


body:
As others have mentioned lookup tables are the way to go if you want speed. I've recently been investigating computation of trig functions on an ATtiny85 for use of fast vector averages (wind in my case). There's always trade off's...for me I only needed 1 deg angular resolution so a lookup table of 360 int's (scaling -32767 to 32767, only working with int's) was the best way to go. Retrieving the sine is just a matter of supplying an index 0-359...so very fast! Some numbers from my tests:

FLASH lookup time (us): 0.99 (table stored using PROGMEM)

RAM lookup time (us): 0.69 (table in RAM)

Lib time (us): 122.31 (Using Arduino Lib)

Note these are averages across a 360 point sample for each. Testing was done on a nano.


message:
Is setting AVR TWCR for mega328p TWEN in each function necessary?

I found this useful website explaining for to configure and implement the TWI for mega328p, but what I found not so obvious is that in the website they set TWEN in every function, while in the datasheet C code example, they only set it in START and STOP functions.

I also find another style in Arduino Wire library, that they implement more easier functions for starting and ending the module.

This is the website, could anyone take a look and tell me if setting TWEN in each function is necessary?

Also, is it necessary to check for TWINT after sending STOP command?

[http://www.embedds.com/programming-avr-i2c-interface/][1]

Regards,

  [1]: http://www.embedds.com/programming-avr-i2c-interface/

body:
The big difference is interrupt driven or busy wait implementation of the TWI hardware module protocol. Enabling interrupts is necessary in an interrupt driven implementation while busy wait should not enable interrupts.

A busy wait implementation is much simpler but it cannot be asynchronous. An interrupt driven implementation can be asynchronous and even power down the rest of the MCU during the TWI communication. It should be noted that the Arduino Wire class is interrupt driven but synchronous.

Cheers!


message:
How does ESP8266 work as web server with Arduino?

I am trying to learn internet of things with smart home. I will connect an ESP8266 and an Arduino with the IBM Bluemix server to control a circuit from a public IP.

I want to start with the local network for now. I have gone through a couple of links which seem like a great start http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/

They explain how it works, and have source code but no circuit diagram. How should I connect the ESP8266 with Arduino for this example ?

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

[![enter image description here][2]][2]

 #include <SoftwareSerial.h>

 const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
 const byte txPin = 3; // Wire this to Rx Pin of ESP8266

 // We'll use a software serial interface to connect to ESP8266
 SoftwareSerial esp8266(rxPin,txPin);

 void setup() {
   Serial.begin(9600);
   esp8266.begin(9600);
   delay(1000);
 }

 void loop() {
   Serial.println("Sending an AT commands");
   esp8266.println("AT");
   delay(30);
   while(esp8266.available()) {
  String data = esp8266.readStringUntil('\n');
  Serial.println("Got response from esp8266: " + data);
   }
 }

  [1]: https://i.stack.imgur.com/Ldlol.jpg
  [2]: https://i.stack.imgur.com/T2GLD.jpg

body:
The exact same way as any other ESP8266 example. The fact that you are using it as a web server doesn't change how you wire it.

For that specific code snippet it even tells you in the comments:

    // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
    // This means that you need to connect the TX line from the esp to the Arduino's pin 2
    // and the RX line from the esp to the Arduino's pin 3


message:
How does Arduino WiFi Shield connect to Blynk and How can I use ESP Module to connect to blynk?

I was actually quite impressed how easily Blynk gets connected to Arduino. So I had a doubt how does Arduino WiFi Shield allow Arduino Uno to connect to blynk ? And my second doubt is how can I use the ESP boards to connect to blynk using Windows10 ( for steps ) ?
Thank You.

body:
> how does Arduino WiFi Shield allow Arduino Uno to connect to blynk

Blynk is just a web service. The WiFi shield connects your board to the internet and sends data to that web service. The Blynk app is just an interface to that web service.

> how can I use the ESP boards to connect to blynk using Windows10?

That makes no sense. You can connect an MCU to Blynk through something like an ESP8266 board (or program the ESP8266 board directly to communicate with Blynk). It is merely a network interface.

Windows 10 is not an MCU, and you already have an internet connection on it. If you want to communicate with Blynk from Windows 10 I suggest you look at the documents to see if there is an API you can use from your own programs, or a web interface you can view in your browser of choice.

Windows 10 and ESP8266 are two completely alien concepts.


message:
Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible?

Is it possible to sandwich an XBee shield between Arduino Mega and Ramps 1.4 without damaging any of the boards or lose of Ramps functionality ?

I am not trying to make a 3D printer it is rather a completely different project and I am afraid of burning my XBee or losing some functionality of ramps.

Since XBee shield has the form factor of Arduino UNO I had to 3D print the rest of the shield and use some connectors to completely cover the Mega.

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

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

body:
Yes, it would seem like folks on the RepRap forums have gotten this to work with the following setup that should work in general:

> Attach the XBee shield to the RAMPS board by attaching 4 pins on AUX-1 (namely, 5V, Gnd, D1 and D0) to the 5V, Gnd, Rx and Tx pins on the XBee Shield
>
> Switch the UART / DLINE switch on the XBee Shield to UART

Source: [RepRap Forum: Printing completely wirelessly - can it be done?][1]

This [forum thread][2] may also be useful.

  [1]: http://forums.reprap.org/read.php?219,105307
  [2]: http://forums.reprap.org/read.php?219,455864


body:
Yes, and the answer is really simple.  You need to extend the connectors between the xbee shield and the ramps shield.  Either by adding another layer of the through pin connectors you have or by resoldering some longer ones on the RAMPS board.

You might have an issue with the RF signal, sticking that much metal near the xbee board might cause problems, but I think you can get external aerials for them, if that becomes an issue.


message:
Can I cut the pin holes off of my Arduino board?

I'm making a project, but my arduino pro micro is just slightly too big to fit in it's case.

What would happen if I cut off the pin holes that I don't need? Would it still work? Or would it be ruined?

body:
I guess that one *could* cut (or hone down) parts of the PCB. Obviosly this process devoids the warranty and there is the risk of damaging either the board or some components on it (i.e. by holding or clamping it during the process).

I would not expect any other wiring besides those connecting the pins to run in this part of the PCB. The reference layout (see [board layout](https://www.arduino.cc/en/Main/arduinoBoardMicro#documentation) and using [Eagle (free version)](http://www.autodesk.com/products/eagle/free-download)) - if the clones follow that layout - confirms that there are no other traces there. So it is mostly important to not cut any other traces and remove any chippings after the cutting to avoid short circuits.

If in doubt buy two or three boards ;) to try and repeat the process.


body:
This is a bad ideas:

 - the PCB is made of fiber glass which, when broken, cut or filed, produces a very fine powder; any powder you might breath in during the process wil stay in lungs for a very long time, in the order of decades

 - the risk of cracking traces running close to the are of cut, even if they are not directly being cut, is pretty high; the copper traces rely on the fiberglass rigidity, but a crack in the fiberglass propagating under the traces is welcoming a broken trace

Go for a different case, if that's not a viable option go for a barebone arduino. If that is also a non viable option consider the idea of producing a few custom PCBs: they are not that expensive!


body:
Rather than trying to modify the board (which I think is a bad idea) why not use a `Pro Mini`.

These are smaller (and cheaper), and almost identical in function, apart from the USB interface. You do need a serial interface (or ICSP) to program.


body: You could use a Pro Mini as Milliways suggested, but you don't necessarily need a USB interface to programme it.  You can use your Arduino UNO to directly programme the Arduino Pro Mini.


message:
Testing an oscilloscope with my Arduino

I bought a very old oscilloscope and although it works, I have my doubts about refreshing the screen (the electron beam fades away very slowly or is not showing up consistently across the screen).

I tested a bit with `digitalWrite` and `anlogWrite`, but this only sends either 0 or 5V out. Is there a way to make a preferably sine or triangle wave of 0 to 5V or -5 to +5V... I guess the Arduino should be capable of it, but so far I only get 0V or 5V out, nothing in between.

According to [lesson 8][1] I should get a variable voltage of 0-5V on a pin with `analogWrite`, but all I get is 0 or 5V.

  [1]: http://www.toptechboy.com/arduino/lesson-8-writing-analog-voltages-in-arduino/

For what I see:

1. PWM gives with `analogWrite` a pulse signal of 0V or 5V with a duty cycle.
2. non PWM pins give either 0V or 5V (`analogWrite` of 0-127 appr: 0V, >127: 5V).

body:
You can convert the PWM output of `analogWrite()` into an (approximate) analog voltage by adding a low-pass filter. That is, a resistor in series followed by a capacitor to ground.

The values to choose depend on the frequency response you want.

* [RC Filter Calculator](http://sim.okawa-denshi.jp/en/CRtool.php) (second section).

For anything more complex or accurate you will need a DAC. I often use the MCP4822 SPI DAC chip.


body:
a few ways:

1) you can generate a square wave of a known frequency to test the time base of the scope;

2) you can generate an analog signal to test for the vertical. that can be done via pwm or dds.


message:
Can I make existing libraries use external SRAM for the Arduino

I am running out of memory on my Arduino due to the libraries I am using. After I have included all the libraries I need then there is very little in the way of free memory for my own code.

If hook up some external RAM to the Arduino, is there a way I can make existing libraries use the external RAM rather than the SRAM on the arduino or will I need to alter the code in the library to do it.

If I have to modify the code is that a relatively easy thing to do?

body:
Making a library use external SRAM is not an easy task. It *can* be cone, but it takes quite a bit of work.

The best start would be to abstract the SRAM into a library that provides simple access to it. Then you would need to use that new library to read and write data in the SRAM instead of accessing variables in the other libraries.

There is no way of simply mapping a variable into external SRAM - for that you need a microcontroller with an MMU  and/or an EIB.


body:
> What did programmers do back in the 80-ies when they run out of memory?

There is an old technique called [overlays][1]. The same area of memory is used for different phases/steps of a program. Results are naturally saved but any intermediate data is discharged before the next phase/step which reuses the "common" area of memory. Necessary state may be saved to an external storage between execution of the phase/step to increase available local memory.

To compile and link this you have to do some deep diving into the manual and read up on [memory sections][2].

It is possible to abstract this using C++ smart pointers but getting existing libraries to use it will be a very tough challenge. There are a few attempts to support virtual memory such as [virtmem][3].

Cheers!

  [1]: https://en.wikipedia.org/wiki/Overlay_(programming)
  [2]: http://www.nongnu.org/avr-libc/user-manual/mem_sections.html
  [3]: https://github.com/rhelmus/virtmem


message:
Getting an error while uploading code to Arduino when ESP8266 is attached

I am trying to use an ESP8266 and an Arduino to access the Arduino from the network. I tried to do something but I'm facing some challenges. I hope I am using the correct board "Generic ESP8266 Module".

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

[![enter image description here][2]][2]

 #include <SoftwareSerial.h>

 const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
 const byte txPin = 3; // Wire this to Rx Pin of ESP8266

 // We'll use a software serial interface to connect to ESP8266
 SoftwareSerial esp8266(rxPin,txPin);

 void setup() {
   Serial.begin(9600);
   esp8266.begin(9600);
   delay(1000);
 }

 void loop() {
   Serial.println("Sending an AT commands");
   esp8266.println("AT");
   delay(30);
   while(esp8266.available()) {
  String data = esp8266.readStringUntil('\n');
  Serial.println("Got response from esp8266: " + data);
   }
 }

**Error**

    Archiving built core (caching) in: C:\Users\XYZ~1\AppData\Local\Temp\arduino_cache_322251\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
    Sketch uses 226657 bytes (52%) of program storage space. Maximum is 434160 bytes.
    Global variables use 32464 bytes (39%) of dynamic memory, leaving 49456 bytes for local variables. Maximum is 81920 bytes.
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/bxbUr.png
  [2]: https://i.stack.imgur.com/PK7K9.jpg
  [3]: https://i.stack.imgur.com/COggx.png

body:
Uploading programs to the Arduino requires the RX and TX lines. The ESP8266 module is probably interfering. You will need to disconnect the ESP8266 module, or at least, don't power the module while uploading.

Connecting the ESP8266 to RX/TX pins will probably also prevent you from using the serial terminal to output debugging information.

An alternative would be to use the (not so great, but it works) [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) library.


body:
First off you have the wrong board selected. It's the Arduino Uno that you are programming, not the ESP8266. Just because you have connected an ESP8266 to the Arduino doesnt't magically change what the Uno is.

Secondly you cannot have anything connected to pins 0 and 1 of the Arduino while programming. Those pins are used for communication with the PC. As a general rule it is best to never use ghem for anything.

To communicate between the Arduino and the ESP8266 you should either pick two other pins and use SoftwareSerial or invest in a board that has at least one independent UART (such as the Mega2560 or the Leonardo).


body:
I believe you are trying to directly program the ESP8266 and you're simply using the Arduino Uno as a USB to serial interface for your computer. There are many tutorials on the web on how to do this. First thing I see wrong with your setup is you've left the Arduino Uno MCU attached to the board. The first thing you'll want to do is remove this chip carefully (the pins can bend easily so apply force evenly). Right now when the Arduino IDE tries to talk to the ESP8266 the communication is going to both the ESP8266 and the Arduino. Physically removing the Arduino MCU chip will ensure any communication is directly with the ESP8266.

Also make sure you are connecting the correct voltage. ESP8266 can only handle 3.3V max, while the Arduino runs at 5V mostly. I believe the Uno board provides a 3.3V output but I'm not 100% sure.


message:
How to pass a string pointer to a function

I'm working on a project, where I wish to use pointers. I had a very quick overview of using pointers in C in collage, but I don't know how to use them.

I want that function uses input String (answer) as pointer.

Calling function in setup block

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

    void setup() {
     sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");
     sendCommand("AT+CWSAP_CUR=\"mega\",\"password123\",10,3\r\n", 4000, DEBUG, "OK");
    }

    String sendCommand(String command, const int timeout, boolean debug, String *answer)
    {
     String response = "";

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

     long int time = millis();

     while ((time + timeout) > millis())
     {
      while (Serial1.available())
      {
       // The esp has data so display its output to the serial window
       char c = Serial1.read(); // read the next character.
       response += c;
      }

      //Waiting for the right answer and breaking a while loop
      if (response.indexOf(*answer) > 0)
      {
                break;
      }

     }

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

     return response;
    }

body:
What you have there are not String objects, but *string literals*. Their type is `const char *`

You should avoid using String objects if at all possible. Instead use character arrays.

To get a character array out of a function it is best to create one outside your function and pass it to the function as one of the parameters. The return value of the function can then be a status value indicating if the call worked or not.


body:
If you want to use the `String` type, have a variable `String rdy="ready";` and pass `&rdy` (the address of the variable). Same with "OK".

I assume you want to use a pointer to avoid copying?

As you are already using C++ techniques (`String` is C++, not C), you might want to consider to pass `rdy` (not a pointer), and to write `const String &answer` in the `sendCommand` parameter list (meaning: reference to a string, which will not be modified), and omit the `*` when using the parameter. Passing references is quite similar to pointers: no copying involved. The additional benefit is that you may even write `sendCommand("AT+RST\r\n", 5000, DEBUG, "ready");` then... the "ready" is automagically converted into a `String`, and passed via reference.


body:
You can pass parameters to functions by reference by value or 'by pointers'.

Passing a parameter by value means that the function has a separate copy of the parameter so this is more expensive in terms of memory.  It also means that any changes you make to the parameter inside the function are not reflected outside the function, they are two separate variables after all.

Passing by reference in C/C++ is done by adding a & after the parameter's type, `(int& byRef)`.  This means that you are using the same variable inside and outside of the function.  If you want to prevent the function changing the value then you set the parameter to be a constant reference. `const int& constByRef`

There is a third method which is passing a pointer.  This is very useful for parameters that are a few bytes in size, i.e. strings and structures `char* ptr`.  When you pass a pointer it is passed by value, you can modify the pointer or the data it points to.  Since a pointer is usually only the word size of the processor it is only as expensive as passing an int parameter.

When you pass a `const char* cPtr` you can not modify the value of the pointer, but you can modify the value of the data pointed to.  This type of parameter will let you pass in string literals.

To make you code cleared always write functions to accept constant parameters.  If the parameter is larger than a word pass it by reference unless its an array (including char*) in which case pass it by pointer.  If in doubt it should be a constant reference to start with.  Sometimes embedded constraints affect these rules.