text:
Write and read operation via synchronous serial port (Arduino Uno + ADNS2610)
1.Preliminaries
I have optical sensor ADNS2610 (see datasheet here) which I plug in to Arduino Uno R3 board.
It is possible either to read from either to write to the sensor. Here is what datasheet says (p. 12):

Write Operation
Write operations, where data is going from the microcontroller to the
  ADNS-2610, is always initiated by the microcontroller and consists of
  two bytes. The first byte contains the address (seven bits) and has a
  “1” as its MSB to indicate data direction. The second byte contains
  the data. The transfer is synchronized by SCK. The microcontroller
  changes SDIO on falling edges of SCK. The ADNS-2610 reads SDIO on rising edges of SCK.

Read Operation
A read operation, meaning data that is going from the ADNS-2610 to the
  microcontroller, is always initiated by the microcontroller and
  consists of two bytes. The first byte that contains the address is
  written by the microcontroller and has a “0” as its MSB to indicate
  data direction. The second byte contains the data and is driven by the
  ADNS-2610. The transfer synchronized by SCK. SDIO is changed
  on falling edges of SCK and read on every rising edge of SCK. The
  microcontroller must go to a High-Z state after the last address data
  bit. The ADNS-2610 will go to the High-Z state after the last data
  bit. Another thing to note during a read operation;
  SCK needs to be delayed after the last address data bit to ensure that the ADNS-2610 has at least 100 μs to prepare the requested data.
  This is shown in the timing diagrams below (See Figures to 23).

2 Arduino program
WriteRegister and ReadRegister functions are borrowed (though slightly modified) from OptiMouse project by zapmaker.
2.1 SetAddress function
This function writes the first byte: data direction (MSB) and address of a register (seven bits) which user intents to read from or to write to.
void ADNS2610::SetAddress( uint8_t address, DataDirection direction ) const
{
    pinMode( sdioPin, OUTPUT );

    /*Specify data direction:
     *MSB = 0   ===>   read operation
     *MSB = 1   ===>   write operation*/
    switch( direction )
    {
        case( toSensor ) :
            address |= 0b10000000 ;
            break;
        case( fromSensor ) :
            address &= ~0b10000000 ;
            break;
    }

    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, address & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between address write operation
    *and read data operation (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

2.2 ReadRegister function
uint8_t ADNS2610::ReadRegister( uint8_t address ) const
{
    SetAddress( address, fromSensor );

    uint8_t data = 0;

    /*Read data from a register*/
    pinMode( sdioPin, INPUT );
    for( int i = 7; i >= 0; i++ )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sckPin, HIGH );

        data |= ( digitalRead( sdioPin ) << i );
    }

    /*Wait for 0.25 microseconds between read and either
     *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 1 );

    return data;
}

2.3 WriteRegister function
void ADNS2610::WriteRegister( uint8_t address, uint8_t data ) const
{
    SetAddress( address, toSensor );

    /*Write data to a register*/
    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, data & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between write and either
    *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

3.Discussion
3.1 Write operation
According to the datasheet

... The microcontroller changes SDIO on falling edges of SCK. The ADNS-2610 reads SDIO on rising edges of SCK.

And this is how I understand the code (see sec. 2.1):
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

Two questions here:

The first line in the above creates a falling edge only if the previous state of SCK was HIGH, doesn't it? So would it be better to have the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

On figure 20 (see sec. 1, Write operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration? I know that ATMega328p has frequency 16 MHz, so it seems that time between two operations could be less than 250 ns. Am I right?

3.2 Read operation
According to the datasheet

SDIO is changed on falling edges of SCK and read on every rising edge of SCK. The microcontroller must go to a High-Z state after the last address data bit. The ADNS-2610 will go to the High-Z state after the last data bit

And this is how I understand the code (see sec. 2.2):
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

Three questions here:

The first line in the code above creates a falling edge only if the previous state of SCK was HIGH, doesn't it? Would it be better to have the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

On figure 23 (see sec. 1,Read operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration?
How do I set the microcontroller into High-Z state after the last address data bit?

Question 1

The first line in the code above creates a falling edge only if the
  previous state of SCK was HIGH, doesn't it? Would it be better to have
  the following:
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

If you start from Cycle one.. Yes. Looking at the read cycle waveform, SCLK should be high before initiating a read or write request and after completing the communication.
Question 2

On figure 23 (see sec. 1,Read operation) you can see that it is
  required some minimal duration of the clock pulses (250 ns). Does the
  above code provide such a duration?

Here is the code for digital write function
void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN)
        return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER)
        turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    }
    else {
        *out |= bit;
    }

    SREG = oldSREG;
}

Please do not give any delay. the above DigtalWrite function will take 1000's of ns of delay already. it is sufficient.
Question 3:

How do I set the micro controller into High-Z state after the last
  address data bit?

I would do the following. Configure the pin which you want to set to high impedance as input pin. You can always change it to output mode before you want to use it again.


text:
OBOE: Need help understanding, possible type conversion issue
I have an algorithm that its main purpose is decoding, converting, or what have you a string of uppercase letters (A-Z) into a number. This is almost like converting a base 26 number into base 10, however I believe that a base 26 number encoded would actually include numbers, I am working strictly with uppercase letters, I digress.
I have an implantation working in C++11, in fact most of the controller algorithm was a direct copy, with a slight change to the indexOf method.
The C++11 version works as I expect it to. So initially I thought the new indexOf method was incorrect, but after a simple test, it is working as expected. I have narrowed down the problem to a line in the convertTo10 where I am calling the pow function.
As you can see from the Serial.println()'s in the convertTo10 method, the output is printing exactly what we expect, 0 & 26.
However, the output of this function is 25. WHAT?
I have read the docs on the pow method from the Arduino lib, and it takes in two floats and returns a double. Even if the issue was a type conversion issue, converting a double to an int truncates the number, it does not round it. Well, this is from working with C++.
Any help with this issue would be much appreciated.
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <inttypes.h>

#include <Arduino.h>
#include <avr/pgmspace.h>
#include <Wire.h>

const char _values[26] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z'
};

const int _val_len = 26;

int indexOf(char needle);
int convertTo10(String value, int len);

String x = "BA";
int len = 2;

void loop() {
  Serial.print(x);
  Serial.print("=> ");
  Serial.println(convertTo10(x, 2));
  delay(50000);
}

int convertTo10(String value, int len) {
    int lastIndex = len - 1;
    double output = 0;
    int pos = 0;
    Serial.println();
    for (int i = lastIndex; i >= 0; i--) {
        int r = indexOf(value[i]);

        output += (r * pow((_val_len, pos));
        Serial.print("     output => ");
        Serial.println( output );
        pos++;
    }
    return output;
}

int indexOf(char needle) {

    int first = 0;
    int last = _val_len - 1;
    int mid;

  do {
    mid = (first + last) / 2;

    if (_values[mid] == needle)
      return mid;
    if (_values[mid] > needle)
      last = mid - 1;
    else
      first = mid + 1;
  } while (first <= last);

  return -1;
}

For Reference, Here what it is outputting:
BA =>
     output => 0.00
     output => 26.00
25

Also posted on the Arduino Forum.

You can make the return value be 26 in this case by rounding. That is change the last line of your conversion function to be: return round (output);. The fact that it is returning 25 indicates that the pow function is not giving an exact result. If you increase the number of decimal places printed you will see that you are actually getting 25.9999961853.

way too complicated:
int convertTo10(char *num_26, int len) {
  int tmp = 0;  //hold the output
  int i = 0;  //indexing the input
  while (len--) tmp = tmp * 26 + (num_26[i++]-'A');
  return tmp;
}

note:

"* 26" can be further simplified;

error checking could be built-in here, or somewhere else (better).

better structuring could get rid of one of the temporary variables.

Thank you for the optimized code! However, I was hoping I could get an explanation on what is happening in the code I posted? What did I do wrong?

What you did wrong was to rely on a floating point number to be exact.  They hardly ever are.

@Delta_G I realize this now. Thank you for the correction, I should have just waiting until the morning to revisit the problem, instead of ask dumb questions. I do appreciate the help.

@dannyf As much as I appreciate this solution and the time and effort you took to help me. I have to mark this solution as incorrect. I have verified that  on a atmel2560 compiled with avr-gcc, and on Debian x64 compiled with g++ under standard 11, this method will always return 0.

This code fails because i is not initialized. Otherwise it is conceptually similar to my answer. If you change the third line to int i = 0; it works.

Your code is incredibly complex for a simple thing like converting a number from another base. This works (prints 26):
const char * test = "BA";

long convertTo10 (const char * s)
  {
  long result = 0;
  for (const char * p = s; *p; p++)
    {
    result *= 26;   // base
    result += *p - 'A';  // make zero-relative
    }
  return result;
  } // end of convertTo10

void setup()
  {
  Serial.begin (115200);
  Serial.println ("Starting.");
  Serial.println (convertTo10 (test));
  }

void loop() { }

With input "CBA" it prints 1378 as expected.  Sketch size: 2,300 bytes of program memory. The sketch size reduces to 2,236 bytes if I make the function return int (as you did) rather than long.
You don't need to use String (in fact it saves RAM and avoids memory fragmentation to not use it). You don't need to pass the length, with both char* and String you can deduce the length. If you use long as the return type you can handle larger numbers.
By using pow you are bringing in a library which is not needed and which will consume program memory. By using double you are introducing possible inaccuracies since double does not necessarily store numbers exactly. Your code used 7,604 bytes of program memory once I corrected the syntax error and added an empty setup function.

Also, the method I illustrate above is much faster. I timed it at converting "BA" in 4.3 µs, whereas the method using the pow function takes 442 µs. So the simpler method is also 100 times faster.

source: Stack Exchange

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

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

sort: votes


text:
How do I import data from serial monitor to excel document without copying and pasting?
I need to be able to import incoming data from a motion sensor and then from the serial monitor (where the data is) import the data to an excel document or file.
Any suggestions would help,
Thanks.

The Arduino IDE's serial monitor is just one of many tools that can open a serial port and collect information from it.
The first step is to make sure the data you are writing to the Serial object in the Arduino is in a format suitable for importing into Excel. Separate multiple values on one line with a comma "," or tab "\t" character.
If you are running windows, you can often just use the built-in type command from a command prompt to write the serial port to a file:
type COM4 >> log.txt

(Assuming the Arduino is on COM4 and you want to write the data to a file called log.txt.)
If you're on a Mac, open the Terminal app and type:
screen -L /dev/tty.usbmodem1441335 9600

(Assuming your Arduino is on serial port named tty.usbmodem1441335 and your port speed is 9600 bps.) The session will be written to a file called screenlog.0.
Then you can open the text/log file in Excel. If you rename it to end in .csv, that may also help Excel recognize it as tabular data.

You could even connect directly to the serial port, from within excel, using VBA. http://www.dailyfreecode.com/Forum/accessing-serial-port-excel-vba-26041.aspx

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


text:
Problem : Trigger limit switch to stop DC motor
I want to make a project about automatic gate and garage door via Android app and connected by HC-05 bluetooth module.
Each of the gate and garage door have two limit switches(located at each end of travel) to trigger the DC motor to stop.
I have made some code and do researches, but the DC motor will only stop when I pressed it, if I release it again it will start automatically. I want to make it stop until the bluetooth module send the code again.
I have input the pull-down resistor into the limit switch.
Can anybody please help me?
Here's my current code, thank you
// Motor for Gate (MotorA)
int IN1 = 2;
int IN2 = 3;
int EnableMotorA = 9;

// Motor for Garage Door (MotorB)
int IN3 = 4;
int IN4 = 5;
int EnableMotorB = 10;

const int LimitSwitch1 = A1;
const int LimitSwitch2 = A2;
const int LimitSwitch3 = A3;
const int LimitSwitch4 = A4;

int state;

void setup(){
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(EnableMotorA,OUTPUT);

  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  pinMode(EnableMotorB,OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  digitalWrite(LimitSwitch1, LOW);
  digitalWrite(LimitSwitch2, LOW);
  digitalWrite(LimitSwitch3, LOW);
  digitalWrite(LimitSwitch4, LOW);

  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    state = Serial.read();
    }
    if(state == 'A') {
      OpenGate();
      if(digitalRead(LimitSwitch2) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'B') {
      CloseGate();
      if(digitalRead(LimitSwitch1) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'C') {
      OpenGarageDoor();
      if(digitalRead(LimitSwitch4) == HIGH){
      StopMotorB();
      }
    }
    else if(state == 'D') {
      CloseGarageDoor();
      if(digitalRead(LimitSwitch3) == HIGH){
      StopMotorB();
      }
    }
}

//******************   Motor A control   *******************
void OpenGate(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(EnableMotorA, 250);
  }
void CloseGate(){
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 250);
}
void StopMotorA(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 0);
 }
//******************   Motor B control   *******************
void OpenGarageDoor(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(EnableMotorB, 250);
}
void CloseGarageDoor(){
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 250);
}
void StopMotorB(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 0);
}
//**********************************************************

do not start the motor after the switch is closed. start it with BT only. .... draw up a flowchart on paper, then create the code that emulates the flowchart.

I am sorry but what is BT? I have made the flowchart, it goes like motor DC turn in clockwise -> is limit switch pressed? -> if yes, stop the DC motor. and I thought i have made it that way

BT ... bluetooth   ..... you are getting your states from a serial connection. that is ok, but you need internal states also. example: state E --- status: everything stopped .... enter from state B when limit switch is activated (and from others)

you need at least 4 separate stop states ... door open, door closed, door stop at opening, door stop at closing.   .... do a web search about state machine or arduino state machine

the state is referring the character that is received from the BT.
do the if statement for limit switch also included into the stop state?
okay i will have a research about that, thank you

DISCLAIMER: I haven't tested the code in this answer, but I hope there are no problems.
Your code has a major problem: what happens when one gate is moving and you trigger another movement? (reply: something bad). This design issue can be solved by using a standard way of designing these kind of state machine.
In your case a small state machine is what best fits your problem. Better give your states a meaningful name, no?
Ok, so just to start, let's define the states and how to transition through them.
You have basically an idle state, open gate, close gate, open garage door, close garage door. What should you do in these states, both when entering the state and during the time you are in the state? Here is a table to summarize
State       | Enter         | During time
----------------------------------------------
Idle        | Stop motors   | -
OpenGate    | Start A dir 1 | -
CloseGate   | Start A dir 2 | -
OpenGarage  | Start B dir 1 | -
CloseGarage | Start B dir 2 | -

The transitions are pretty straightforward. Exit from idle when you receive a (valid) command, exit from the others when you reach the endstop.
The implementation is pretty standard:
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte State_Idle = 0;
const byte State_OpenGate = 1;
const byte State_CloseGate = 2;
const byte State_OpenGarage = 3;
const byte State_CloseGarage = 4;
byte currentState;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentState = 0xFF; // Force a change to enter the idle state
}

void loop(){
    // Check if we need to change state
    byte nextState = currentState;
    switch (currentState)
    {
    case State_Idle:
        { // If we received a valid command, start the operation
            if(Serial.available() > 0)
            {
                switch (Serial.read())
                {
                case 'A':
                    nextState = State_OpenGate;
                    break;
                case 'B':
                    nextState = State_CloseGate;
                    break;
                case 'C':
                    nextState = State_OpenGarage;
                    break;
                case 'D':
                    nextState = State_CloseGarage;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case State_OpenGate:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGate:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_OpenGarage:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGarage:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    default:
        nextState = State_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentState)
    {
        currentState = nextState; // Move in the new state
        switch (currentState)
        { // Entering the new state
        case State_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case State_OpenGate:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case State_CloseGate:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        case State_OpenGarage:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case State_CloseGarage:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

(Note: I changed some types because your poor 8-bit uC asked me to avoid complicating its calculations unnecessarily)
One modification to your algorithm is to detach the two loops, since they seem, well, detached.
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
byte currentStateA;

const byte StateB_Idle = 0;
const byte StateB_Open = 1;
const byte StateB_Close = 2;
byte currentStateB;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentStateA = 0xFF; // Force a change to enter the idle state
    currentStateB = 0xFF; // Force a change to enter the idle state
}

void loop()
{
    byte readChar = 0;
    if(Serial.available() > 0)
        readChar = Serial.read();

    stateMachineA(readChar);
    stateMachineB(readChar);
}

void stateMachineA(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateA;
    switch (currentStateA)
    {
    case StateA_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'A':
                    nextState = StateA_Open;
                    break;
                case 'B':
                    nextState = StateA_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateA_Open:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    case StateA_Close:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    default:
        nextState = StateA_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateA)
    {
        currentStateA = nextState; // Move in the new state
        switch (currentStateA)
        { // Entering the new state
        case StateA_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            break;
        case StateA_Open:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case StateA_Close:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        }
    }
}

void stateMachineB(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateB;
    switch (currentStateB)
    {
    case StateB_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'C':
                    nextState = StateB_Open;
                    break;
                case 'D':
                    nextState = StateB_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateB_Open:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    case StateB_Close:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    default:
        nextState = StateB_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateB)
    {
        currentStateB = nextState; // Move in the new state
        switch (currentStateB)
        { // Entering the new state
        case StateB_Idle:
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case StateB_Open:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case StateB_Close:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

This second implementation has two parallel state machines (sharing only the serial input). This will allow you to control both gates at the same time (for instance when the gate is closin you can open the garage)

Oh my god! it works perfectly for my circuit. i planned to make it like your second implementation. Thank you so much! :D

@HusnaAmiliansyah did you already test it? Does it work? Really? :-P

of course it works xD, i had tested it on breadboard

btw,
const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
what is this part mean?

@HusnaAmiliansyah there are tons of jokes on software which runs the first time (for instance this) ;) anyway those lines are to give a meaningful name to states. It's easier to write (and understand) nextstate = StateA_Open; than nextstate = 1;. In order to do this you have usually three ways: use a #define, use an enum or use some constants. I tend to prefer the third because it's, for me, the easiest way to force the 8-bit size to the state variable and values

Alright, got it!! thank you so much for your help!! :) btw, i am sorry i can not vote this answer because i dont have enough poin:(

@HusnaAmiliansyah don't worry, the most important thing is that you understood it ;) and that you marked the answer as accepted, so other people looking at your question can understand that the answer "answers" it.

Okay, i have accepted it long time ago :D. Btw i have another questions in mind... If i want to add buzzer inside the states, do i need to change the 'byte'? And is there any limitation for the number of states in one function (for exampe in statemachineA function)?

The byte type can hold values from 0 to 255, consequently if you have to code 257 states you need at least a 2-bytes int, while for 65537 states you need at least 3 bytes. But IMHO whenever you are exceeding 20-30 states you are going too far. So, theoretically there is no limit (you just have to make the variable holding the state bigger), but any state machine with more than some tens of states is too big to be managed effectively, and maybe re-thinking the machine (as a series of nested machines, for instance) can become a better solution


text:
Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually?
Let's assume I want to make an asterisk (*) out of LED strips. I want to control each leg individually, while still being connected to only one GPIO pin. The layout I had in mind, looks like this:

Since it's an LED strip with individually addressable LEDs, I can't just supply 5V, GND, and DATA to the middle and expect it to work (I highly assume).
If I want to do this, I assume I need to keep running them in "series", basically meaning I hook up one of the strips to the Arduino, then at the end of the strip I run a long wire to the start of one of the others and then repeat. Something like this:

but only for the data wire, as I can simply power all of them in the middle. If not, how can I do this? What happens if I hook up 5 strips' DATA to a single GPIO pin on the Arduino? Are all 5 strips shared then, so each strip's first LED is also the first I would turn on?

The LEDs are "addressed" in series; if you address the first LED then you address all connected first LEDs. So yes, you must connect the Data Out of the previous LED/strip to the Data In of the next in order to address all of them individually.

Right, so the second image I put in is basically what I have to do?

Or you can flip every other strip in order to have the shortest data paths. Just keep in mind the direction of each strip if you do.

Right, so something like this? https://i.imgur.com/MusZ8Hc.png

@MortenMoulder: Correct.

Awesome, thanks a lot for the confirmation :-)


text:
Arduino Nano + ESP8266 and saving to EEPROM
I am going to create a project with a friend, but I have some technical questions.
The Arduino Nano has an EEPROM capable of storing the known WiFi connections. Basically what I want is say "Arduino, connect to this WiFi and remember it". When I then disconnect the Arduino completely, it should still save that information. Can the EEPROM store that without power?
I need an easy, but rather small, WiFi module to work with the Arduino Nano. I've looked at the ESP8266. I don't mind soldering the ESP8266 to the Arduino Nano once, but doing it more times (perhaps because I need more GPIO or something) is not a variable solution. If I get the ESP8266 ESP-12, I would only have to solder it to the Nano once. However:

Is the ESP8266 ESP-12 compatible with the Arduino Nano?
I like the ESP-05 because it's small and simple. Would that work?

Are there perhaps better ways of doing this whole thing? Should I go for something else than the Arduino Nano? I need to hook up:

WiFi
Microphone (smallest and easiest way)
LEDs

All these questions are very easily answered using google. You should look at the possible solutions and come back with specific questions. What were your attempts, what did you not understand, etc..?

Quick search shows EEPROM solutions to save data w/o energy both on the Arduino Nano and ESP8266. Another search shows many projects with ESP12, ESP05 and Arduinos. "Better" ways of doing this is not a good format of question for SE and even if it were, we know nothing of you application, so no way we can suggest anything (whats good for your application: less power, availability of parts, reliability, etc etc?).

What does mic has to do with serial? Look up Software Serial. Also, you might not even need an Arduino..

What I meant was.. you can develop with Arduino IDE directly on an ESP12. Look up nodeMCU.

Yes, but it has trade-offs, might want to look into them before deciding. There's actually a nodeMCU board (and clones) with the USB>Serial adapter embedded which makes prototyping much easier.

"Site available only for Denmark. If you mistakenly nevertheless have been banned(...)" but well, you get the idea. Good luck with your project.

I'm sorry for prolonging this but, when I said nodeMCU I meant something like this with an ESP + USB/Serial converter (not a standalone ESP, which is doable but more of a hassle). Not endorsing any vendor in particular. You can use either LUA/or Arduino IDE, I tried LUA and didnt like it very much.

The ESP8266 is a SoC (System On Chip) that includes a microcontroller. For most applications, you’ll need only the ESP without the Nano. ESP-12E boards are very handy for tinkering. You can program the ESP in different languages, even in Arduino C (https://github.com/esp8266/Arduino/).
Note that the ESP is only 3.3V tolerant, so it is not that easy to use it with a Nano that works at 5V. It is of course possible to use logic level shifters, but frankly, I would rather use the ESP alone.
You don’t have to worry about storing WiFi connection settings, they are usually hard-coded in the main program.
Connecting LED is described everywhere on the internet, so I don’t think that is a major problem. If you need a lot of LEDs, you can buy LED strips.
For the microphone I suggest that you search for I²C modules.

Thanks for the comment! The beauty of this is if no known wifi has been found, create hotspot and let the user connect. Then I tell it to connect to the known WiFi, which it should then remember. The LEDs are basically just a couple of WS2812B, so it shouldn't be a problem to power those off 3.3v. I've ordered a ESP-12E NodeMCU and I'm looking forward to that!

It sounds like you are quite new to all this stuff.  In summary I think you are taking the wrong approach and need to re-think things.
EEPROM is capable of storing data without any power.
Both the devices have EEPOROM, also you could look at external devices, which would be easier to replace if you wear them out (limited number of write cycles - see their data sheets for details but they are usually in the tens of thousands).
The difference between the ESP8266 range are the number of GPIO lines they offer up, to the 12E has more than the 5, etc.
You shouldn't be soldering this stuff more than once.  You should design it right in the first place (easier said than done!)  What you could do is mount the Nano on a board that took all the lines off to a single 30 odd pin connector the design a series of daughter boards for the ESP8266 which were compatible with the base board, so you could switch between the different ESPs.
Also, don't forget you will need logic level conversion between the 5V Arduino and the 3.3V ESP8266 unless you are planning on smoking electronics.
What do you think you are doing with the MIC connector?  Are you planning on processing sound on the Arduino?  You might want to research that before you design it.
Are you aware that the ESP8266 can be programmed via the Arduino and has a 80MHz processor and 256KB of RAM (compared to the Nano's 32Mhz & 32KB) so using the ESP as a slave to the Arduino is not necessarily the best idea.
If you are interested this is the approach I would take:
 1. Solder some male pins to the Nano so you can put it into a bread board.
 2. If you have a 12E, Buy a ESP8266 mounting board (£1 for 10 from you favourite Chinese web market) and solder pins to that.
 3. If you have a 5 then solder pins to that.
 4. Make all you other parts breadboard-able and try it all out.
 5. Once it works download Fritzing and draw it up.
 6. Make a Vero board version and play with it for real.

Thanks! Yeah I'm quite new to this. I've bought an ESP-12E NodeMCU and I plan on going with Arduino C on it :)


text:
Send serial commands through IDE while RX pin is in use
This is really a two part question. I have an ESP8266 hooked up to USB. I have connected my LED strip (WS2812B LEDs) to the RX port, so I can control them individually and so on. I realised WiFi is a bit slow and will eventually crash the ESP8266 if I send enough requests, which is why I want to give serial a go.

If I open up the serial monitor, how do I send something to it, such as a color or 100 colors in one command? I'd assume Serial.read() inside a Serial.write() would display whatever I type in, but it doesn't do that. I can Serial.write() inside a loop, and it will display that.
Is something like this even possible? I'm looking for a way to send a lot of information (could be 100 colors (1 per LED)) as fast as possible. Speed is the key here.

Software serial is an option as well, as long as it's faster than WiFi.

what are the LEDs saying that you need to listen to them? ;) do you need RX?

Are you suing the NodeMCU eLua-based firmware or the ESP8266 Arduino Core?

@EdgarBonet Arduino :)

Regarding “I have connected my LED strip (WS2812B LEDs) to the RX port”:  If you connect an LED strip to the RX pin, there's a good chance you won't be able to read serial data reliably on that pin, and may have trouble loading new sketches.  It makes sense to connect the LEDs to some pin other than RX.
Regarding “If I open up the serial monitor, how do I send something to it”:  Ordinarily, one uses the serial monitor to receive data from an attached MCU or to send data to the MCU. (An MCU is a microcontroller – eg an Arduino or ESP8266.)  In the sketch on the MCU, use Serial.write() to send binary data to the monitor, and Serial.print() to send text and formatted numbers to the monitor.
If you want to send serial data rapidly from your host computer to the MCU, write a C or Python (etc) program that opens a serial port, marshals the data, and sends it.  In the  sketch on the MCU, use Serial.available to test if characters are available to read, and Serial.read to read a character.  For faster transmission, you can send binary data instead of ASCII, but would need to read up on that before attempting it.
For fast data transmission, aim for either high data rates or strong data compression.  For example, you might make up a protocol that only sends colors for pixels that are going to change; or might have high-level commands that tell the MCU how to generate a set of data, via color end points, step rates, and numbers of steps.
In general, wifi data rates are somewhat higher than serial data rates.  If that is not what you are experiencing, perhaps review the article Found a way to upload data VERY fast by wifi from github.com/esp8266.

Edit 1:
Regarding “Nothing is displayed in the serial monitor” [from code like if (Serial.available()) { Serial.write(Serial.read()); }]:  I'm assuming that the sketch in use has a setup() routine containing a Serial.begin(somedatarate) statement, with the same data rate selected in the serial monitor as in the Serial.begin() statement.   I'm also assuming the sketch has a loop() routine containing the if (Serial.available()) { Serial.write(Serial.read()); } code.
I'm also assuming the sketch was properly downloaded, and then the serial monitor was opened, using the USB-serial port the ESP8266 is attached to, and then you typed some text into the text entry box of the serial monitor and pressed or clicked Enter to send the text to the ESP8266, with a proper setting for the end-of-line character.
If all those assumptions are correct, but nothing shows up in reply to the text you send, then it seems likely some hardware or software issue is occurring.  For example, when the Serial data structure is set up (when the sketch begins running) it might be selecting an incorrect Rx pin.  Or something may be loading down the Rx pin.  To find out if either of those is the case, use an oscilloscope (if you have one) to look at what's arriving at different ESP8266 pins when you send text from the  serial monitor.  If no scope, connect a 5K-10KΩ resistor to an LED and use that as a logic probe.  One end of the resistor connects to a probe; the other end goes to the LED anode; and the LED cathode is grounded.  Test if that's working by touching the probe to +3.3V.  When the probe appears to be working ok, use it to check for brief flashes of data at different Rx pins on the ESP8266 when you send data from the serial monitor.  If no data gets to the ESP8266, it can't echo it.  (Note, I'm not sure how your NodeMCU ESP8266 handles serial-via-USB data; my notion that serial data should be visible on some Rx pin might be wrong.)
If it appears data is getting to some pin but isn't showing up as available, you might try opening software serial on that pin.  Some examples appear in code in a serial monitor note at github.com/esp8266.  I don't know enough about NodeMCU / ESP8266 to say what to do if probing and software serial don't help.

Thanks a lot for the reply! I am using NeoPixelBus which automatically sends the data to the LED strip through the RX pin (because I use NeoEsp8266Dma800KbpsMethod and couldn't get any other to work). In my void loop(void){} function, I can write if (Serial.available()) { Serial.write(Serial.read()); } right? If I then input something into the Arduino IDE serial monitor (like 0xff0000) it should write that in the monitor right after, right? Because that doesn't seem to work.

“Doesn't seem to work”  is what symptoms?  No LEDs lighting up?  No serial monitor output at all?  Wrong monitor output? If the latter also try Serial.print(Serial.read());.  Note, I'm assuming RX is pin D3.  You might put LED strips on several pins at once, eg D2 as well as D3, while trying to find a Neo Esp method that works.  Perhaps detach LED strips while trying out Serial comms

"Doesn't seem to work" meaning nothing it displayed in the serial monitor. The LED strip is hooked up to GPIO03/RXD0. Check out this image (bottom right)

I added some paragraphs in Edit 1 that might help, but I don't really know what the problem is due to.

Thanks a lot for the reply! As far as I remember, I had to remove all the serial commands from my Arduino code before I could get the LED strip to work (in the first place). It's really bugging me why it won't work properly. Do you happen to have any kind of guide I can follow (that you know works), which allows me to enter something like 0xff0000 into the serial monitor console and read it straight back in the console? Not even a guide, just some code that works on the ESP8266.

I have some ESP8266's which I haven't hooked up yet; can't vouch for any code.  It sounds like your setup has a LED vs. serial-data conflict.  If you have a USB serial adapter, or another Arduino, you could wire up to use an alternate serial port on the ESP8266.    Or perhaps follow up on the Found a way to upload data VERY fast by wifi article mentioned before.


text:
Convert string into char array in Arduino?
I am not that great at Arduino and C++ yet, but I'll give this a shot:
I have a char array that looks like this:
char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

However, I receive this char array from a string, which is basically:
String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

How do I turn my input variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.
I feel like this should be super simple to do, but I can't wrap my head around it.
Things I've tried and didn't understand that much:
1:
char delimiter[] = ",";

char* ptr = strtok_r(text, delimiter);

while (ptr != NULL) {
  Serial.println(ptr);
  ptr = strtok_r(NULL, delimiter);
}

cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'

2:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
int i = 0;
char bitmap[115];
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = str;
  i++;
}
Serial.println(bitmap);

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)
Error: Apparently you can't use  =?
3:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  Serial.println(str);
}

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.
4:
char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
char *ptr;
char bitmap[115];
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, &ptr, 16);
  i++;
}

Serial.println(bitmap);

I'm getting a lot closer now. strtol(str, &ptr, 16) actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap_caps.c", line 171, function: heap_caps_free
  abort() was called at PC 0x4011c173 on core 1

While it may be frustrating to not get the answers you wanted, this isn't a code-writing service. Both here and on SO, good explanations have been given about the need to parse the string by the comma character, then parse each element therein from a set of characters into the actual byte you want. It's not impossible, but it's not necessarily a one-line-of-code answer, either.

@josecanuc I completely agree that this isn't a code-writing service. However, when I've tried basically everything I've seen so far, that should be able to do it, I'm really desperate. I'm not asking for someone to give me the code. I am more than capable of looking at different functions and do my own research, but when everything I've tried has failed, what's there left to do? I come with my case and idea and hope that someone understands it and helps me solve the problem. Not give me the answer, although that would help more, but help me.

Seperate using strtok into individual strings is done and easy. Adding them to an array of chars is not that easy.

You got some useful comments on SO and an answer here, but now you deleted both questions and wasted everyone's time, who tried to help you. That isn't nice.

Also show us what you tried and explain why it isn't working. Otherwise the question is too-broad.

@gre_gor I'm not here to discuss the way I ask questions. I'll update my post with things I've tried, hold on.

@gre_gor See updated post.

@gre_gor, would you mind posting a link to the deleted questions? You can find the URLs in your browser history. That would be useful for others to determine whether they should spend any time trying to answer this question and also anyone who has a similar question.

@per1234 Unfortunately I was at work at that time and the browser history is gone. And as far as I know, you can't really see the deleted questions, event if you still have the URL.

@per1234: https://stackoverflow.com/questions/46225826/convert-string-into-char-array-in-arduino https://arduino.stackexchange.com/questions/44745/convert-string-into-char-array

So after a lot of help and some tweaking, I finally got it to work!
String text = server.arg(0);

char buf[text.length()];
text.toCharArray(buf, text.length());
char *p = buf;
char *str;
char bitmap[960]; //960 is fixed for now, need to count amount of commas + 1
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, NULL, 16);
  i++;
}

bitmap now contains all the XBM data from the GET request. I ran into some issues, causing the device to restart, because I accidentally forgot that the length of the bitmap array isn't 114 (that's the amount of horizontal pixels of the display). This caused it to overflow by a lot.
Huge thanks to jose can u c for helping me.

You note you can easily use strtok() to get individual strings of the text representation of the hex values. So now all you need is to convert the string "0xD7" or similar into the number 0xD7.
Have a look at strtol() function to perform that task.

Now that's something I like to see. Using strtok() I now have each value as a string. Using strtol() on that, I now get them all as longs. See my updated post (number 4). The Arduino crashes when I try this.

strtol(str, NULL, 16)

Same problem. Here's a small detail: If I remove the Serial.println(bitmap) it does not crash immediately. If I then add the display.drawXbm() to draw it on my OLED screen, it crashes the Arduino. Am I running out of memory perhaps?

Serial.println(bitmap) is interpreting bitmap as a C-style string, but it's not null-terminated (nor does it likely contain printable ASCII values), so it runs amok and causes a crash. Once you have your array of bytes, it's no longer a string, but an array of bytes, and you can't use it where you would use a string. What are you trying to print? What output are you expecting from Serial.println(bitmap) ?

I'm not sure. I was hoping I could see what it contained, but that's not how it works. Discard the Serial.println(bitmap).

If you want to see what it contains, print each element of the array separately (bitmap[0], then bitmap[1], ...). Handily, Serial.println(bitmap[0], HEX); will print the byte in hexadecimal representation.

Roger that. However, it does not fix the crashing. I've never seen an error like this.

Change your bitmap type as uint8_t bitmap[115];

Still crashes with the same error. Not sure if this backtrace helps: Backtrace: 0x400872b4:0x3ffd01c0 0x400873b3:0x3ffd01e0 0x4011c19b:0x3ffd0200 0x400825c3:0x3ffd0230 0x40082a35:0x3ffd0250 0x4000bec7:0x3ffd0270 0x400d4f02:0x3ffd0290 0x400d1710:0x3ffd02b0 0x400d1733:0x3ffd1620 0x400d40fb:0x3ffd1640 0x400d414b:0x3ffd1660 0x400d4182:0x3ffd1690 0x400d4295:0x3ffd16d0 0x400d185e:0x3ffd1710 0x4011b4c8:0x3ffd1730

Let us continue this discussion in chat.


text:
What does (byte*)variable_name mean in C++?
Gentlemen,
  I am a novice C++ programmer, When I was trying to learn how to use EEPROM with Arduino, I came across this statement

i2c_eeprom_write_page(0x57, 0, (byte *)somedata, sizeof(somedata));

where I need to know what does (byte*) somedata mean?, please let me know if someone know the answer
Regards,
Mr.B

external EEPROM?

It means "Interpret this pointer as a pointer to byte data".  It's called "Casting" and allows you to fool the compiler into thinking that one type of data is another.
For example, your function expects a byte * (a pointer to byte data), and if you have char * as your variable you can change it on the fly to byte * by casting it like that.

Thanks Mr.Majenko Can you please refer me some material or website for me to learn more about this topic, It would be helpful . Thanks for the reply

https://www.tutorialspoint.com/cprogramming/c_type_casting.htm

Thanks Mr.Majenko

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


text:
ESP8266 on WiFi without password, possible?
Is it possible to connect to an SSID that does not require a password?
My project using ESP8266-01 modules will sometimes be used in non-password protected guest networks.

yes, just skip the password. it works.

Yes, it works! You can use:
WiFi.begin(ssid, NULL)

or even leave the passphrase empty, because it is optional:
WiFi.begin(ssid)

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


text:
Using a Micro SD card for data logging, bad idea? Reliable?
I'm planning a project that will read data from an I/O board.
The micro SD card would hold data for input bit identity, labeling ?, then logging after events end.
Nothing would be written to or read from the micro sd, unless an event takes place, usually 2-10 events/hour. System will run 24/7 for years, hopefully.
Is a micro sd card the best way?  Is it reliable enough?

We've been maintaining a network of loggers (60+ currently deployed) using SD card connected directly to the SPI pins (see: http://www.mdpi.com/1424-8220/18/2/530 for details) and our experience is that the SD cards are really reliable provided you don't have a brown-out when they are writing, even when we abuse them with hot surface deployments in the tropical sun. And we buy them used, (since the older, smaller Nokia & Sandisk cards have lower sleep currents) but test them well with H2testw.
 However there is one problem that develops over time: the actual SD adapters are not made that well, and tend to have solder flux residue left on the little pads used to hold the contact springs, and these will corrode over time if moisture gets in. I give everything a sonic bath in 90% isopropyl until the parts are squeaky clean, and then always put 2x10gram desiccant packs into the logger housings (with color indicator beads). If you are careful about the cleaning, the contacts last for years, but if you forget, and moisture gets into the housing, then the SD card contact spring solder points are often the first things to corrode.

As far as durability concern, SD cards are quite durable.
8-10 years data storage and operations would be OKAY. In a practical scenario, average time is about to 5-6 years.
Just you have to keep some important and necessary instructions/cautions keep in mind while dealing with SD card and for its long life.
Importantly, use standard standard manufacture SD card (suggestion - Swissbit)

Don't store them below -40 °C or above +70 °C
Don't pressurized

Here are a few links, which may help you.
https://superuser.com/questions/17350/whats-the-life-expectancy-of-an-sd-card
SD cards generally have wear leveling (https://en.wikipedia.org/wiki/Wear_leveling)
Hope, this will helpful.

My concern wasn't so much the age, but read/write frequency and quantity.
And the mean time between failure.  I've read a bit in years past that lots of long-term read/writes are not the best use of SD/Micro SD cards.  I'm hoping the technology has improved.


text:
Connect arduino pro mini 3.3v to 5v
Is it safe to run an arduino pro mini 3.3v by 5v?
I mean directly connect 5v to vcc not raw pin.

Have you examined the schematic yet?

Can you remove the voltage regulator? Just to be sure that it doesn't get reverse voltage.

Yes, an 8 MHz resonator-clocked Promini will happily work at 5V vs 3.3V.
If you want, add a diode from VCC to the RAW pin to protect the regulator, altho it's datasheet does not indicate such is warranted.  Anecdotally, I used about 10 of these in my fencing club powered from 5V to the VCC line for quite a few years with no such protection and they ran fine for ~ 10 years, until we closed the club.

Yes you can.
The only difference between the 3.3 V and 5 V Pro Mini is the crystal and the voltage regulator.


text:
Controlling multiple solenoids with arduino
I was wondering how I could connect multiple 12v solenoids (more than the 53 allowed on mega because of the pins) on the Arduino Mega 2560 to get it to control the keys on a piano/keyboard/organ. Would 74HC595 shift register work for it with the 12v? (Many of them) Because there are so many high voltage solenoids is it possible to control a few of them at a time? I was wondering if someone has a link to somewhere that I could refer to. Thanks

you could also use a 74HCT259 or a PCF8574 to expand the number of pins

Arduino I/O pins, and the output pins of 74HC595 shift registers are logic-level outputs, and are not intended to drive power-hungry items like solenoids. In either case (direct I/O or shift registers) you need to use the logic signal from the output pin to drive something else that switches the 12V source.
That something else can be a MOSFET or a relay, though often even relay coils are themselves driven by a MOSFET or other transistor that is switched by a microcontroller output pin.
One of the many search results that describe this is at http://hades.mech.northwestern.edu/index.php/Driving_using_a_single_MOSFET

Ok thanks for the link and explanation - it'll help with the project!

the shift register has 2 features that will help you:

a latch pin. When a the storage register pin is kept low the outputs won't change this allows you to shift in a new value without perturbing the outputs.
a Qh' output this is the output from the last bit that bypasses the normal output. If you connect that to the next shift register you can daisy chain several registers.

The outputs of the chip are not meant to driver significant currents. Instead use them to drive a mosfet that in turn drives the relay. There are boards that contain all the support circuitry needed to drive relays using low power signals.


text:
Arduino Burn the code programmatically
Is it possible to burn arduino code programmatically?
I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.
Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

You mean like https://create.arduino.cc/editor ?

it should be possible. ... store the new sketch on an external eeprom ... modify the bootloader so that it checks for the existence of the new program and loads it

First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.
Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.
An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/
Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question OTA updates for Arduino using nRF24L01+
MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader
I know there exists another bootloader that does just that, but I can't seem to find it.

Does arduino uno have internal (built-in) EEPROM? If yes, then can we use this internal EEPROM instead of using the external?

Internal EEPROM is only 1kb if I remember correctly. So too small to be of use.

Which EEPROM would you suggest me?

There are only two options. SPI or I2C. The choice depends on which bootloader you use/write. And maybe which other devices you have attached to the Arduino.

The guys at http://phoenard.com/ wrote a bootloader that loads compiled code from the SD card.


text:
Powering 30+ LEDs and flickering one at random
I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.
Is this possible to do using an Arduino? I totally new to this so please bear with me.
This is the type of flicker effect I'm hoping to achieve: https://www.youtube.com/watch?v=753-lkao8l0
Many thanks

Yes, it is. How much money and board space are you willing to throw at it?

@IgnacioVazquez-Abrams Preferably <$100. Space isn't an issue.

Do you mean have 29 LEDs on, and the 30th flicker? Or 29 LEDs off, and one flicker (but only one at a time)?

@NickGammon Thanks for the extremely detailed reply. I mean 29 LEDs on, while the 30th flickers.

OK, that was what my test did. The code I presented had a rather simple flicker effect, but if you worked through an array of on/off times you could probably have quite complex flickering.

Yes, it is possible, but it's harder than making one LED light up, and then doing the other 29 the same.
An LED typically draws 20mA, which is within the limit for an Arduino pin (40mA); however, there is also a 200mA limit for all pins together, so you cannot power more than 10 LEDs off the same arduino. Also, the Arduino only has 13 digital pins, and 5 analog pins, a total of 18 pins. This includes 2 pins used for programming your Arduino.
If you want to run lots of LEDs, the easiest way is running it through an external chip. You can buy a pre-made board e.g. https://www.adafruit.com/products/1429 (24 channel, these can be daisy-chained together for more than 24 LEDs).
Alternatively, you can save yourself some money if you can just buy the chip - a DIP chip, or through-hole, will slot directly into a solderless breadboard, and can be soldered onto veroboard later to make your project more permanent.
There are a number of chips that will do the job, you want an "LED PWM driver" chip - for example, the TLC5940. There is a tutorial for this at http://tronixstuff.com/2013/10/21/tutorial-arduino-tlc5940-led-driver-ic/ - PWM just means you can control the brightness of each LED (individually).
If you want to make your project more permanent, you can solder a board of your own - find someone who can solder (your local makerspace/hackspace will be glad to help, I'm sure!) to teach you the basics, don't burn yourself. The easiest way is to use stripboard (aka Veroboard), this also means you can solder the resistors on to the same board (the LEDs too, if you like!). It sounds very intimidating, but it's not hard to learn. You can then buy PWM chips (make sure you get through-hole, aka "DIP" chips - https://en.wikipedia.org/wiki/Dual_in-line_package ) rather than "surface mount" chips. The chips are sensitive to heat, so to start you might want to solder on sockets (see same wiki page), then you can slot the chips in later.
You should consider very carefully your power supply - find out how many milliamps (or amps) it can provide - every (lit) LED will draw 20 milliAmps, and the Arduino is rated for 200mA, so if you want more than 9 LEDs, you will want an external power source, with an appropriate rating - 500mA = 0.5 amp will drive 24 LEDs. In this case, do NOT use the 2.1mm jack on the Arduino to power it; the transformer will overheat.
P.S. - you will be able to control the exact brightness of each LED independently. Also, if you use RGB leds, and use 3 pins on the IC to drive each LED, then you will be able to control the exact colour of each LED too!
Good luck!

I've successfully set up a flickering test with 32 LEDs, based on Using a 74HC595 output shift register as a port-expander.

Demo of the overall speed (but not the flickering effect): Vimeo - Shift Register Demo with 32 LEDs
That uses 4 x 74HC595, 32 LEDs, and 32 resistors, plus some decoupling capacitors.
Test sketch which does flicker one and leave the rest alone:
#include <SPI.h>
const byte LATCH = 10;
const byte numberOfChips = 4;
byte LEDdata [numberOfChips];  // initial pattern

void refreshLEDs ()
  {
  digitalWrite (LATCH, LOW);
  for (byte i = 0; i < numberOfChips; i++)
    SPI.transfer (LEDdata [i]);
  digitalWrite (LATCH, HIGH);
  } // end of refreshLEDs

void setup ()
{
  SPI.begin ();
}  // end of setup

void showPattern (unsigned long patt)
  {
  LEDdata [0] = patt & 0xFF;
  LEDdata [1] = (patt >> 8) & 0xFF;
  LEDdata [2] = (patt >> 16) & 0xFF;
  LEDdata [3] = (patt >> 24) & 0xFF;
  refreshLEDs ();
  } // end of showPattern

const int whichFlicker = 12;  // which LED to toggle
unsigned long pattern = 0xFFFFFFFF;  // pattern for other LEDs

void loop ()
{
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (100);
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (20);
}  // end of loop

The flickering is quite fast, but it isn't PWM. If you make the delays lower, the flickering just becomes a duller light, so I think by getting the timing right you could get flickering going fine.
The wiring (in part) is:
The rest is similar. Of course, you need current-limiting resistors for the LEDs (one each).
You can get the 595 chips from eBay for around $US 1.70 for 20 of them. LEDs are cheap. Resistors are cheap.

The other answers use other components to achieve more LEDs. Part of an led is its a diode. You can use this property to link 2 LEDs together and use a high or a low signal to light one. This has a limitation that you can't light both at the same time. But with lighting both for 50% of the time with a short time between each cycle will illuminate both of them. ( though obviously not as bright as if they were powered 100% of the time. )
This idea can be extended into a grid to get more LEDs per pin
Though not an ardiuino its the same chip using the technique mentioned here
http://www.nerdkits.com/videos/ledarray2/

Here is an example of a project that simultaneously drives 40 individually controllable LEDs directly connected to an ATTINY...
http://ognite.com
The same technique would also work directly connecting LEDs to the Arduino IO pins.


text:
How to send keyboard signals to two separate computers (arduino due)
The arduino due has 2 micro-usb ports that you can connect to two separate computers. I need to send different keyboard signals to each computer. How would I do this?

possible duplicate of Can the 2nd MCU on the UNO R3 be used for keyboard emulation?

Guess what the other USB connector on the Due is connected to. That's right, a ATmega16U2.

@IgnacioVazquez-Abrams except that is not what he is asking. He's asking "How to send keyboard signals to two separate computers" of which he has a theory that because it has two USB ports, this should be possible. Even if this isn't the case, the other answer doesn't answer his question.

@JakeC: It actually does. The answer is "reprogram the '16U2 to act as a keyboard". Communication between the SAM3X and the '16U2 is left as an exercise for the reader.

@IgnacioVazquez-Abrams But because it doesn't specifically address multiple computers, it doesn't fulfill the criteria of a duplicate question.

While the Arduino Due has two separate USB ports, only one of them is a native port accessible to the processor. The second port is only usable for programming, and is connected to a different and much smaller chip that handles the programming task.
To connect to multiple computers from an Arduino Due, you have two options:

You can reprogram the second MCU to allow it to connect to the computer as a keyboard. This method is tricky because it requires an external programmer for it to work.
You can use a software USB implementation such as V-USB to use regular digital pins to connect to the computer. This is also tricky because it requires a little electronic know how a few extra components to make this work.

Both options require a little something else to make it work, so you will have to pick based on what you feel more comfortable doing.

For one of them, use Keyboard as you normally would.
For the other, do whatever Can the 2nd MCU on the UNO R3 be used for keyboard emulation? tells you to do to reprogram the ATmega16U2 connected to the other USB connector.


text:
Using union to return a range of bits from a data frame: wrong approach?
I'm working on an adaptation of Jason Leyrer's Guitar Hero Library for Arduino.  My version is for a DJ Hero controller, and I've also borrowed some code from this Arduino forum thread: topic=120527 (sorry can't post links yet).
The protocol is i2c and I am successfully reading data from it, however I'm not 100% sure what to do with the data.
The buttons are fine, as they are mapped to just one bit in a given byte.  However the other controls are a combination of 4, 5 and 6 bit longs.
The format according to Wiibrew is like so:

BE is for Euphoria button
CS : Crossfade Slider, lower is left and upper is right
SX and SY are the black analog stick.
ED is the Effect Dial
RTT is the turntable on the right as a 6-bit signed integer (positive = CW; negative = CCW)
RBG,RBR,RBB are the Green, Red and Blue buttons on the right
LTT is the turntable on the left as a 6-bit signed integer (positive = CW; negative = CCW)
LBG,LBR,LBB are the Green, Red and Blue buttons on the left

I'm trying to do this:
 signed long DJ_ED()
{
  pack5 ED;
  ED[0] = (DJ_buf[3] >> 5) & 1;
  ED[1] = (DJ_buf[3] >> 6) & 1;
  ED[2] = (DJ_buf[3] >> 7) & 1;
  ED[3] = (DJ_buf[2] >> 5) & 1;
  ED[4] = (DJ_buf[2] >> 6) & 1;

  return ED;
}

Where pack5 is the following:
#define packet5
union pack5
{
   signed long value;
   int ints[5];
};

but I'm getting the following error:
no match for 'operator[]' (operand types are 'pack5' and 'int')
What am I doing wrong?

Why are you not using a bitwise struct?

@IgnacioVazquez-Abrams tbh I'm not very experienced in C and don't really know what I'm doing!  Is a bitwise struct the same as a bitfield?

You are using a union so you have to specify which part of the union you want. Your function should read:
 signed long DJ_ED()
{
  pack5 ED;
  ED.ints[0] = (DJ_buf[3] >> 5) & 1;
  ED.ints[1] = (DJ_buf[3] >> 6) & 1;
  ED.ints[2] = (DJ_buf[3] >> 7) & 1;
  ED.ints[3] = (DJ_buf[2] >> 5) & 1;
  ED.ints[4] = (DJ_buf[2] >> 6) & 1;

  return ED.value;
}

It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.

The code below seems to match the data structure you posted an image of:
struct packedFields
{
  // byte 0
  unsigned int sx      : 5;
  unsigned int rtt_4_3 : 3;

  // byte 1
  unsigned int sy      : 5;
  unsigned int rtt_2_1 : 3;

  // byte 2
  unsigned int rtt_5   : 1;
  unsigned int cs      : 4;
  unsigned int ed_4_3  : 2;
  unsigned int rtt_0   : 1;

  // byte 3
  unsigned int ltt_4_0  : 5;
  unsigned int ed       : 3;

  // byte 4
  unsigned int ltt_5    : 1;
  unsigned int rbr      : 1;
  unsigned int b_plus   : 1;
  unsigned int filler_2 : 1;
  unsigned int b_minus  : 1;
  unsigned int lbr      : 1;
  unsigned int filler_1 : 2;

  // byte 5
  unsigned int filler_4 : 2;
  unsigned int rbb      : 1;
  unsigned int lbg      : 1;
  unsigned int be       : 1;
  unsigned int rbg      : 1;
  unsigned int filler_3 : 1;
  unsigned int lbb      : 1;

};

union packedFieldsUnion
  {
  packedFields a;
  byte b [6];
  };

void doSomethingWithTheFields (packedFieldsUnion & theFields);  // prototype
void doSomethingWithTheFields (packedFieldsUnion & theFields)
  {
  theFields.a.rtt_4_3 = 3;
  theFields.a.ltt_4_0 = 2;
  }  // end of doSomethingWithTheFields

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("packedFields sized = "));
  Serial.println (sizeof (packedFields));

  packedFieldsUnion foo;
  memset (&foo, 0, sizeof foo);

  doSomethingWithTheFields (foo);

  Serial.println (F("-- packedFields bytes --"));
  for (int i = 0; i < sizeof foo; i++)
    Serial.println ((int) foo.b [i], HEX);

  }  // end of setup

void loop ()
  {
  }  // end of loop

I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.
A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.

If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.

... hit enter too early!  This has saved me at least an evening or two so I greatly appreciate the effort.  I hope you don't mind if I ask a follow-up question... since I'm trying to make this into a library I'm planning on passing foo to my library functions which I've named DJ_funcs.ino.  I'm presuming declaring foo globally here would be a no-no?  Is there a best practise here?

Just pass it by reference. See amended post above, I show an example of doing that.

Hi @nick-gammon, sorry I thought I replied to your above comment! I checked it late at night and ended up practically falling asleep in front of the laptop... your revision was extremely helpful but I'm still having trouble connecting the dots.  I've made a post on the arduino forum; any help I can get is hugely appreciated!


text:
Send information from computer to Arduino via USB (basic clock)
I've created a small project using an Uno. I usually mess around with ESP8266 chips, because they have WiFi and are relatively easy to work with. However, this time I've decided to go right back to the Uno.
I've made a clock using a bunch of MAX7219 matrix displays (32x8 total). I want to be able to sync the time from the computer to the Arduino, no matter which PC is connected.
My thought was to create a small program, that detects the connected Uno, then sends the data over serial. However, there's probably a more clever way to do that, which requires very little programming on the PC side.
Any clues? The Arduino is connected via USB. Would love this to work on both Windows and MacOS.

no, there is no other way

you might find a terminal app that can echo the current time, but it's a one-line program anyway...

in windows, you could write a batch file


text:
ESP8266 NodeMCU first WS2812 LED lights up green
I'm trying to power some WS2812 LEDs from my ESP8266 ESP-12E NodeMCU board (circuit here). I'm simply trying to use the NeoPixel Strandtest which works perfectly on my Arduino UNO with the same LED strip, but when I change the #define pin 6 to #define pin D4 (or 12 as GPIO) only the first LED lights up and it's green. I did throw in a 470 ohm resistor between data and DIN, but that didn't do anything different.
When I use one of the other pins, nothing seems to light up, even if I disconnect all pins and hit reset. Here is my wiring:

Don't mind the actual 3v -> 5v. It works fine with 3v. I have also tried powering it off externally. I have tried all other pins from D0 to D7 (I saw many people say "STAY AWAY FROM PIN D8"). Could my ESP8266 be dead on arrival?

How long is your strip? And have you read and understood the NeoPixel uberguide (https://learn.adafruit.com/adafruit-neopixel-uberguide/overview)?

@Paul 3 pixels long. NeoPixel has nothing to do with this, except I'm using their example code. It works fine on my Arduino UNO so it should work fine on this as well.

Could you hook up the 5V input from the LED strip to USB-POWER pin of the NodeMCU?

@Paul There is no 5v USB-POWER pin. VIN doesn't provide 5v. Even if I hook it up externally to 3.3v or 5v, the LED strip won't work.

Hmm, I have a NodeMCU board that has an 5V usb pin, don't get why they shouldn't break that out, since it's an useful pin.

But, it's either that the strip doesn't get enough power (or the voltage drops after each LED) or the ESP8266's timing being messed up (or some sort).

To debug the voltage, you can try powering with another 5V supply and connect both grounds. You could also try to power it with the Arduino, and control it with the ESP8266 (and combine grounds).

@Paul How come it that all examples I've found online (literally 10+) won't work? I can light up a regular LED simply setting it to HIGH though.

What if you power the strip from behind the first LED?

@Paul From behind the first LED? Meaning what?

I'll write up an answer with my options/thoughts, that'll be easier

@Paul If it's not an answer, don't bother writing an answer. If it's assumptions, don't bother writing it.

The WS2812 parts are very picky with respect to timing.  Any jitter at all will give unexpected results.  We're talking less than a millionth of a second off. This is why you have difficulties controlling WS2812 parts with OS based computers like a Raspberry Pi.  My guess is that a ESP8266 is too preoccupied with controlling the radio to be able to keep to the precise timing necessary to control WS2812 parts.

You should also be aware that the Arduino paradigm (I resist calling it an OS) has not been cleanly ported to every processor / target which claims to be Arduino compatible.  Last month I was having problems controlling simple things like GPIO state on an ARM based Arduino.

@st2000 How come it that everyone else has no issues then?

My suggestion, if nothing else here works, is to use a common / well-known Arduino (like a ProMini) to drive the WS2812 parts and control it from the ESP8266.  Both are small boards and shouldn't mess with the size of your project.  Sorry about so many comments instead of an Answer.  But I am guessing at your problem.  And putting a guess into a StackExchange Answer is looked down upon.

@st2000 I could control my other Arduino from the ESP8266, but that's honestly not going to happen.

@MortenMoulder, really?  Well then, long wires and under powered supplies are my next goto answers (guesses).  After that comes product variation.  Including parts (so do check, as already pointed out, if another board works) as well as software (try to get older or newer versions of the board). w.r.t. power, are you asking for more power from the ESP8266 than it can deliver to the strip?  If you are using a 5 volt supply, try bypassing the ESP8266 and deliver 5 volts to the strip directly from the power supply.  Depending on your strip length, your supply should be of good size (Amps).

@st2000 Power is not the issue. Leave that out of the equation :) My guess goes to faulty board. If none of the examples I have tried (10+ at the moment), my guess is that it's faulty. I see no other explanation. If people with the exact same board can get theirs to work, mine should work as well.

I'll add one more suggestion.  As this is almost the same problem I had when moving from an Uno to an ARM based Trinket.  Make sure your SDK is up to date.  I'm more familiar with how ARM folds into the Arduino SDK.  But I suspect the ESP8266 will also have custom files that have their own versions independent of the SDK to support the differences between it and a classic Arduino.

@st2000 So updating my Arduino IDE? It's set to auto update and it's the newest according to their website. Could the bootloader have something to do with it? I haven't touched that at all.

Let us continue this discussion in chat.

So here comes my solution: I was playing around with NeoPixelBus by Makuna and the examples. I noticed in one of his examples, it said:

// You can also use one of these for Esp8266,
// each having their own restrictions
//
// These two are the same as above as the DMA method is the default
// NOTE: These will ignore the PIN and use GPI03 pin
//NeoPixelBus<NeoGrbFeature, NeoEsp8266Dma800KbpsMethod> strip(PixelCount, PixelPin);

So I tried outcommenting that line and used that instead, and then it worked! I've always used Neo800KbpsMethod whenever I saw NeoPixelBus being used, because that was what other people did. Notice it also said:

These will ignore the PIN and use GPI03 pin

That pin is the RX pin on my board. No other example I have seen, has used the RX pin on the board.
After 6+ hours of constant troubleshooting, I can finally power on my strip and control each LED!

The Adafruit library uses direct port manipulation. It doesn't totally surprise me that trying to run this on another chip doesn't work as expected. I did a small library that uses the SPI hardware for a simple implementation (no assembler). However that also only works on a single pin - the one that supports SPI output on the Atmega328P.

I believe the Adafruit libraries have defines for specific implementations on Arduino and the ESP8266. However, since the timing is so strict, it may just be a little off on your specific board (and just right with the other options enabled). Also mind that ESP8266 pin  numbering isn't the same as the Arduino numbering (and maybe even specific to your board). You may still want to consider using another type of (spi based) ledstrips in the future, since it's easier, less dependable/flimsy, more tweakable and much more cross platform.

Ok i got it working after banging my head for couple of days, i was using a Node MCU Board V3, the pin number on board were D1 D2 D3 D4 etc all other library when data was connected to D4 in code where we specify the pin number we use to write D4.
However for FASTLED codes tbe code you need to write is just 4 without the letter D and when i did the same it just worked like magic

Please read and understand the manual
You say it works on an Arduino, a big difference between the Uno and ESP8266 is the voltage (and voltage regulators).
Another difference is the chip/architecture itself.
So that leads to having to debug these two factors.
Debug the power/circuit/voltage
Please check if the 3V pin of your particular dev board can supply the current for the 3 LED's.
Alternatively you can try by using another 5V power supply, or the 5V from your USB or (Arduino, since that did work) to try and power the LED's.
Another problem may be that the voltage will slowly go down over the length of the strip. Your strip is small, though you also power it from 3V, increasing the effect. You can try to power it on multiple points, or from the middle.
Try using a logic level shifter to increase the logic output pin from 3V to 5V, it may not be sufficient to transmit the data. This usually isn't a problem, but you should exclude this possibility.
The guide also shows some peculiar things regarding the wiring. They say you should use a capacitor between the + and - lines. I don't see how that can fail, but you may as well try.
Also doublecheck the wiring, maybe some connector is a little loose. I've also had problems with LED strips that have been bent, the copper may come loose from the strip, or the strip may get teared a little.
You should also check with another piece of LED strip, just to be sure.
Debug the controller
It works on the Arduino, but not the ESP8266, and we have checked that it's not due to the voltages/power.
The NeoPixels have pretty strict timing, I would actually advise anyone to NOT use them. Since you can't write to the strip "pixel by pixel", you'll have to put the whole strip in memory, and then send it all at once.
Other SPI based LED strips can receive the pixels one by one, like streaming. So you can simply make a loop that sets a color and sends it (while slowly increasing color, to make an virtually infinite rainbow effect). The cool thing is that it even doesn't block interrupts from happening. (Neopixels disable interrupts, need 3 bytes per pixel, and can't do calculations between sending)
If you still want to use NeoPixels, there may be a timing issue. You can check at which clock speed you've set the ESP8266.
Also are you using ESP show with the right "is800KHz" option? espShow(pin, pixels, numBytes, is800KHz);
You may also try another ESP8266 from another manufacturer, to be sure that it's not the board. They may have used a crystal that isn't as accurate as it should be.

I am 1000000% sure the voltage is not the problem. When powering the strip from the ESP8266, but getting the data from my Arduino, it works perfectly. I did specify the 800 KHz when setting up the NeoPixelBus (using NeoPixelBus example, for instance). The problem is this: Everyone who has guides on how to set this up, does nothing but grab an example and change to the correct pin. I did that. I did exactly what they did. I have the exact same pinout as them, so I expect the boards are somewhat similar (same MHz clock, same board type, etc.).

From practice, when your expected results do not manifest .. isolate and go back to basics, test on a known working strip/board, test 3V/5V, read the available options .. as @MortenMoulder mentioned the trick was the  NeoPixelBus lib and the specific RX pin

Ok, I am using WS2812B with nodemcu and Fastled. Now all folks out there reading this need not worry about voltages if your led is not blinking at all. It was not working at D0, it worked for me when I changed to D1, I am not aware of issue though. Need to check that.
I did not use any other component and connected directly to nodemcu.
Below is the simple code for first led to blink.
#define FASTLED_ESP8266_RAW_PIN_ORDER
#include <FastLED.h>
// How many leds in your strip?
#define NUM_LEDS 3

// For led chips like WS2812, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define DATA_PIN D1
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(9600);
    // Uncomment/edit one of the following lines for your leds arrangement.
    // ## Clockless types ##
    FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
    Serial.println("Setup");
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  //digitalWrite(DATA_PIN, HIGH);
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}


text:
Fastest way to send serial commands and do something
I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:
void loop() {
    if(Serial.available()) {
        if(Serial.read().first(8) == "0xABCDEF") {
            //0xABCDEF is basically my indicator saying "this is for individual LEDs"
            //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
            char* colors[] = Serial.read().split(" ");
            colorLED(colors);

        }
    }
}

void colorLED(colors) {
    for(i = 1; i < colors.length; i++) {
        strip.SetPixelColor(i, color[i]);
    }
}

I hope this example makes sense. I can send a serial command like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000. 5 colors in HEX.
My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:
//hexColor can be "FF0000"
int number = (int)strtol(&hexColor[0], NULL, 16);

int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;

Simple answer: don't.
Don't even consider strings in any form. Instead you want a state machine.
In pseudocode:

Start with an invalid count number (-1)
Read a character.
If that character is x then set your counter to 0.
Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
Increment counter
If counter is 6 then set your LED colours and set the counter to "invalid".
Return to start.

Or, in untested C:
static int8_t counter = -1;
static uint8_t r = 0;
static uint8_t g = 0;
static uint8_t b = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == 'x') {
        counter = 0;
    } else {
        if (c > 0x39) c -= 7;
        uint8_t v = c & 0x0f;
        switch (counter) {
            case 0: r = v << 4; break;
            case 1: r |= v;
            case 2: g = v << 4; break;
            case 3: g |= v;
            case 4: b = v << 4; break;
            case 5: b |= v;
        }
        counter++;
        if (counter == 6) {
            counter = -1;
            analogWrite(3, r);
            analogWrite(5, g);
            analogWrite(6, b);
        }
    }
}

The "clever" bit that may confuse you is:
if (c > 0x39) c -= 7;
uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it should be a-f. Subtracting 7 from it converts ASCII HEX from 0123456789ABCDEF to 0123456789:;<=>?.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.
The rest just takes each nibble and places it into the right half of the right colour variable.

Damn, I see that is pretty freaking fast! Immediately when I send the command, it's being sent to the serial monitor (even using Serial.println() which I assume is somewhat "slow"). That works pretty damn well! Thanks a lot for the help!

Sorry for hijacking this, but while I have an experienced person here: I use Makuna's NeoPixel library. This requires me to set my LED strip to the RX on the ESP8266. I currently use the NeoEsp8266Dma800KbpsMethod method, which you can read more about here, and this means Serial.read() will be unavailable (as far as I understand). Do you happen to know if there is an alternative? I did try all the other ones, but unfortunately none of them worked. I think I need to hook it up to another pin, so RX/TX is free (at least RX is)

I don't know what is available for the ESP8266. There is probably a software serial implementation, but I don't like them much, they tend to mess with interrupts and block things from happening. Better would be if you could use some other communication protocol, such as I2C, to get the data in.

I probably could, but it all depends on the NeoPixel library I'm using. Can you skim that page really quick and see if I can use any of the other ones, and if it's only a question of specifying the right pin and using another method/bus (and also hook up the LED strip data pin to that pin).

I actually got it to work with NeoEsp8266Uart800KbpsMethod and GPIO02 (D4). Holy freaking hell it's fast now!

Note that you don't need to break the data into R, G and B, as the Neopixel library has an overloaded setPixelColor(uint16_t pixelIndex, uint32_t color) with the color given as 0x00RRGGBB. The switch can then be replaced by color = (color << 4) | v;

@EdgarBonet Indeed. Another method, if you do want separate RGB values is to shift the nibbles into a union with a 32-bit integer overlay divided into a 4 byte struct.

You could get a 50% reduction in serial data by sending the raw binary values rather than as hex. e.g. for each pixel send 4 binary bytes rather than sending 6 bytes of ascii. Less data sent and less decoding = faster code. Decoding becomes as simple as uint8_t r = Serial.read(); Why 4 bytes rather than 3? Because that way the data lines up nicely if you to use a uint32_t at one end or the other (stick to uint8_t's on 8 or 16 bit MCUs but on an ARM part or if a PC is sending the data then this is worth it) and you can then use the top (unused) byte as a start of data marker.

@Andrew Sending binary data is much more tricky than you are suggesting. A single "start of data" byte, when you're working with 8-bit data, is not practical - how do you distinguish it from data? Instead you would need proper packets with data escaping and such - and for such a small amount of data you would end up with a packet only fractionally smaller than (if not bigger than) the 7 bytes of ASCII representation.

@Majenko Sorry, I wasn't clear, I didn't mean an 8 bit start marker, I meant a 32 bit message where that byte was also set could act as a start marker. e.g. 0x01010101. If you look for 4 or more non-zero bytes in a row then you know that the next 0 byte will always be the first (always 0) byte of color data.

@Andrew And if you don't have 4 or more non-zero bytes in a row? Synchronisation is not possible with just one byte when that byte may appear in the data. You need at least 2 bytes for the synchronisation in a specific pattern. Then you need an "escape" byte in the data stream to prevent that pattern from ever appearing in the data, and of course escaping of that escape byte to prevent it being interpreted as an escape byte. Take a look at some existing binary protocols, such as telnet's IAC system, for examples.

@Majenko "Synchronisation is not possible with just one byte when that byte may appear in the data. You need at least 2 bytes for the synchronisation in a specific pattern." Correct. Hence the 32 bit start marker where none of the values are 0. If you don't have 4 non-zeros in a row the you have connected in the middle of a message and must wait for the next start marker, exactly the same as with ascii.

@Andrew Ah, right, got you now. So you would want to re-synchronise periodically to make sure no bytes have been lost - so efficiency depends on how often you want / need to re-sync. You wouldn't want to leave it too long between syncs in case you missed the very first one, and an initial sync never happened. You'd then discard a large number of packets until the next sync - so getting the balance right would be important. Adds a lot of complexity to think about to save a couple of bytes per packet.

@Majenko He's talking about an LED strip with different colours per LED so presumably WS2812 parts. It would be logical to resync at the start of each refresh, exactly how he was doing it in the initial question using ASCII but missing from your solution.

@Andrew Ah, so make the whole stop worth a packet, with a header of, say, 0x5555AAAA. That would work for this specific instance.

Since Majenko is convinced that using binary is far too complicated here's how to do it in binary sending 32 bits per color.
The start of strip marker is any 4 non-zero bytes in a row e.g 0x01010101
Each LED is then sent as four binary bytes: 0x00, 0xRR, 0xGG, 0xBB
In the unlikely event that a byte is lost in transmission then it will re-sync at the start of the next update, depending upon the pattern there is a fair chance that lost data will be noticed and the incorrect colors not get displayed on the strip.
loop() {
  static color_t color;
  static int8_t counter = -1;
  static int ledIndex = 0;
  static bool aligned= false;

  if (Serial.available()) {
    if (aligned) {
    switch (counter) {
      case 0: color.r=Serial.read(); break;
      case 1: color.g=Serial.read(); break;
      case 2: color.b=Serial.read();
              strip.SetPixelColor(ledIndex, color);
              ledIndex++;
              break;
      case 3: // first byte of next data, should always be 0
              // only not 0 if we've lost a byte or want to restart the strip
              if (Serial.read() != 0) {
                aligned=false;
                counter = 0;
              } else
                counter = -1;
              break;
      default: break;
    }
    counter++;
  } else { // not aligned
    ledIndex = 0;
    if (Serial.read() != 0) // count non-zeros
      counter++;
    else {
      if (counter >= 4)     // had a start marker, next byte is r
        aligned = true;
      counter = 0;
    }
  }
}

Is it worth doing it in binary? It gives a 50% decrease in RS232 data which if serial data rate is an issue will be a big help. It also gives a decrease in required calculations, if you look at the code there are virtually no mathematical operations beyond increasing counters.
Personally I prefer this method because it just seems more efficient and cleaner to transfer numbers as numbers rather than converting them to text and back but ultimately if you don't need every last bit of performance then it comes down to what you feel most comfortable with.

So far what I have counted using a high FPS camera, I can easily track 20+ updates a second using Majenko's code. I think that's very, very good considering I won't ever need to do that.

I would hope so, twenty updates a second isn't that fast unless you have a very long chain of LEDs. If you code it right the RS 232 should be the slowest part of the system and you should easily be able to get 20 FPS on chains of several hundred LEDs. As I indicated, binary gives you that little bit more if you need it, if you don't need it then it's simply an alternative approach.