text:
LCD Weather Station - "Press To Start" Function
I've been trying to make a weather station using a I2C LCD Display and a DHT11, I know, the DHT11 is a bit low res and all that, but it came with the kit I ordered, so it's okay.
However, I'm trying to have it display like a "title" screen, and after a 2sec delay it should proceed to say "Welcome!" and "Press to Start", and wait there until the button is pressed, and after the button is pressed it should proceed to show the temp and humidity.
However it doesn't seem to mind any of the functions added, unless I set the "if" statement at the beginning of the loop to "LOW", then for some reason, the program stops at "Welcome!" and "press to start".
If I change the "if" statement condition to "HIGH" it just proceeds straight through to the temp and humidity.
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

//CONSTANTS
#define DHTPIN 3
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2);

//Variables
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value

const int buttonPin = 6;

int buttonState = 1;

void setup()
{
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  dht.begin();
  lcd.begin();
  lcd.clear();
  delay(1000);
  lcd.setCursor(0, 0);
  lcd.print("WeatherMate");
  lcd.setCursor(0, 1);
  delay(250);
  lcd.print("Press 'Start'");
  delay(1000);;
  if (buttonState = 0)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Welcome!");
    lcd.setCursor(0, 1);
    lcd.print("Press Start");
  }
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState = 1) {
  delay(500);

  hum = dht.readHumidity();
  temp = dht.readTemperature();
  if (temp <= 25) {
    digitalWrite(13, LOW);
    digitalWrite(12, HIGH);
  }
  if (temp >= 25) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
  }
  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.println(" Celsius");

  lcd.setCursor(0,0);
  lcd.print("Temp: ");
  lcd.print(temp);
  lcd.print(" ");
  lcd.print("C");
  lcd.setCursor(0,1);
  lcd.print("Hum:  ");
  lcd.print(hum);
  lcd.print(" %");

  delay(500); //Delay 2 sec.

}
}

Anyone? I'm stuck on this one.

Assignment is =. Comparison is ==.

As Majenko points out in his comment, a couple of your if statements have the assignment operator (ie. =) whereas you are actually after the comparison operator (ie. ==).
if (buttonState = 0)

should be:
if (buttonState == 0)

And
if (buttonState = 1) {

should be:
if (buttonState == 1) {

When an assignment is used, the if statement will execute if the value being assigned is a non-zero. For more information see Using assignment as a condition expression? over on Stack Overflow.

Actually it's not an indication of assignment success, but the value assigned 'falling through' to the if which is why changing 0 to 1 makes it stick in the first if.

Thank you!
This worked a charm, but it doesn't go to the "Welcome" screen now, any ideas?

Where in setup are you reading the current state of the button?

@Majenko Quite right. A mistruth that I learnt early on that has been hard to shake.  I'll change it right away. I don't want to pass on this mistruth to others!


text:
Communication serial port with matlab
I am trying to communicate with a serial port trought matlab. This is my code:
delete (instrfindall)
clear all
close all
clc;

s=serial('COM4');
set(s,'BaudRate',4800);
set(s,'DataBits',8);
set(s, 'Parity','none');
set(s,'StopBits',1);
set(s, 'FlowControl','none');
set(s,'Terminator','CR');
set(s,'TimeOut',5000);

fopen(s)
%Move the probe radial
fprintf(s,'%s','RADIAL=100');

out=fgets(s);

fclose (s)
delete (s)
clear (s)

But i cannot make the serial port to answer me.
Can you help me? Is this code right?
Best regards,

The baud rate seems a bit low. Have you tried higher rates, ex: 38400?

source: Stack Exchange

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

sort: votes


text:
Sparkfun Si4703 FM not getting to loop
I recently purcahsed an si4703, from sparkfun
https://www.sparkfun.com/products/11083
I got it soldered to some headers and now I am not getting anything to work on it, my wire diagram is as follows

( I know the FM module pictured is different but its ultimately wired up the same I think)
And I am just trying to run the out of box example code modified to my Arduino Mega board
#include <SparkFunSi4703.h>
#include <Wire.h>

int resetPin = 35;
int SDIO = A15;
int SCLK = A14;

Si4703_Breakout radio(resetPin, SDIO, SCLK);
int channel;
int volume;
char rdsBuffer[10];

void setup()
{
  Serial.begin(9600);
  Serial.println("\n\nSi4703_Breakout Test Sketch");
  Serial.println("===========================");
  Serial.println("a b     Favourite stations");
  Serial.println("+ -     Volume (max 15)");
  Serial.println("u d     Seek up / down");
  Serial.println("r       Listen for RDS Data (15 sec timeout)");
  Serial.println("Send me a command letter.");

  radio.powerOn();
  radio.setVolume(0);
}

void loop()
{
  Serial.println("looping");
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch == 'u')
    {
      channel = radio.seekUp();
      displayInfo();
    }
    else if (ch == 'd')
    {
      channel = radio.seekDown();
      displayInfo();
    }
    else if (ch == '+')
    {
      volume ++;
      if (volume == 16) volume = 15;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == '-')
    {
      volume --;
      if (volume < 0) volume = 0;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == 'a')
    {
      channel = 930; // Rock FM
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'b')
    {
      channel = 1067; // BBC R4
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'r')
    {
      Serial.println("RDS listening");
      radio.readRDS(rdsBuffer, 15000);
      Serial.print("RDS heard:");
      Serial.println(rdsBuffer);
    }
  }
}

void displayInfo()
{
   Serial.print("Channel:"); Serial.print(channel);
   Serial.print(" Volume:"); Serial.println(volume);
}

However I do not think it is ever getting to the actual loop, it seems to get stuck on the code radio.powerOn() and then does nothing after that, what can I do to make this work?

Welcome to Arduino StackExchange! But could you please add an actual picture of your wiring instead of that image?

According to your hookup image, you have connected I2c pins to A14 and A15, I2c on Mega is on pins 20 and 21 , clearly marked SDA and SCL.
Also note that this module can ba powered by 5V but is only 3.3V tolerant on the input pins, you should use a level converter.

Thank you so much, It worked, why on an UNO board in the hookup guide does it say to use Analog ports A4 and A5, is it because the Mega offers something the UNO does not?  Just would like to know the reasoning as to why it works, thanks

The AtMega328p and the AtMega2560 are wery different in many ways and the pinout and what hardware features are available on which pin is also different, while they are made to be as similar looking as possible this might often lead to your little snafu.

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


text:
Use SD Card while Pin 11 is being used for PWM
On Arduino Uno Rev3, I just ran the speaker_pcm demo that used TIMER1 and TIMER2 to generate a PWM wave. However, this means that the Pins 3, 9, 10 and 11 can not be used anymore; according to the documentation:
Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
(analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
for the pulse width modulation, breaking PWM for pins 11 & 3.

I wanted to change the program such that the WAV data was read from a SD card. However, this is what documentation for SD.h library says:
The communication between the microcontroller and the SD card uses SPI,
which takes place on digital pins 11, 12, and 13 (on most Arduino boards)

This means both the SD.h and speaker_pcm want to use pin 11, and the requirement to use these pins is dictated by the hardware. I am guessing that this clash will create problems.
Is there any way I can make this work? Can I switch between SD card reading and Audio playing somehow (essentially multiplexing in software)? Or will this collision of pin usage not be a problem?

The program you link to does not take over pins 3, 9, 10 and 11, it
takes over Timer 1 and Timer 2, which are used to provide PWM capability
on those pins. This means you cannot do analogWrite() on those pins
anymore, but you still can use them for other purposes, including SPI
access to an SD card.
Note, however, this line of code:
int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

This of course will conflict the SPI port using pin 11 as MOSI. You can
fix this conflict simply by setting speakerPin to 3 instead of 11.


text:
Servo issue, won't go into negative range
I'm trying to create a small laser "turret" with x-axis control. The arduino receives input through IR sensor. I'm having a problem where my servo will preform my up and reset function(moves and prints as intended), but When i preform the down function the servo does not move. I believe the function is executing (it outputs angle to LCD and text to serial monitor) but there is no movement.
Any help would be greatly appreciated!
#include <IRremote.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>

int IRPIN = 3;
int angle = 0;
int test = 0;
IRrecv irrecv(IRPIN);
decode_results results;
Servo spinnything;
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup()
{
    irrecv.enableIRIn();
    lcd.begin(16, 2);
    lcd.backlight();
    spinnything.attach(5);
    spinnything.write(angle);
    lcd.setCursor(0, 0);
    lcd.print("WARNING");
    lcd.setCursor(2, 1);
    lcd.print("!!!LASER!!!");
    delay(1500);
    lcd.clear();
}

void loop()
{
    if (irrecv.decode(&results)) {
        irrecv.resume();
    }
    if (results.value == 0xE172C837) {
        up();
        results.value = 0x00000000;
    }
    if (results.value == 0xE17228D7) {
        down();
        results.value = 0x00000000;
    }if (results.value == 0xE1724CB3) {
        reset();
        results.value = 0x00000000;
    }
    lcd.setCursor(0,0);
    delay(10);
}

void up() {
    if (angle < 180) {
        angle = angle + 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("up");
    }
}
void down() {
    if (angle > -180) {
        angle = angle - 18;
        spinnything.write(angle);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Current Angle");
        lcd.setCursor(3, 1);
        lcd.print("=");
        lcd.setCursor(5, 1);
        lcd.print(angle);
        Serial.print("down");
    }
}
int reset() {
    angle = 0;
    spinnything.write(angle);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Current Angle");
    lcd.setCursor(3, 1);
    lcd.print("=");
    lcd.setCursor(5, 1);
    lcd.print(angle);
    Serial.print("reset");

}

First of all Servo.write(int) takes a value ranging from 0 to 180 degrees.
Then, servos themselves can only move from 0 to 180 usually. Some can do more, some can do less. But regardless of how much a servo actually moves, you should expect that doing Servo.write(0) the servo would rotate all the way to one side, doing Servo.write(180) it should go to the other side, doing Servo.write(90) it should stay in the middle.
Also, lcd.setCursor(5, 1); is basically useless as the lcd driver itself would advance the cursor as the previous characters are written. Just do lcd.print("= "); if you want an additional space between the equals symbol and the number

Thanks so much Valerio! My project is now working thanks to you. Time to go fire up the 3d printer for a base. :)


text:
Potentiometer with switch wiring question. Not reading correctly
I have a potentiometer with switch, that seems to be working a little wonky (Keep in mind I have tried this with a few different pots and they all behave the same way which leads me to believe I am wiring them wrong).
I can easily hookup the potentiometer and it's three terminals on the side, 1 being ground, 2 being output, 3 being input power. I can monitor it's value on a serial port with Arduino.  However when I try and test the switch, which are two terminals on the bottom of the pot.  I get an on signal when the pot is on, but when it is clicked off I get a random on/off signal.  As in it reads that it is sort of on but never truly reads off.
Right now I am simply giving it 5v from the Arduino to both the switch and the third terminal.  Should I be giving the switch power via a capacitor? Not sure, have not tried that yet but that may smooth out my readings.
Any suggestions?

From your description of switch wiring, it sounds like you have one of the switch leads attached to +5 V and the other switch lead to an input.
As noted in comments and answers to  “Why all unset pins of my Arduino Uno are outputting 2 volts?”, such an input will read high when the switch is closed, and will read randomly when it is open, because an input is a high-impedance device that can accumulate charge:

... input impedance typically can be taken as 100 MΩ for design purposes. ... Each pin has a few pF (5-10?) of capacitance ... which in general is small compared to stray capacitances of attached wiring.
When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin. You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the [voltage] you are seeing.

The easy fix for the problem is to attach one switch-lead to ground, one to an input pin, and initialize the pin with INPUT_PULLUP pinmode instead of just INPUT.

Perfect, that makes sense, I now remember this small detail when learning Arduino a long time ago


text:
Two Identical Potentiometers, two different results
quick question.  I have two 10 turn precision potentiometers and I tested both when I bought them a few weeks ago, both worked as expected.  However now that I have epoxied one of them into my project and wired it up, I don't get any resistance.  I get a max reading all the time regardless of where the dial is set.  So then I pull off the wiring and do the same setup with the other potentiometer and I am still getting expected results.
What could be the reasoning for the sudden difference in readings? Could the first one have gone bad, and if so how often does this happen and how can I avoid it in the future?
Everything falls within recommended specs of the pot and neither has been really used at all.

Could the epoxy have entered the pot?

Multi turn pots range in size from about sugar cube dimensions:

...to weighing a pound or more:

It would be easy to imagine epoxy entering a small plastic multi turn pot and "freezing" the parts within.  If this is what happened, try using a faster curing glue or mount the pot on a Printed Circuit Board (PCB) and glue the PCB.

I suppose it is possible, I will have to remove it and try the working one and see if I cant be more careful in the mounting process.  It is fairly solid and I doubt any epoxy got in it  but you never know.

Trimmers have a really low current rating, so if you hadn't protect it enough, maybe you have broken it. Always remember a pull up resistor of 10k or more.


text:
Common button on two Arduinos and two computers
We have two computers giving two presentations that need to    be triggered in sync. I know how to send the space button via Arduino, but I want to check it will be safe for the computers. If each Arduino is connected to their computer via USB, both data pins togeather and both grounds togeather (not sure if I can find a dt momentarily push button in two days). Is there anything I should keep in mind incase both sides are not at the same voltage as eachother?

As long as you don't have to send anything from the pcs to the arduinos (or at least not with both) you can simply connect the arduinos TX with both pc's RX. This way you need only one arduino. Use series resistors (1k) to handle voltage differences between the pcs.
If you need two arduinos you're fine without galvanic isolation, but I recommend series resistors on the reading gpios as well (just in case you configure the ports as outputs accidentially). In case you use laptops which usually don't have PE, you have to connect the arduinos grounds as well.

The ground of both computers are connected also via their power lines. You get a ground loop that might result in malfunctions and/or defects.
Think about using a galvanically separated connection, for example via an optocouple.

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


text:
Delete line from text file
In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno
Thank you

Is it necessary to re-write the file, or is this a file whose later contents will be read and processed by the Arduino? If the latter, then you can just read and throw away a character at a time until you get to '\n' after you open the file.

Well, in this case, the Arduino is connected to Wifi and serves each produced data point as a .csv to a server. I suppose this counts as "processing by Arduino".
So what you suggest would work. I'm not sure though how one would go about to "throw away a character". Is there a search term for that, so I can check it out? Thanks!

To read the file, you would use fopen() to open it and get a file handle. Then you use fgetc() to read one character at a time and check that character to see if it's '\n'. By "throwing away", I mean that the character you read can just be overwritten by the next one you read -- you don't have to build a string or anything or try to save the character for later in the program.

What you can do is:

opening a file (to read)
opening a new file (to write)
since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
For every character you read:

If Remove is TRUE, don't write to the output file, otherwise write it
If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)

Remove file to read
Rename written file


text:
Arduino IDE libraries search
Where I can do search libraries on WEB, that similar search in IDE? I did not find search page on arduino.cc

The online analog of the Arduino IDE's Library Manager search feature is located here:
https://www.arduinolibraries.info/
That website is generated from the same index file Library Manager uses:
http://downloads.arduino.cc/libraries/library_index.json

You get widest search with Google. Write "arduino" and then the device or topic name.
Most of the libraries have a GitHub repository. You can use a search field on GitHub.
A list of selected libraries sorted by topic is on Arduino playground.

A good way to discover Arduino libraries on GitHub is the arduino-library topic: https://github.com/topics/arduino-library. It only contains repositories where the owner has bothered to add the topic but that's somewhat an indicator of how actively maintained the project is.

You can search the PlatformIO Library Database. It covers libraries for many architectures and platforms, but if you add framework:arduino to the start of your search it narrows it down to just Arduino libraries.
From there you can go to the homepage or repository for a library you want.
It doesn't have all libraries, only the ones that have been set up for PlatformIO support, but that is quite a lot of libraries now.


text:
Arduino MKR1000 as Access Point
I want to turn my Arduino MKR1000 into an Access Point. My code is the following:
#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

WiFiServer server(80);
char ssid[] = "MKR1000";
int status = WL_IDLE_STATUS;

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.print("Creating access point named: ");
  Serial.println(ssid);
  if (WiFi.beginAP(ssid) != WL_CONNECTED) {
    Serial.println("Creating access point failed");
    while (true);
  }
  server.begin();
  printStatus();
}

void loop() {

}

void printStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("To connect, join the network and open a browser to http://");
  Serial.println(ip);
}

After uploading this, in the serial monitor I get this:
Creating access point named: MKR1000
Creating access point failed

I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.Thank you in advance.

Hopefully you mean you want the board to function in AP mode for connected clients to exchange messages specifically with it.  Trying to actually make it a wifi access point in the sense of a wifi router is not a viable idea.

Yeah sorry, that's what I meant.

I found this reference for Wifi.beginAP() in the Wifi101 library, which I hope is the correct one - apologies if it's not.
It says that beginAP() returns either WL_AP_LISTENING or WL_CONNECT_FAILED, so checking for WL_CONNECTED is not sensible.
Try this:
if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
  Serial.println("Creating access point failed");
  while (true);
}


text:
MKR1000 - Connecting to Pubnub
I don't know if it's a stupid question but I need some help.
I am trying to follow this tutorial and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#include "PubNubDefs.h"

class PubNub PubNub;

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.
The PubNub library has an example titled PubNubWifi101 which shows the client type being set with a #define before including the PubNub headers:
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

I don't have a MKR1000 to test with, but I was able to compile the example from the tutorial by adding that single #define after the #include <WiFi101.h>.


text:
A library for manipulate Intel Hex data?
For a project i need to extract some data from an external eeprom and then store it somewhere. Suddenly after some manipulations (not necessarly with Arduino board) i need to put them in an external eeprom.
What I would do is to convert the extracted data from the EEPROM in Intel Hex data and vice versa.
To do this I wanted to know if there is already a library for that purpose "ready to use" made for Arduino boards.
thanks

Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:
#include <EEPROM.h>

void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  for (int addr = 0x0000; addr < 0x0010; addr++)
    {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
    }

}  // end of setup

void loop ()
{
}  // end of loop

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

I have code that uploads and downloads files to the Arduino. Inside that is code to read/write Intel hex format. However it isn't a library.
Inside File_Utils.ino are some comments that show the format:
/*
Line format:

  :nnaaaatt(data)ss

  Where:
  :      = a colon

  (All of below in hex format)

  nn     = length of data part
  aaaa   = address (eg. where to write data)
  tt     = transaction type
           00 = data
           01 = end of file
           02 = extended segment address (changes high-order byte of the address)
           03 = start segment address *
           04 = linear address *
           05 = start linear address *
  (data) = variable length data
  ss     = sumcheck

            * We don't use these

*/

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):
void readFlashContents ()
  {
  if (!haveSDcard)
    {
    Serial.println (F("*** No SD card detected."));
    return;
    }

  progressBarCount = 0;
  pagesize = currentSignature.pageSize;
  pagemask = ~(pagesize - 1);
  oldPage = NO_PAGE;
  byte lastMSBwritten = 0;

  while (true)
    {

    Serial.println ();
    Serial.println (F("Choose file to save as: "));

    getline (name, sizeof name);
    int len = strlen (name);

    if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
      {
      Serial.println (F("File name must end in .HEX"));
      return;
      }

    // if file doesn't exist, proceed
    if (!sd.vwd()->exists (name))
      break;

    Serial.print (F("File "));
    Serial.print (name);
    Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

    if (getYesNo ())
      break;

    }  // end of checking if file exists

  // ensure back in programming mode
  if (!startProgramming ())
    return;

  SdFile myFile;

  // open the file for writing
  if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
    {
    Serial.print (F("Could not open file "));
    Serial.print (name);
    Serial.println (F(" for writing."));
    return;
    }

  byte memBuf [16];
  bool allFF;
  unsigned int i;
  char linebuf [50];
  byte sumCheck;

  Serial.println (F("Copying flash memory to SD card (disk) ..."));

  for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
    {

    unsigned long thisPage = address & pagemask;
    // page changed? show progress
    if (thisPage != oldPage && oldPage != NO_PAGE)
      showProgress ();
    // now this is the current page
    oldPage = thisPage;

    // don't write lines that are all 0xFF
    allFF = true;

    for (i = 0; i < sizeof memBuf; i++)
      {
      memBuf [i] = readFlash (address + i);
      if (memBuf [i] != 0xFF)
        allFF = false;
      }  // end of reading 16 bytes
    if (allFF)
      continue;

    byte MSB = address >> 16;
    if (MSB != lastMSBwritten)
      {
      sumCheck = 2 + 2 + (MSB << 4);
      sumCheck = ~sumCheck + 1;
      // hexExtendedSegmentAddressRecord (02)
      sprintf (linebuf, ":02000002%02X00%02X\r\n", MSB << 4, sumCheck);
      myFile.print (linebuf);
      lastMSBwritten = MSB;
      }  // end if different MSB

    sumCheck = 16 + lowByte (address) + highByte (address);
    sprintf (linebuf, ":10%04X00", (unsigned int) address & 0xFFFF);
    for (i = 0; i < sizeof memBuf; i++)
      {
      sprintf (&linebuf [(i * 2) + 9] , "%02X",  memBuf [i]);
      sumCheck += memBuf [i];
      }  // end of reading 16 bytes

    // 2's complement
    sumCheck = ~sumCheck + 1;
    // append sumcheck
    sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "%02X\r\n",  sumCheck);

    myFile.clearWriteError ();
    myFile.print (linebuf);
    if (myFile.getWriteError ())
       {
       Serial.println ();  // finish off progress bar
       Serial.println (F("Error writing file."));
       myFile.close ();
       return;
       }   // end of an error

    }  // end of reading flash

  Serial.println ();  // finish off progress bar
  myFile.print (":00000001FF\r\n");    // end of file record
  myFile.close ();
  // ensure written to disk
  sd.vwd()->sync ();
  Serial.print (F("File "));
  Serial.print (name);
  Serial.println (F(" saved."));
  }  // end of readFlashContents

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.

But the Intel Hex isn't made for that purpose?

Hex is Hex. Intel Hex is a file format for storing data (in ASCII-HEX) to be loaded to specific addresses. It's a very plain ASCII format and easy to read, write (by humans) and to code for. There really isn't much more to do than skip past an address value and start reading byte data. What might a library to do for you?

avrdude himself is very good at providing/inferring the various formats. We are ourselves manipulating output - EEPROMs, for example - in an external editor.
Of course, avrdude is neither external nor a library, but...

Nick's answer assumes you just want to read/process/write the data from one place to another.  If that's the case, there's no need to store the data into an Intel Hex Data formatted file – just keep it in a flat array, or a file that's formatted conveniently rather than in a form that requires parsing.
Of course, if you actually need the formatted file for some reason – such as an intermediate program only working with Hex files – you could edit the question and say so.
Note,  Python Software Foundation's IntelHex page provides a

Python library to read, write, create from scratch and manipulate data from HEX (also known as Intel HEX) file format.

To use it, you would write a Python program that (on your host computer) reads serial-port data with values to be stored, and uses the IntelHex library to write a Hex file.  After the intermediate program fiddles with the Hex file, another Python program on your host computer uses IntelHex to read the modified Hex file and writes it to EEPROM or to serial for an Arduino to write it to an EEPROM.


text:
Link Arduinos over 5 acre laser tag field
I am building a laser tag system with an Arduino in each gun.
I want the guns to be linked during game play for many different reasons:

Start/Stop game
Nearby teammates
When a flag is captured
etc.

I don't know how to link the guns to one another during game play because the field may be large (e.g. a park). Wifi has too short of a range, cellular would cost, linking to a phone via bluetooth would drain the phone battery (and require each player have a smart phone to play).
Can you think of another way to link the guns? Radio transmitters?
Thanks!

You can use nRF24L01+
The chips offer:

Really high range with power amplifier (1km open field radius (776 acres if I'm right) , but fairly high power consumption 100-150mA @ 3.3V)
High range with PCB antenna (50-80m open field, low power consumption 14mA peak)
Low cost (0.8£-6£ a piece)
Many easy to use libraries available, possible to create a mesh network
High usable voltage range (direct Li-Po for example without step-up)

That's a great idea! Just to clarify, they could transfer custom data packages, like to notify the end of a game? They aren't only used for sending up and down movements to a drone, correct?

Payload and header can be whatever you wish it to be. Check out https://tmrh20.github.io/RF24/ library for more details what the chip can do.

Optionally you could add a single central node. You could place it in a central location. Preferably in a higher location. You could even use a version with an amplifier. That way you get the optimal coverage, even if two players are at opposite ends. To conserve power you could have the player units poll the central node, instead of having to listen all the time, and use power.

So you're saying, place a high powered unit in the central node, and then low powered units in the players guns? Would they have enough range with the low powered? Or is it only the strength/range of the high powered unit that matters in the equation?

@Aaron If the base station beams strong enough and frequent enough it's fairly certain the guns will receive the payload if close enough (1km field, maybe 500m dense forest). (Make it beam at full power, often, to all devices (one pipe, listen to one pipe), no ack and slow transmission speed) It's a matter of testing. Buy a pair. One high powered one and one regular one (make sure it's genuine) and then test the range, make the base beacon transmit as I've told, you can use even multiple and test it.

Perfect! Thanks for your help! This helps a lot!


text:
How do you connect parts once all GPIO ports are used?
I have a rather ambitious project in mind. Lots of buttons, sensors, feedback.
If I run out of GPIO ports to attach stuff to my Arduino, what's next? Do you have to buy a separate Arduino to run the extra parts, and then link the two arduinos somehow?
Thanks for any direction you can give.

There is no one solution.  It depends on what you are connecting.

Yes, it is one possible way, another are using some kind of multiplexing as input shift registers, Charlieplexing http://www.instructables.com/id/Charlieplexing-7-segment-displays/?ALLSTEPS, button matrix http://pcbheaven.com/wikipages/How_Key_Matrices_Works/ or i2C bus, which can connects up to 127 different i2c devices

You can use I2C or SPI port expanders (SPI ones are a bit faster but require more pins). Examples are the MCP23017 (I2C) or MCP23S17 (SPI). Or alternatively you can also add shift registers (chained outputs or inputs with just three pins). Good catch the button (or LED) matrix, and thanks for the Charlieplexing (I always used the usual multiplexing, but this is "smarter")

I2C can't connect 127 different I2C devices - not if you wish to adhere to the standard. You can only officially use addresses 16 to 123, which is 107 devices. The other addresses are reserved for specific uses.


text:
Relational Database for Arduino on SD card?
I have been searching for some sort of library that can create, query, and insert data into a SQLite style database from an Arduino to an SD card.
I have looked at the Arduino Extended Database library. But I don’t think it will quite fill this role.
I don’t need all the features of sql. But a simple query system would go a long way.
Does anyone know of a library like this?

RDBMS generally take lots of memory - the Arduino doesn't have lots of memory, so anything you implemented would be horrendously slow. Better is to use a fixed-format binary record based system. Record location = record size * record number.

can you use wifi to push the data to a "real db"?

I agree with the two above, if you are looking for a DB on an Arduino you have the wrong hardware solution.  If Wifi is not an option could you use Serial or I2C to connect to a Pi and use the PI as a database server?  Another option might be an ESP32, but I don't know if there are any DB libraries out there for it.

Alright, no worries. This is good to know. At least I know why this doesn't exist. It's mostly memory constraints. Thanks for the advice!


text:
How to Determine Fuse Settings
I bought an arduino compatible board here: http://unsigned.io/projects/micromodem/
and am trying to flash new supported firmware onto it. The only instructions given to flash the board is to use the command avrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -F -U flash:w:YourFirmwareFile.hex .
I'm trying to follow the tutorial here using an Uno as a programmer: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader#uploading-code---hard-way but I don't know what to use for the fuse settings. I've tried a few different fuse settings such as the one for the Uno, and default 328p ones using a fuse calculator but it seems like they all have unpredictable results. Some fuse settings make it so that I can't connect  to the COM port at all to monitor the traffic, and others let me connect, but send a message of . I'm expecting an introduction message from the firmware that is supposed to be built in.
Thanks for the help.

Hi, I like to use a gui front for avrdude called avrdudess it might help you read the fuse settings from your modem board. Also remember that fuses are inverted, meaning a 0 means activated.

Hey, thanks for the response. I'll definitely check this out as it seems easier, but I'm trying to figure out what settings to use that would work my with the new firmware. I don't think reading the current fuse settings off of the board would help very much unless I had a working one already. Unless I'm understanding what you're saying incorrectly.

Ok, what do you want your fuse settings to do? Are you using a crystal? Do you need power brownout? Do you want to lock your chip from ever being programmed again. There is many settings in the fuses that can mess things up so please tell us what you want and why, and we'll try to help.

I don't really have any information other than the board and the specs of the board. I would like to load a different MicroAPRS firmware than the current one that is on the board and listed on the same project link above. To load that firmware I was trying to find the appropriate fuse settings so that I could get information from the serial port, as well as load my own programs on the board.

Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of
lowfuse=0xff
highfuse=0xde
extendedfuse=0x05
Serial should work fine.

I tried using those fuses. Here is a link to the pictures of what I am trying and the result is the serial port is always busy.
https://imgur.com/a/dU71h
I changed the baud rate that was given for flashing the modem (115200) to (19200) because every time I used 115200 I would get an Out of Sync() error and it wouldn't do anything.

Not sure if you can change fuse settings by serial programming...


text:
How do I use lambda functions in Arduino?
I want to pass a lambda function as an argument to a method. Example:
T reduce(const T initial, const std::function<T(T, T)> acc) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }

    return value;
}

...

int sum = this->reduce(42, [](int acc, int value) { return acc + value; });

If I try to compile this code for Arduino, I get an obvious error:

error: 'function' in namespace 'std' does not name a template type

How can I use a lambda function in Arduino?

std::function is not supported by the Arduino environment.
(Edit: as mentioned by KIIV in a comment, it's supported on ARM
targets, but not on AVR.) You can, however, pass a non-capturing lambda
to a function that expects a plain function pointer. For example, given
T reduce(const T initial, T (*acc)(T, T)) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }
    return value;
}

You can call it as
int sum = test.reduce(42, [](int acc, int value){ return acc + value; });

If you want your lambda to capture something, it would seem you are out
of luck...

Not completely true. It's not supported by avr-g++ compiler. However compilers for ARM based arduinos usually have full support of STL libraries including std::function

@KIIV: thanks for the heads up. I edited the answer.

You can emulate a closure by an instance of a helper class that stores the captured values and implements the function. I didn't try it, but I expect it to work even for AVRs.

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


text:
How do I provide a negative current?
I'm trying to use an ATMega328 board to control a board of a broken UPS device. I replaced all the internals of the UPS by custom components, so the only things which remain are the chassis and the front board.
On this board, there are five buttons, and three LEDs.

All those components are connected to the ground, each one through its own resistor. By connecting the different pins to the ground and to analog pins of the ATMega328 board, I can successfully detect when the buttons are pressed.

Things, however, get tricky when I want to turn the LEDs on. They have their anode connected to the ground (through a 47Ω resistor), and their cathode connected to a dedicated pin. This means that if I apply voltage to this pin, the LED remains off.
The LED, however, turns on if I connect the ground to a 5V pin on ATMega328 board and the cathode pin to the ground of the ATMega328 board. However, connecting the ground to 5V makes it impossible to read the state of the buttons (or should I wire them somehow specifically?)
Therefore, how do I feed negative current from the ATMega328 board?
There is a similar question on this subject, but while the author wants to “understand the underlying electronics of the arduino and microcontrollers in general,” I, instead, just want to know how to make it work. Reading the answers from the linked question, I have an impression that this is possible, but they don't explain how to do it.

what is negative current?

you may have mixed up the 5V and GND connections .... the buttons probably have pullup resistors, not pulldown  resistors ..... same with the LEDs

If the LEDs turn on when you apply 5V to ground then what you have identified as GND on the board is actually VCC.
There is no such thing as negative current: current is either sourced or sinked, depending if it’s exiting or entering into a node.
The diodes (LED) are one way valves, so you have a clear current direction: once that is established, identifying a button press can work either triggering when it gets LOW or when it gets HIGH, in other words that can be easily reversed.
If previously you where detecting a button press with digitalRead(BTN_PIN) == HIGH then just switch to digitalRead(BTN_PIN) == LOW and you have your solution.

The answer by Roberto Lo Giacco was helpful, but I still had hard time understanding what is happening and how should I wire the boards properly. Since others may encounter similar problems, I'll explain the solution in my own words.
Note that an answer to a similar question helped me as well.

When a digital pin is set to high with digitalWrite(LED_PIN, HIGH);, it's similar (probably not in electrical terms, but at least in terms of interface) to connecting to 5V what was previously connected to the pin.
Similarly, digitalWrite(LED_PIN, LOW); is similar to connecting to GND what was previously connected to the pin.
This means that when the LED is connected as usual, cathode to the GND and anode (through a resistor) to a digital pin:

digitalWrite(LED_PIN, HIGH); turns the LED on, and:
digitalWrite(LED_PIN, LOW); turns it off.

Now, if the cathode is connected to the digital pin, the anode (through a resistor) can be connected to 5V. In this situation:

digitalWrite(LED_PIN, HIGH); turns the LED off.
digitalWrite(LED_PIN, LOW); turns it on.

On the photo in my question, the black wire is connected to GND. Instead, it should be connected to 5V. Other wires remain unchanged.
When it comes to the buttons, in order to determine whether the button is pressed or not, I was doing this:
if (analogRead(ESC_PIN) == 0) {
    // The ESC button is pressed.
}

When the button wasn't pressed, the values from analogRead were quite random, ranging from 50 to 250, or something like that. A zero value would indicate that the button was pressed.
With the new wiring (5V instead of GND), the new values from analogRead range from 350 to 900 when the button is not pressed. When the button is down, the value becomes 1023. Therefore, the new condition is simply:
if (analogRead(ESC_PIN) == 1023) {
    // The ESC button is pressed.
}

Why using analogRead instead of digitalRead?!? Please consider analog sampling is a lot slower than reading a digital value... You said there are resistors connected to the buttons: those resistors should act as pull-down, forcing the non-pressed buttons to GND so that when you press the button the voltage jumps to 5V while the resistor limits the current flowing.

@RobertoLoGiacco: because digitalRead always returns 1, independently of whether the button is pressed or not.

Then the part in the question where you state all those components are “connected to ground with their own resistor” was wrong: there are no resistors in series with the buttons.

Interesting. I found that they have each a resistor by testing the board with a multimeter, but given my low experience with electricity, I may have made a mistake. I was also under impression that if I don't use a resistor, I'll burn the board if I set pinMode to INPUT instead of INPUT_PULLUP. I'm happy this impression is wrong (since the board is still alive).


text:
Where do I find the enclosures for an Arduino and a bunch of sensors?
I recently started playing with Arduino in order to do several projects, including:

A system which will measure some characteristics of the indoor air and could alert me if something goes wrong (for instance if the percentage of CH4 goes beyond a threshold).
A system I can bring with me on a walk which will measure the pollution and other characteristics of the air outdoors.

While the quantity and the diversity of the sensors for such projects, as well as the ease of use is mind blowing, I'm blocked at one aspect: the casing. Both of the projects require to put the electronics within a plastic case with:

Enough space for not only Arduino, but also the sensors. Some, such as MQ2/MQ5, can be quite large.
Holes for air flow, which are large enough to let small particles, but small enough to keep insects and large dust out of the electronics.
A hole for an USB cable and possibly a hole for the LED.

Unfortunately, the popular sites selling Arduino-related stuff have practically nothing when it comes to the cases. In most cases, the choice is limited to (1) the enclosures for Arduino itself (or other boards), with no holes in them and (2) the multicolored modular systems which look like LEGO bricks.
Outside Arduino-related sites, the only idea I have is to buy somewhere an old smoke detector, throw away the electronics and put Arduino and the sensors inside. For now, most smoke detectors I've seen seem too small for the task, and have to be modified in order to accommodate the USB cable.
Am I missing something? How other people do when they need an enclosure which fits Arduino and sensors and doesn't look geeky?

https://www.shapeways.com/

@IgnacioVazquez-Abrams: I may be wrong, but I suppose that custom-made enclosures would be either expensive, or their quality would be too low (just like with 3D printers).

you can gets lots of them on thingiverse, for not just the boards, but even several permutations of popular modules and boards. if you don't have a 3D printer, you can order the parts from an online printer or find a local fab lab that will let you print for a small donation or fee. I've also taken to small cheap wooden boxes from ebay:  biodegradable, easy to work with a dremel, and under $3usd delivered.

I think your problem is that you are looking specifically for Arduino enclosures. Such a search tends to lead you to boxes for just an Arduino and nothing else - maybe with the headers poking out the top.
Instead, you should be looking more generically. There are thousands and thousands of "project enclosures" from many manufacturers (Hammond is a big name in these).
You take a generic project box of the right size and shape for what you want to create and in a material suitable for your needs, and cut / grind / drill / glue it to be what you want.
Most electronics suppliers will have an "Enclosures and Housings" section on their website. Have a browse through your favourite.
As far as air vents go, one good trick I have used is to simply drill holes (with a steady hand so you get them lined up nice and straight) and glue some fine mesh on the inside.  One good source of fine mesh is to go to your local smoking supplies reseller (tobacconist) and buy some "pipe meshes" (the flat ones, not bowl shaped ones) - also available from low-cost online resellers of any old junk (eBay, etc), which look like this:

(Also available in brass).  They typically come in different mesh sizes to suit your needs.

for many projects i use distribution box like this one:

I just came across your question, and I think this may be useful if you're still interested in project enclosures. I've designed and created stackable, modular and extensible enclosures for Arduino (fits Uno and Mega footprints), Raspberry Pi (three different versions, for A+, B+/4B and Zero (can accommodate up to 4 Zeros), and Breadboard and breadboard-friendly MCUs. All of these enclosures have 4"x2.4"x1.2"(h) space on the inside, enough for one or two shields or hats. They also come with replaceable sides/tops that can allow you to add sensors and peripherals, like a Pi Camera, High Quality Camera, Tripod mount, Ultrasonic sensors (HC-SR04), momentary push button switches, RS232 ports and more. The enclosure is made of acrylic with 6 separate flat pieces, so that means you can also hack it to easily add holes and mounts to customize it yourself.
You can find more details on https://www.protostax.com/
Hope you find it helpful! Let me know if you have any questions.
Cheers, and Happy Making!
Sridhar Rajagopal

Look into "Really Useful Boxes", found online, or at stores like Office Depot.  Lot of sizes available, pretty easy to mount cards & connectors into.
I have several projects lower down on this page where you can see how I used them.


text:
What's wrong with the ACS712 sensor?
I have two ACS712 sensors, one rated for 5A, another—for 20A.
I wanted to test how precise they are, and played with different devices (in my case, old PC fans). I copy-pasted the source code from here, and changed only the Vref value as expected, so that I get a measurement of zero when there is no current. I double-checked, the value remains zero for both ACS712 sensors. The sensor (or the multimeter) is connected in series. Only one sensor (or multimeter) is connected at the same time.
Here's the data I get. Values in parenthesis correspond to the percentage of the value compared to the one got with a multimeter.

Setup
Measured bya multimeter
Measured byACS712 5A
Measured byACS712 20A

Old CPU fan
87 mA
73 mA (84%)
49 mA (56%)

UPS fan rated 1.9 W
174 mA
170 mA (97%)
97 mA (55%)

Two fans together
0.25 A
244 mA (98%)
146 mA (55%)

Server fan rated at 0.6 A
0.49 A
463 mA (95%)
268 mA (55%)

Three server fans
1.35 A
1,293 mA (96%)
683 mA (51%)

While the 5A variant seems to be slightly off (another possibility would be that the multimeter is off and the ACS712 measurements are exact), things are very different for the 20A-rated counterpart: its values are wrong initially, and for higher current, they are getting wronger.
Why is it so? Is it broken, or have I missed something?

nothing's wrong with it. Those values actually look very consistent, just double them for better accuracy. Remember that your 20A one can only sense to the nearest 40ma value (20A / 512 levels) where there is no error whatsoever (0LSBs), which is why they are about useless for hobby applications.

Your problem is that you are trying to measure motes of dust with a yard stick. The yard stick is great at measuring things in inches and feet, but when you want to find the size of something that's around 1mm in size all you can say is "it's less than an inch" or "smaller than an eighth of an inch".
You have to remember that a 20A sensor has to fit that whole range of 0-20A - that's 0-20,000mA into half the range of the ADC. That's at most 512 graduations on an Arduino, and since you can usually count on "±1 LSB quantisation noise" you really only get half that as a usable value. So you're looking at a resolution of about 40mA at best with an accuracy of  ±40mA. When you want to measure small currents they're just going to get lost in the lack of resolution. At 100mA you're still only in the range of just "There might be a current there, somewhere".
For measuring current you need to size your sensor / shunt appropriately to the range of the currents you're sensing. If you're working with small variations in a large DC current then pre-conditioning the sensing to change the offset and amplify the interesting part of the signal is required, so that the signal isn't swamped by the underlying offset. If you're working with small currents then you require a sensor / shunt that gives you an appropriate signal for that current range.
Additionally, different variants of the sensor have different sensitivity: 185 mV/A for the 5A model, and 100 mV/A for the 20A model. The code you are using doesn't take this in account. Using the correct sensitivity, the last value in your table, 683 mA, becomes 1,264 mA (683×185/100=1264). This is close enough, if you consider the ±40mA accuracy.


text:
What happens, memory-wise, when I call a function from another function?
I'm inspecting where the memory is used in an application which runs on Arduino. To my surprise, there are several locations where 100 to 200 bytes are consumed by simply calling a function. Example:
void Dispatcher::processCommand() {
    ...
    displayMemory();
    this->process(this->instruction);
}

void Dispatcher::process(const Instruction &instruction) {
    displayMemory();
    if (instruction.length > 0) {
        ...
        return;
    }

    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);
}

The first call to displayMemory() will report that there is 351 bytes left. The second one will tell that only 159 bytes remain (that is, 192 bytes less).
If I alter the body of the process function, the difference between the two memory reports vary. For instance, if I remove the two last lines, the difference drops from 192 bytes to 12 bytes.
I don't understand why this happens. I was thinking that between the moment I'm ready to call a function and a moment when the function starts, the memory should be used exclusively by the additional element in the call stack (the aforementioned 12 bytes maybe?) and the copying of the parameters passed by value (none here). Why is this not the case? What really happens under the hood?

The clue is in those last two lines:
    ErrorResponse::componentNotFound(instruction).output(this->serial);
    TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Let's tear them apart and see what they actually do.
ErrorResponse::componentNotFound(instruction).output(this->serial);

Call the static function componentNotFound with your instruction, then take the object that is returned, and call the output() method on it passing this->serial as a parameter.
The hint there is take the object that is returned.
componentNotFound() returns an object. That object has to be stored somewhere. That "somewhere" is on the stack.  And stack space is allocated during the function preamble.  That's the bit of code that runs at the start of the function allocating stack, pushing registers to the stack, etc.
The same happens in the second line:
TerminationResponse(instruction.commandId, 0xFF).output(this->serial);

Create a new TerminationResponse object and call the output method.
All that goes on the stack.
It's not the calling of the function that is using the memory, it's what the function is doing that is using the memory.

A function's data-memory space is reserved on the stack when the function is called, and returned when the function returns. If that function1 calls another, function2, then function1's space remains on the stack and more space is reserved for function2 for the duration of its execution. When function2 returns to function1, function2's memory is released, and finally, when function1 returns, its memory is released.
Now in a little more detail:
When you call function1, the arguments you pass it are put on the stack. When control actually passes to function1, the instruction address following the call, where function1 should eventually return to, is put on the stack. If function1 needs data temporary data space (automatic variables), space for those is put on the stack. (Ditto for function2, if one is called from function 1; and so on.)
When each of those functions returns, their automatic data space (just the space, not the data!) and the return address are removed from the stack; the caller removes the space for the arguments it had pushed, and execution resumes immediately following the call.
The difference in usage you're seeing depending on the presence or absence of the last two lines of Dispatcher::process(), is the memory (arguments+return address+automatic data) used by those two functions.


text:
How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?
I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.
Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.
Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?

You may have the most luck by ignoring the "arduino" and shield aspect aspect and looking for resources for the ATmega, and for whichever Ethernet IC/module is being used by that shield.

Just take a look at the source code. But I have to say that your assignments sounds like a ridiculous amount for work.

Are you allowed to use the built-in Arduino.h functions like digitalWrite()?

For serial and spi read the documentation for the atmega328p for whatever ethernet chip in use, it's datasheet. Might be alot to read but should give you a clue how it's supposed to work.

Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries - you aren't allowed to use C++?

C++ is fairly controversial in small embedded systems, so it should not be the least bit surprising if an academic assignment mandates traditional C, especially in a setting where the goal seems to be really understanding how things work in detail.

Are you allowed to use the avr-libc? If so, the doc on stdio.h has a simple example on setting up stdout in order to printf() to the serial port. It's really basic, and lacks the ring buffer, but it can get you started.

As Hans Neve wrote, you should really refer to the docs.
This is how it works in real life, when you want to write a driver for a new piece of HW.
You have to at least understand the block diagram, programming models and register sets of the device you want to control.
Then read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.
As generic programming advice goes:

avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.

SPI is pretty trivial (see the existing SPI library). Serial is easy enough. As for the Ethernet shield you would need to look at either the existing library or the manufacturer's datasheet. Some Ethernet chips are much easier to work with than others.

If you look at the datasheet for the Atmega328P (as used in the Uno) they have example code (in C) for SPI - along with comments. That should let you knock off the SPI part in an hour.
They also have example code for serial. Add in a ring buffer and you should be able to get serial going in half a day.
After all, the assignment doesn't tell you to not use the datasheet.
Depending on the Ethernet chip, you should be able to dig up (possibly in the chip datasheet) example code for that as well.

You could always use existing libraries (eg. Serial.print) for debugging, and then pull that code out once you are happy your own code works.


text:
User input for utility program
I am writing a utility program to test relay boards. I'd like to be able to accept a user input of the number of relays on the board. Is this doable via the serial monitor since when I'm testing boards I'm generally doing it at my desk with my testing Arduino attached to my laptop? I'd prefer not to go the LCD and keypad route.
Is there an accepted practice for doing this?

Yes, it is perfectly do-able through the serial monitor.  However the serial monitor is very very basic and you will be able to create a much better user experience using a proper serial terminal emulator (such as TeraTerm, Putty, etc) and using ANSI control codes to lay the screen out as a proper text-based application.
A useful resource is on Wikipedia: https://en.wikipedia.org/wiki/ANSI_escape_code
I have a little library that I started a while back and never finished that performs two basic ANSI control sequences - clear screen and set cursor. You can look at it to see how to perform ANSI control codes: https://github.com/MajenkoLibraries/ANSI


text:
Using a 5 pin button with Arduino Correctly
I am trying to build a simple motor test sketch, currently, to test a NEMA 23 stepper motor and the DM542T stepper driver.
Here is the code, and I am having trouble figuring out how to properly wire the 5-lead button (+, -, Common, NO, NC)
Here is the code
// Pin numbers
const int buttonPin = 2;
const int directionPin = 8;
const int stepPin = 9;

// Other constants
const int NumSteps = 5000; // steps
const int Speed = 500;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(directionPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(directionPin, LOW);
  digitalWrite(stepPin, LOW);
}

void loop() {
  if (digitalRead(buttonPin)) {
    // Move in one direction
    for (int distance = 0; distance < NumSteps; distance++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(Speed);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(Speed);
    }
   // Reverse direction
   digitalWrite(directionPin, !digitalRead(directionPin));
 }
  delay(5);
}

The button is a momentary button, so I am holding it in to simulate a latching button.
I have the buttons Common and Neg leads wired together, and connected to the Gnd pin on the Arduino (mega rev3)
I have the buttons Positive and the NC wired together and connected to pin 2.
Wiring that button in that manner, works fine in the button-controlled blink sketch, but is not working here (LED on the button doesn't light up and the motor test doesn't run).
Note: I am using a 5 lead momentary button as that what the project these motors will be for will be using.
Any help appreciated.

Can you link to the buttons product page or datasheet? A simple button with 5 pins is not very common, so it is important how the button is  using the pins.

There is no datasheet for it. It is a standard 5 lead LED button with +,-,common,NC,NO. It worked fine when wired for the button controlled blink sketch with NO not connected, NC and + wired together to 5V and Common and - wired together to Gnd. The led on the button lights up and the led on the Mega lights up when you press the button

Oh, haven't seen, that it is an LED button. Can you please make a diagram which connections you really have? It is difficult to interpret with the text (and you have different wirings in the question and your comment). You can also use the builtin schematic editor of the question editor. Use a normal switch and an LED to simulate your 5 pin switch

first thought, do not connect the LED to the switch .... second thought, if the button works in a blink sketch, then use the working switch code in the motor sketch

You don't need a sketch to control the on-board LED. Just wire the + to 5V and the - to Gnd and the button will turn the on-board LED on/off. If it's an LED halo or lighted button combine the NO and + to 5V and the common and - to Gnd.

The button's pins are as follows:

+: The LED's anode
-: The LED's cathode
C: The common pin of the switch
NC: Normally Closed - is normally connected to the C pin until the button is pressed
NO: Normally Open - is connected to the C pin when you press the button

So to use the button as a button the two pins you care about are C and NO. Use those pins (in any order) as you would any normal button with a pullup resistor (or the internal INPUT_PULLUP resistor).
To use the LED can be a little more tricky. Most of this style of button have the LED set up for 12V usage. While you may get a slight glow from it from 5V you would probably need to switch it with a transistor and power it from 12V to get it to light up properly. However your button may be rated differently and need a different voltage.

So, in this case which would you use as the signal and send to pin 2, the NO wire or the common? The other would go to Gnd I believe.

@dinotom It really doesn't matter. They are just lumps of metal that touch when you press the button, and since you're not using the NC pin which is which for C and NO makes absolutely no difference.

Yep, used the NO to pin 2 and the C to Gnd, serial monitor shows it changing. Onto the next problem, the button isn't turning the motors on. Connecting pos to 5V and Neg to Gnd does get the light on the button to flicker, weird it works as described before. Ill post a different question later if I can't figure that one out myself. Motors first.


text:
Reading data from potentiometer with MISO and MOSI on same pin
I am working with the MCP4131 Digital Potentiometer and I am running into some trouble. The MISO and MOSI functionalities are multiplexed onto the same pin. Obviously, this means that I have to have Pin 13 and 12 hooked into the same pin on the chip.
I want to read send a READ command to the chip so that I can get the current value of the POT; however, when I send the lower byte in order to retrieve the value, I simply am getting back whatever I send because pins 13 and 12 are hooked into the same spot.
Is there any examples on how to work with a module such as the MCP4131 where the MISO and MOSI are on the same pin? Thank you!

I’d not use the SPI bus for this but use the (bitbanged) Arduino function shiftOut and shiftIn.

You need to do a little conversion:

Connect the SDI/SDO line to MISO on the Arduino.
Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.
Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).

Awesome I will give this a try later!

The solution worked, while digging through the datasheet I found this page SPI Examples . I followed this and it worked perfectly!


text:
Can a cheap RF module be used for two way communication
Can a cheap RF(transmitter and receiver) module be used for two way communication, not at the same time of course but for example arduino A sends string to be printed on lcd the arduino B receives it and prints it on lcd, then after some time arduino B sends a temperature data back to arduino A, then arduino prints the temperature data on the serial monitor. All of this while arduino A is connected to a transmitter and arduino B is connected a receiver.

Yes you can, but you'd need both modules on both Arduinos. So two sending modules, and two receiving modules.

Each device that will ever transmit anything will need a transmitter. Each device that will ever receive anything, needs a receiver. The devices you show in your question are separate receivers and transmitters, so on Arduino A and Arduino B, you will need both a receiver and a transmitter in order to have real, two-way communication between them.
Some RF devices are "Transceivers" which have both a receiver and a transmitter in the same module. Some of these can operate "full-duplex", meaning they can receive at the same time they are transmitting other data (Typically each direction is on a different frequency, but not necessarily.) Most cheap ones are half-duplex, meaning the module can only receive or transmit at any one time.
ADDITIONAL INFORMATION ABOUT RADIOHEAD
Your comment mentioned the RadioHead library. I was able to find the documentation on the library and see that it supports a wide range of radio chipsets and modules. The cheap ones you note are simple ones that use OOK (on-off-keying) or ASK (amplitude-shift-keying) and don't actually have a protocol. The receiver simply provide a HIGH or LOW output if it detects a signal on it's designated receive frequency. The transmitter simply oscillates at the transmit frequency when it's input pin sees a HIGH value, and stops when it sees a LOW value.
The RadioHead RH_ASK class deals with these simple transmitters. The documentation is at http://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html#details
This page notes the way to connect both a transmitter and receiver thus:
Connecting to Arduino

Most transmitters can be connected to Arduino like this:

Arduino                         Transmitter
 GND------------------------------GND
 D12------------------------------Data
 5V-------------------------------VCC

Most receivers can be connected to Arduino like this:

Arduino                         Receiver
 GND------------------------------GND
 D11------------------------------Data
 5V-------------------------------VCC
                                  SHUT (not connected)
                                  WAKEB (not connected)
                                  GND |
                                  ANT |- connect to your antenna syetem

i have searched everywhere for a diagram of some sort of how to connect both transmitter and receiver to one arduino, i cant find any, do you have some advise? i am asking this because the "RadioHead" library expects data from pin 12, and i don't know if any other pin would work? thanks.

This sounds different enough to become a new question itself. That is, the RadioHead library and dealing with separate transmitter and receiver modules.

Sure it can.  A transmitter is only a transmitter while it's actively transmitting.  And you can have as many receivers as you like.

wait... so does this mean when a receiver is not receiving it can transmit? and when a transmitter is not transmitting it can receive?

No, it means you can have two people in a room. Each has a mouth, and each has ears. Only one should talk at once, but both people's ears are working all the time. The person talking knows he's talking though so ignores whatever comes in through his ears.

not those ones, those look to be separate transmitter and receiver modules.  But something like the nrf24 is a transceiver, meaning it can do both   like this   https://www.amazon.com/dp/B00O9O868G/ref=sspa_dk_detail_1?psc=1

I'll second Chad G's recommendation of the NRF24L01 unit, cheep/readily available(Ebay) and very effective. I am using these to remote control my projects, range depends on who you talk to but have seen statements ranging from 100 to 1000mts. This item is well supported in the Arduino community.


text:
Connecting and using ESP8266 wifi
My ESP8266 has stopped working.
The red power light comes on and the blue TX light is on solid.
Here's what I did.
Connecting
ESP8266  -> Arduino nano
VCC, CH_PD, RST  -> 5V (external supply)
TX -> TX
RX -> RX
I could send AT commands via the serial monitor.
Then I connected
RX -> 11
TX -> 10
and set up software serial intending to repeat the experiment.
I was getting garbage characters in the response, and found that I had to esp8266.println("AT+IPR=9600"); to reduce the baud rate.
Then the blue TX light cam on permanently and it's stopped working at all.

Reflash the firmware. That fixes most issues.

It's looking that way.
Do you know of a good guide on reflashing via arduino?

Serial devices should be connected RX to TX and TX to RX.
When you connected the RX to RX you connected the esp8266 to USB chip on Nano. Because the USB chip is connected to Atmega on Nano RX to TX, so if you connect the esp8266 to the same line, the it is connected RX to TX to USB.
On this picture esp8266 is connected to Atmega and not accessible from USB:

Communication from Serial Monitor over USB to esp8266 on pins 10 and 11 of the Atmega could work only with SerialPassthrough sketch resending data between Serial and SoftwareSerial on pins 10 and 11.


text:
Send AT commands to ESP8266 from Arduino Nano serial monitor
I have an Arduino nano and an ESP8266-01.
The first thing to do seems to be to send AT commands via the serial monitor and see the replies.
ESP connect as follows:
  GND   GND
  GPIO2 not connected
  GPIO0 not connected
  RX    to Arduino RX via level shifter
  TX    to Arduino TX via level shifter
  CHPD  3.3V
  RST   3.3V
  VCC   3.3V

Image of breadboard (imgur rejects)
https://www.dropbox.com/s/aif8afi29amy02h/20180807_135218.jpg?dl=0
When connecting the red light comes on and the blue light flashes quickly (and the Arduino RX light flashes with it) then goes out.
Here is the sketch I'm using. (The ESP8266 must be disconnected from RX+TX for uploading of the sketch to work.)
     void setup() {
  Serial.begin(115200);

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(250);
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
 }

(I like to blink the LED to demonstrate that uploading worked.)
With the serial monitor set to 115200 (NL&CR) I sent AT and nothing happens.
What have I got wrong? I really don't understand! Thanks in advance for any suggestions.
(This is actually my third ESP8266. The first worked fine on 5V but stopped working after I set the baud rate to 9600. I presume 5V killed it but it's strange that it worked for so long. The second, connected as above, when powered up made that power supply red hot and melted the jumpers.)

First problem is that io 0 of the esp8266 must be pulled HIGH for normal boot. With io 0 not HIGH, the esp8266 starts in flashing mode.
Your other problem is the reset pin connection. It must be connected with pull-up resistor or not connected.
See ESP8266 Hardware Design Guidelines

Pin32 serves as an RST pin which can be left floating when it is not
  used. The reset pin is held low when the chip is enabled. In order to
  avoid resets caused by external interference, the lead is generally
  required to be short, and no external pull-up resistor is necessary

I suspect that "The reset pin is held low when the chip is enabled." is a bad translation. They say in pin description "32 EXT_RSTB I External reset signal (Low voltage level: Active)". What they mean is that the chip resets when reset pin is set LOW.

Disconnecting it hasn't made any difference.

remove the level shifter from esp8266 TX pin

With TX connected directly to Arduino TX: no change except that the ESP8266 blue light does not now flash when powering it on.

important! set io0 of esp8266 HIGH with a pullup resistor

Put GPIO0 via 3k3 to 3.3V and still nothing.

remove Serial.begin from Nano sketch or better put Nano in permanent reset connecting reset pin of Nano to ground

Progress!
With Arduino RST connected to GND powering on the ESP produced junk on the terminal.
I then tried all the different baud rates until I found that at 74880.
GPIO0 connected or disconnected makes no difference.
TX via level shifter makes no difference. ESP RST to 3.3V makes no difference.
Still no response from AT.

If I connect EXP TX and TX directly to Arduino TX and TX (resp.) then I get a response from AT but it is junk.
Changed the baud rate to 115200 and AT works with direct connection.
So is my level shifter bust?

the bootllog is printed at 74880 and it contains junk (chinese characters perhaps)

AT works with TX,TX directly connected without Serial.begin.

So:

Connect the ESP8266 RX/TX directly to the Arduino, not via the level shifter.
No need to connect GPIO0.
RST can be either left floating or connected to 3.3V; it makes no difference.
No need to Serial.begin; an empty sketch will work.

This is what you want to see in the terminal:
AT

OK
AT+CWMODE?

+CWMODE:2

OK
AT+CWMODE=1

OK
AT+CWLAP

+CWLAP:(3,"SKY61611",-83,"90:21:06:79:fb:0a",1,110,0)
+CWLAP:(3,"SKY3CA89",-90,"60:38:e0:d4:7d:7d",6,96,0)
+CWLAP:(3,"PLUSNET-TS2H",-75,"a4:08:f5:ae:ab:c2",6,103,0)
+CWLAP:(3,"SKY3CA89",-79,"90:21:06:c6:1f:6d",6,120,0)
+CWLAP:(3,"MY WIFI 6739",-38,"18:e3:bc:2c:67:39",6,127,0)
+CWLAP:(3,"BTHub6-CF7H",-88,"88:a6:c6:27:53:a4",6,108,0)
+CWLAP:(3,"SKY7A62E",-79,"7c:4c:a5:1c:7f:59",11,130,0)
+CWLAP:(4,"EE-mce6kx",-86,"e4:3e:d7:71:35:f3",11,128,0)

OK

The next thing to do is to set the ESP8266's baud rate to 9600 so that it can be used with SoftwareSerial. The command to do this is
AT+UART_DEF=9600,8,1,0,0

Then we can move the ESP8266 off the Arduino's RX/TX pins onto some other pins and forward commands from the terminal to the ESP8266 and print the responses.
#include <SoftwareSerial.h>

#define RX 10
#define TX 11
SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  Serial.println("setup() done");
}

    // Check for messages form the ESP8266 and process them.
void processEsp() {
  while (esp8266.available() > 0) {
    String line = esp8266.readStringUntil('\n');
    processLine(line);
  }
}

void loop() {
  if (Serial.available() > 0)
  {
    String command = Serial.readStringUntil('\n'); // AT+CWLAP
    Serial.println("Command Sent: " + command);
    esp8266.println(command);
  }

  processEsp();
  //Serial.println("...");
  //delay(1000);
  // We wait once.
  // During that wait the buffer fills, and we only see what's in the buffer.
}

void processLine(String line) {
  Serial.println(line);
}

The serial reader must run in a tight loop; a delay causes it's buffer to fill and characters beyond the buffer length are lost. Enabling the delay causes the AT+CWLAP response to be truncated.
There is no way to detect the end of a response to an AT command. The ESP8266 can send anything at any time. What it sends should be processed line by line; the line/record delimiter is \r\n.

the WiFiEsp library has standard Arduino networking API over esp8266 AT commnands. the library can detect the end of the response. (you could al least upvote my answer)


text:
Can send AT+ commands, but can't upload sketch to ESP8266 via Arduino Uno
Connected a generic ESP8266 to an Arduino Uno.
I can send AT commands fine and generate a normal response, but cannot upload sketches to the ESP8266. I have "Generic ESP8266 Module selected as the board. Tried everything e.g. switching Tx and Rx, connecting GPIO0 and GPIO2 to to Vcc or ground, but to no avail.
Arduino IDE spits this out -
esptool v0.4.5 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    stat C:\Users\Michael\AppData\Local\Temp\build7227402767538495982.tmp/wifi_setup.cpp.bin success
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2013 bytes of data
    read 0, requested 1
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed

Not sure, but I think you need to flash the NodeMCU firmware first.

You are going to have to provide a bit more detail on your setup. How do you have the ESP8266 connected to the Arduino? What are you using to program the ESP 8266?  This?

Hi @user2277005 ! did you manage to solve this problem? All the solutions here don't work

You mention:

connecting GPIO0 and GPIO2 to to Vcc or ground

I've had success with this sequence:

GPIO0 to gnd (and hold momentarily)
RST to gnd (then let go, while holding GPIO0 to gnd)
let go of GPIO0 from gnd (e.g. let it float again)

To do a firmware flashing, you need to hold GPIO0 to ground for the duration of the flashing process, so the sequence would be slightly different.
You can do this just prior to "build and upload" in the Arduino IDE—provided the build process doesn't take too long.  It will sometimes still fail, in which case reset the ESP8266 (RST to gnd momentarily) and restart the sequence.
I've found a little test/development harness (like this one http://www.buildcircuit.com.au/esp8266-test-board) is very handy for doing this repeatedly.

Your solution worked for me, when I have this error.   Thanks!

You don't need an Arduino UNO to program the ESP. You just need an USB to UART adapter (CP210x or FTDI one) and the Arduino IDE. Hook the ESP rx and tx to the tx an rx of the adapter and you are ready to go.
Here is an detailed explanation how to program ESP using arduino
If you don't have an USB to UART bridge you can use the Arduino board as bridge: check this

I have been hooking the ESP8266 straight up to my PC and programming it in NodeLua.  Of course it depends on what you want to do, but consider dropping the Arduino and just using the ESP8266.

Alright will give that a go.


text:
Using Processing to send data to Arduino
  import processing.serial.*;
import java.io.*;
Serial myPort;
int mySwitch;
String transmitter[] = new String[1280000]; //initialize array

void setup(){
         mySwitch=1;
         //Open the serial port for communication with the Arduino
         //Make sure the COM port is correct
         myPort = new Serial(this, "COM6", 9600);
         myPort.bufferUntil('\n');
}

void draw() {
        if(mySwitch == 1)
        {
           readData("input.txt");
           int index = 0;
           while(index < 128000)
           {
             myPort.write(transmitter[index++]);
             if(index%128 == 0)
               delay(100);
           }
        }

         mySwitch = 0;
}

void readData(String myFileName){

         File file=new File(myFileName);
         BufferedReader br=null;

         try{
           br=new BufferedReader(new FileReader(file));

           String transmit=null;
           int i = 0;
           /* keep reading each line until you get to the end of the file */
                while((transmit = br.readLine()) != null)
                   transmitter[i++] = transmit;

         }catch(FileNotFoundException e){ e.printStackTrace(); }

         catch(IOException e){ e.printStackTrace(); }

         finally{
                 try {
                   if (br != null) br.close();
                 }
                 catch (IOException e) { e.printStackTrace(); }
         }
}

In the above code, I have an String array and I'm reading lines from a file and saving them as strings. How would I save them as byte/char inside an array of byte/char?
Basically, I have a file of integers on each line, each integer in the range [0, 255]. And I want to read this integer and send it to the Arduino. The Arduino serial.read() function reads a byte at a time. This is the issue I am trying to solve.

Hi, please could you give us an idea of what you have tried or written and what your results have been so far.

Well I am writing each index in my transmitter array and each index holds a "String" value. Thus, serial.write() will write a string to the serial port. However, I want it to write it as an integer for the purposes of speed and efficiency.

how are your values arranged on each line of the file?

just a number in the range of [0, 255] on each line. No other splits such as comma, etc.

I believe I have actually found a very efficient solution to this problem by re-writing the code the following way by using the "Scanner" class and not the "BufferedReader" class. Any input on making this more efficient is welcome!
import processing.serial.*;
import java.io.*;
import java.util.*;
Serial myPort;
int mySwitch;
Scanner file;
byte transmitter[] = new byte[1280000]; //initialize array

void setup(){
    mySwitch=1;
    //Open the serial port for communication with the Arduino
    //Make sure the COM port is correct
    myPort = new Serial(this, "COM6", 9600);
    myPort.bufferUntil('\n');
}

void draw() {
    if(mySwitch == 1)
    {
        readData("input.txt");
        int index = 0;
        while(index < 128000)
        {
            myPort.write(transmitter[index++]);
            if(index%128 == 0)
                delay(100);
        }
    }

    mySwitch = 0;
}

void readData(String myFileName){
    try{
      file = new Scanner(new File(myFileName));
    }
    catch(Exception e){System.out.println("NOT FOUND!");}

    int i = 0;
    while(file.hasNextByte())
      transmitter[i++] = file.nextByte();

    file.close();
}


text:
5pt font for Neopixel shield
I have a 5x8 Neopixel shield for my Arduino. I want to display text on it, while it is in "landscape mode", i.e. a only 5pt high text. The default font that is used by the printcommand is 8pt high. How can I load a font with 5pt height into my code?
I understand that the Neopixel library depends on Adafruit GFX, which allows for different fonts. But changing the font according to the Adafruit tutorial on GFX to one of the supplied fonts does not return any readable text (only a moving line of dots). I found this font converter and used it to produce a 5pt font, but again only a moving dot appears.
This is my code (basically the Neomatrix example with modified orientation of the matrix):
// Adafruit_NeoMatrix example for single NeoPixel Shield.
// Scrolls 'Howdy' across the matrix in a portrait (vertical) orientation.

#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>
#include <Fonts/Dialog_plain_5.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

#define PIN 6

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(8, 5, PIN,
  NEO_MATRIX_TOP     + NEO_MATRIX_LEFT+
  NEO_MATRIX_ROWS + NEO_MATRIX_PROGRESSIVE,
  NEO_GRBW  + NEO_KHZ800);

const uint16_t colors[] = {
  matrix.Color(255, 0, 0), matrix.Color(0, 255, 0), matrix.Color(0, 0, 255) };

void setup() {
  matrix.setFont(&Dialog_plain_5);
  matrix.begin();
  matrix.setTextWrap(false);
  matrix.setBrightness(30);
  matrix.setTextColor(colors[0]);
}

int x    = matrix.width();
int pass = 0;

void loop() {
  matrix.fillScreen(0);
  matrix.setCursor(x, 0);
  matrix.print(F("Howdy"));
  if(--x < -36) {
    x = matrix.width();
    if(++pass >= 3) pass = 0;
    matrix.setTextColor(colors[pass]);
  }
  matrix.show();
  delay(100);
}

and this is the content of the font file:
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
const uint8_t Dialog_plain_5Bitmaps[] PROGMEM = {

    // Bitmap Data:
    0x00, // ' '
    0xF0, // '!'
    0xC0, // '"'
    0x07,0xF2, // '#'
    0x79,0xF4, // '$'
    0xD1,0x10,0xB0, // '%'
    0x88,0xCA, // '&'
    0x80, // '''
    0x2A,0x00, // '('
    0x15,0x00, // ')'
    0x08,0x00, // '*'
    0x01,0x1C,0x40, // '+'
    0x00, // ','
    0xC0, // '-'
    0x00, // '.'
    0x6A,0x00, // '/'
    0xD6,0xE0, // '0'
    0xC9,0x20, // '1'
    0x62,0x48, // '2'
    0xE8,0xE0, // '3'
    0x26,0x62, // '4'
    0x08,0x90, // '5'
    0x7A,0xE0, // '6'
    0x25,0x20, // '7'
    0xEA,0xE0, // '8'
    0xD5,0xE0, // '9'
    0x00, // ':'
    0x00, // ';'
    0x02,0xC6, // '<'
    0x77, // '='
    0x06,0x16, // '>'
    0xD0, // '?'
    0x27,0xB7,0x66,0x00, // '@'
    0x4A,0x68, // 'A'
    0xFA,0xD0, // 'B'
    0x68,0x86, // 'C'
    0xE9,0x9A, // 'D'
    0xDA,0x40, // 'E'
    0x9A,0x40, // 'F'
    0x78,0xB5, // 'G'
    0xBE,0xD0, // 'H'
    0xF0, // 'I'
    0x55,0x40, // 'J'
    0xAC,0xCA, // 'K'
    0x92,0x40, // 'L'
    0x9F,0xF9, // 'M'
    0xBF,0xD0, // 'N'
    0x69,0x96, // 'O'
    0xF7,0x40, // 'P'
    0x69,0x96,0x00, // 'Q'
    0xEA,0xCA, // 'R'
    0x91,0x60, // 'S'
    0x21,0x08,0x40, // 'T'
    0xB6,0xE0, // 'U'
    0xAA,0xA4, // 'V'
    0xAF,0xBC,0xA0, // 'W'
    0xA4,0x4A, // 'X'
    0x53,0x08,0x40, // 'Y'
    0x64,0x88, // 'Z'
    0xAA,0x80, // '['
    0xAA,0x40, // '\'
    0x55,0x40, // ']'
    0x61, // '^'
    0x70, // '_'
    0x00, // '`'
    0xDE,0x80, // 'a'
    0x9A,0xE0, // 'b'
    0x92,0x00, // 'c'
    0x3E,0xD0, // 'd'
    0xDE,0x00, // 'e'
    0x49,0x20, // 'f'
    0xF6,0xA0, // 'g'
    0x9E,0xD0, // 'h'
    0xF0, // 'i'
    0x55,0x40, // 'j'
    0x9A,0x60, // 'k'
    0xF0, // 'l'
    0xFD,0x6A, // 'm'
    0xF6,0x80, // 'n'
    0xD7,0x00, // 'o'
    0xD7,0x40, // 'p'
    0xF6,0xB0, // 'q'
    0x2A, // 'r'
    0x4C,0x80, // 's'
    0x49,0x20, // 't'
    0x16,0xD0, // 'u'
    0xB9,0x00, // 'v'
    0xD7,0x60, // 'w'
    0xCB,0x00, // 'x'
    0xB9,0x40, // 'y'
    0x68, // 'z'
    0x4A,0x24, // '{'
    0xF8, // '|'
    0x48,0xA4 // '}'
};
const GFXglyph Dialog_plain_5Glyphs[] PROGMEM = {
// bitmapOffset, width, height, xAdvance, xOffset, yOffset
      {     0,   1,   1,   3,    0,    0 }, // ' '
      {     1,   1,   4,   3,    0,   -4 }, // '!'
      {     2,   2,   2,   3,    0,   -4 }, // '"'
      {     3,   4,   4,   5,    0,   -4 }, // '#'
      {     5,   3,   5,   4,    0,   -4 }, // '$'
      {     7,   5,   4,   6,    0,   -4 }, // '%'
      {    10,   4,   4,   5,    0,   -4 }, // '&'
      {    12,   1,   2,   2,    0,   -4 }, // '''
      {    13,   2,   5,   3,    0,   -4 }, // '('
      {    15,   2,   5,   3,    0,   -4 }, // ')'
      {    17,   3,   3,   4,    0,   -4 }, // '*'
      {    19,   5,   4,   6,    0,   -4 }, // '+'
      {    22,   2,   3,   3,    0,   -2 }, // ','
      {    23,   2,   1,   3,    0,   -2 }, // '-'
      {    24,   2,   1,   3,    0,   -1 }, // '.'
      {    25,   2,   5,   3,    0,   -4 }, // '/'
      {    27,   3,   4,   4,    0,   -4 }, // '0'
      {    29,   3,   4,   4,    0,   -4 }, // '1'
      {    31,   4,   4,   4,    0,   -4 }, // '2'
      {    33,   3,   4,   4,    0,   -4 }, // '3'
      {    35,   4,   4,   5,    0,   -4 }, // '4'
      {    37,   3,   4,   4,    0,   -4 }, // '5'
      {    39,   3,   4,   4,    0,   -4 }, // '6'
      {    41,   3,   4,   4,    0,   -4 }, // '7'
      {    43,   3,   4,   4,    0,   -4 }, // '8'
      {    45,   3,   4,   4,    0,   -4 }, // '9'
      {    47,   2,   3,   3,    0,   -3 }, // ':'
      {    48,   2,   4,   3,    0,   -3 }, // ';'
      {    49,   4,   4,   5,    1,   -4 }, // '<'
      {    51,   4,   2,   5,    0,   -3 }, // '='
      {    52,   4,   4,   5,    0,   -4 }, // '>'
      {    54,   2,   4,   4,    0,   -4 }, // '?'
      {    55,   5,   5,   6,    0,   -4 }, // '@'
      {    59,   4,   4,   4,    0,   -4 }, // 'A'
      {    61,   3,   4,   4,    0,   -4 }, // 'B'
      {    63,   4,   4,   4,    0,   -4 }, // 'C'
      {    65,   4,   4,   5,    0,   -4 }, // 'D'
      {    67,   3,   4,   4,    0,   -4 }, // 'E'
      {    69,   3,   4,   4,    0,   -4 }, // 'F'
      {    71,   4,   4,   5,    0,   -4 }, // 'G'
      {    73,   3,   4,   4,    0,   -4 }, // 'H'
      {    75,   1,   4,   2,    0,   -4 }, // 'I'
      {    76,   2,   5,   2,   -1,   -4 }, // 'J'
      {    78,   4,   4,   4,    0,   -4 }, // 'K'
      {    80,   3,   4,   4,    0,   -4 }, // 'L'
      {    82,   4,   4,   5,    0,   -4 }, // 'M'
      {    84,   3,   4,   4,    0,   -4 }, // 'N'
      {    86,   4,   4,   5,    0,   -4 }, // 'O'
      {    88,   3,   4,   4,    0,   -4 }, // 'P'
      {    90,   4,   5,   5,    0,   -4 }, // 'Q'
      {    93,   4,   4,   4,    0,   -4 }, // 'R'
      {    95,   3,   4,   5,    1,   -4 }, // 'S'
      {    97,   5,   4,   4,   -1,   -4 }, // 'T'
      {   100,   3,   4,   4,    0,   -4 }, // 'U'
      {   102,   4,   4,   4,    0,   -4 }, // 'V'
      {   104,   5,   4,   6,    0,   -4 }, // 'W'
      {   107,   4,   4,   4,    0,   -4 }, // 'X'
      {   109,   5,   4,   4,   -1,   -4 }, // 'Y'
      {   112,   4,   4,   6,    1,   -4 }, // 'Z'
      {   114,   2,   5,   3,    0,   -4 }, // '['
      {   116,   2,   5,   3,    0,   -4 }, // '\'
      {   118,   2,   5,   3,    0,   -4 }, // ']'
      {   120,   4,   2,   5,    0,   -4 }, // '^'
      {   121,   4,   1,   4,   -1,    1 }, // '_'
      {   122,   2,   1,   4,    0,   -4 }, // '`'
      {   123,   3,   3,   5,    1,   -3 }, // 'a'
      {   125,   3,   4,   4,    0,   -4 }, // 'b'
      {   127,   3,   3,   4,    0,   -3 }, // 'c'
      {   129,   3,   4,   4,    0,   -4 }, // 'd'
      {   131,   3,   3,   5,    1,   -3 }, // 'e'
      {   133,   3,   4,   3,   -1,   -4 }, // 'f'
      {   135,   3,   4,   4,    0,   -3 }, // 'g'
      {   137,   3,   4,   4,    0,   -4 }, // 'h'
      {   139,   1,   4,   2,    0,   -4 }, // 'i'
      {   140,   2,   5,   2,   -1,   -4 }, // 'j'
      {   142,   3,   4,   4,    0,   -4 }, // 'k'
      {   144,   1,   4,   2,    0,   -4 }, // 'l'
      {   145,   5,   3,   6,    0,   -3 }, // 'm'
      {   147,   3,   3,   4,    0,   -3 }, // 'n'
      {   149,   3,   3,   4,    0,   -3 }, // 'o'
      {   151,   3,   4,   4,    0,   -3 }, // 'p'
      {   153,   3,   4,   4,    0,   -3 }, // 'q'
      {   155,   2,   4,   3,    0,   -4 }, // 'r'
      {   156,   3,   3,   5,    0,   -3 }, // 's'
      {   158,   3,   4,   3,   -1,   -4 }, // 't'
      {   160,   3,   4,   4,    0,   -4 }, // 'u'
      {   162,   3,   3,   4,    0,   -3 }, // 'v'
      {   164,   4,   3,   5,    0,   -3 }, // 'w'
      {   166,   3,   3,   4,    0,   -3 }, // 'x'
      {   168,   3,   4,   4,    0,   -3 }, // 'y'
      {   170,   2,   3,   5,    1,   -3 }, // 'z'
      {   171,   3,   5,   4,    0,   -4 }, // '{'
      {   173,   1,   6,   2,    0,   -4 }, // '|'
      {   174,   3,   5,   4,    0,   -4 } // '}'
};
const GFXfont Dialog_plain_5 PROGMEM = {
(uint8_t  *)Dialog_plain_5Bitmaps,(GFXglyph *)Dialog_plain_5Glyphs,0x20, 0x7E, 7};

I was having the same problem until I read the library source code. Later I found the documentation reference.
The classic font cursor position is defined as the top-left corner of the character cell. For GFX and custom fonts it is the 'y' position is relative to the baseline of the character cell.
My display is 5 by 5. The TomThumb font is 3 by 5. Instead of matrix.setCursor(x, 0); I needed to use matrix.setCursor(x, 5); so the 'y' coordinate corresponds with the bottom of the pixel matrix, not the top.
It's described in Adafruit's docs.