message:
Fan dropping voltage?

I have students using an arduino to control a fan.  We have multiple types of fans. We want to turn the fan off/on with digital HIGH.  When the 5V fan is plugged into 5V and ground, it runs.  When I ground it and attached the power side to a pin set to HIGH the voltage drops down to 2.2V??? When the fan is not plugged into the pin there is 5V.  Why would the power drop when the fan is plugged in?

body:
Most digital pins on Arduinos are qualified to handle up to 25 mA typically and 40 mA at most.  If more current than that is drawn or sunk, the pin voltage will drop or rise, out of specification.  This is due to resistance in the pin drivers, and by Ohm's law, voltage equal to current times resistance will develop.  That “lost” power (voltage times current) is converted to heat within the microcontroller, and can damage it.

The fan motors probably draw rather more than 25 mA; they probably require a few hundred mA.  You can add transistors or motor controllers between the Arduinos and the fans to deal with such current loads.


sender: user

sender: assistant

body:
Absolute Maximum Current per Pin is 40mA (in Arduino Uno) so when you connect the fan with the I/O pins at that time the fan may draw more current from the pin and because of this the voltage level of the pin may drop down. Because Fan or Motor want more current then the capacity of Arduino pins capacity so if you want to On/Start the Fan/Motor then you have to connect Fan/Motor Driver between the Arduino Pin and Fan/Motor. And you have to provide external power source to the motor driver circuit.
For your reference:
[![Transistor base Motor Driver Circuit][1]][1]
[![Motor Driver Module][2]][2]

  [1]: https://i.stack.imgur.com/qJQdL.png
  [2]: https://i.stack.imgur.com/4SKoI.jpg


message:
UART communication issue on Arduino Mega

I am using an MH-Z19 CO2 sensor with an Arduino Mega using UART. As per the specifications of this sensor, after we send a command, we expect the response in a particular 9 byte format (with starting bytes as 0xFF and 0x86).

    byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
    byte response[9];
    Serial.flush();
    Serial.write(cmd,9);
    while (Serial.available()<9) {}
    for(int n=0; n<9; n++) {
      response[n] = Serial.read();
    }
    if (response[0] != 0xFF) {
      //Error
      predictCo2 = 0;
    } else if (response[1] != 0x86) {
      //Error
      predictCo2 = 1;
    } else {
      predictCo2=((response[2]*256)+response[3]);
    }

I wait till all the 9 bytes are filled in to read the values.

The problem here is that, when I turn the board ON, most of the times the response isn't in the required format (starting bytes aren't 0xFF or 0x86).
But, if I press the Arduino reset button, it starts reading values in proper format straight away.

I'm wondering why this is happening. Why is the UART response not in the proper format immediately after I turn on the Arduino, and I have to explicitly do a reset? Is the reset button clearing the serial stream? How can this be achieved through software?

I included `serial.flush()` before sending the command, but that didn't help either.

body:
`Serial.flush()` only empties the output buffer, so that won't achieve anything. Reading exactly 9 bytes and hoping they match the input stream is not very effective, as you found. If you are out of sync with the incoming bytes, you will stay out of sync.

It would be better to keep reading (single bytes) until you get 0xFF or 0x86 and then read the rest.


message:
Arduino and GPS module Neo 6m

I have an Arduino Leonardo and a GPS module "NEO 6M"

Pinout:

    PPS->free
    rxd->11
    txd->10
    gnd->gnd
    vcc->5v

I'm running this code:

    #include "SoftwareSerial.h"
    SoftwareSerial gps(10,11);
    void setup(){
      Serial.begin(9600);
      gps.begin(9600);
    }

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

In serial monitor I'm getting random characters like this

[![Screenshot of serial monitor][1]][1]

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

Where am I going wrong?

I tried the same with an Arduino Mega but have the same result.

body: Solved: GPS module was broken. Now I use another GPS module, same model. Sorry for my English.


message:
Powering up LED strip - How many amps?

I want my Arduino to drive a LED strip.
The LED strip in particular is the 3528 non-waterproof type.
To power this up, I need a 12V power supply.
My LED strip is going to be 5 meters.

Now my questions are:

1. Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?

2. Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?

body:
> 1) Is it important on how many amps, my powers supply will feed?

Yes.  You need the PSU to be able to supply as much current as you will need for everything you are powering form it.

You don't say how many LEDs will be on this strip (only the length of the strip) and I am not sure how much current/power a single one consumes, but **for illustration** let's imagine there are 100 LEDs on your strip and each one takes 0.8W.

100 LEDs x 0.8W per LED = 80W.

P = VI, where P=Power, V=voltage, I=current.

So I = P/V = 80 / 12 = 6.66A -- call it 7A.

The amount taken by the Nano will be small in comparison - if you said 0.5A you'd be safe.

So with these figures you'd need a 7.5A PSU.

> Considering that i need a particular value of amps to power up my LED strip, can the nano handle this many amps?

You can power the Arduino from the same power supply, yes.  The Arduino will *draw* whatever current it needs.  (Think of it this way: mains sockets are 13A - a desk lamp won't draw 13A.)  What matters is that the supply can supply at least enough current, and that the voltage is correct.

As mentioned in the comments, you can't drive 3528s directly from the Nano - but you don't ask about that so presume you either know how to do it, or will ask another question.


body:
Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.

Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).

This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.

Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).

Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current >3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.


body:
Because there are three LEDs in series, you cannot drive these LEDs from a 5V supply. The LED strips say "+12V" on them to mark the anode and that's the maximum voltage we suggest. We've found that if you're ok with them being a little dimmer, even 9VDC works very well.

Each segment of 3 LEDs draws approximately 20 milliAmperes from a 12V supply, per string of LEDs. So for each segment, there is a maximum 20mA draw from the red LEDs, 20mA draw from the green and 20mA from the blue. If you have the LED strip on full white (all LEDs lit) that would be 60mA per segment.

To find the total maximum current draw per meter, we would multiply 60mA x 10 (ten segments per meter for the 30/LED per meter strip) = 0.6 Amps per meter OR 60mA x 20 (twenty segments per meter for the 60/LED per meter strip) = 1.2 Amps per meter. Again, that's assuming you would have all the LEDs on at once and that you are powering it from 12V. If you're going to be PWM-fading between colors, maybe 1/2 of that is what you'll be drawing. Still, you do need to have a fairly decent power supply to run this strip, all those LEDs add up!


message:
max7219 chained display showing mirrored text

I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code with the one that can be found online at [arduino code][1] and changed the display with the chained one, the text appears to be mirrored on the matrix display.

[![like in this picture][2]][2].

Below, I'll attach part of the code. Please help me find the problem.

    #include <MD_Parola.h>
    #include <MD_MAX72xx.h>
    #include <SPI.h>

    // Define the number of devices we have in the chain and the hardware interface

    #define MAX_DEVICES 4
    #define CLK_PIN  13
    #define DATA_PIN 11
    #define CS_PIN  10

    // Hardware SPI connection
    MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);
    // Arbitrary output pins
    // MD_Parola P = MD_Parola(DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);

    void setup(void)
    {
      P.begin();
      P.displayText("Hello", PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
    }

    void loop(void)
    {
      P.displayAnimate();
    }

  [1]: https://github.com/MajicDesigns/MD_Parola
  [2]: https://i.stack.imgur.com/bzlIH.jpg

body:
Check the configuration in MD_MAX72xx.h file and ensure you have the right module selected.

For example there is a define

    #define USE_PAROLA_HW 0

if your hardware is this item then turn off the other hardware settings and turn this one on so it reads as follows:

    #define USE_PAROLA_HW 1

there many other settings if it is not there then you will have to experiment until you find the correct one.


body: In library, change `#define USE_GENERIC_HW 0`  to `#define USE_GENERIC_HW 1` is the solution.


body:
Since version 3.0 `MD_MAX72xx.h` no longer supports that definition. Now the hardware type is defined as a parameter on creation (in the "Example" file you are using - not in `MD_MAX72xx.h`)

    #define HARDWARE_TYPE MD_MAX72XX::FC16_HW
    ...
    MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

Note that I've changed the hardware type from `PAROLA_HW` to `FC_16`.


body:
In latest version of `#include <MD_Parola.h>`, `#include <MD_MAX72xx.h>` you have to define the following and characters will display correctly.

    #define HARDWARE_TYPE MD_MAX72XX::FC16_HW


message:
Would an Arduino Uno be suitable for a simple time-based locking circuit?

Background: I'm looking to start on my first real electronics project and I have an Arduino Uno I bought a while back. I've only done a few of the starter Arduino tutorials and that was a while back as well. Starting from very little electronics knowledge, I'm trying to get a bit of advice on how to tackle my first project.
**TL;DR:** I have an Arduino Uno but very little experience with it or electronics.

Project: I want an object that locks, I want the duration of the time it stays locked for to increase by ~1-3% every time it locks. I want to put my nicotine products in there to gradually pull myself off nicotine. I have designed a rough 3D model of the box, which I can 3D print so now I'm looking at the electronics.
**TL;DR:** A box which stays locked for longer, every time it locks.

Electronics: A microcontroller/Arduino/Pi to increase the locking duration; a locking circuit and some form of power supply.

My 2 questions are

1. Would the Arduino Uno be suited to this type of project?

2. What sort of components should I be looking for for the locking circuit and power supply (I'm thinking some sort of solenoid actuator and a battery pack)?

body:
It is a great occasion to use the Arduino!

There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

---

***The following contains MY OPINION***

In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.

A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work **IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$**. A servo does a decent job as a lock.

---

Good luck!


body:
Regarding your second question about what components to use, there are a couple arguments for a servo over a solenoid.

A solenoid in the energized state is relatively power hungry compared to a servo, which only requires any appreciable power while actually moving. Also, on power loss or interruption a servo fails as-is; a solenoid goes to the off position, which could cause an unwanted change of state for the lock.


message:
How do you configure ADC7 on the Arduino Pro Mini as a digital output?

I'm attempting to use the pin labeled 'ADC7' from the Atmega328p TQFP package. The Atmega documentation suggests that can be used either as an analog or digital I/O point. I'm trying to configure it as a digital output.

Referencing the documentation (and specifically arduino_pins.h), I determined the associated pin number was 21. Thus I called pinMode(21, OUTPUT). However, this pin does not appear to be working with my SPI device. I previously tested that the device worked, but I made a last second change of pin and am now using ADC7.

So my question, is there an additional step required to configure this pin as a digital output? I noticed that this pin doesn't exist on the DIP Atmega328p (used on the Arduino Uno), so I'm not sure if I have to add another line of code somewhere.

Any ideas?

Regards,

body: Those are analog pins only. They can't be used as outputs or digital inputs.


body:
Gerben's answer probably is correct, but there are some interesting discrepancies in Atmel datasheets for various models of the ATmega168 and ATmega328, as outlined below.

Some Atmel datasheets refer to ADC6 and ADC7 as PE2 and PE3, while others just refer to them as ADC6 and ADC7.

Regarding port E, the 2014 ATmega168PA and 2015 ATmega168 datasheets say nothing, don't list any of PE0 to PE3, and don't specify port membership for ADC6 and ADC7.  They show pins 3 and 6 on the LQFP as Gnd and Vcc, vs PE0 and PE1 as in the ATmega168PB sheet.

Regarding port E, the 2015 ATmega168PB datasheet says:

    Table 15-12.  Port E Pins Alternate Functions
         Port Pin       Alternate Function
           PE3          ADC7 (ADC Input Channel 7)
           PE2          ADC6 (ADC Input Channel 6)
           PE1          NONE
           PE0          ACO (AC Output Channel 0)

Regarding port E, the 2016 ATmega168PB datasheet, Atmel-42176G-ATmega48PB/88PB/168PB_Datasheet_Complete-03/2016, says the following
and also lists several Alternate Functions while referring to
Timer/Counters 3 and 4 (although there seem to be no registers in the
register summary relevant to such Timer/Counters):

"Port E is an 4-bit bi-directional I/O port with internal pull-up
resistors (selected for each bit). The Port E output buffers have
symmetrical drive characteristics with both high sink and source
capability. As inputs, Port E pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port E pins
are tri-stated when a reset condition becomes active, even if the clock is not running."

    Table 19-12.  Port E Pins Alternate Functions
     Port Pin            Alternate Function
     PE3                 ADC7 (ADC Input Channel 7)
                         T3 (Timer/Counter 3 External Counter Input) & PCINT27
     PE2                 ADC6 (ADC Input Channel 6)
                         ICP3 (Timer/Counter3 Input Capture Input)
                         SS1 (SPI1 Bus Master Slave select) & PCINT26
     PE1                 T4 (Timer/Counter 4 External Counter Input)
                         SCL1 (2-wire Serial1 Bus Clock Line) & PCINT25
     PE0                 ACO (AC Output Channel 0)
                         ICP4 (Timer/Counter4 Input Capture Input)
                         SDA1 (2-wire Serial1 Bus Data Input/Output Line) & PCINT24


body:
According to everything you can find in [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) about ADC6 and ADC7 they are analog only pins.

The pinout for the TQFP-32 as used on the Pro Mini shows those two pins as *only* having the analog functions:

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

I suspect the color coding of the pins may be wrong - they should be solid green. They have no port names on the pins, purely the ADCx designation.

The block diagram for the chip shows the ADC6/7 pins being separate from a port:

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

As you can see the other 6 pins are referred to by the digital port they share, but ADC6 and 7 are known purely as ADC6 and ADC7.

The pin function table, 6-1, shows ADC6 and ADC7 as the only functions on those pins. No digital port names, nothing - just purely analog input.

So in summary, for the ATMega328P chip used in the Arduino Pro Mini you cannot use those two pins for digital at all, only for analog input.

  [1]: https://i.stack.imgur.com/NVdFq.png
  [2]: https://i.stack.imgur.com/y2nqK.png


body: This may be a little left field, but I use the ADC6 and ADC7 inputs to detect switches.  I just don't use the digitalRead() function, but instead use analogRead() function.  Using a resistor network and switches and some decoder software code in our sketch, we can use a single input pin to interface with many more switches.  The switches can only be on one at a time, but in many instances, this would be OK.


body:
I appreciate this is an old question but those pins are subtly different on the ATMEGA328PB compared to the ATMEGA328P which I discovered recently. See the Microchip app note AT15007, page 3.

[Microchip AT15007 app note][1]

  [1]: http://ww1.microchip.com/downloads/en/Appnotes/Atmel-42559-Differences-between-ATmega328P-and-ATmega328PB_ApplicationNote_AT15007.pdf


message:
32x32 RGB-LED Matrix displaying Arabic Font with Font Forge more easily

At the moment I am using a separate function to display byte arrays like these:

    const PROGMEM unsigned char arab4[] = {
      0x00, 0x00, 0x00, 0x00,
      0xf0, 0xff, 0xff, 0x01,
      0xf8, 0xff, 0xff, 0x01,
      0xf8, 0xff, 0xff, 0x00,
      0x04, 0xf8, 0x0f, 0x00,
      0x00, 0x7c, 0x00, 0x00,
      0x00, 0x0e, 0x00, 0x00,
      0x80, 0x03, 0x00, 0x00,
      0xc0, 0x01, 0x00, 0x00,
      0x60, 0x00, 0x00, 0x00,
      0x20, 0x00, 0x00, 0x00,
      0x10, 0x00, 0x00, 0x00,
      0x18, 0x00, 0x00, 0x00,
      0x08, 0x10, 0x06, 0x00,
      0x0c, 0x70, 0x0f, 0x00,
      0x04, 0xf8, 0x0f, 0x00,
      0x04, 0x78, 0x06, 0x00,
      0x06, 0x20, 0x00, 0x00,
      0x06, 0x80, 0x00, 0x00,
      0x06, 0xc0, 0x01, 0x00,
      0x06, 0xc0, 0x03, 0x00,
      0x0e, 0xe0, 0x01, 0x00,
      0x1c, 0x80, 0x01, 0x00,
      0x1c, 0x00, 0x00, 0x00,
      0x7c, 0x00, 0x00, 0x00,
      0xf8, 0x00, 0x00, 0x00,
      0xf0, 0x07, 0x00, 0x00,
      0xe0, 0x7f, 0x00, 0x3c,
      0xc0, 0xff, 0xff, 0x0f,
      0x00, 0xff, 0xff, 0x01,
      0x00, 0xf0, 0x1f, 0x00,
      0x00, 0x00, 0x00, 0x00};

My function for displaying uses Adafruit libraries

    #include <RGBmatrixPanel.h>
    #include <Adafruit_GFX.h>

Finally my Function:

    void xbm32_n (const PROGMEM unsigned char bild[32],word cchsv) {

    int i = 0;
    while(i<32){

        for(int k=4*i;k<(4+4*i);k++)
        {

        for(int ii = 0; ii<8; ii++){

           int bit = ((pgm_read_byte(&(bild[k]))) >> ii) & 1;
           if(bit == 1) { matrix.drawPixel(ii+8*k-4*8*i, i, cchsv);}}}

       i++   ;
        }
       }
The inner workings are as follows:

The function draws each 32 bit row with the color chosen on the Panel depending on the 4 bytes in each "row" of the hex array.

Essentially 2 loops *(to draw the row in byte increments)* with outer while loop *(to move to next row)*.
The calculation of the *pixel positions* can be seen inside the `matrix.drawPixel(x-pos,y-pos,color-value)` Adafruit-function, and were made up by experimenting long hours.

See for the whole .ino File [here](https://www.dropbox.com/s/tnrt9iq6dunaon4/sketch_led32-painter.ino?dl=0)

**Notes on the file**

---
It also features among others

> *(like a displaying shifting 8x8 symbol-array saved in `const PROGMEM byte IMAGES2[][8]` used in the function `bildlauf(1,...)`*

an updated function `void xbm32_4c(char bild[32],word* cchsvar[4], int duration,int cseq[4]))` where:

 - `word* cchsvar[4]` points to four color data values

 - `cseq[4]` is the sequence for displaying the colors in each panel
   quadrant

The subdivision of the panel is realized via `if()` and `else if()` commands checking the conditions for positions:

`x = (ii+8*k-4*8*i) </>` *some value*
 *&&* `y = i </>` *some value*

---

**Function input:**

 - `bild[32]` is used for the hex array as in my case `arab4[]`
 - `cchsv` is a color data value . I am using sparkfun 32 LED Matrix and
   found the following function for hsv color space to work well:

          word hsvcolor(int h, int s, int b ) { //Try HSV colors http://colorizer.org/
          int hue1, sat1, bright1;
          word result;

          hue1=map(h, 0, 360, 0, 1535);
          sat1=map(s, 0, 100, 0, 255);
          bright1=map(b, 0, 100, 0, 255);
          result = matrix.ColorHSV(hue1,sat1,bright1,true);

          return result;
        }

**Current Issues to solve:**

I am using Font Forge to create XBM Files in helping me create the hex letter array, but found it very clumsy to export, as the width size must be a multiple of eight to adjust height by deleting 0x00 rows.

At the moment I am searching for easier ways to "correct" the exported XBM arrays (like using 8x8 Editor [8x8 Editor](http://xantorohara.github.io/led-matrix-editor/), only for 32x32 Matrices).
Is there a possibility for this?

Alternatively it would also help to create a function to truncate hex arrays to fit 32x32 dimensions somehow.

Additionally, in Arabic there is the issue of variant glyphs for the different letter positions (isolated, medial, initial, final). It seems possible to create byte arrays for all variants but "correcting" each bitmap so that a scrolling effect (I plan to upgrade to 64x32 LED Matrix) "adds up" visually seems daunting. I am happy for suggestion on realizing this challenge as well.

I am aware that there is a Adafruit function for bitmaps:
`void Adafruit_GFX::drawBitmap()`

I couldn't get it to work with my hex array, also the possibility on how to change quadrant colors or other subdivisions lead me to write my own version I modified from 8x8 Panel case. I am not sure whether there are inefficiencies in the code I have written, I therefore am happy for suggestions.

body:
The solution to creating Arabic characters with typographic ligature and scrolling them, is:

 Using the application _RTB RichText to Bitmap_ :

 1. Set width-size of bitmap in increments of 32*n while using a height
        initially bigger than 32
 _(saving the bmp will allow for cropping of rows so that bigger letters can be produced, a bit offset to fit height 32)_

 1. Saving the bmp and editing it _(take care that bitmap rows are saved in rows, if not switch scanning line mode)_

 Also the byte    endian for output must be rightly chosen: _("Lsb" for pc-editing, uploading to    arduino for use in the function provided [here](https://www.dropbox.com/s/gwigwdbofgksi6t/sketch_led32-64-painter-finally-2.ino?dl=0), it is in
        "Msb")_

 The cropped characters bitmap must be then reloaded into RTB Pixel Editor on a fitting canvas (generate an empty one) and set to a different scanning mode (rows now in columns) with byte endian Msb

 2. Group the array of hex elements in pairs of four (you can use
    notepad++ and
 _regex find:_
    `(((0[xX][0-9a-fA-F,]{2})[,]){3}((0[xX][0-9a-fA-F,]{2})))`

    _replace:_ `{/1}`

Using a suiting arduino scrolling [function](https://www.dropbox.com/s/gwigwdbofgksi6t/sketch_led32-64-painter-finally-2.ino?dl=0) (on top of adafruit    libraries)

 1. Insert 32x(4_hex) chunks of your bitmap data in the file provided
    above as array element in:
 `const PROGMEM unsigned char
    I[][32][4]= {{here},{here},...,{here}}`

 2. Adjust _main loop_ code for scrolling direction (here r to l) via increment or
    decrement and number of scrolls (panel-size is here chosen 32):

    `int es=64; while (es>0) {   scroller01(I,32,dpink,es,go);   --es; }`

 3. Verify if you need to load a chunk of your bitmap group to `const
    PROGMEM unsigned char I[][32][4]` , so that scrolling is fluid and
    does not jump when the arduino re-cycles

The Question got solved in detour via another question  in this exchange (see  [here](https://arduino.stackexchange.com/questions/34328/on-extending-scrolling-8x8-bitmap-to-32x32-or-32x64-see-clip) ). I am answering it to resolve parts of it.

The scrolling is slow when extended fully onto 64x32 Panels with arduino Mega 2560.

For a clip see:
>!  www.dropbox.com/s/qth8iuygra1wx9b/VID-20170210-WA0000.mp4?dl=0

 If somebody comes up with a more efficient,faster way, please do share!


message:
Push to 2D array (log) but last value pushed is everywhere

I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).

What am I doing wrong here?

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

    #define log_size 5
    #define line_height 12
    char *log_lines[log_size] = {"Hello", "World"};

    void addToLog(char *text) {
      for(int i = log_size - 1; i > 0; i--) {
        log_lines[i] = log_lines[i-1];
      }
      log_lines[0] = text;
    }

    void printLog() {
      for(int i = 0; i < log_size; i++) {
        Serial.print(i);
        Serial.print(" ");
        Serial.println(log_lines[i]);
      }
    }

    void loop(void)
    {
      char msg[20];
      sprintf(msg, "%d", millis());
      addToLog(msg);
      printLog();
      delay(1000);
    }

The output after the first addToLog is

    0 1000
    1 Hello
    2 World

second addToLog is

    0 2001
    1 2001
    2 Hello
    3 World

body:
It is easy - in your log you store POINTERS to strings.

And you then create variable on the stack (ouch) and put its address to the log.

Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).

Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.

Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.

Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].

Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)

Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

---

Some of possible solutions are:

1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.

2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]

3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)


body:
Here is a solution which does not use dynamic allocation nor does it
copy any log message. It's essentially a zero-copy implementation of
gilhad's solution 3. The idea is: instead of having an `addToLog()`
function that takes an already prepared message (which it would need to
copy), you have a `get_log_buffer()` function that tells you where to
write the message in the first place. This way you can `snprintf()`
directly into the right place in memory.

    const size_t LOG_SIZE = 5;
    const size_t MSG_SIZE = 20;

    char log_stack[LOG_SIZE][MSG_SIZE];  // circular log buffer
    size_t log_index;  // next available slot in the circular buffer

    // Return the address of the next available message slot.
    char *get_log_buffer()
    {
        char *buffer = log_stack[log_index];
        if (++log_index == LOG_SIZE) log_index = 0;  // increment index
        return buffer;
    }

    void print_log()
    {
        Serial.println(F("--------"));
        for (size_t i = 0, j = log_index; i < LOG_SIZE; i++) {
            j = (j ? j : LOG_SIZE) - 1;  // decrement index
            if (log_stack[j][0]) {  // should be a non-empty message
                Serial.print(i);
                Serial.print(" ");
                Serial.println(log_stack[j]);
            }
        }
    }

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

    void loop()
    {
        snprintf(get_log_buffer(), MSG_SIZE, "%lu", millis());
        print_log();
        delay(1000);
    }

Note that `log_stack` and `log_index` are zero-initialized by the C
runtime. Note also the use of `snprintf()` instead of `sprintf()` in
order to avoid buffer overruns.


message:
EEPROM put and get not working on ESP8266 (NodeMCU)

The Arduino documentation provides two examples to store data in the EEPROM.

https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.

These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

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

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

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

body:
The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also [here]( https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM/examples)).


body:
**EEPROM for the ESP8266/NodeMCU**

This is a bit different from standard EEPROM class for Arduino. You need to call `EEPROM.begin(size)` before you start reading or writing, size being the number of bytes you want to use. Size can be anywhere between 4 and 4096 bytes.

`EEPROM.write` does not write to flash immediately, instead you must call `EEPROM.commit()` whenever you wish to save changes to flash. `EEPROM.end()` will also commit, and will release the RAM copy of EEPROM contents.

EEPROM library uses one sector of flash located just after the SPIFFS.


message:
Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?

I have an Arduino Mega clone and I haven't used it for a while. I remember it not working so when I plugged it in and tried uploading the code to it and sure enough it didn't work. So I plugged in an Uno and it worked. The Mega is a 2560 Atmel. Here's my code:
<!-- language-all: lang-cpp -->

    #define distanceForward A0
    #define distanceLeft A1
    #define distanceRight A2
    #define distanceRightAngle A3
    #define distanceLeftAngle A4
    #define distanceBack A5
    int talk = 2;

    void setup() {
      Serial.begin(9600);
      pinMode(talk, OUTPUT);
      pinMode(distanceForward, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Front Facing
      pinMode(distanceLeftAngle, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Left Angle
      pinMode(distanceRightAngle, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Right Angle
      pinMode(distanceLeft, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Left
      pinMode(distanceRight, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, Right
      pinMode(distanceBack, INPUT);
      // /\ Ir distance sensor pin for input signal to arduino, back
    }

    void hall_roam() {
      Serial.write("forward");
      if (analogRead(distanceLeftAngle) < 30) {
        Serial.write("right");
        if (analogRead(distanceLeftAngle) > 30) {
          Serial.write("forward");
        }
        if (analogRead(distanceRightAngle) < 30) {
          Serial.write("left");
          if (analogRead(distanceRightAngle) < 30) {
            Serial.write("forward");
          }
          if (analogRead(distanceForward) < 60) {
            Serial.write("stop");
            if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
              Serial.write("left");
              if (analogRead(distanceForward) > 60) {
                Serial.write("stop");
              }
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) > 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) > 60) && (analogRead(distanceRight) < 60)) {
            Serial.write("left");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          }
          if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) > 60)) {
            Serial.write("right");
            if (analogRead(distanceForward) > 60) {
              Serial.write("stop");
            }
          } else {
            Serial.write("forward");
          }
        }
      }
    }

    void roam() {
      Serial.write("forward");
      if (analogRead(distanceForward) < 60) {
        Serial.write("stop");
        Serial.write("left");
        if (analogRead(distanceForward) > 60) {
          Serial.write("stop");
          Serial.write("forward");
        }
      }
    }

    void talkbb8() {
      pinMode(talk, HIGH);
      pinMode(talk, LOW);
    }

    void chill() {
      Serial.write("stop");
      talkbb8();
    }

    void loop() {
      if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
        hall_roam();
      } else if ((analogRead(distanceForward) < 60) && (analogRead(distanceBack) < 60)) {
        Serial.write("left");
        if ((analogRead(distanceLeft) < 60) && (analogRead(distanceRight) < 60)) {
          Serial.write("stop");
          hall_roam();
        }
      } else {
        roam();
      }
    }

If there's a bracket out of place or something it's probably nothing. I'm talking about the characters. Is there anything in the characters that would screw up the upload like the three "!!!" problem I heard about or something like that. It's possible that the USB chip in it isn't recognized by my iMac. If so how do I fix that?

body:
The error message basically means that the programmer is unable to contact the `boot-loader` on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:

 1. Wrong Port Selected:

    If `TX/RX` led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.

 2. Board is not in `Bootloader` Mode:

    The `Arduino Mega` is not executing the `bootloader` for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the `bootloader` from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.

 3. Arduino Mega 2560 only: ATmega8U/16U software

    Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer to` reflash` the target.

 4. Hardware damage:

    There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this [answer][1].

  [1]: https://stackoverflow.com/questions/19645441/avrdude-stk500v2-receivemessage-timeout


body:
I tried all the solutions listed on this page:

- changed ports,
- checked correct port on Arduino IDE,
- restarted,
- reconnected,
- bought a new arduino mega,
- etc.

Nothing worked.

Finally gave up and used the web version of the Arduino IDE and it worked just fine.


body:
If you have a timeout issue please ensure the crystal used on board is 16 Mhz.

change

mega.menu.cpu.atmega2560.upload.protocol=wiring
To:

mega.menu.cpu.atmega2560.upload.protocol=stk500v2

Thank you!
Solved my problem!


body:
I had the same issues on MAC OSX El Capitan (older iMAC) using IDE 1.8.x and of course JAVA performed an update.  I regressed the Arduino AVR drivers to 1.6.21 (as instructed online) and this did not resolve the Timeout errors.

I gave up and used IDE 1.8.9 on my OSX MB Pro, and it worked flawlessly.

I think that Java versions and IDE drivers were the issue.


message:
Reading multiple DI pins in parallel as one byte/word

I need to capture a single parallel 'snapshot' from a 10-bit shaft encoder. I understand that I can read individual bits and shift them into position, but any given input pin might change while reading the bits sequentially, which would give an bogus value. In fact, given the asynchronous nature of the device this is guaranteed to happen on occasion.

I've read hints that it might be possible to combine pins into a 'port' for this purpose but I can't find any examples. Is this ability available only on certain processors? Or is there some way to latch the input pins while scanning them into a pair of bytes, to avoid them changing while I read?

If not I suppose I could use external latches but I'm hoping to avoid additional hardware.

It did occur to me that I could sync readings using an ISR triggered by a change in the LSB, but alas, this encoder outputs Gray code. :(

body:
Without knowing the encoder in question (which you seem extremely reluctant to disclose for some reason that I have trouble understanding) it is hard to give a good answer. However ...

---

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).

Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.

Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.

To read all of port D you could just do this:

    byte foo = PIND;

(For inputting it is PINx, for outputting it is PORTx).

---

What could help is an I/O expander such as the MCP23017.

> I'm hoping to avoid additional hardware

Well, that's a pity.

---

I'm a tiny bit surprised that the device doesn't support some sort of "latching" of the data which gives you a finite time to extract the information from it. However without reading the datasheet I can't comment further.


body:
If you would like to read multiple inputs, you can access port register directly. For 8 bit AVR:

    DDRA = 0;            // set pins A0-A7 as input, modeInpit() in Arduino
    uint8_t data = PINA; // read all A0-A7 inputs (8 bits)

To read more than 8 bits, you need 32 bit ARM based MCU/board like Arduino Due, other Atmel SAM, STM32Fxxx MCU etc. For STM32, there is Arduino like IDE available - [http://www.stm32duino.com/][1]

Even on 32 bit MCU you can read only 16 GPIO simultaneously (GPIO registers are 32 bit but handles 16 GPIO).

  [1]: http://www.stm32duino.com/


body:
I mean, *you could* look up the port and the pin in the port and read in the portByte. This example does work:

    //given two GPIOs on a port(PortC) eg: 12(right button) & 13(left button)
    byte portByte = (*portInputRegister(digitalPinToPort(rightButtonGpio)));
    rightButtonPinHigh = portByte & (digitalPinToBitMask(rightButtonGpio));
    leftButtonPinHigh = portByte & (digitalPinToBitMask(leftButtonGpio));

However, in my experience, your output will look pretty much the same as if you had done two sequential Arduino blessed `digitalRead`. I suppose you might (in the example above) get the leftButtonHigh value 1 instruction ealier, but I don't know if the register can even update at that resolution.


body:
I'm sure time has already passed for this persons project. But for those visiting this page for whatever reason (mine was different than the information here) here is a solution I would implement. Also this is assuming the individual is not willing to use a latched external buffer where they can read from it however they need to. Simply split the total pins among 2 registers making sure the following
1. The pins used are in sequential order to both the MCU and the encoder (gray coding will require some thought to this).
2. Group as many on a single register as possible and this will be the low order value.

Read from the low order value first (the one that will be changing at the highest rate). Then read from the high order value (where it will be far less likely to change between the low order and the high order read). You need to understand bit masks and bit shifting to do this...

uint16_t nEncoder = (PINB & 0x1F);   // Example if your 5 pins are the low ones on PORTB

uint16_t nEncoder = ((PINB & 0x7C) >> 2);  // Example if your 5 pins are 6:2 where you pull your set of pins off of PORTB then bitshift them down into their proper place.

then you read in the high order part

nEncoder |= ((PIND & 0x1F) << 5);  // Example if your 5 pins are the low ones on PORTD. However you pull them off of the next port, you will need to make sure you bitshift them into the upper 10 bits of nEncoder to get your final value.

In the above, you can see that the more bits (pins) you can use on your first register (port), the less likely your second read will have a pin change.

Gray coding will be different than binary. The above example assumes binary where the high order bit will change the least and the low order the most. Gray coding is specifically used because of how minimally the bits change in-between each number change (i.e. they are suppose to only have 1 bit change per number change no matter the number rather than 10 bits change when a binary count rolls over - i.e. it minimizes this exact problem). So for the original poster, most of this should be irrelevant (since they said they were using a gray code encoder).

But for those seeking an optimal solution (for binary counters or just because) where they cannot stick all pins on a single port. Splitting it between two registers with only two reads will optimize your read time and minimize the pin change possibility.


message:
How can I run HC-05 on 8MHz Pro Mini?

I run an Arduino Pro Mini on ATMega328 3.3V 8MHz, and I am unable to send data over HC-05 breakout board on this frequency, and on 5V 16Mhz, it has no issues.

The Arduino code is down below:

    #include <SoftwareSerial.h>
    #include <Wire.h>
    SoftwareSerial BT(10, 11);
    byte value;
    unsigned long pmillis_bt = 0;

    void setup() {
      Serial.begin(19200);
      BT.begin(9600);
    }
    ///////////////////main///////////////////

    void loop () {
      if (millis() - pmillis_bt >= 100) {
        byte Data[3];
        byte cmmd[20];
        int insize;
        char str[256];
        int i = analogRead(A0);
        value = BT.read();
        Data[0] = 'a';
        Data[1] = i / 256;
        Data[2] = i % 256;
        sprintf(str, "%d", i, Data[0], Data[1], Data[2]);
        Serial.println(str);
        if (value == 49) {
          for (int j = 0; j < 3; j++)
            BT.write(Data[j]);
          value = 0;
        }
        pmillis_bt = millis();
      }
    }

body:
You are probably using the HC-05 Module with a power regulator and levelshifter designed for use with Arduinos that typically run with 5V. What you need is the plain HC-05 as can be found on [AliExpress][1]. Those run with 3.3V but it can be tricky to use them in prototypes.

  [1]: https://www.aliexpress.com/item/1pcs-hc-05-HC05-RF-Wireless-Bluetooth-Transceiver-Module-RS232-TTL-to-UART-converter-and-adapter/32736755254.html


body:
Basically Arduino Uno Is working On 5v Voltage Level so you can Directly connect the HC-05 Bluetooth module to it using it 4 lines VCC,TX,RX,GND.

But in Pro mini 3.3 V level due to you need to [Generic 3.3V To 5V 2 Channel Logic Level Converter Bi-Directional Module][1]

using this you can easily convert the vlotage level.

if you have to make using simple component also using

[SparkFun Logic Level Converter - Bi-Directional][2]

  [1]: http://www.amazon.in/Generic-Channel-Converter-Bi-Directional-Module/dp/B011ECG2MM?tag=googinhydr18418-21&tag=googinkenshoo-21&ascsubtag=452c9032-ae7a-4c0b-bf42-18085457ab13
  [2]: http://file:///C:/Users/Kalarav/Downloads/Logic_Level_Bidirectional.pdf


message:
Manipulating 3 IR led's on Arduino Uno

I have an Arduino Uno and 3 IR led's. Each of my IR led's works fine individually if I connect them to pin 11.

However I want to connect all 3 of the led's to the Uno and have them send different signals according to pin number.

e.g

**IR LED 1** connected to **pin 11** - send signal **0xABCDEFGH**

**IR LED 2** connected to **pin 10** - send signal **0xSJKLMNOP**

**IR LED 3** connected to **pin 09** - send signal **0xZXYRWVUG**

I tried making my own code below but it does not work. If anyone has any pointers i'll be very happy.

    //LED 1

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 11; i++) {
                irsend.sendNEC(0xABCDEFGH, 32); //Settings Menu
                delay(1000);
            }
            delay(1000); //1 second delay
        }

    //LED 2

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 10; i++) {
                irsend.sendNEC(0xSJKLMNOP, 32); //HDMI Port
                delay(1000);
            }
            delay(1000); //1 second delay
        }

    //LED3

        #include <IRremote.h>

        IRsend irsend;

        void setup()
        {
        }

        void loop() {
            for (int i = 0; i < 9; i++) {
                irsend.sendNEC(0xZXYRWVUG, 32); //Switch Off Monitor
                delay(1000);
            }
            delay(1000); //1 second delay
        }

body:
I think what you have done is a perfectly logical thing to do.  You had three programs that worked and so you pasted them all into the same file and compiled it.  The compiler spat its dummy out of the pram and you didn't understand what the h*ll went wrong.  Is that about right?

    // You only need to include each header file once
    #include <IRremote.h>

    // You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
    IRsend irsend_led1;
    IRsend irsend_led2;
    IRsend irsend_led3;

    // This is where you do all the setup, it only gets executed once.
    // You might need to assign the pin numbers to the irsend_ledX variables here.
    void setup()
    {
    }

    // This function is called repeatedly.  You can only have one of these.
    void loop() {
        // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
        // I think the data is being sent multiple times, don't know why though
        for (int i = 0; i < 11; i++) {
            irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
            delay(1000);
        }
        delay(1000); //1 second delay
        for (int i = 0; i < 10; i++) {
            irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
            delay(1000);
        }
        delay(1000); //1 second delay
        for (int i = 0; i < 9; i++) {
            irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
            delay(1000);
        }
        delay(1000); //1 second delay
    }

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.

Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.


body:
@Matt has the main problem resolved, but I do want to add a note.

`<IRremote.h>` has the default IR led pin as pin 3 (last time I checked, maybe it has changed). I don't know how to change it, but if you are considering to use multiple IR leds, you might have to debug that problem!

So try to make 1 code work before you attempt to stick them togheter


message:
Servo motors not working when called upon using I2C

So I'm using this `movement()` function inside the slave Arduino Uno, which basically handles two stepper motors and one servo motor. When I call this function through the `Serial.read()` of the Arduino Uno, it works perfectly, both the steppers and the servo.

I have a master Arduino Mega interfaced with the Uno (mentioned above) when I send a wire message from the Mega to Arduino to run the `movement()` function in the Uno, the steppers work fine, but the servo does not work. Although, again I mention that when the function is called upon using the `Serial.read()` of the Uno, it works absolutely fine.

I'm using an Adafruit motor shield on the Arduino Uno as well.

OK so this is the Uno (slave code)

    void setup() {
      servo1.attach(9);
      Serial.begin(9600);
      Wire.begin(5);
      Wire.onReceive(receiveEvent);
      Serial.begin(9600);
    }

    void loop() {
      //other stuff
    }

    void receiveEvent(int howMany) {
      while(Wire.available()) {
        char c = Wire.read();
        int From = Wire.read();
        int To = Wire.read();
        int x = 0;
        movement(From,To);
      }
    }

    int movement(int from,int to) {
      int X_From = from / 10;
      int X_To = to/10;
      int Y_From = from % 10;
      int Y_To = to % 10;
      /* First we have to get the motor position and move the motor to the from position */
      /* === START === */
      int diff_X = X_From - motor_X;
      int diff_Y = Y_From - motor_Y;
      int Y_Value = abs(diff_Y * Y_Steps);
      servoDown();
      if(diff_X != 0) {
        if(diff_X > 0) {
          /* Positive value means the X_Axis motor will move in the forward direction */
          int X_Value = abs(diff_X * X_Steps);
          X_Forward(X_Value);
        } else if(diff_X < 0) {
          /* Negative value means the X_Axis motor will move in the backward direction */
          int X_Value = abs(diff_X * 400);
          X_Backwards(X_Value);
        }
      }
      if(diff_Y != 0) {
        if(diff_Y > 0) {
          Y_Forward(Y_Value);
        } else if(diff_Y < 0) {
          Y_Backwards(Y_Value);
        }
      }
      Serial.println("Motor movement done");
      /* === END === */
      motor_X = X_From;
      motor_Y = Y_From;
      int diff_X_2 = X_To - motor_X;
      int diff_Y_2 = Y_To - motor_Y;
      int Y_Value2 = abs(diff_Y_2 * Y_Steps);
      servoUp();
      if(diff_X_2 != 0) {
        if(diff_X_2 > 0) {
          /* Positive value means the X_Axis motor will move in the forward direction */
          int X_Value2 = abs(diff_X_2 * X_Steps);
          X_Forward(X_Value2);
        } else if(diff_X_2 < 0) {
          /* Negative value means the X_Axis motor will move in the backward direction */
          int X_Value2 = abs(diff_X_2 * 400);
          X_Backwards(X_Value2);
        }
      }
      if(diff_Y_2 != 0) {
        if(diff_Y_2 > 0) {
          Y_Forward(Y_Value2);
        } else if(diff_Y_2 < 0) {
          Y_Backwards(Y_Value2);
        }
      }
      motor_X = X_To;
      motor_Y = Y_To;
      Serial.println("piece movement done");
      return 1;
    }

    void servoUp() {
      for (i = 100; i >= 0; i--) {
        servo1.write(i);
      }
    }

    void servoDown() {
      for (i = 0; i < 100; i++) {
        servo1.write(i);
      }
    }

This is the master Mega Code:

    void setup() {
      Wire.begin();
    }

    void loop() {
      //check if a condition appeared from sensor and then send the data to Uno to run the movement function through sendData()
      sendData(From,To);
    }

    void sendData(int From,int To) {
      Wire.beginTransmission(5);
      Wire.write('f');
      Wire.write(From);
      Wire.write(To);
      Wire.endTransmission();
    }

Any suggestions what's wrong?

body:
I don't know if this is the whole problem, but if you call `sendData (0, 270)` you are only going to send 3 bytes to the Uno `0x66, 0x00, 0x01`.  You should be sending 5, `0x66, 0x00, 0x00, 0x01, 0x0E`

The Uno only reads three bytes and receives:
    c = 0x66;  // 'f'
    From = 0x00; // 0
    To = 0x01; // 1

This is because Wire.write() and Wire.read() send/read a single byte (when you call them like this).  What you need is:

    void sendData(int from, int to)
    {
        Wire.beginTransmission(5);
        Wire.write('f');
        Wire.write(&from, sizeof(int));  // Write an array of 'size of int' bytes
        Wire.write(&to, sizeof(int));
        Wire.endTransmission();
    }

    int readInteger (void)
    {
        int result= 0;
        for (int byte = 0; byte < sizeof(int); byte++)
        {
           result = result << 8;  // Left shift the current data (multiply by 2^8)
           result += Wire.read(); // Add the next byte as the LSB
        }
        return result;
    }
    void receiveEvent(int howMany)
    {
      while(Wire.available())
      {
        char c = Wire.read();
        int from = readInteger();
        int to = readInteger();
        int To = Wire.read();
        movement (from, to);
      }
    }

This code sends and receives the complete integers, so it should work.

Sorry I can't compile it, but I think its right.


body:
If you are using Servo library, which uses timer (and so interrupts) for manipulating the servos then you may have the problem, that from `loop` it works (as interrrupts are enabled), but from interrupt (ISR) it does not work, because while serving interrupt (from I2C) all other interrupts are (temporary) disabled.

In `receiveEvent()` you are inside interrupt serving, so other interrupts are disabled and so anything, what depends on interrupts does not work, until you leave the function.

So it is the more probable cause, why your servo does not move, while called from `receiveEvent()`, while it moves, if called from `loop()`

And you wait inside the interrupt routine, until all Wire input is read fully and then while the (slow, as it probabely involves mechanical components like motors or servos) `movement(from,to)` ends (if it can even end with interrupts disabled).

The solution would be to do all `movement(..)` in the `loop` and int the `receiveEvent()` just store the already aviable values and put them into some `static volatile` variables, when transfer ends together with mark, that some change was done.

    static volatile int from;
    static volatile int to;
    static volatile int changed;

    void loop() {
    int my_from,my_to;
      if (changed) {
         noInterrupts();  // critical, time-sensitive code here
           my_from=from;
           my_to=to;
           changed=0;
         interrupts(); // enable interrupts, so I2C, servo and such can work again
         movement(my_from,my_to);
      }
    }
    void receiveEvent(int howMany)
    {
      if(Wire.available())
      {
        char c = Wire.read();
        from = readInteger();
        to = readInteger();
        changed = 1;
      }
    }

Not totally perfect (mainly reading the Wire, which I would just tak as much as is ready to some buffer and decode it only when buffer is sufficiently full and syntactically correct, but if would make the idea here more complicated), but should work much better, than the current version.

Better version of `receiveEvent can look like this:

    char buf[20];
    int buf_pos;
    void receiveEvent(int howMany)
    {
      while (Wire.available()) {
        buf[buf_pos] = Wire.read();
        buf_pos++;
        if (buf[0] == 'f') { // starts with known command
          if (buf_pos>= sizeof(char)+2*sizeof(int)) { // have all data already collected
            from=0;
            for (i=0;i<sizeof(int);i++) from=from<<8+buf[sizeof(char)+i];
            to=0;
            for (i=0;i<sizeof(int);i++) to=to<<8+buf[sizeof(char)+sizeof(int)+i];
            changed = 1;
            buf_pos=0;
            } // end of buf_pos>= ...
         } else { // not started with 'f' (or anything it should know) - throw all transfer away as bad
            while (Wire.available()) Wire.read();
            buf_pos = 0;
         }
    }


message:
Building a low voltage disconnect w/ timer - need help with the timer

I'm trying to build almost exactly this device:

http://www.reuk.co.uk/wordpress/reuk-shop-low-voltage-disconnects-lvd/buy-reuk-programmable-low-voltage-disconnect-with-display/

It is a low voltage disconnect but has an interesting feature that requires the "cutoff" and "reconnect" voltages to be reached for 10 seconds before the connection is actually cut/re-connected to prevent premature status changes from voltage spikes/sags (Such as starting a car, or a motor with high start draw)

I need some example code that handles the timer portion. I can handle the "if this voltage is reached, disconnect the relay" (or transistor in the link I provided) part.

I need help making it "If this voltage has reached XX for 10 seconds then -do something-"

body:
Assuming you have a function `voltageIsReached()`, here's a very simple way of doing it, which is OK if you don't have anything else to do in the mean time.

    if (voltageIsReached()) {
        long end = millis() + 10000;   // 10s from now
        boolean voltageWasReachedFor10s = false;
        while (voltageIsReached()) {
            if (millis() >= end) {
                voltageWasReachedFor10s = true;
                break;
            }
            delay(1);
        }
        if (voltageWasReachedFor10s) {
            // Do whatever you have to do
        }
    }

If you *do* have something else to do while you're waiting for this 10s state, you will need to adapt this, but I hope it'll get you started.


body:
Write a function that has a static variable that keeps the previous time that the voltage has not been reached. That routine will read the voltage and reset the static variable to current time whenever the voltage has not been reached.

Such a routines can either return a logic value or a time value , depending on your implementation.


message:
How to run functions concurrently

I'm building a scale which reads a value (from a load cell) and outputs it on a LED screen.

There is a function for the scale, *read* which will read the value from the scale.
However this is not instantaneous - it uses the yield function to wait until the scale is ready.

The LED screen has a function, *display* which will display an integer on the screen with no delay. However, this lasts barely a fraction of a second, so it must be repeatedly called.

These functions as is are called one after another inside *loop()*, but it causes only a quick flash of the LED screen followed by a half second of reading.

How would I allow the LED screen to keep displaying a value while the scale reads? I know there's BlinkWithoutDelay - but I'm not using specific times. There is no instance of the function *delay* anywhere in the program. I also am not going to edit the library which reads the load cell.

body:
There is only one execution unit in this MCU so you can not truly run multiple tasks concurrently.

However, you can achieve the appearance of concurrency by running a higher priority task through an interrupt. For example, you cannot afford to have flickering disspplay. So set up a timer that invokees the display routine periodically. If you set the timer interrupt sufficiently small (over 25hz for example), the display will not flicker.

Your other routines can be run in other isr or in the main loop so they are interrupted by the display routine periodically. In a way that's fully transparent to you.


body:
There is similar questions answered a day ago - [Multithreading with Arduino][1]. What your are asking is multitasking or multithreading. Tasks have own loop and task scheduler stops and switches tasks periodically so they appear as if running simultaneously. Task scheduler in turn is usually driver by timer ISR, for AVR a 50-100Hz scheduler timer tick frequency is reasonable.

If there are 2 tasks with same priority (given task scheduler supports priority), they will spare MCU time ~ 50% / 50%. So if timer is 100Hz, each task runs 5ms and interrupted.

Surely task scheduler have overhead, but for small frequency it is negligible, less than 1%. There is no need to modify existing code/library, time sharing is organized transparently.

There are rules to follow when doing multitasking: for example when the scale related function is writing measured value of `double` type into some variable, this task might be interrupted (by scheduler) during the writing (when only half of the values is written) - and another task will see an incorrect value. The easiest way would be disabling the interrupts during such shared variable update. Google for "race condition", atomic operation, synchronization.

  [1]: https://arduino.stackexchange.com/questions/18538/multithreading-with-arduino


body:
Here is sketch in pseudo-code that can keep your display going and still make frequent weight measurements, without having to do any multi-threading or similar. The value of 'if a measurement is ready' (below) may come from a status bit in the scale, or simply a time difference using the millis() function; I don't know the specifics of your hardware.
I showed weight being an integer. Again, you may need to adapt this to your own hardware. But it is an uncomplicated process for displaying frequently to maintain the display, and reading whenever data is available so the display updates as you get new data, no concurrency required.

    void setup()
    {
       // initialize everything;
       // start the first measurement;
    }

    void loop()
    {
       static int16_t weight = 0;

       // if a measurement is ready,
          // read the value and store it in 'weight;'
          // start a new measurement
       // endif

       // display 'weight' on the LCD;
    }


message:
Remote controlled lights

I have a fixed roof light in my room that came with a remote control that can be fully taken apart. The remote control can switch the lights on or off using a radio system. I was wondering if there was any way to use my Arduino to control the remote control (through wires) to control the lights. I do not have any Arduino radio components so it would still need to go through the original remote. I have taken the remote apart and this is what it looks like:

http://go.hma-uk.org/dlt

The buttons are as follows: the top two (K1 & K2) buttons is to turn on/off a coloured LED but these are not important to me. The button K3 is to turn on/off the main light (I want the effect of this button being pressed to be created using the Arduino) and the button K4 is to turn all lights on/off.

  [1]: https://i.stack.imgur.com/pXRMk.jpg
  [2]: https://i.stack.imgur.com/t82kJ.jpg
  [3]: https://i.stack.imgur.com/l0dM1.jpg

body:
I used to use gamepads as input device for USB many years ago. I simply soldered wires paralel to buttons and shortcut them to "simulate" the button press - it worked nice and reliable.

With Arduino - I would measure the voltage on the button in question with Voltmeter - if the voltage is less then Vcc of Arduino (5Volts), I would simply connect Arduino ground to lower side (negative) of the button and output pin to the high side of the button. Then I would set that pin for Input to have the button released (from Arduino side) and to LOW + Output to have it pressed. (maybe I would first shortcut the button with Ampermeter to see, that no more, than 100mA is sinking there).

If the sink is more, or the voltage is more, then I would use relay and shortcut the button with the relay, switching the relay with Arduino.

( something like this http://www.instructables.com/id/Home-Automation-How-to-Add-Relays-to-Arduino/?ALLSTEPS )


message:
ATtiny88 ADC reference voltage setting

I'm writing a simple application that reads voltage from analog input 0. Here is the code:

    #define OUT 5
    #define ADC 0

    void setup() {
      ADMUX &= (0<<REFS0); //Setting reference voltage to internal 1.1V
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(0);
      float voltage = sensorValue * (1.1 / 1023.0);
      if (voltage>0.5) {
        digitalWrite(OUT,HIGH);
      } else {
        digitalWrite(OUT,LOW);
      }
    }

When I apply 1 V on ADC0, the OUT pin is low. Seems like the reference voltage is not set properly. When I set VREF to VCC (5V), everything works fine.

I cannot find the mistake. Would appreciate any help:)

Edit:

Link to datasheet: http://www.atmel.com/images/doc8008.pdf

body: In your setup section, you want to set or clear all relevant bits in admux.


body:
The statement

    ADMUX &= (0<<REFS0);

AND's the current value of ADMUX with zero, resulting in a zero value, and stores it into ADMUX.

To clear the REFS0 bit in ADMUX without affecting the rest of it, one generally would instead say

    ADMUX &= ~(1<<REFS0);

which will AND its value with the complement of `1<<REFS0`.

However, you should use the statement

    analogReference(INTERNAL);

instead of setting ADMUX directly.  One of the first statements executed in the [`analogRead()` source code](http://garretlab.wb.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html) is

    ADMUX = (analog_reference << 6) | (pin & 0x07);

which overrides reference selections made by just changing ADMUX.

Parameters `INTERNAL` and `DEFAULT` to [analogReference()](https://www.arduino.cc/en/Reference/AnalogReference) select either the 1.1 V internal bandgap reference or the default analog reference, Vcc.

---

*Edit 1:*  If you replace `ADMUX &= (0<<REFS0)` with `analogReference(INTERNAL)` in setup and it still doesn't work, you will need to apply some more-powerful debugging aids.  For example, check that you got the sketch to correctly compile and that you uploaded it ok.  Check that AVCC is connected to Vcc, preferably through a low-pass filter, as noted in datasheet sections §1.1.2 and §17.9, “Analog Noise Canceling Techniques”.  Then, try several voltage inputs to see at what level the LED comes on.  If it doesn't ever come on, look for LED problems using a simple sketch like Blink.  If it comes on consistently at some input voltage, work out what reference is being applied.

---

*Edit 2:*  Apparently the source code of `analogRead()` is different for ATtiny parts vs others.  The code that I see for it in ... /arduino/avr/cores/arduino/wiring_analog.c [your path may differ] is like the following (I've elided some comments and blank lines).

    uint8_t analog_reference = DEFAULT;
    void analogReference(uint8_t mode) {
      analog_reference = mode;
    }

    int analogRead(uint8_t pin) {
      #if defined( CORE_ANALOG_FIRST )
        if ( pin >= CORE_ANALOG_FIRST ) pin -= CORE_ANALOG_FIRST; // allow for channel or pin numbers
      #endif
      ADC_SetVoltageReference( analog_reference );
      ADC_SetInputChannel( pin );
      ADC_StartConversion();
      while( ADC_ConversionInProgress() );
      return( ADC_GetDataRegister() );
    }

Some `ADC_...` functions and constants are defined in ... avr/cores/tiny/core_adc.h; and which definition of `ADC_SetVoltageReference()` is used depends on conditional compilation.  For a definitive check on how `analogReference()` is defined for your part, look for `analogReference()` within the assembly listing of your program.  Obtain that listing as explained in several Arduino SE answers, for example in the  “Making assembly listings” paragraph near the end of [my answer to question #33033](https://arduino.stackexchange.com/a/33042/3917). Also, [a forum.arduino.cc thread from late April 2016](https://forum.arduino.cc/index.php?topic=299759.45) has some discussion of reading ADC inputs on tinys; I don't know if it's relevant.


message:
How to identify connection lost on HC-06?

I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.

    int in1 = 4;
    int in2 = 5;
    int in3 = 6;
    int in4 = 7;

    void setup() {
      Serial.begin(9600);
      pinMode (in1, OUTPUT);
      pinMode (in2, OUTPUT);
      pinMode (in3, OUTPUT);
      pinMode (in4, OUTPUT);
    }

    void loop() {
      if (Serial.available()) {
        int command = Serial.read();
        move(command);
      }
    }

    void move(int command) {
        if (command == 'f') forward();
        else if (command == 'b') backward();
        else if (command == 'l') left();
        else if (command == 'L') leftback();
        else if (command == 'r') right();
        else if (command == 'R') rightback();
        else if (command == 's') stop();
    }

Now what I want is to identify whether there is connection or it is lost. For example:

    if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

body:
Two possible ways I see:

 - Connect the HC-06 LED anode (or cathode, depending on how it's driven) to an Arduino input pin. Since you can tell from the blink frequency if the module is paired with your phone or not, you can use that (through interrupts maybe) as a means to know if you're still connected to your phone.
 - Find a way to configure the android app (or write your own app) to either regularly ping your Arduino or to respond to ping requests from the Arduino. If the Arduino fails to get a ping request (in the first case) or a ping response (in the second case) after some pre-agreed interval, it decides the connection has been broken and halts the RC car.

Second way is less messy but may require some android programming skills on your part. I remember coming across an app in the Play Store that sends '#' constantly even when idle, with your own characters in between. That would work as well as a ping, if you could find something similar, and the only programming you'd need to do would be on the Arduino's side.


body:
My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.

Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) [datasheet][1].

[![Location of LED edge-pin][2]][2]

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.

[![LED signal detail][3]][3]

  [1]: https://www.olimex.com/Products/Components/RF/BLUETOOTH-SERIAL-HC-06/resources/hc06.pdf
  [2]: https://i.stack.imgur.com/BZsyL.jpg
  [3]: https://i.stack.imgur.com/8agdp.jpg


message:
Arduino and ESP8266 Two-way Communication

I've searched the internet quite a bit and all I find is how to make two esp8266 communicate. What I am trying to do is connect a single esp8266 to the arduino and have a two-way communication between them.

I want to send and receive data on both the Arduino and ESP8266. The concept is to send data to the esp8266 over WiFi connection and then send that data to the Arduino. The Arduino will manipulate it and send it back over WiFi.

I feel like this would be a common beginner example to have a two-way communication over a TX/RX connection, but I can't seem to find any. All examples I find are strictly one as sender and other as receiver.

body:
See https://arduino.stackexchange.com/questions/33540/how-can-i-verify-that-my-esp8266-is-working asked 2 hours before.

use something like https://www.sparkfun.com/products/12009 or https://learn.adafruit.com/arduino-tips-tricks-and-techniques/3-3v-conversion

Usual way is let the Arduino direct the ESP, but if you are able to program ESP too, then any communication can work the same way as between twou ESPs or two Arduinos (with the level shift in mind)


body:
The best way for connecting ESP8266, Arduinos and devices like displays, RTC, etc., is using the serial protocol I2C.

I2C is a master-slave protocol. In this case, ESP8266 will be your master, and every other device (including Arduino) will be a slave. Every slave had an *address*, for id purposes. You can have up to 127 slaves, in theory, but real limits is determined by space, distance, capacitance, etc.

Only masters can initiate communication, so you have to program your ESP8266 to poll the the Arduino for sending back the processed information.

Connection is simple. For a I2C device (slave or master), you need Vcc and GND, plus two lines for communication: SDA and SCL.

For programming, you have lots of tutorials and examples on how to use I2C.

Both ESP8266 and Arduino (an many others MCU I think) can speak I2C. I strongly recommend you to adopt this protocol for everything. If you want to buy some device (like a display), always looks for the I2C version.


message:
Replace Wire library with TinyWireM

I want to integrate Pololu's [vl53l0x Time of Flight distance][1] sensor into a project of mine. They created a [library][2] to interface with the vl53l0x over I2C, which works great on my Uno. The only problem is that Wire.h doesn't work on the ATtiny85.

[TinyWireM][3] is a replacement library for Wire that I think would be compatible. My question is this: how can I go about replacing all the calls to the Wire library with calls to the TinyWireM library? Is it as simple as replacing all instances of Wire with TinyWireM? Is there anything else I need to do to make the library ATtiny85 compatible?

Thanks!

  [1]: https://www.pololu.com/product/2490
  [2]: https://github.com/pololu/vl53l0x-arduino
  [3]: https://github.com/adafruit/TinyWireM

body:
In fact, there would be nothing to do now I guess, as TinyWireM is now included tiny boards packages.

If you just include Wire as usual, it should work as on an UNO.
Except for setting a different clock, if I remember well, it is fixed to 400kHz.


body:
I can't guarantee it will work, but it is probably possible to just modify the library. You can find the source code for that ToF sensor library here:

https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp

The first step is to find the reference to *Wire.h* (line 7 in that file) and change it to *TinyWireM.h*. After that, you would need to find the functions that call the *Wire* library and replace them with the appropriate *TinyWireM* functions instead. Those begin at line 284 (`Wire.beginTransmission(address);`). You can find the source code for TinyWireM here (which should tell you all of the functions in the library):

https://github.com/adafruit/TinyWireM/blob/master/TinyWireM.cpp

So `Wire.beginTransmission(address);` would become `TinyWireM.beginTransmission(address);` and `Wire.write(reg);` would become `TinyWireM.send(reg);`

I'm not sure if that's all of the solution, but I think that's a good start.


message:
Arduino time between interrupts in POV led display

I'm making a POV display (4 spokes) on a bike wheel using a Hall effect sensor to measure how long the last revolution took and based on that I calculate delays in the display. By pedalling at a constant rate I should get roughly a nice image but all I got is an unsynchronized mess. It seems like it is going and image is stable but after around half of a turn it scrambles.

I divided the wheel into 32 even parts which uses the same LED colour. Any advice how to achieve full synchronization. Any thoughts?

Here is my code:

    #include "Adafruit_WS2801.h"
    #include "SPI.h"
    #ifdef __AVR_ATtiny85__
    #include <avr/power.h>
    #endif
    #include <time.h>
    #include <stdlib.h>

    #define MIN_TIME 150000
    #define MAX_TIME 1000000
    #define RADIUS 240
    #define MAGNETS_NUM 1
    uint8_t shwFg = 1;
    uint8_t dataPin1  = 2; // White wire on Adafruit Pixels
    uint8_t dataPin2  = 3; // Yellow wire on Adafruit Pixels
    uint8_t dataPin3  = 4; // Yellow wire on Adafruit Pixels
    uint8_t dataPin4  = 5; // Yellow wire on Adafruit Pixels
    uint8_t clockPin1 = 10; // White wire on Adafruit Pixels
    uint8_t clockPin2 = 11; // Green wire on Adafruit Pixels
    uint8_t clockPin3 = 12; // Green wire on Adafruit Pixels
    uint8_t clockPin4 = 13; // Green wire on Adafruit Pixels
    uint8_t hallPin  = 20;
    uint8_t pointer1 = 0;
    uint8_t pointer2 = 8;
    uint8_t pointer3 = 16;
    uint8_t pointer4 = 24;
    uint8_t LED1R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED2R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED3R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED4R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED5R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED6R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED7R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED8R[32] = {0, 0, 0, 0, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144, 1, 1, 1, 1, 128, 128, 128, 128, 0, 0, 0, 0, 144, 144, 144, 144};
    uint8_t LED1B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED2B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED3B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED4B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED5B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED6B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED7B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED8B[32] = {128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1, 128, 128, 128, 128, 1, 1, 1, 1};
    uint8_t LED1G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED2G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED3G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED4G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED5G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED6G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED7G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    uint8_t LED8G[32] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0};
    long now = 0;
    long prev = 0;
    int hallState = 0;
    unsigned long previous = 0;
    unsigned long dlyMic = 123456;
    Adafruit_WS2801 strip = Adafruit_WS2801((uint16_t)8, dataPin1, clockPin1);
    Adafruit_WS2801 strip2 = Adafruit_WS2801((uint16_t)8, dataPin2, clockPin2);
    Adafruit_WS2801 strip3 = Adafruit_WS2801((uint16_t)8, dataPin3, clockPin3);
    Adafruit_WS2801 strip4 = Adafruit_WS2801((uint16_t)8, dataPin4, clockPin4);
    int a = 0;
    unsigned long current = 0;
    unsigned long  delta = 0;

    void GetDelay() {
      previous = current;
      current = micros();
    }

    void setup() {
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif
      pinMode(hallPin, INPUT);
      Serial.begin(115200);
      strip.begin();
      strip2.begin();
      strip3.begin();
      strip4.begin();
      attachInterrupt(3, GetDelay, HIGH);
    }

    void delayMicroseconds2(unsigned int us) {
      // calling avrlib's delay_us() function with low values (e.g. 1 or
      // 2 microseconds) gives delays longer than desired.
      //delay_us(us);
      // for the 16 MHz clock on most Arduino boards
      // for a one-microsecond delay, simply return.  the overhead
      // of the function call yields a delay of approximately 1 1/8 us.
      if (--us == 0) return;
      // the following loop takes a quarter of a microsecond (4 cycles)
      // per iteration, so execute it four times for each microsecond of
      // delay requested.
      us <<= 2;
      // account for the time taken in the preceeding commands.
      us -= 2;
      // busy wait
      __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
      );
    }

    void loop() {
    delta  = current - previous;
    delta<<5;
    delta-=6800; //time required for loop

      if (shwFg == 0) {
        int i;
        for (i = 0; i < 8; i++) {
          strip.setPixelColor(i, 0, 0, 0);
          strip2.setPixelColor(i, 0, 0, 0);
          strip3.setPixelColor(i, 0, 0, 0);
          strip4.setPixelColor(i, 0, 0, 0);
        }
      } else {
        strip.setPixelColor(0, LED1R[pointer1] , (LED1B[pointer1] ) , (LED1G[pointer1] ) );
        strip2.setPixelColor(0, LED1R[pointer2] , (LED1B[pointer2] ) , (LED1G[pointer2] ) );
        strip3.setPixelColor(0, LED1R[pointer3] , (LED1B[pointer3] ) , (LED1G[pointer3] ) );
        strip4.setPixelColor(0, LED1R[pointer4] , (LED1B[pointer4] ) , (LED1G[pointer4] ) );
        strip.setPixelColor(1, LED2R[pointer1] , (LED2B[pointer1] ) , (LED2G[pointer1] ) );
        strip2.setPixelColor(1, LED2R[pointer2] , (LED2B[pointer2] ) , (LED2G[pointer2] ) );
        strip3.setPixelColor(1, LED2R[pointer3] , (LED2B[pointer3] ) , (LED2G[pointer3] ) );
        strip4.setPixelColor(1, LED2R[pointer4] , (LED2B[pointer4] ) , (LED2G[pointer4] ) );
        strip.setPixelColor(2, LED3R[pointer1] , (LED3B[pointer1] ) , (LED3G[pointer1] ) );
        strip2.setPixelColor(2, LED3R[pointer2] , (LED3B[pointer2] ) , (LED3G[pointer2] ) );
        strip3.setPixelColor(2, LED3R[pointer3] , (LED3B[pointer3] ) , (LED3G[pointer3] ) );
        strip4.setPixelColor(2, LED3R[pointer4] , (LED3B[pointer4] ) , (LED3G[pointer4] ) );
        strip.setPixelColor(3, LED4R[pointer1] , (LED4B[pointer1] ) , (LED4G[pointer1] ) );
        strip2.setPixelColor(3, LED4R[pointer2] , (LED4B[pointer2] ) , (LED4G[pointer2] ) );
        strip3.setPixelColor(3, LED4R[pointer3] , (LED4B[pointer3] ) , (LED4G[pointer3] ) );
        strip4.setPixelColor(3, LED4R[pointer4] , (LED4B[pointer4] ) , (LED4G[pointer4] ) );
        strip.setPixelColor(4, LED5R[pointer1] , (LED5B[pointer1] ) , (LED5G[pointer1] ) );
        strip2.setPixelColor(4, LED5R[pointer2] , (LED5B[pointer2] ) , (LED5G[pointer2] ) );
        strip3.setPixelColor(4, LED5R[pointer3] , (LED5B[pointer3] ) , (LED5G[pointer3] ) );
        strip4.setPixelColor(4, LED5R[pointer4] , (LED5B[pointer4] ) , (LED5G[pointer4] ) );
        strip.setPixelColor(5, LED6R[pointer1] , (LED6B[pointer1] ) , (LED6G[pointer1] ) );
        strip2.setPixelColor(5, LED6R[pointer2] , (LED6B[pointer2] ) , (LED6G[pointer2] ) );
        strip3.setPixelColor(5, LED6R[pointer3] , (LED6B[pointer3] ) , (LED6G[pointer3] ) );
        strip4.setPixelColor(5, LED6R[pointer4] , (LED6B[pointer4] ) , (LED6G[pointer4] ) );
        strip.setPixelColor(6, LED7R[pointer1] , (LED7B[pointer1] ) , (LED7G[pointer1] ) );
        strip2.setPixelColor(6, LED7R[pointer2] , (LED7B[pointer2] ) , (LED7G[pointer2] ) );
        strip3.setPixelColor(6, LED7R[pointer3] , (LED7B[pointer3] ) , (LED7G[pointer3] ) );
        strip4.setPixelColor(6, LED7R[pointer4] , (LED7B[pointer4] ) , (LED7G[pointer4] ) );
        strip.setPixelColor(7, LED8R[pointer1] , (LED8B[pointer1] ) , (LED8G[pointer1] ) );
        strip2.setPixelColor(7, LED8R[pointer2] , (LED8B[pointer2] ) , (LED8G[pointer2] ) );
        strip3.setPixelColor(7, LED8R[pointer3] , (LED8B[pointer3] ) , (LED8G[pointer3] ) );
        strip4.setPixelColor(7, LED8R[pointer4] , (LED8B[pointer4] ) , (LED8G[pointer4] ) );
      }
      strip.show();
      strip2.show();
      strip3.show();
      strip4.show();

      pointer1++;
      pointer1 &= 31;
      pointer3++;
      pointer3 &= 31;
      pointer2++;
      pointer2 &= 31;
      pointer4++;
      pointer4 &= 31;
      delayMicroseconds2(delta);

    }

Pardon me, it was late in the night and I put wrong code. Of course delay should depend on delta. Changed to newest code with less job in delay. Still yields similar results.

body:
As noted in a comment, `dlyMic` should be declared as a `volatile` variable.  This is true of any variables where `loop()` gets a value changed by an interrupt service routine, or where it puts a value for the ISR to use.  In either case, if the variable is multibyte, you may wish to surround the get or put by code to turn interrupts off and on, to avoid race conditions where the ISR is reading or changing a value coincidentally with `loop()` changing or reading it.  For example:

    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++somethingimportant;  // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status

Aside from that, your treatment of `dlyMic` resembles a bad random number generator.  It consists of a declaration line; a couple of lines in the ISR; and use as a delay parameter in `loop()`:

    unsigned long dlyMic =123456;
    ...

      dlyMic<<5;
      dlyMic-=6500;
    ...
    delayMicroseconds2(dlyMic);

The following two lines of Python compute the series of numbers that will result as values of `dlyMic`.

    dlyMic=123456; mk = 2**32-1
    for i in range(14): print dlyMic; dlyMic=(dlyMic*32-6500)&mk

They produce:

    123456
    3944092
    126204444
    4038535708
    384117276
    3701811740
    2493852188
    2493852188
    2493852188
    ...

You may wish to connect up your `dlyMic` calculations with your measurement, `delta`.