text:
ESP8266 as WiFi for Arduino
I have a pretty simple project, where some data has to be read from a mySQL server. My idea is to do this with an ESP8266, and then provide that data to the Arduino Mega.
Is this possible or am I going to have to use the ESP8266 itself? I highly doubt that I would have enough pins then.
I read something about AT-commands. But I have no idea how to send those commands to the ESP.
Thanks in advance,
Michidez

Yes its possible, you can use the ESP8266 as a dumb Wifi to Serial convertor.  Set you Arduino IDE up so you can program the ESP8266 like an Arduino, and then write a simple program to connect to the WIFI network and read the data from the server, then just print it to the default serial console with a special sequence of characters at the beginning of each line, like 'DATA'.
Connect the serial port on the ESP8266 to the Mega, don't forget top cross the RX and TX wires and then write a program on the mega that reads from the serial port you have allocated and only process lines beginning with the special sequence of characters.
Yes you could use the AT commands, but that involves a fair amount of learning. pain and different software, when you already probably have the knowledge that you need.
Some of the later version of the ESP8226 can run at 160MHz and have 1MByte or memory so you might want to hand off some of the data crunching to the ESP.  (But that's a decision for later, once its working).
Hope that helps.

Check out ESP-LINK You can find it here
ESP-LINK is a esp8266 wifi-serial bridge, outbound TCP, and arduino/AVR/LPC/NXP programmer. It has several configuration, one of them allowes uploading new firware ower wifi, or to act as a serial link just like if usb cable is pluged in and serialport viewer is active. The website has great documentation and has one of the slickest configuration interfaces seen on ESP.

Could you expand out your answer a bit please? Perhaps a brief description of what we find if we visit the link (I've already done that).  Plus describe the gist of what it is about. Stack Exchange frowns on link-only answers. If the link ever goes down the answer becomes useless.

Updated the answer with more info


text:
Error on Arduino Code (unknown type name 'LiquidCrystal')
I am using Arduino IDE 1.6.8 and I am trying to compile the following code Wheatstone Bridge. I have currently a really weird error:
unknown type name 'LiquidCrystal'

This error seems to come from the header file:
// Include the Wheatstone library
#include <WheatstoneBridge.h>

// Include the LCD library
#include <LiquidCrystal.h>

// Declare external global lcd
extern LiquidCrystal lcd; <<<Error

I have already installed the LiquidCrystal library but I don't know if this trouble is due to the compiler (and the IDE) or something is wrong. The compiler seems to find the right libraries...

"I have already installed the LiquidCrystal library" ... It already comes with the IDE, so what exactly did you install?

@IgnacioVazquez-Abrams  You are right. I don't install it. This library is installed with the IDE and the compiler find it well.

Using "extern" when instantiating a class is unusual.  We can not tell what your intentions are because this is only part of your code.  However it would be my guess that this code:
// Declare external global lcd
extern LiquidCrystal lcd;

Should actually be written like this:
// Declare external global lcd
LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins!  Comments from the HelloWorld example to help you out:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

Background:
Arduino sketches are written mostly in C while the libraries take advantage of C++.  As such the libraries can use a C++ feature called "overloading".  This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed.  The LiquidCrystal class has defined all these possibilities:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

But in none are there no parameters.  That is why the compiler could not find the class in your code.  You needed to match one of the above class types.

Removing extern change nothing. Obtain the same error unknown type name 'LiquidCrystal'.

In the Arduino IDE: 1) Click on Sketch -> Import Library, do you see the LiquidCrystal library? 2) Double check the spelling in your code, I've been tripped up by this more than once. 3) Try compiling the HelloWorld example in the LiquidCrystal library example directory.

no trouble when compiling the HelloWorld example of LiquidCrystal library

Hang on, I think I need to edit my comment to pass values to the constructor.

Finally this error is not the right. When I read the compilation log I have found an other error. In fact Arduino IDE try to compile using gcc and not g++ due to the fact the example folder contains one .c file. Changing the extension to .cpp solves the problem.

Please verify the code you posed in the question compiles unaltered.

The code I have proposed in the initial question doesn't work (the github repository is not mine). But if you change the extension, it will compile.

Download the Liquidcrystal.zip file from this link,
Crystal link
Now add that file into documents/Arduino/libraries folder.
Now check if the library is added in the library.
It should probably work.

Thank for your proposal but I have the same error with this library.

Have read your solution, at the end of discussion. I was having similar issues, saying "IDE try to compile using gcc and not g++". Close this problem

source: Stack Exchange

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

sort: votes


text:
AVR has no vprintf_P?
Well this was unexpected. AVR libc has many the variants of printf, including vprintf, but is missing vprintf_P. Is this really just not present or implemented elsewhere?

It has vfprintf_P and stdout is a FILE. Why would you want to waste time and space with implementing vprintf_P as well?
If you really want it, you can make your own:
#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to vprintf looks like this:
int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.
It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to inline that function, which since it is in a library it likely won't).
The non-FILE based functions can be considered simple wrapper functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since _P is specific to AVR libc there is nothing historical for it to be compatible with.

That wouldn't be a good explanation for why it does have printf, sprintf, snprintf, vsprintf, vsnprintf, fprintf, vfprintf and all of their _P variants, would it?

It would be just idiotic to miss out printf. All the others either take a file or string as their target, which means they are the base ones. All other functions can be made from them. You don't like it? Then submit a patch to the repository and stop complaining.

Wow. Fair question met with an obnoxious attitude. Okay, I'm going to go waste everyone's time and space with the patch!

I was going to say the same thing - fair answer met with an obnoxious attitude. You ask a question, get the answer, but don't like that answer because it doesn't agree with the answer you have already formulated inside your head, so start with the 'tude.

I asked yes/no question. I would've accepted the answer "no, it's not implemented". I didn't ask for your opinion on whether the function is a waste of time and space, did I? It's also a laughable answer in itself since you yourself illustrated that it's a trivial one-liner. That's okay. This is all public. Let others judge.

So you don't think it's even slightly valuable that, since as you say this is public, other people might not want to know why it might not have been implemented, and how to implement it themselves should they want to? Maybe you should have privately emailed one of the developers of libc instead.

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


text:
What programmer do I select in Arduino IDE for the ATMEL-ICE ISP?
I have been using an AVRISPmkII for many years but recently gave mine away to another hobbiest. I wnated to buy a replacement and have had to buy an ATMEL-ICE ISP as the AVRISPmkII is now unavailable.
Occasionally, I like to program the Arduino Uno from the Arduino IDE using the ISP.
However when I go to select the programmer (from the tools menu), I don't see the ATMEL-ICE in the list.
How do I get Arduino IDE to recognize the ATMEL-ICE ISP?
Note: I am using Arduino IDE v1.6.8.

Is the AVRISP MKii unreliable because the 6-pin cable is worn out? I made a new one for mine with a new piece of ribbon cable and two header connectors. Might be able to reuse the same cable even, just cut it a little shorter at both ends. I think mine wore out at the plastic case end.  https://www.digikey.com/product-detail/en/amphenol-icc-fci/71600-006LF/609-2841-ND/1302571

@CrossRoads Thanks for the information. I often give my programmers away (in a bundle of other Arduino bits and pieces) in an attempt to inspire more people to take up coding.

Atmel is no longer selling the AVRISP MKii. I'm holding onto mine! Still works great after changing the ribbon cable out.  Not too hard too split the case to unplug and plug a new one on.

@CrossRoads I am glad to hear that yours is working great, however, this is not the problem I am having.

As of V1.8.2, the ATMEL-ICE is now included as a programmer in the Arduino IDE.
The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was released as a version on the 22nd of March 2017.

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


text:
Three phase sine wave inverter using Arduino
I want to design three phase sine wave inverter using Arduino I found this link with circuit diagram and simulation results but he did not provide code. can anyone help me with code http://microcontrollerslab.com/three-phase-sine-wave-inverter/

The author explains the design of the code in http://microcontrollerslab.com/spwm-generation-using-pic16f877a-microcontroller/

It's a pretty cool article-Bilal Malik varies the duty cycle of a 20kHz PWM with a look-up table to produce 50 PWM cycles of a rising quarter-sine-wave, 50 cycles back down, then switches the polarity and does it again, using it to drive an H-bridge feeding a transformer.

This guy is doing the same. His code is free of charge. http://www.eprojectszone.com/how-to-generate-three-phase-spwm-signal-with-arduino/

At the end of the page you are linking to, there is this notice:
"Code for three phase inverter is not free of cost. If you want to purchase code, you can contact me at bilalmalikuet@gmail.com"
If you are Bilal Malik, you should already have the code since you are offering to sell it - unless you want someone here to write it for free so you can sell it afterward.
If you are NOT Bilal Malik, you should not impersonate someone else here.
I am not a huge fan of the concept of intellectual property, but it seems you are trying to do something shady here.

It is a Roger Finer who asked the question. Why do you think he could be Bilal Malik?

@PimV: When you change your name in your stackexchange account, all your previous posts suddenly show your new name. So it is possible for a question to be asked by "a", and then show it was asked by "b".


text:
How to use the timer to generate a pulse wave of the specified frequency and duty cycle
So we have the tone library, which produces a 50% duty cycle square wave of varying frequency, and analogWrite() which produces a fixed frequency wave of varying duty cycle. Is there any way to control frequency and duty cycle at the same time on an Atmega328-based board?

I don't know of any ready-made library for that, but you can always configure the timer yourself. Read the datasheet and use one of the so called “CTC” (Clear Timer on Compare Match) modes. Avoid using Timer 0 unless you don't care about loosing the Arduino timing functions (millis(), micros(), delay() and delayMicroseconds()).

Also, another related question: will using setPwmFrequency() disrupt the operation of micros() and delayMicroseconds()? The sample code at the arduino playground only says it will stop millis() and delay() from working.

If you change the Timer 0 prescaler with setPwmFrequency(), then yes, you will also disrupt micros() and delayMicroseconds(). But this gives you a limited choice between only a few frequencies. If you want a specific frequency, you should better configure the timer yourself, based on the datasheet.


text:
I'm having some undefined references and can't figure out why
Try verifying the code to see the errors.  This is on a arduino nano with a 328 processor.  I put the necessary library in the code.
Pastebin for code
 #ifndef Pushbutton_h
#define Pushbutton_h

#include <Arduino.h>

#define PULL_UP_DISABLED    0
#define PULL_UP_ENABLED     1

#define DEFAULT_STATE_LOW   0
#define DEFAULT_STATE_HIGH  1

/*! \brief The pin used for the button on the
 * [Zumo Shield for Arduino](http://www.pololu.com/product/2504).
 *
 * This does not really belong here in this general pushbutton library and will
 * probably be removed in the future. */
#define ZUMO_BUTTON 12

class PushbuttonStateMachine
{
public:
  PushbuttonStateMachine();
  bool getSingleDebouncedRisingEdge(bool value);
private:
  uint8_t state;
  uint16_t prevTimeMillis;
};

class PushbuttonBase
{
public:

  PushbuttonBase();

  // wait for button to be pressed, released, or pressed and released
  void waitForPress();
  void waitForRelease();
  void waitForButton();

  // more complex functions that return true once for each button transition
  // from released to pressed or pressed to released
  bool getSingleDebouncedPress();
  bool getSingleDebouncedRelease();

  // indicates whether button is currently pressed
  bool isPressed();

  // Initializes I/O pin for use as button input.
  // This gets called automatically so normally you will not need to call this,
  // but it might be useful if the pin for the button is in the wrong state.
  virtual void init2() = 0;

protected:

  virtual bool _isPressed() = 0;

private:

  PushbuttonStateMachine pressState;
  PushbuttonStateMachine releaseState;
  bool initialized;

  // TODO: move all this init stuff down into Pushbutton
  inline void init()
  {
    if (!initialized)
    {
      initialized = true;
      init2();
    }
  }
};

/* \class Pushbutton Pushbutton.h
 * \brief Interface with pushbuttons on dedicated pins.
 *
 */
class Pushbutton : public PushbuttonBase
{
public:

  // constructor; takes arguments specifying whether to enable internal pull-up
  // and the default state of the pin that the button is connected to
  Pushbutton(uint8_t pin, uint8_t pullUp = PULL_UP_ENABLED,
      uint8_t defaultState = DEFAULT_STATE_HIGH);

  virtual void init2();

protected:

  virtual bool _isPressed();

private:

   uint8_t _pin;
   bool _pullUp;
   bool _defaultState;
 };

 #endif

// PIN Configurations #define SEARCH_SPEED 255

#define echoPin A0
#define triggerPin 3
#define rightBackMotor 4
#define rightMotorSpeed 10
#define leftMotorSpeed 9
#define leftForwardMotor 7  //if a motor goes backward swap the number on the FwdPin and BckPin
#define rightForwardMotor 8   //if a motor goes backward swap the number on the FwdPin and BckPin
#define leftBackMotor 11
#define LED 13
#define leftSensor A1
#define rightSensor A2
#define IRdriver 6

// Robot Configuration Parameters
// Speed range is -255 -> 255
#define MAX_SPEED 255
#define QTR_Threshold 500
#define ATTACK_DISTANCE 25
#define BACKUP_DISTANCE 4000
#define SEARCH_SPEED 255

// State variables
bool isBackup = false;
int backupTimer = 0;
long distance = 1000;
Pushbutton button(ZUMO_BUTTON);

void setSpeed(int speed, int motor);

void setup() {
   Serial.begin(9600);
   Serial.println("Setup.");

  pinSetup();

   Serial.println("Waiting for button");
}

void loop() {
   digitalWrite(IRdriver, HIGH);

  if (button.isPressed()) {
    // if button is pressed, stop and wait for another press to go again
    button.waitForRelease();
    waitForButtonAndCountDown();
 }

  int leftInput = analogRead(leftSensor);
  int rightInput = analogRead(rightSensor);

  if ( isBackup ) {
    backupTimer = backupTimer + 1;
    setSpeed(-MAX_SPEED, 0);
    setSpeed(-MAX_SPEED + 20, 1);
    if (backupTimer >= BACKUP_DISTANCE ) {
      isBackup = false;
      backupTimer = 0;
    }
  } else {
    if ( leftInput <= 500 || rightInput <= 500 ) { // WHITE LINE ABORT!
      //Serial.println("Abort! - "); Serial.println(leftInput); Serial.println(rightInput);
      isBackup = true;
      setSpeed(-MAX_SPEED, 0);
      setSpeed(-MAX_SPEED, 1);
    } else {
      distance = getDistance();
      if ( distance <= ATTACK_DISTANCE ) { // ATTACK!
        Serial.println("Attack!");
        setSpeed(MAX_SPEED, 0);
        setSpeed(MAX_SPEED, 1);
      } else { // search
        // TODO(erh): implement other searching algorithms
        Serial.println("Search");
        setSpeed(SEARCH_SPEED, 0);
        setSpeed(-SEARCH_SPEED, 1);
      }
    }
  }
}

void pinSetup() {
  // motors!
  pinMode(leftMotorSpeed, OUTPUT);
  pinMode(rightMotorSpeed, OUTPUT);
  pinMode(leftForwardMotor, OUTPUT);
  pinMode(leftBackMotor, OUTPUT);
  pinMode(rightForwardMotor, OUTPUT);
  pinMode(rightBackMotor, OUTPUT);

   // sonar sensor
  pinMode(LED, HIGH);
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // qtr light sensor
  pinMode(leftSensor, INPUT);
  pinMode(rightSensor, INPUT);
  pinMode(IRdriver, OUTPUT);
}

void setSpeed(int speed, int motor = 0) {
  int speedPin, forwardPin, backPin;
  if ( motor == 0 ) {
    speedPin = leftMotorSpeed;
    forwardPin = leftForwardMotor;
    backPin = leftBackMotor;
  } else if ( motor == 1 ) {
    speedPin = rightMotorSpeed;
    forwardPin = rightForwardMotor;
    backPin = rightBackMotor;
  }

  if ( speed == 0 ) {
    analogWrite(speedPin, 0);
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, LOW);
  } else if ( speed > 0 ) {
    digitalWrite(forwardPin, HIGH);
    digitalWrite(backPin, LOW);
    analogWrite(speedPin, speed);
  } else if ( speed < 0 ) {
    digitalWrite(forwardPin, LOW);
    digitalWrite(backPin, HIGH);
    analogWrite(speedPin, abs(speed));
  }
}

long getDistance() {
  long duration, distance;
  digitalWrite(triggerPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  return distance;
}

void waitForButtonAndCountDown() {
  digitalWrite(LED, HIGH);
  button.waitForButton();
  digitalWrite(LED, LOW);

  for (int i = 0; i < 3; i++ ) {
    Serial.println(i);
    delay(1000);
  }

  delay(1000);
  Serial.println("ATTACK!");
  delay(1000);
}

Could you put the error (and code) in this question?

Your code contains only the header declarations (.h file) for those classes. There should also be another file (probably .cpp) that actually implements the code for the classes.
What you pasted looks very similar to the Pushbutton stuff in this project on GitHub.
You can look at their Pushbutton.h and Pushbutton.cpp files to get an idea of what I mean. In fact, you might be able to use those files instead of what you have. I can verify that it does compile, but not whether it works or not.

It is the github stuff but I'm new to arduino. Can I take the .cpp file and copy paste the code in because I'm using school computers without much control.

Ideally you would download the files (e.g. with the "Raw" link when viewing the files) and use them as a library. But yes I think it should also work if you just copy/paste the contents into your project. Just make sure the .h code is above the .cpp code. I had done that and it compiled okay.

Could you possibly upload your code because I tried to copy paste but I keep getting previous definition of 'class PushbuttonStateMachine'

I don't have any code saved. I just copied your Pastebin code, deleted the old header stuff (everything between #ifndef Pushbutton_h and #endif) and pasted in those other two files instead.

The error Undefined reference is a linker error, which means that the Arduino ecosystem is missing some of the pieces for the build. If you have indeed provided PushButton.cpp - whether in a library or not - you need to put a #include of Pushbutton.h inside the .ino file. This tells Arduino that you want to include PushButton's code as well as everything else.
If Pushbutton.cpp is inside the same directory as the .ino file then that will "just work". If it's elsewhere, you need to tell Arduino.


text:
ESP8266 Arduino 2.2inch ILI9341 TFT library
I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.
This is the one.TFT LCD
I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino.
(https://github.com/esp8266/Arduino)
I made the following connection :
SCK #14, MOSI #13, MISO #12 and CS #4, DC #5,RESET #0
and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds.
In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .
In my existing project, I used the following code to just show some messages :
Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.
I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.
I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.
Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.
Thanks in advance. !!!

You did not include any output from the esp8266, but I'm pretty sure what is happening is that the watchdog timer is expiring and resetting your board. This is because the SPI transactions to transfer data to the display are taking too long.
Put the following line in both setup() and loop() before any display operations happen:
wdt_disable();
Needless to say, if you actually do need the WDT in your application, you can reenable it after the display operations complete (of course, if you are doing something that depends on the wdt, you already know this!)
Look at the source for the Adafruit library, make sure there are #ifdef ESP8266 statements there; older versions did not support the 8266.
You may also want to increase the default speed at which the library drives the SPI bus from 8000000. I've gotten it to work at up to 40MHz, with the board flashed at 160MHz of course, and it's a lot faster (unsurprisingly), but if you have long wires or a marginal-quality display, that may fail.
Post pictures :)

Thanks a lot for the suggestions .Its too early in the morning here to check what you have mentioned .I will check the following once later today and will post the results :) I hope with your help I can sort it out and too much thankful for such lengthy explanation and details about the whole issue. I expect you to help me further in case it doesn't sort out the issue .

Thanks for the detailed explanation .I tried putting the wdt_disable() void showmessage(String message) {   wdt_disable();   tft.fillScreen(ILI9341_BLACK);   tft.setCursor(0, 0);   tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);   tft.println(message); }  but it doesn't work .it still continues to reset

What do you see on the serial port output? (If you are not using the serial port in your code, just put Serial.begin(115200) or some such, as the debugging output defaults to 74300bps or some weird number like that which most terminal emulators, including the arduino ide serial monitor, do not support.

I made it work as you mentioned .disabled the watchdog timer before writing to LCD and then once that is done called the enable with a time value of 10 and now it works without any exception . But still I feel the speed is bit slow for esp8266 .You said about 40Mhz . Is that done using the spin set frequency method and then flashing at 160 ? anyway thanks for fixing my issue :)

I'm glad you got it to work. The 40MHz is the SPI bus speed, which you set in the spi settings, for example here: https://github.com/adafruit/Adafruit_ILI9341/blob/master/Adafruit_ILI9341.cpp#L39
You also appear to be using the software (bit-banged) SPI code; use the constructor that does not specify the miso/mosi/sclk pins, and use the hardware spi pins on the 8266 (mosi: 13, sclk: 14, cs: 16, miso: 12 (unused for the display, but if you have the card that also has a touch screen, you need that. With a different chip select, of course!)

Thanks again and the hardware SPI is fast now. But I would like to know one more thing from you whether the adafruit library for the esp8266 supports any kind of scrolling by default or there is any other library which supports that ?


text:
Using a button to cycle an array
So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.
Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?
//------------------------------------------------------------------------------------------------
// Displays information when a push button is pressed. Also turns on and off a corresponding led.
// 5/3/2016
//------------------------------------------------------------------------------------------------

// declare variables

char* titles[] = {
  "RELATION",
  "FIRST NAME",
  "LAST NAME",
  "LOCATION",
  "PHONE NUMBER"
};
char* user_info[] = {
  "SELF",
  "JOHN",
  "SMITH",
  "FLORIDA",
  "999-888-6666"
};
char* econ_one[] = {
  "BROTHER",
  "MICHAEL",
  "SMITH",
  "FLORIDA",
  "999-888-5555"
};
char* econ_two[] = {
  "WIFE",
  "EMILY",
  "SMITH",
  "FLORIDA",
  "999-888-4444"
};
char* econ_three[] = {
  "SISTER",
  "SOPHIA",
  "ADAMS",
  "NEW YORK",
  "888-777-3333"
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;
// setup - set pins

void setup() {
  Serial.begin(9600);
  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.println("Emergency Contact");
}

// main
void loop() {
  if (digitalRead(buttonPin)) {
    if (state == 0) {
      int x;
      for (x = 0; x <= 4; x++) {
        Serial.println(" ");
        Serial.print(titles[x]);
        Serial.print(" ");
        Serial.print(user_info[x]);
      }
      Serial.println(" ");
      setLights(HIGH, LOW, LOW, LOW);
      state = 1;
    } else if (state == 1) {
      int y;
      for (y = 0; y <= 4; y++) {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econ_one[y]);
      }
      Serial.println(" ");
      setLights(LOW, HIGH, LOW, LOW);
      state = 2;
    } else if (state == 2) {
      int z;
      for (z = 0; z <= 4; z++) {
        Serial.println(" ");
        Serial.print(titles[z]);
        Serial.print(" ");
        Serial.print(econ_two[z]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, HIGH, LOW);
      state = 3;
    } else if (state == 3) {
      int q;
      for (q = 0; q <= 4; q++) {
        Serial.println(" ");
        Serial.print(titles[q]);
        Serial.print(" ");
        Serial.print(econ_three[q]);
      }
      Serial.println(" ");
      setLights(LOW, LOW, LOW, HIGH);
      state = 0;
    }
    delay(1000);
  }
}

// function to turn LEDs on/off

void setLights(int one, int two, int three, int four) {
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

output image
https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU_X0bl04KXFAQyja

The question is how do you want to cycle through the array? Also its Ctrl+T in the IDE to format the code.

Since the question is pretty old and it has some answers, if some of them fits your needs please accept it; otherwise the question will periodically show up in the homepage making possible answerer's lose a lot of time for matters you don't care anymore...

I would recommend using multidemnsional arrays for both your contacts and your light states.
//------------------------------------------------ declare variables

char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

char* econs[][5] = {
  {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
  {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
  {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
  {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
};

uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
  {LOW, HIGH, LOW, LOW},
  {LOW, LOW, HIGH, LOW},
  {LOW, LOW, LOW, HIGH},
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;

//------------------------------------------------ setup - set pins
void setup() {
  Serial.begin(9600);

  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);

  Serial.println("Emergency Contact");
}

//------------------------------------------------ main
void loop() {

  if (digitalRead(buttonPin))
  {
    if (state > 3)
      state = 0;

    {
      for (int y = 0; y <= 4; y++)
      {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econs[state][y]);
      }

      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
    }

    delay(1000);
    state++;

  }

}

//------------------------------------------------ function to turn LEDs on/off

void setLights(int one, int two, int three, int four)
{
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

I haven't tested the above, but it should provide the same result.
As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.

The multidimensional array is a good idea. I haven't used one before. The code you provided cycles through the array entirely with one button push. I was trying to see if I could cycle through the elements one at a time with each button press. I might try a switch-case. Thank you again for your help I really appreciate it.

I guess i misunderstood yohrnask. You could accomplish what you want to do with a counter, but stil, store the data as shown above. Instead of having the nested for loops (for x, for y), you could replace the for x with a counter that increments with each button press until it reaches 4, the cycles back to zero. It would be a simple change to the code above. When I get a chance, I can show you how to change it.

I updated the code in the answer above to cycle through the contacts with each button push.

@Prdufresne if you keep the button pressed it will cycle through all the values; moreover if you press it twice within 1 second it will not cycle twice. I'd use the bounce library to detect just the rising edge and avoid that delay; for more info see my answer

@frarugi87, I think you're right on the point of debounce. I was focused on giving him a cleaner way to cycle the records.

As for your question, your way is (kind of) the best way.
I just saw a problem: when you keep the button pressed you will go on showing. Moreover I really don't like the delay at the end, and if its purpose is just to avoid bounces, well, use the Bounce2 class.
As for the repeated ifs, I prefer a switch-case statement.
I highly suggest you to use the Bounce2 class, though. Here is an example of its usage:
Bounce debouncer = Bounce();

void setup()
{
    ...
    pinMode(buttonPin, INPUT);
    debouncer.attach(buttonPin);
    debouncer.interval(5); // interval in ms
}

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        switch (state)
        {
        case 0:
            {
                int x;
                for (x=0; x <= 4; x++)
                {
                    Serial.println(" ");
                    Serial.print(titles[x]);
                    Serial.print(" ");
                    Serial.print(user_info[x]);
                }
                Serial.println(" ");
                setLights(HIGH, LOW, LOW, LOW);
                state = 1;
            }
            break;
        case 1:
        ...
        }
    }
}

As you can see the class has a rose member, which tells you if the button was just pressed (only on the rising edge).
Now, your particular problem can be solved in another way. Since you are repeating the same code for all the cases, you can cycle through two arrays; one stating which is the second array you need to use, the other the lights.
This is an example. Please note that I haven't tested it, so there might be some errors
char ** second_array[] = { user_info, econ_one, econ_two, econ_three }
uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
                        {LOW, HIGH, LOW, LOW},
                        {LOW, LOW, HIGH, LOW},
                        {LOW, LOW, LOW, HIGH},
                    }

void loop()
{
    debouncer.update();
    if (debouncer.rose())
    {
        int x;
        for (x=0; x <= 4; x++)
        {
            Serial.println(" ");
            Serial.print(titles[x]);
            Serial.print(" ");
            Serial.print(second_array[state][x]);
        }
        Serial.println(" ");
        setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
        state++;
        if (state >= 4)
            state = 0;
    }
}

Try to use it and then report back if there is some issue ;)

thank you very much, I will look at this this evening after work.


text:
Working on a reaction test for the Arduino Uno using an led and an lcd shield
The situation involves some Asm inline practice and a basic circuit. The program turns an LED on after a somewhat random period of time then waits until the button is pressed to report back how many milliseconds it took. This is then printed by the LCD shield. My confusion occurs because after each reset it prints a 1 before the button is pressed, which overlaps returned millisecond value on the screen giving me some false data. I tried to cut the code down so if there is anything else that might be helpful let me know. I think the issue may be in the test reaction time function but am not sure.
/* --------------------------------------------------------------------------------------
  Includes
--------------------------------------------------------------------------------------*/
#include <LiquidCrystal.h>   // include LCD library

/*--------------------------------------------------------------------------------------
  Init the LCD library with the LCD pins to be used
--------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
  setup()
  Called by the Arduino framework once, before the main loop begins
--------------------------------------------------------------------------------------*/

void setup()
{
   //button adc input
   pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
   digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
   //lcd backlight control
   digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is high (on)
   pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
   pinMode(3,OUTPUT);                         //d4 is are LED
   //set up the LCD number of columns and rows:
   lcd.begin( 16, 2 );
   //Print some initial text to the LCD.
   lcd.setCursor( 0, 0 );   //top left
   //          1234567890123456
   lcd.print( "LinkSprite  16x2" );
   //
   lcd.setCursor( 0, 1 );   //bottom left
   //          1234567890123456
  // lcd.print( "Btn:" );

    Serial.begin(9600);

 pinMode(2, INPUT);

 }
/*--------------------------------------------------------------------------------------
  loop()
  Arduino main loop
--------------------------------------------------------------------------------------*/
void loop()
{

      //read the button
     byte result;//  = digitalRead(2);
      asm volatile(
          "ldi %0, 0 \n\t"
          "sbic 0x09, 2 \n\t"
          "ldi %0,1 \n\t"
          "nop \n\t"
          :"=r" (result)
          :
          :
      );
      int t =(random(0, 10000)+1000);
      unsigned long currentM = millis();
      //int t =(random(0, 10000)+1000 +millis());
      while( t < currentM){
      int x = testReactionTime();
       lcd.setCursor( 0, 1 );
     //if (result){
         lcd.print( "on " );
         lcd.setCursor(7,1);
         lcd.print(" ");
         //int x = testReactionTime();
         lcd.print(x,DEC);
         //delay(1000);
         //lcd.print("     ");
      //}else{
        //testReactionTime();
        // delay(random(0, 1000)+1000);
        //lcd.print( x,DEC );
        //digitalWrite(3, LOW);
      }
//}
}

/*
 *  after a random delay call this function to measure their reaction
 *  time in milliseconds
 *  It will immediately turn on a LED (pin 3)
 *  And then start timing the milliseconds until they hit the button (pin 2)
 *
 */
int testReactionTime()
{
  int answer;
  //delay(rand());
  asm volatile(
    "ldi %A0, 0 \n\t"  // initializw anwer to 0
    "ldi %B0, 0 \n\t"  // answer should be the number of ms until they hit the button
    "sbi 0x0b,3 \n\t"  //turn on the led pin 3
    "ldi r16, 1 \n\t"
    "ldi r17,0 \n\t"
    "movw r26, %0 \n\t"
    "rcall killms%= \n\t"
   "cbi 0x0b,3 \n\t"  //turn on the led pin 3

      "rjmp end%= \n\t" //skip over the routine
      //start of kill millesecond subrouting, need to waste ~16000 clock cycles
      "killms%=:ldi r24, 0x90 \n\t"  //lo8(3984)
      "ldi 25, 0x0f  \n\t"      //hi8(3984)
      "kloop%=: sbiw r24, 1 \n\t"   //2 clocks
       "brne kloop%=   \n\t"       //2 clocks since most times true!!
       "add r26, r16 \n\t"
       "adc r26, r17 \n\t"
       "movw %0, r26 \n\t"
       "sbis 0x09, 2 \n\t"
       "ret       \n\t"
       "rcall killms%= \n\t"
      //end of the kill millesecond loop
      "end%=: nop \n\t"
    :"=r" (answer)
    :
    :"r24", "r25"
    );

  return answer;
}

Looks to me like killms is calling itself recursively every millisecond. Your are going to quickly overflow your stack.

Expanding on my comment... I see a few issues in your asm code, not all
as serious as the first one:

killms is calling itself recursively indefinitely, which should
overflow your stack. The last rcall killms%= should probably be an
rjmp.
There is no need to move the answer around between register pairs.
Just use the compiler-allocated registers instead of r17:r16.
By adc r26, r17, you probably mean adc r27, r17.
Instead of add and adc, you could just adiw, which saves a
register pair.

Below is my version of testReactionTime(). I tested it on an Uno (with
Serial instead of an LCD) and it works fine. The assumptions on the
hardware are:

The LED is on pin 13 (PB5): it's the built-in LED.
The button is on pin 2 (PD2), which goes HIGH when the button is pressed.

/*
 * After a random delay, call this function to measure the reaction time
 * in milliseconds. It will immediately turn the built-in LED and then
 * start timing the milliseconds until the user hits the button (pin 2
 * going HIGH).
 */
int testReactionTime()
{
    int result, counter;
    asm volatile(
        "    clr %A[result]                      \n" // clear result
        "    clr %B[result]                      \n" // ditto
        "    sbi %[led_port], %[led_bit]         \n" // LED on

        // delay to make the loop 0 last exactly one millisecond
        "0:  ldi %A[counter], lo8(%[iterations]) \n"
        "    ldi %B[counter], hi8(%[iterations]) \n"
        "1:  sbiw %[counter], 1                  \n"
        "    brne 1b                             \n"
        "    nop                                 \n"

        "    sbic %[button_pin], %[button_bit]   \n" // unless button up:
        "    rjmp 2f                             \n" //     we are done
        "    adiw %[result], 1                   \n" // increment result
        "    rjmp 0b                             \n" // loop back
        "2:  cbi %[led_port], %[led_bit]         \n" // done: LED off

        : [result]     "=w" (result)
        , [counter]    "=w" (counter)
        : [led_port]   "I"  (_SFR_IO_ADDR(PORTB))  // LED on PB5
        , [led_bit]    "I"  (5)
        , [button_pin] "I"  (_SFR_IO_ADDR(PIND))   // button on PD2
        , [button_bit] "I"  (2)
        , [iterations] "i"  ((16000 - 8) / 4)
    );
    return result;
}

Thank you for the answer I did end up axing the recursion and going about it using a loop but this is very through and I like this way better than mine.

@SamKemp: In principle you can recurse in assembly, but 1) you have to make sure you ret as many times as you rcall, which seems to not be the case in your original code. 2) You must be aware that the Uno has only 2 KiB of RAM, which means you cannot recurse very deep before smashing the stack against the heap (or the BSS if you have no heap). Oh, BTW, you probably want to turn interrupts off in the timing routine.


text:
How to monitor a sensor for specific period
As noted in earlier posts, I am building a model railroad crossing gate signal, complete with gate arms, flashers and sound. Although I haven't settled on exactly how I am going to implement detection of the train entering the zone, determining when its completely passed the entry sensor, tripped the exit sensor and completely passed the exit sensor to re-open the gate, I am researching using RFID for this now.
My thought is to have an RFID card in every car of all my rolling stock. Therefore, I want to read all the ID's of the cars as they go buy and for this particular need, always store the latest ID in a variable so that once the whole train has passed by, the last ID in the variable SHOULD be the ID of the last car in the train. I would also have a counter incrementing for each unique ID read so I can use that as a secondary check for the exit routine (check that the exit RFID reader gets the same car count as the entry reader). The exit reader would also match its exitTag to the entryTag from the entry reader.
I am implementing a state machine to control all this functionality but the problem lies in the RFID reading, I need a way to determine when the reader has read all the train cars tags. I thought the easiest way to do this was to use the elapsedMillis library and monitor for some interval where no card was read (two seconds? that would be way more than the time between two train cars) and once met, change state.
That is proving more problematic than I thought. Here is my latest attempt.
I also think it might be better if the tag reading method only returned the last tag ID AFTER ITS DETERMINED NO MORE TAGS TO BE READ so that the code in the case statement is not the code that's running continuously.
Note: I am using the Adafruit RFID shield and Mifare Classic 1k S50 IC 13.56MHz RFID cards.
Any thoughts appreciated
case CrossingZoneState::CROSSINGZONE_RFIDDETECTED:
    if (crossingZoneEntered == true)
    {
        // only thing we do here is monitor and identify the RFID tags of each car to determine last cars tag id
       //well, this doesnt work
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            tag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (tag != priorTag)
            {
                tagCount += 1;
            }
            priorTag = tag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        // need to figure out how to determine no more cards are being read and change state and crossingZoneEntered back to false
    }

    if (crossingZoneExited == true)
    {

    }
    break;

IdentifyTags method:
uint32_t IndentifyTag(Adafruit_PN532 rfidReader)
{
    uint8_t tagID[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
    uint8_t tagIDLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
    uint32_t rfidCardID = tagID[0];
    boolean success = rfidReader.readPassiveTargetID(PN532_MIFARE_ISO14443A, &tagID[0], &tagIDLength);
    if (success) {
        // Display some basic information about the card for testing
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: "); Serial.print(tagIDLength, DEC); Serial.println(" bytes");
        Serial.print("  UID Value: "); rfidReader.PrintHex(tagID, tagIDLength);

        if (tagIDLength == 4)
        {
            // Mifare Classic card
            rfidCardID <<= 8;
            rfidCardID |= tagID[1];
            rfidCardID <<= 8;
            rfidCardID |= tagID[2];
            rfidCardID <<= 8;
            rfidCardID |= tagID[3];
            Serial.print("Mifare Classic card #");
            Serial.println(rfidCardID);
        }
        Serial.println("");
    }
    return rfidCardID;
}

Full switch statement:
switch (state)
{
case CrossingZoneState::CROSSINGZONE_CLEAR:
    // only thing we do here is monitor the zone entry sensor
    if (digitalRead(entrySensorPin) == HIGH) {
        crossingZoneEntered = true;
        state = CrossingZoneState::CROSSINGZONE_ACTIVATEGATES;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ACTIVATEGATES:
    // Do these once: turn on the flashers, put down the arms and turn on the crossing gate bells
    if (didOnce = false)
    {
        // turn on flashers
        // turn on sound
        // lower gate arms
        didOnce = true;
        state = CrossingZoneState::CROSSINGZONE_READENTRYRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    // only thing we do here is monitor and identify the rfid tags of each car to determine last cars tag id
    // need to figure out how to determine no more cards are being read and change state
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            entryTag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (entryTag != priorTag)
            {
                entryTagCount += 1;
            }
            priorTag = entryTag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        else {
            //change state now that entry rfid tag reader is finished
            state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        }

    break;
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
    {
        //do all the tag reading in here
        exitTag = IndentifyTag(entryRFIDReader);
        readCount += 1;

        if (exitTag != priorTag)
        {
            exitTagCount += 1;
        }
        priorTag = exitTag;
        timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
    }
    else {//check tags and count now that entry rfid tag reader is finished
        if (entryTagCount == exitTagCount && entryTag == exitTag)
        {
            state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
        }
    }
    break;
case CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES:
    // Do these once: turn off the flashers, raise the arms and turn off the crossing gate bells
    if (didOnce = true)
    {
        // turn off flashers
        // turn off sound
        // raise gate arms
        didOnce = false;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ERROR:
    boolean success = writeToFileOnSD(modelRRErrorLogFile, "ModelRRXingErrorLog.txt", "error string");
    break;
}

What kind of RFID reader and tags are you using? What exactly happens when you try your current code?

I am using the Adafruit RFID shield and Mifare Classic 13.56 Hz cards. @TisteAndii  ... I can read the tags but there a number of problems. 1. I run the train by the reader, (there are three cars with rfid tags) it reads the first tag 3-5 times but doesn't read the rest. I get why it might read a tag more than once as it passes by, and I handle that in IndentifyTags(), but its not reading tags 2 & 3

I thought about using a while loop, i.e. in psudecode while(Im reading tags) {//put the tags in a variable and increment the counter} and once im not reading tags (the elapsedtime is more than the inactive interval) then move on

Provide the whole switch statement. What exactly is crossingZoneEntered and crossingZoneExited? What do they represent in terms of your train's movements? Is this code for the entry reader or the exit reader?

@TisteAndii...Full switch added to original post

It stopped reading the other tags only after you added the IF block in the switch statement? You're sure that the other tags have 4-byte UIDs? If the answer is yes to these questions, then try my answer.

Here is a solution I found on one of the forums, I modified/simplified it to suit, but it does what you are after.
I use a cheap MP3 player and small amp that runs all the time with the speaker output switched by a baby relay controlled by the UNO R3 and IR sensors from Ebay, you should be able to convert this for use on your player.
It runs the 4 steps you described.
code attached.
(could not figure out how to get code into a box-very confusing..please enlighten me,,,,and what is a back tick??)
#include <Servo.h>

Servo gate1servo;// create servo object to control crossing gate 1
//ASSUMPTION Gate is down at position gatedownposition and up at position gateuppostion
Servo gate2servo; // create servo object to control crossing gate 2
unsigned long previousMillisSERVOSTART=0; //FLASH Millis() setup
int intervalSERVOSTART = 1000;
unsigned long previousMillisFLASH=0;  //FLASH Millis() setup
int intervalFLASH = 250;
int gateup  =  120;  // servo position for gate up
int gatedown = 30;
int gatepos; // variable to store the servo gateposition
int gp = 120;  // servo position for gate down
int sensor1 = 5; // IR sensor pin Assumption== Pin goes LOW when train detected
int sensor2 = 6; // IR sensor pin Assumption== Pin goes LOW when train detected
int led1 = 10;  // Led 1 pin first alternating flasher
int led2 = 11;  // Led 2 pin first alternating flasher
int gates_started = 0; // this says if the crossing is active

int entering_sensor = 5; //this will tell which sensor was triggered first
int leaving_sensor = 6; // this will tell which sensor shows train leaving
int flash_state = 0;

void setup() {
   Serial.begin(9600);
  gate1servo.attach(3);// attaches the servo on pin 3 to the servo object
  gate2servo.attach(4);// attaches the servo on pin 4 to the servo object
  gate1servo.write(gp);//start assuming no train
  gate2servo.write(gp);//start assuming no train
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  digitalWrite(led1, LOW);// Start with all flashers off
  digitalWrite(led2, LOW);
}

void loop() {
    if ((digitalRead (sensor1)==LOW)&& (gates_started==0)) {//read sensor 1, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor2;
    }
    if ((digitalRead (sensor2)==LOW)&& (gates_started==0)) {//read sensor 2, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor1;
    }
    unsigned long currentMillisFLASH = millis();                                                      // get current time stamp, only need one for all if-statements
    if ((unsigned long)(currentMillisFLASH - previousMillisFLASH) >= intervalFLASH) {// time between button presses
       flash_state = ~flash_state;
       digitalWrite(led1, flash_state);                                           //toggle flash_state
      digitalWrite(led2, ~flash_state);
      previousMillisFLASH = currentMillisFLASH;
  }

  unsigned long currentMillisSERVOSTART = millis();                                                     // get current time stamp, only need one for all if-statements
  if ((unsigned long)(currentMillisSERVOSTART - previousMillisSERVOSTART) >= intervalSERVOSTART) {      // time between button presses
    for(gp = gatedown ; gp <= gateup ; gp++) {                                                          // goes from gatedown  degrees to gateup degrees
      gate1servo.write(gp);                                                                             // tell servo to go to gateposition in variable 'gateposition'
      gate2servo.write(gp);

  previousMillisSERVOSTART = currentMillisSERVOSTART;
 }
 Serial.println(gp);
}
}

@Doug...Thanks for this. I edited your code input. All code lines need 4 spaces in from left margin and it will format properly. Ill test this later today or tomorrow.

Your algorithm is the probably the problem. Use this entry case instead:
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    entryTag = IndentifyTag(entryRFIDReader);
    if (!entryTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // seems u want to count number of reads

        if (entryTag != priorTag) {
            entryTagCount += 1;
            priorTag = entryTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;   /// reset the counter when u read ANY tag; negate the effects of reading a card more than once

    }
    // only check timeout if you didnt read ANY tag at all
    else if (timeElapsedBetweenCardReads >= readerInactiveInterval){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
    }

    break;

Something similar for the exit:
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    exitTag = IndentifyTag(entryRFIDReader);
    if (!exitTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // remember this variable is shared with the other case

        if (exitTag != priorTag) {
            exitTagCount += 1;
            priorTag = exitTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;

    }
    else if ((timeElapsedBetweenCardReads >= readerInactiveInterval) &&
             (entryTagCount == exitTagCount) && (entryTag == exitTag)){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
    }
    break;

And in the OCCUPIED case:
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
        timeElapsedBetweenCardReads = 0;   // reset the counter to prepare for exit case
        priorTag = 0;  // just in case
    }
    break;

I'm on vacation. I'll test when I return next week. Thanks for the answer.


text:
Serial Communication Between Two arduinos (Asking and Receiving)
Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches
//Arduino Sketch 1
uint16_t alpha;
uint16_t lambo;
Banana nanas;    //to hold the Banana object
uint16_t dataArray[2];
void Setup(){
    Serial.begin(9600);
    establishContact();
}

void loop(){
    alpha=nanas.getRad;
    lambo = nanas.getBars;
    dataArray[0] = alpha;
    dataArray[1] = lambo;
    Serial.write((uint8_t*)dataArray, sizeof(dataArray));
    Serial.flush();   //clear the serial port
}

void establishContact()
{
    if (Serial.available())
    {
        while (Serial.available()  > 0)
        {
            int newByte = Serial.read();
            if (newByte == 'Q')
            {
                Serial.write(newByte);
                Serial.flush();
            }
        }
    }
}

The sketch for the other arduino is shown below
//Arduino sketch 2
static char buffer[2];
void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
    establishContact();
}
void loop(){
    if(Serial1.available())
    {
        while(Serial1.available() > 0){
            uint16_t gondola1 = Serial1.read();
            uint16_t gondola2 = Serial1.read();
            uint16_t crixus = gondola2 >> 8;
            crixus = (crixus | gondola1);

            gondola1 = Serial1.read();
            gondola2 = Serial1.read();
            uint16_t mario = gondola2 >> 8;
            mario = (mario | gondola1);
            buffer[0] = crixus;
            buffer[1] = mario;
            Serial.write(buffer, sizeof(buffer);
            Serial1.flush();
        }
    }
}
void establishContact(){
    if (Serial.available()){
        uint16_t newByte = Serial.read();
        if(newByte == 'Q')
        {
            Serial.flush();
            Serial.write(newByte);
        }
    }
}

Please elaborate.
What boards do you use?
What libraries do you use?(code does not compile as it is)
What connections you have made between the boards?
Also, I cannot really understand what exactly you want to happen when which board recieves what from the other board? Send a message back to the sender's board? Send a message elsewhere?

@foivaras..the boards in question are an arduino uno which the sensor is connected to and an arduino mega which is used to receive the data being sent, The connections are the usual tx/rx from the uno to serial1 on mega. there are no other libraries included. The Mega request for data from the uno..uno sees the request command and then sends data .. mega receives data and request for more data. Thats it in a nutshell

if you do not use any library then your code does not compile.
Sketch one has an undeclared Servo type.
Sketch two gives a redeclaration of uint16_t gondola1 error.

@foivaras the Servo class I used is just a random name I adopted ...in hindsight I should have changed it to something else..i just wanted to show that there is a class that an object can be declared from,  to call its respective methods. I'll edit the sketches out now

Setup() should be setup() in the first sketch? What exactly is Banana? Why complicate things, if all you want to do is send 'Hello world' on request? If that isnt your goal, then edit your post and say exactly what the sketches are for and exactly what you mean by it didn't work for me.

it is not really easy to follow your code but here is a "hello world" procedure to do an on demand data send between two arduinos:

upload this code to arduino uno before you make any connection on pins 0 and 1 of the board:
/**
 * Code for server side (arduino uno)
 */

uint8_t data2send = 'A'; //data to send on a received request
uint8_t incomingByte;

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

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 0) {

                // read the incoming byte:
                incomingByte = Serial.read();

                if(incomingByte=='Q'){  //if incoming data is the expected request (request code = 'Q' in this example)
                        Serial.write(data2send);
                }
        }
}

connect:
UNO  | MEGA
------------
pin0 | pin18
pin1 | pin19
GND  | GND

upload to arduino mega this code:
 /**
 *  code for arduino mega.
 *
 *  proxy between Serial0 and Serial1
 *
 *  send data to Serial0 to forward it to Serial1.
 *  when data is received from Serial1 it will be forwarded to Serial0.
 */

void setup() {
        // initialize both serial ports:
        Serial.begin(9600);
        Serial1.begin(9600);
}

void loop() {
        // read from port 1, send to port 0:
        if (Serial1.available()) {
                int inByte = Serial1.read();
                Serial.write(inByte);
        }

        // read from port 0, send to port 1:
        if (Serial.available()) {
                int inByte = Serial.read();
                Serial1.write(inByte);
        }
}

open the mega's serial monitor and send some characters. Check that you receive back data only when you send a 'Q' character.

generally speaking, if a given answer is satisfying you then you should mark it as accepted.
See also faq about accepting answers. Thank you.


text:
Time Stamping data on an Arduino and reading it on a Java IDE
Does anyone have an idea on the best way to time stamp an arduino sketch that contains a data packet which is to be read out using a java IDE (IntelliJ) for graphic visualization of the packet. I tried declaring the time variable on the arduino section but having problem unpacking the unsigned long variable in java. Below is a snippet of the arduino code.
             unsigned long codeTime = 0; //The time the sketch takes to execute
         static unsigned long char dataArray [1]; // a variable to hold both sensor data

         void setup(){
              Serial.begin(9600);
              Serial1.begin(9600);
          }
         void state1(){
             if (Serial1.available()){
                    while (Serial1.available() > 0){
                 codeTime = millis(); //using the millis() instead of micros()
                 //memcpy should copy the whole data into position 0 ????
                 memcpy(&dataArray[0], &codeTime,sizeof(codeTime));
                 uint16_t newByte1 = Serial1.read(); // read in the first byte
                 uint16_t newByte2 = Serial1.read(); //read in the second byte
                 uint16_t dataByte = newByte2 >> 8;
                 dataByte = (dataByte | newByte1);
                 dataArray[1] = dataByte;
                 Serial1.write((uint16_t*)dataArray, sizeOf(dataArray));
                 }
               }
              }

            void loop(){
                   state1();
                   Serial1.flush();  //clear the serial port
                   delay(100);
                }

The question now is how do i unpack the data in java to ensure that the time variable (unsigned long time variable is well unpacked in the correct order)????. The second variable i could easily unpack in java as
              int variable1 = variable2 >> 8; //as it is a 16 bit integer I shifted
                                              // the msb/lsb accordingly
              variable1 = (variable1 | variable2);  // and finally casting it.

I don't see in your code where you are actually sending the time through serial.

@majenko I saved the time variable 'codeTime' in position zero in the buffer (buffer[0]).. and i wrote both data through to serial using Serial.write(buffer,sizeof(buffer));

I don't see that in your code.

@majenko  I just saw the mistake.. fixing now

There's a number of fundamentally wrong things in your sketch.
static char buffer[1]; // a variable to hold both sensor data

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.
buffer[1] = newByte;

No. There is no buffer[1]. You count slices from 0.  buffer[0] exists (the first one) but buffer[1] doesn't.
buffer[0] = millis;

You aren't calling the function, you are assigning the address of the function. And worse than that, buffer is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an unsigned long which is 4 bytes in size.
You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.

i replaced the buffer with a 16 bit array that could comfortably contain all 4 bytes but the problem still persist

In what universe can you fit a 32 bit value and an 8 bit value into a 16 bit array with 1 slice? You can't count, can you?

was a little bit buggered there, got that fixed now, is that fine by you??

No. You still can't count. Where is your dataByte going? Scrap the array. Don't use it. There's no point. Just send the 6 bytes you need to send as bytes. That is, split your unsigned long into 4 bytes sending each one as you go (bit-shift and mask), then you data bytes. 6 bytes. That is all. And then work out how you are going to know at the other end which byte is which. Your whole methodology is flawed. You have no protocol, only raw data.


text:
What is the proper way to send data through http using sim908?
Preamble:
I have a sim908 shield and I'm trying to send some data periodically to a server using AT commands.
For every command, I wait for the response to check if everything is working.
Actually the sketch works but, often, I noticed errors during http request.
State of the art:
Here it is the sequence of AT commands (not the entire code) into the loop:
1) Check the Network Registration and, if necessary, wait
AT+CREG?

2) Set params for GPRS connection (no user or password required)
AT+SAPBR=3,1,"Contype","GPRS"
AT+SAPBR=3,1,"APN","web.omnitel.it"

3) Get current bearer
AT+SAPBR=2,1

4) If bearer == 0,0,0,0 (not assigned) get a new bearer
AT+SAPBR=1,1

5) Init HTTP
AT+HTTPINIT

6) Set CID and URL
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

7) Execute the HTTP command (POST)
AT+HTTPACTION=1

8) Close HTTP connection
AT+HTTPTERM

Question:
Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?
Thank you in advance :)
Important update:
If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)
Answers to the comments:
a) Shield has an antenna and it works. If I try to disconnect the antenna, code still  search the network (step 1) untill I reconnect the antenna.
b) Some times I have this error initializing HTTP (step 5):

AT+HTTPINIT
+CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

+HTTPACTION:1,200,xxx

Or this response:

+HTTPACTION:1,600,0

c) I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

AT+SAPBR=1,1
+CME ERROR: 3

For this reason I do a check (step 3)

Does it have an antenna? And what particular error do you get back? Post messages should get an http+error back with a nummer.

Did you get the results of the new bearer settings returned by AT+SAPBR=1,1? Post the exact +CMEE error code you're seeing.

I edited the original post

CME ERROR: 3 is "operation not allowed".
And HTTP response code 600 isn't officially something, try reading the message header and body, but it may be "invalid request".

Thank you Paul. From documentation (http://www.waveshare.com/w/upload/4/4e/SIM908_AT-Command-Manual.pdf) 600 is "Not HTTP PDU".
This error doesn't appear every time. For what you know, my procedure is correct?

@Lipsyor, hard to tell, has been quite a time since I worked with those GSM modules and I don't have one available to test. If AT+HTTPINIT fails, you might want to force close an existing http setup with AT+HTTPTERM.

You mention two different error messages.
1. AT+HTTPINIT fail
You get +CME ERROR 3. Which means "operation not allowed".
This can be due to an improperly closed HTTP setup.
If you get this error (or just always do before setting up), call AT+HTTPTERM to be sure that it's closed.
2. AT+HTTPACTION=1
I notice you're trying to do a POSTmessage, while your variables are in the URL (which is GET style afaik).
I've found a source that states you need to call AT+HTTPDATA with apropriate values.

Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say DOWNLOAD, and you can send the POST body.

After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data.
  AT+HTTPDATA=192,10000

And after that you can send the POST message.

Execute the HTTP POST command so that the buffer contents are POST to
  the server AT+HTTPACTION=1 OK

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

+HTTPACTION:1,200,141
  This URC means that the data was successfully posted to the server and received 141 bytes of data.
  which is the server response to your HTTP POST

You can use AT+HTTPREAD to receive these bytes.

The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data
  received from the server
  +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post
  body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on HTTP GET: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)
You could also omit this by using HTTP GET since it's somewhat easier.
If all else fails, you can set up a TCP IP connection with the GSM module and manually set up the HTTP GET/POST message.

Thank you for answer. About HTTPINIT fail, note that (step 8) I use HTTPTERM for each loop. I'll try what you suggest about GET and POST.
However I don't understand why sometimes my code works and other times no.

I tried but without results. Now I'll try to wait more time for responses.

@Lipsyor which option did you try? I suggest trying to make a GET request working before you try the POST requests.

I tried to wait more time for response: now GET and POST works. I have some problems with HTTPINIT: when it fails I can't recover with HTTPTERM and I had to try more times.
I'm considering to reset shield if more than two or three errors occurs consecutively.

Hmm, atleast we're making progres here ;) have you checked how other libraries handle errors? If http init fails, you could check all the above again, at+creg?, at+sapbr and whatnot. Having to reset it is a bit crude (if it happens often). But it's good to have such a feature built in anyway.

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


text:
What is the best way to get more RAM for a sound buffer?
The problem:
How to extend the memory for a sound buffer (intensively used) if:

SD card library supports only one file open at a time (and I have one open already)
EEPROM chips are able to stand about 100,000 write cycles only (see the datasheets!)
I can't find anything else to buy! (a standard and durable RAM chip that loses its content when switched off would be the best).

About the 2nd point. Let's assume that the chip is 64KB and I want to use half of it for a circular sound buffer (it's small, I know). Let's also assume that a standard MP3 song is 160kbps and it's 3.5 min long. Given that, the EEPROM chip (with 100k write cycles limit) in this condirions will reach its limit after 3.2GB of played sound, which is about 762 songs, 44 hours. That can be reached in a single week! Replacing a chip every week is not an option. I'm not a fan of planned obsolescence...
Do you know any chip that will be right for the job? (and can be bought on eBay and it's affordable?)
Background:
I have built a WWW-controlled MP3 and online radio player (using ESP8266 and VS1003) and it's working really great, we're using it whole days, but ESP is not fast enough to handle WWW requests and play MP3 at the same time (especially from SD card), so the sound is paused for about 0.5 - 1 sec every time a www page is served (a really small page! Just basic HTML with a title and a list of file links!). SD card content cannot be cached for generating the pages on the fly (not enough heap memory) and two files cannot be opened at the same time by the SD library (one is open for the currently playing file - if not playing an online stream - and I'm currently closing it during reading and sending of requested html page). So I've got two memory problems: 1. serving the www pages and 2. buffering the online stream (usually not needed, most streams can play on my 4KB buffer without a glitch whole day but some of them are jamming very often - depends on the server). I'm thinking about both caching the pages (so I don't have to read them from SD and my music won't be interrupted) and creating a circular buffer (for live streams) in external memory chip. It does not need to keep the data after cutting the power. I've got about 24KB of heap left in my sketch (max) and it can fall even to about 6KB when a single folder's content is loaded to memory. It's not far away from heap overflow... I need to load at least the current folder (with long filenames).

This is a software problem, and properly solved there.  Compared to an ordinary Arduino, an ESP8266 has quite a bit of buffer memory.  The problem is that by not really implementing multiple tasks, you put yourself in the position of needing absurd amounts of buffer.  Your best solution on this platform will be to rework the SD card access library to handle multiple files, or perhaps permit multiple instances to request sectors from the same card.  Then your buffer need only be a few sector's size, which should not be a problem.

A simple SPI SRAM chip. Available up to 128KB, such as the 23LC1024: http://www.microchip.com/wwwproducts/en/23LC1024

This chip is great! Thanks! Although it's very expensive as you compare it. You can get ESP-12 for $2.5 and this little chip costs above $8! For that price you can buy 3 pcs of ESP-12 (or 4pcs ESP-01 or 5pcs ATmega328P-PU!) and make memory out of them (by a sketch), even with WiFi interface... :] That's even more true for these Adafruit non-volatile modules (from JRobert's answer), which have 32KB only!

This is silly way to solve a software problem.

@ChrisStratton Yeah, but it's the typical PC software developer request/solution. Software is running slow => throw more hardware at it.

This is not a software problem. If you download a radio stream from Internet and you don't have a big buffer, then you will eventually always get lags in sound. You can't speed up the whole Internet. I agree that SD library probably could be made better (to handle multiple files) but even then it wouldn't help because I'm getting like 2 sec delays when opening SOME of the files on my SD card! You can't cheat time and memory size by software. It's just physically not possible. Check out by yourself how WinAMP (for example) delays the online radio streams. It's about half a minute!

You should switch to SdFat instead of SD.

An FRAM chip?

Non-volatile (though you don't need that)
SPI or I^2C available on a breakout board from Adafruit
Or roll you own from a bare chip, if you're handy with Surface Mount Devices.


text:
Creating date string for error log
Well, googling didn't do much to help me here and I'm shocked that something I can do in two lines of code in C#
DateTime dateTime;
string text = dateTime.ToLongDateString();

is this difficult for Arduino, but how do you get a string version of a date time stamp?
I want the current date and time as a string in this format

May 4, 2016 17:15:33

Since I can't use any of the C++ includes, like ctime, I'm not sure how to accomplish this.

I found a great library for this very purpose!  https://github.com/PaulStoffregen/Time

But I can't get any of the examples to work on an Uno

Which examples did you try? What results did you get?

What time do you want to get? The Arduino has no concept of the time, unless you add an RTC module, and then it is down to whatever library the RTC module uses.

I wasn't aware of that. So an additional hardware piece(RTC) is required to capture time? I'll look into that

That's right. The processor chip costs about $US 2. It doesn't include a real-time clock. If it did, how would you set it? And if it did, you would need a battery on the board to keep it powered when you unplug it from the USB/power. There is no battery there.

You need additional hardware like a RTC for example an DS1307 or on the other hand an arduino/shield with ethernet or wifi so you could get the time by NTP another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.


text:
Error loading Blink sketch in esp01 (esp8266)
I have the esp01 connected the serial port using a usb to ttl serial cable and also using the Arduino UNO as suggested in some tutorials. I can execute AT commands. But loading a sketch from Arduino IDE results in error messages show below. If anyone can help, it would be greatly appreciated. Note the error message:

serialport_receive_C0: F0 instead of C0

Build options changed, rebuilding all

Sketch uses 219,211 bytes (50%) of program storage space. Maximum is 434,160 bytes.     Global variables use 31,416 bytes (38%) of dynamic memory, leaving 50,504 bytes for local variables. Maximum is 81,920 bytes.
      /Users/syedtariq/Library/Arduino15/packages/esp8266/tools/esptool/0.4.8/esptool -vv -cd ck -cb 115200 -cp /dev/cu.usbmodem14221 -ca 0x00000 -cf /var/folders/hx/m49nxmvn0799w816ct3tgsjm0000gp/T/build10f6b721887f9efd16f05460daf22810.tmp/Blink.ino.bin
esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
setting board to ck
setting baudrate from 115200 to 115200
setting port from /dev/tty.usbserial to /dev/cu.usbmodem14221
setting address from 0x00000000 to 0x00000000
espcomm_upload_file
espcomm_upload_mem
opening port /dev/cu.usbmodem14221 at 115200
tcgetattr
tcsetattr
serial open
opening bootloader
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: FF instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
resetting board
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
trying to connect
setting character timeout 0
done
setting character timeout 1
done
espcomm_send_command: sending command header
espcomm_send_command: sending command payload
serialport_receive_C0: F0 instead of C0
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

How is it wired up? Are you pulling down pin 0 and resetting to enter firmware upload mode? You might want to read this: http://www.esp8266.com/wiki/doku.php?id=getting-started-with-the-esp8266

I have pin 0 grounded as suggested in various tutorials. It appears that this has to do with inability to flash since I am able to use AT commands without any problem.

The problem is related to the Arduino Uno, seems that you haven’t bypassed the Arduino board (since you need to program the esp you should communicate directly with it).
To do this you need to wire the reset pin of Arduino to the ground (also the GPIO1 of esp should be connected to the ground in order to go in programming mode).


text:
error loading an array of strings
I'm trying to have a user enter a series of strings. This is my code.
this is my error message - cannot convert 'String' to 'char*' in assignment
char* titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup() {
 Serial.begin(9600);
 Serial.println("Storing numbers in an array");
}

void loop()

{

for (int x =0; x < 5; x++)
{
  if (Serial.available() > 0)

  {
   Serial.println("Enter a word... ");
   titles[x] = Serial.readString();

    Serial.println(" ");
    Serial.println(chartitles[x]);

   }
  }
 }

This is really not how you want to do this.

You are confusing the concept of a "string" (C string - char array) with a "String" - the Arduino-specific class that people who don't know better use.

So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:
String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup(){
  Serial.begin(9600);
  Serial.println("Storing numbers in an array");
}

void loop(){
  for (int x = 0; x < 5; x++){
    if (Serial.available() > 0){
      Serial.println("Enter a word... ");
      titles[x] = Serial.readString();
      Serial.println(" ");
      Serial.println(titles[x]);
    }
  }
}

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:
String titles[]

Instead of:
char* titles[]

The second change is related to Serial.println(chartitles[x]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.

I modified the code slightly. Im getting a strange output. I placed the print statement outside the for loop to enter the strings. Now when it prints it prints the original values for the strings and the ones that are entered from the serial monitor.
See the image.
https://www.dropbox.com/sc/5ubcn2raee4vmkn/AADBvjHcQVMhpCsIIW3cahXba

@MichaelNiebauer I think this is what you want to code: https://codeshare.io/9ko5o

thank you, this does exactly what I was looking for. I have a question whats the difference between using if and while before the (Serial.available() > 0) statement. I was using an if and it didn't work it looks like by switching it to a while it does.

try to think about the else, if you were not writing something in the Serial console, the program would skip the if and continue, but since the code was inside a void loop, this would be repeated, making your program repeat the println and the for

when you use a while the program waits a response


text:
Why ModBus RTU Master-Slave Dont Work
I have two mega arduino and want to them communicate with modbus rtu together, i use below link circuit for this :
http://www.microcontroller-project.com/rs485-communication-between-arduino-mega-and-arduino-pro-mini.html
but dont work!! while they work in simple rs485 and without modbus with same above link code !?
my code in modbus mode is based on this forum :
https://forum.arduino.cc/index.php?topic=176142.0
MASTER CODE
    //#include <LiquidCrystal.h>

#include <SimpleModbusMaster.h>

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 50

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2

#define LED 9

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 12

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];
int In22=22;

// LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup()
{
  Serial.begin(9600);
//  Serial1.begin(9600);
//Serial.begin(speed,9600);
// lcd.begin(16, 2);
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0, 5, 0);
//  modbus_construct(&packets[PACKET2], 1, PRESET_MULTIPLE_REGISTERS, 1, 1, 0);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial1, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();

//  regs[0] = analogRead(0); // update data to be written to arduino slave
//regs[1] =In22;
//  analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
//  regs[1];
 if (Serial1.available()){
//regs[1]=In22;
//if(regs[1]==123){
    Serial.println(regs[0]);
    Serial.println(regs[1]);
    Serial.println(regs[2]);
    Serial.println(regs[2]);
//}
//  lcd.setCursor(6, 1);
//    lcd.print(regs[0]);
//lcd.print("hgftf");پ
 }
  delay(1000);
//lcd.clear();

}

SLAVE CODE
#include <SimpleModbusSlave.h>

/* This example code will receive the adc ch0 value from the arduino master.
   It will then use this value to adjust the brightness of the led on pin 9.
   The value received from the master will be stored in address 1 in its own
   address space namely holdingRegs[].

   In addition to this the slaves own adc ch0 value will be stored in
   address 0 in its own address space holdingRegs[] for the master to
   be read. The master will use this value to alter the brightness of its
   own led connected to pin 9.

   The modbus_update() method updates the holdingRegs register array and checks
   communication.

   Note:
   The Arduino serial ring buffer is 64 bytes or 32 registers.
   Most of the time you will connect the arduino to a master via serial
   using a MAX485 or similar.

   In a function 3 request the master will attempt to read from your
   slave and since 5 bytes is already used for ID, FUNCTION, NO OF BYTES
   and two BYTES CRC the master can only request 58 bytes or 29 registers.

   In a function 16 request the master will attempt to write to your
   slave and since a 9 bytes is already used for ID, FUNCTION, ADDRESS,
   NO OF REGISTERS, NO OF BYTES and two BYTES CRC the master can only write
   54 bytes or 27 registers.

   Using a USB to Serial converter the maximum bytes you can send is
   limited to its internal buffer which differs between manufactures.
*/

#define  LED 9

// Using the enum instruction allows for an easy method for adding and
// removing registers. Doing it this way saves you #defining the size
// of your slaves register array each time you want to add more registers
// and at a glimpse informs you of your slaves register layout.

//////////////// registers of your slave ///////////////////
enum
{
  // just add or remove registers and your good to go...
  // The first register starts at address 0
  ADC_VAL,
  PWM_VAL,
  HOLDING_REGS_SIZE // leave this one
  // total number of registers for function 3 and 16 share the same register array
  // i.e. the same address space
};

unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array
////////////////////////////////////////////////////////////

void setup()
{
  /* parameters(HardwareSerial* SerialPort,
                long baudrate,
        unsigned char byteFormat,
                unsigned char ID,
                unsigned char transmit enable pin,
                unsigned int holding registers size,
                unsigned int* holding register array)
  */

  /* Valid modbus byte formats are:
     SERIAL_8N2: 1 start bit, 8 data bits, 2 stop bits
     SERIAL_8E1: 1 start bit, 8 data bits, 1 Even parity bit, 1 stop bit
     SERIAL_8O1: 1 start bit, 8 data bits, 1 Odd parity bit, 1 stop bit

     You can obviously use SERIAL_8N1 but this does not adhere to the
     Modbus specifications. That said, I have tested the SERIAL_8N1 option
     on various commercial masters and slaves that were suppose to adhere
     to this specification and was always able to communicate... Go figure.

     These byte formats are already defined in the Arduino global name space.
  */

  modbus_configure(&Serial1, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);

  // modbus_update_comms(baud, byteFormat, id) is not needed but allows for easy update of the
  // port variables and slave id dynamically in any function.
  modbus_update_comms(9600, SERIAL_8N2, 1);

  pinMode(LED, OUTPUT);
}

void loop()
{
  // modbus_update() is the only method used in loop(). It returns the total error
  // count since the slave started. You don't have to use it but it's useful
  // for fault finding by the modbus master.

  modbus_update();
//  holdingRegs[0] = 123; // update data to be read by the master to adjust the PWM
  holdingRegs[1] = 123; // update data to be read by the master to adjust the PWM
    holdingRegs[2] = 123;
//    holdingRegs[3] = 123;
//    holdingRegs[4] = 123;
  //  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
  delay(1000);
  /* Note:
     The use of the enum instruction is not needed. You could set a maximum allowable
     size for holdinRegs[] by defining HOLDING_REGS_SIZE using a constant and then access
     holdingRegs[] by "Index" addressing.
     I.e.
     holdingRegs[0] = analogRead(A0);
     analogWrite(LED, holdingRegs[1]/4);
  */

}

I even didn't check the Modbus part of your code but the first think what I found:
You are using the D2 pin for LCD and at the same time as TXEnablePin...


text:
Using two ultrasonic sensors together
Using two ultrasonic sensors together, how can I enable one before the other?

Do you have a circuit?  Any code?

You need to tell the sensor to send their pulse using the trigger line.  So triggering isn't a problem.
The problem is that you might get an echo returned on both sensors, but you know which sensor sent the pulse so you can ignore the return that was received by the 'wrong' sensor in your code.
So
While(1)
{
  SendPulse(SensorTx1);
  GetEcho(SensorRx1);
  SendPulse(SensorTx2);
  GetEcho(SensorRx2);
}

Is that what you mean?  If not please can you expand you question?


text:
How to turn two LED's on and off with one button?
I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.

Other than with the ! operator?

Commenting instead of replying because you asked for code, but this could be done in hardware.  If you wire in a PNP transistor to switch the second LED, it will free up the second DIO pin.

Can I ask why you don't want to use if and else?  Is this just hypothetical fun?

@KJP if you add an x amount of shift registers, you'll free up an (x*8)-6 amount of in/outputs? ;D

Just use the return value of digitalRead (which is 1 or 0) as the input to digitalWrite:
int btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

Or using boolean instead:
bool btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, !btnVal);     // Off when button is HIGH

You can also use ! with int values.

You don't say....

Wasn't necessarily telling that to you, but leaving that comment as a note to the OP, which seems to be a beginner, or to any future reader.

in C, bool and int are interchangeable.

There is no such thing as bool in C.

@Majenko: In C99 there is _Bool, and bool if you #include <stdbool.h>.

@EdgarBonet It may be called a _Bool but it's still an integer: Boolean values still behave as integers, can be stored in integer variables, and used anywhere integers would be valid, including in indexing, arithmetic, parsing, and formatting. This approach ("Boolean values are just integers") has been retained in all later versions of C.

Yes, C bools are integers, yet (bool) 1 == (bool) 2.

And also (1 != 0) == (2 != 0)

You could do it with only a switch/case statement. You do not even need to de-bounce the switch.