text:
Are all the pins on Arduino shields available for use?
Basically, if I put a shield on my Arduino (mine is Uno, but I'm asking generally), can I freely use all the pins that are there on the shield?
I have an Ethernet shield and almost all of the pins that the original Uno has, are available on the Ethernet too.
The best results that I could get from googling are this and this which describe that if a shield uses a certain pin, putting another shield that uses the same pin causes conflict.
But what about using them myself? Can I use all the pins on a shield as Input/Output?
If some pins are unusable, then why are they available on the board? For example why doesn't the Ethernet have pins 10-13 blocked so you can't put any jumper wires in them?
Additional info:

There was also this article which didn't seem very credible to me.
Also I've tried using pins 10-13 to light an LED while the Ethernet was busy transferring data. The result was the LED connected to pin 10 was very dim, 11 was less dim and so on. So my guess is yes, they are unavailable. But the fact that this was so rarely mentioned on the internet and that the pins aren't physically blocked made me doubtful.

Short answer: NO.
Each shield adds some feature to the base Arduino Uno board and to do that it's more than probably going to use some of the PINs.
I say more than probably because Arduino do have support for certain protocols which can share the same pins (I2C and OneWire just from the top of my mind), but they are not the most commonly used approaches for shields.
The only reason the shields expose the same set of pins is for stackability, but not every shield is compatible with any other: it depends on the used PINs.
Some shields provide some level of configuration, usually via jumpers, in order to make them usable in more contexts they would usually be.

Documentation regarding the pins used by each shield is generally available along with the shield, but if you buy cheap clones it's no surprise you might have difficulties finding documentation...
The article you were pointing is somewhat creditable because most of what the author says is actually true and real, including the risk of short circuits.
As an example, the test you run with LEDs connected to the Arduino SPI interface (pins from 10 to 13 are used by SPI) could have damaged your board if you didn't use current limiting resistors.


text:
Changing the mode when pressing/holding down a buttton
And first of all sorry for my bad English.
I am trying to write code that allows the user to change between continuous or manual mode, but I am having some issues getting it to work. The goal is to be able to switch from manual SOS (user pressing the button to SOS) and automatic SOS (the led automatically blinking SOS morse).
Currently, when I press down the button it loops once the automatic SOS and returns back to its normal state with LED on.
How would I make it, for an example switch the mode to manual when holding down button and giving user some sort of indication when changing the mode (etc blinking the led for X amount of time?)
What I am looking to achieve is:

Turn LEDS on when pressing the button.
Start looping automatic SOS signal
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch to manual SOS signal (user pressing the button to signal)
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch back to an automatic loop.

The code so far:
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin =  13; // the number of the LED pin
int mode;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  mode = digitalRead(buttonPin);

  // Manual SOS mode.
  buttonState = mode;

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED on:
  } else {
    digitalWrite(ledPin, LOW); // turn LED off:
  }

  // Automatic SOS mode.
  if (mode == HIGH) {
    // check if the pushbutton is pressed.
    // if it is, starts looping automatic SOS.
    int i = 0;
    for (i=0; i<3; i++) {
      digitalWrite(ledPin, HIGH);   // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(1200); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(1200); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }
    digitalWrite(ledPin, LOW);
    // waits 3 seconds before starting the loop again
    delay(3000);
  }
}

What you want to achieve is definitely not clear to me: can you please clearly state what would you expect your Arduino to do?
Eq: "when button is pressed automatic SOS is interrupted and manual SOS signal is emitted once, then no signal is emitted until the button is pressed again".

Sorry, English is not my primary language but I will try my best: What I want is the program to have 2 different modes: mode 1: automatic SOS signal and mode 2: manual SOS signal (led blinking). And then the option to swap between these two modes by pressing/holding down the button

Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.
First we define the PINs: defines are pre-processor macros, even better than const in terms of performance and space consumption:
#define BTN_PIN 2
#define LED_PIN 13

Let's initialize the board as per our requirements:
void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

Now we define the code which emits and SOS signal in morse code using the standard timing:

a long pulse lasts 3 times a short one
a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:
#define UNIT 300
#define SHORT (UNIT)
#define LONG (UNIT*3)
#define PAUSE (UNIT*3)
#define SPACE (UNIT*6)

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the delay(...) function, but this will prevent detecting button presses while signalling:
#define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

With the above in place we can define a function to send an SOS which should be both very compact and also readable:
void sendSOS() {
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
  PULSE(PAUSE); // inter letter pause
  PULSE(LONG);PULSE(LONG);PULSE(LONG);
  PULSE(PAUSE); // inter letter pause
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
}

Now, let's describe what the mode changing should be notified to the user:
#define QUICK 100
bool autoMode = true;

void switchMode() {
  autoMode= !autoMode;
  for (unsigned int i = 0; i < 25; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(QUICK);
    digitalWrite(LED_PIN, LOW);
    delay(QUICK);
  }
}

Now our main loop will have to check the button and act accordingly, right?
#define LONGPRESS 500
unsigned long elapsed;
bool clicked = false;
unsigned long duration;

void loop() {
  if (autoMode) {
    sendSOS();
  }
  elapsed = millis();
  while(clicked || millis() - elapsed <= SPACE) {
    // keep waiting to emit a SPACE or until the button is released

    if (digitalRead(BTN_PIN)) {
      // button has been clicked: trace it and start counting time
      clicked = true;
      duration = millis();
    } else if (clicked) {
      // button has been released: stop tracing and verify click duration
      clicked = false;
      if (millis() - duration <= LONGPRESS) {
        // switch mode on long press
        switchMode();
      } else if (!autoMode) {
        // short press has a meaning only when not in auto mode
        sendSOS();
      }
    }
  }

The solution above has great space for improvement:

there is no de-bouncing on the button
the board is unresponsive while signalling
keeping the button pressed forever will prevent any signalling to occur in any mode
the code is afflicted by millis() rollover if you keep the button pressed for long periods (around 49 days)

UPDATE: I've added the inter-letter pause as suggested in the comments.
UPDATE: apparently auto is a reserved word, so I changed it to autoMode.

#define is not better than const in C++. 2. You forgot the short inter-letter space. 3. Your code is not afflicted by the millis() rollover.

While better is definitely arguable (what's better for me might not be better for you) #define does not increase memory usage, const requires an additional pointer. 2. you are right 3. it is affected by millis() rollover if you keep the button pressed for 49 days...

Thank you, I will take a look at this once I am back at home. It seems complicated but I am sure I can understand it if I just give it enough time.

No, const doesn't cost more memory than #define. Try it! 3. You are right, I edited the answer accordingly.

Once again your comment on point 1 is correct: I thought #define uses FLASH while const uses SRAM but I believe my assumption is not always correct... not sure about all the details and how much compiler optimization options have influence on this. Thanks for the corrections!

So I tried your code, but I can't seem to get it work. It is giving me an error saying: ''expected unqualified-id before '=' token''. Notice that I didn't use the macros as I need to take a better look at those, so I slightly modified the code to use const instead. Anyways here is the current code: http://pastebin.com/mAF6tApf

I identified an issue in my code and updated it accordingly, but you have other issues in your code as a consequence of your manipulations: missing replacement of some defines and a missing closed curly brace, for what I saw.

Yeah, I noticed that too and fixed it again. Now it kinda works but it doesn't have the method for manual SOS from my original code. I added the method to the code but I am not sure how to implement it to your code in order to make it work. Currently, it loops the automatic SOS until I hold down the button for switching the mode, but doesn't change the mode. Here is the updated code: http://pastebin.com/5v6g3igE

You wrote: “I thought #define uses FLASH while const uses SRAM”. On this architecture, numeric literals and #defines tend to be compiled into immediate arguments. Same for const in C++. In plain C, const does cost RAM because it defaults to external linkage. #defines are OK, static const is probably also fine.

source: Stack Exchange

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

sort: votes


text:
Exception 29 ESP12E Arduino
I am getting exception 29 every time I make request to HTTP using GET function. I am requesting HTTP every 20-30ms but using millis I am only reading request at 100ms in order to avoid any overflow or incomplete close connection, but still I am getting an exception after reading some 100 request.
What should I do now?
Here is my code and my Exception Decoder result as well

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80);

const char* ssid = "Led_Downlight1";
char GetString[100];
unsigned int long RedValue;
unsigned long previousMillis = 0;
const long interval = 100;

void setup()
{

  Serial.begin(115200); //Start communication between the ESP8266-12E and the monitor window
  Serial.println();
  Serial.print("Configuring access point...");

  WiFi.mode(WIFI_AP);
  WiFi.disconnect();
  delay(100);
  WiFi.softAP(ssid);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());

  server.begin();
  Serial.println("Server started");
}

void loop()
{

  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval)
  {

  Serial.println("Somebody has connected :)");

  previousMillis = currentMillis;
  String incoming = client.readStringUntil('\r');
  Serial.println(incoming);
  client.flush();
  incoming.toCharArray(GetString, 100);

  char *get = strtok(GetString, " ");
  char *request = strtok(NULL, " ");
  char *rtype = strtok(NULL, " ");

  if (request != NULL)
  {
    char *part = strtok(request, "/");
    bool seenSTA = false;
    bool seenRGBW = false;

    while (part)
    {
      if (!strcmp(part, "RGBW"))
      {
        seenRGBW = true;
      }

      else if (seenRGBW)
      {
        if (!strncmp(part, "R=", 2))
        {
          RedValue  = atoi(part + 2);
          analogWrite(RED_LED, RedValue);
          Serial.print("\n");
          Serial.print("Red:");
          Serial.print(RedValue);

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println(""); //  do not forget this one
          client.println("<!DOCTYPE HTML>");
          client.println("");
          client.println("Red value: ");
          client.println(RedValue);
          client.println("

");
          client.println("");

          Serial.println("Client disonnected");
        }
      }
      part = strtok(NULL, "/");
    }
  }
 }
}

You have raised this same question as an issue with the authors of the ESP8266 core. If they can't answer it what hope do we have?

I hope somebody can come up with the solution

I copy-paste @Majenko's comment as the answer. Please, acept it to close your question.

I get exception 29 when trying to do http.GET, but only when I'm using code that has another large object in memory. Looks like we're running out of memory to do the http.GET(). Now I'm looking for resources to look into that more deeply!

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


text:
check string for specific characters?
I am just wondering if it is possible to check a string for specific characters.  For example if my string is String mystr = "test"; and I wanted to check for the letter t at the beginning and if it is NOT there do something how would I go about this?
I have read about string.startsWith(string2); however it returns true or false, I want to be able to do "XYZ" if "ABC" isn't satisfied, and it would seem that string.contains isn't a thing.
To paraphrase, I am trying to create an if statement that will evaluate if a string starts with a certain character(s) and will do something if this condition is NOT met.

In C and C++, the ! operator means “not”. E.g. if (!(the condition)) { some_action(); } means “do some action if the condition is not satisfied”.

Yes!  I thought that I might be able to adapt the string.startsWith, however it flagged saying expected unqualified id before '!' token

What did you write to get that error? If you don't show us your code, we won't be able to help.

I messed up and put the ! in the wrong place, sorry to have not caught that.

Have you tried the following?
if(!actualString.startsWith(expectedString)) {
  // do whatever you have to
}

BTW, that is what actually suggested in @EdgarBonet's comment.

That did it, I had the ! in the wrong place.

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


text:
Code will not run when Serial Monitor is not open
My code runs perfectly as long as the serial port is open. However if I connect it to external power, or even if I just try to run it plugged into my computer with the Serial Monitor not open, nothing happens. My project doesn't need any serial interaction, it will operate on its own far from any computers. I have it in here to help me debug.
The sticking point appears to be with if (morseInput.available()) on line 63.
Here is everything, including the libraries I am using:
Morse EnDecoder.h
#ifndef MorseEnDecoder_H
#define MorseEnDecoder_H

#if (ARDUINO <  100)
#include <WProgram.h>
#else
#include <Arduino.h>
#endif

#define MORSE_AUDIO true
#define MORSE_KEYER false
#define MORSE_ACTIVE_LOW true
#define MORSE_ACTIVE_HIGH false

class morseDecoder
{
public:
morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup);
void decode();
void setspeed(int value);
char read();
boolean available();
int AudioThreshold;
long debounceDelay;     // the debounce time. Keep well below dotTime!!
boolean morseSignalState;
private:
int morseInPin;         // The Morse input pin
int audioSignal;
int morseTablePointer;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
boolean morseSpace;     // Flag to prevent multiple received spaces
boolean gotLastSig;     // Flag that the last received morse signal is decoded as dot or dash
boolean morseKeyer;
boolean lastKeyerState;
boolean morseAudio;
boolean activeLow;
long markTime;          // timers for mark and space in morse signal
long spaceTime;         // E=MC^2 ;p
long lastDebounceTime;  // the last time the input pin was toggled
long currentTime;       // The current (signed) time
char decodedMorseChar;  // The last decoded Morse character
};

class morseEncoder
{
public:
morseEncoder(int encodePin);
void encode();
void setspeed(int value);
void write(char temp);
boolean available();
int morseSignals;       // nr of morse signals to send in one morse character
char morseSignalString[7];// Morse signal for one character as temporary ASCII string of dots and dashes
private:
char encodeMorseChar;   // ASCII character to encode
boolean sendingMorse;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
int morseSignalPos;
int sendingMorseSignalNr;
long sendMorseTimer;
long lastDebounceTime;
long currentTime;
protected:
int morseOutPin;
virtual void setup_signal();
virtual void start_signal(bool startOfChar, char signalType);
virtual void stop_signal(bool endOfChar, char signalType);
};

#endif

Morse EnDecoder.cpp
/*          MORSE ENDECODER

- Morse encoder / decoder classes for the Arduino.

Copyright (C) 2010-2012 raron

GNU GPLv3 license:

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Details: http://raronoff.wordpress.com/2010/12/16/morse-endecoder/

#include "MorseEnDecoder.h"

// Morse code binary tree table (dichotomic search table)

// ITU with most punctuation (but without non-english characters - for now)
const int morseTreeLevels = 6; // Minus top level, also the max nr. of morse signals
const int morseTableLength = pow(2,morseTreeLevels+1);
const char morseTable[] PROGMEM =
" ETIANMSURWDKGOHVF*L*PJBXCYZQ!*54*3***2&*+****16=/***(*7***8*90*"
"***********?_****\"**.****@***'**-********;!*)*****,****:*******\0";

morseDecoder::morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup)
{
morseInPin = decodePin;
morseAudio = listenAudio;
activeLow = morsePullup;

if (morseAudio == false)
{
pinMode(morseInPin, INPUT);
if (activeLow) digitalWrite (morseInPin, HIGH);
}

// Some initial values
wpm = 13;
AudioThreshold = 700;
debounceDelay = 20;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;

morseTablePointer = 0;

morseKeyer = LOW;
morseSignalState = LOW;
lastKeyerState = LOW;

gotLastSig = true;
morseSpace = true;
decodedMorseChar = '\0';

lastDebounceTime = 0;
markTime = 0;
spaceTime = 0;
}

void morseDecoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseDecoder::available()
{
if (decodedMorseChar) return true; else return false;
}

char morseDecoder::read()
{
char temp = decodedMorseChar;
decodedMorseChar = '\0';
return temp;
}

void morseDecoder::decode()
{
currentTime = millis();

// Read Morse signals
if (morseAudio == false)
{
// Read the Morse keyer (digital)
morseKeyer = digitalRead(morseInPin);
if (activeLow) morseKeyer = !morseKeyer;

// If the switch changed, due to noise or pressing:
if (morseKeyer != lastKeyerState) lastDebounceTime = currentTime; // reset timer

// debounce the morse keyer
if ((currentTime - lastDebounceTime) > debounceDelay)
{
  // whatever the reading is at, it's been there for longer
  // than the debounce delay, so take it as the actual current state:
  morseSignalState = morseKeyer;

  // differentiante mark and space times
  if (morseSignalState) markTime = lastDebounceTime;
  else spaceTime = lastDebounceTime;
}
} else {
// Read Morse audio signal
audioSignal = analogRead(morseInPin);
if (audioSignal > AudioThreshold)
{
  // If this is a new morse signal, reset morse signal timer
  if (currentTime - lastDebounceTime > dotTime/2)
  {
    markTime = currentTime;
    morseSignalState = true; // there is currently a Morse signal
  }
  lastDebounceTime = currentTime;
} else {
  // if this is a new pause, reset space time
  if (currentTime - lastDebounceTime > dotTime/2 && morseSignalState == true)
  {
    spaceTime = lastDebounceTime; // not too far off from last received audio
    morseSignalState = false;     // No more signal
   }
 }
}

// Decode morse code
if (!morseSignalState)
{
  if (!gotLastSig)
  {
    if (morseTablePointer < morseTableLength/2-1)
    {
    // if pause for more than half a dot, get what kind of signal pulse (dot/dash) received last
    if (currentTime - spaceTime > dotTime/2)
    {
      // if signal for more than 1/4 dotTime, take it as a morse pulse
      if (spaceTime-markTime > dotTime/4)
      {
        morseTablePointer *= 2;  // go one level down the tree
        // if signal for less than half a dash, take it as a dot
        if (spaceTime-markTime < dashTime/2)
        {
           morseTablePointer++; // point to node for a dot
           gotLastSig = true;
        }
        // else if signal for between half a dash and a dash + one dot (1.33 dashes), take as a dash
        else if (spaceTime-markTime < dashTime + dotTime)
        {
           morseTablePointer += 2; // point to node for a dash
           gotLastSig = true;
        }
      }
    }
  } else { // error if too many pulses in one morse character
    //Serial.println("<ERROR: unrecognized signal!>");
    decodedMorseChar = '#'; // error mark
    gotLastSig = true;
    morseTablePointer = 0;
  }
}
// Write out the character if pause is longer than 2/3 dash time (2 dots) and a character received
if ((currentTime-spaceTime >= (dotTime*2)) && (morseTablePointer > 0))
{
  decodedMorseChar = pgm_read_byte_near(morseTable + morseTablePointer);
  morseTablePointer = 0;
}
// Write a space if pause is longer than 2/3rd wordspace
if (currentTime-spaceTime > (wordSpace*2/3) && morseSpace == false)
{
  decodedMorseChar = ' ';
  morseSpace = true ; // space written-flag
}

} else {
// while there is a signal, reset some flags
gotLastSig = false;
morseSpace = false;
}

// Save the morse keyer state for next round
lastKeyerState = morseKeyer;
}

morseEncoder::morseEncoder(int encodePin)
{
  morseOutPin = encodePin;
  this->setup_signal();

// some initial values
sendingMorse = false;
encodeMorseChar = '\0';

wpm = 13;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

void morseEncoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseEncoder::available()
{
if (sendingMorse) return false; else return true;
}

void morseEncoder::write(char temp)
{
if (!sendingMorse && temp != '*') encodeMorseChar = temp;
}

void morseEncoder::setup_signal()
{
pinMode(morseOutPin, OUTPUT);
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::start_signal(bool startOfChar, char signalType)
{
digitalWrite(morseOutPin, HIGH);
}

void morseEncoder::stop_signal(bool endOfChar, char signalType)
{
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::encode()
{
currentTime = millis();

if (!sendingMorse && encodeMorseChar)
{
// change to capital letter if not
if (encodeMorseChar > 96) encodeMorseChar -= 32;

// Scan for the character to send in the Morse table
int p;
for (p=0; p<morseTableLength+1; p++) if (pgm_read_byte_near(morseTable + p) == encodeMorseChar) break;

if (p >= morseTableLength) p = 0; // not found, but send a space instead

// Reverse binary tree path tracing
int pNode; // parent node
morseSignals = 0;

// Travel the reverse path from position p to the top of the morse table
if (p > 0)
{
  // build the morse signal (backwards morse signal string from last signal to first)
  pNode = p;
  while (pNode > 0)
  {
    if ( (pNode & 0x0001) == 1)
    {
      // It is a dot
      morseSignalString[morseSignals++] = '.';
    } else {
      // It is a dash
      morseSignalString[morseSignals++] = '-';
    }
    // Find parent node
    pNode = int((pNode-1)/2);
  }
} else { // Top of Morse tree - Add the top space character
  // cheating a little; a wordspace for a "morse signal"
  morseSignalString[morseSignals++] = ' ';
}

morseSignalString[morseSignals] = '\0';

// start sending the the character
sendingMorse = true;
sendingMorseSignalNr = morseSignals; // Sending signal string backwards
sendMorseTimer = currentTime;
if (morseSignalString[0] != ' ') this->start_signal(true, morseSignalString[morseSignals-1]);
}

// Send Morse signals to output
if (sendingMorse)
{
char& currSignalType = morseSignalString[sendingMorseSignalNr-1];
bool endOfChar = sendingMorseSignalNr <= 1;
switch (currSignalType)
{
  case '.': // Send a dot (actually, stop sending a signal after a "dot time")
    if (currentTime - sendMorseTimer >= dotTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case '-': // Send a dash (same here, stop sending after a dash worth of time)
    if (currentTime - sendMorseTimer >= dashTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case 'x': // To make sure there is a pause between signals
    if (sendingMorseSignalNr > 1)
    {
      // Pause between signals in the same letter
      if (currentTime - sendMorseTimer >= dotTime)
      {
        sendingMorseSignalNr--;
        this->start_signal(false, morseSignalString[sendingMorseSignalNr-1]); // Start sending the next signal
        sendMorseTimer = currentTime;       // reset the timer
      }
    } else {
      // Pause between letters
      if (currentTime - sendMorseTimer >= dashTime)
      {
        sendingMorseSignalNr--;
        sendMorseTimer = currentTime;       // reset the timer
      }
    }
    break;
  case ' ': // Pause between words (minus pause between letters - already sent)
  default:  // Just in case its something else
    if (currentTime - sendMorseTimer > wordSpace - dashTime) sendingMorseSignalNr--;
}
if (sendingMorseSignalNr <= 0 )
{
  // Ready to encode more letters
  sendingMorse = false;
  encodeMorseChar = '\0';
}
}
}

Morse.h
#pragma once
/**
* Generate and send Morse Code on an LED or a speaker. Allow sending
* in a non-blocking manner (by calling a 'continue sending' method
* every so often to turn an LED on/off, or to call tone/noTone appropriately).
*
* All input should be lowercase. Prosigns (SK, KN, etc) have special
* character values #defined.
*/

// for malloc and free, for the new/delete operators
#include <stdlib.h>

// Arduino language types
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#define WPM_DEFAULT 12.0
// PARIS WPM measurement: 50; CODEX WPM measurement: 60 (Wikipedia:Morse_code)
#define DITS_PER_WORD   50
// Pass to SpeakerMorseSender as carrierFrequency to suppress the carrier.
#define CARRIER_FREQUENCY_NONE  -1

// Bitmasks are 1 for dah and 0 for dit, in left-to-right order;
//  the sequence proper begins after the first 1 (a sentinel).
//  Credit for this scheme to Mark VandeWettering K6HX ( brainwagon.org ).
typedef int             morseTiming_t;
typedef unsigned char   morseBitmask_t; // see also MAX_TIMINGS
#define MORSE_BITMASK_HIGH_BIT  B10000000

// sentinel
#define END             0

// the most timing numbers any unit will need; ex: k = on,off,on,off,on,end = 5
#define MAX_TIMINGS     15

// Punctuation and Prosigns
#define PROSIGN_SK  'S'
#define PROSIGN_KN  'K'
#define PROSIGN_BT  'B'
typedef struct {
char c;
morseBitmask_t timing;
} specialTiming;
const specialTiming MORSE_PUNCT_ETC[] = {
{'.',       B1010101},
{'?',       B1001100},
{PROSIGN_SK,    B1000101},
{PROSIGN_KN,    B110110},
{PROSIGN_BT,    B110001},
{END,       B1},
};

// Morse Code (explicit declaration of letter timings)
const morseBitmask_t MORSE_LETTERS[26] = {
/* a */ B101,
/* b */ B11000,
/* c */ B11010,
/* d */ B1100,
/* e */ B10,
/* f */ B10010,
/* g */ B1110,
/* h */ B10000,
/* i */ B100,
/* j */ B10111,
/* k */ B1101,
/* l */ B10100,
/* m */ B111,
/* n */ B110,
/* o */ B1111,
/* p */ B10110,
/* q */ B11101,
/* r */ B1010,
/* s */ B1000,
/* t */ B11,
/* u */ B1001,
/* v */ B10001,
/* w */ B1011,
/* x */ B11001,
/* y */ B11011,
/* z */ B11100,
};

/**
* Define the logic of converting characters to on/off timing,
* and encapsulate the state of one sending-in-progress Morse message.
*
* Subclasses define setOn and setOff for (for example) LED and speaker output.
*/
class MorseSender {
protected:
const unsigned int pin;
// The setOn and setOff methods would be pure virtual,
// but that has compiler issues.
// See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1167672075 .

/**
 * Called to set put the output in 'on' state, during a dit or dah.
 */
virtual void setOn();
virtual void setOff();

/**
 * Called before sending a message. Used for example to enable a
 * carrier. (Noop in the base class.)
 */
virtual void setReady();
virtual void setComplete();

private:
morseTiming_t DIT, DAH;
String message;

// on,off,...,wait,0 list, millis
morseTiming_t timingBuffer[MAX_TIMINGS+1];

// index of the character currently being sent
unsigned int messageIndex;
// timing unit currently being sent
unsigned int timingIndex;

// when this timing unit was started
unsigned long lastChangedMillis;

/**
 * Copy definition timings (on only) to raw timings (on/off).
 * @return the number of 'on' timings copied
 */
int copyTimings(morseTiming_t *rawOut,
    morseBitmask_t definition);

/**
 * Fill a buffer with on,off,..,END timings (millis)
 * @return the index at which to start within the new timing sequence
 */
unsigned int fillTimings(char c);

public:
/**
 * Create a sender which will output to the given pin.
 */
MorseSender(unsigned int outputPin, float wpm=WPM_DEFAULT);

/**
 * To be called during the Arduino setup(); set the pin as OUTPUT.
 */
void setup();

/**
 * Set the words per minute (based on PARIS timing).
 */
void setWPM(float wpm);

/**
 * Set the duration, in milliseconds, of a DIT.
 */
void setSpeed(morseTiming_t duration);

/**
 * Set the message to be sent.
 * This halts any sending in progress.
 */
void setMessage(const String newMessage);

/**
 * Send the entirety of the current message before returning. See the "simple"
 * example, which uses sendBlocking to send one message.
 */
void sendBlocking();

/**
 * Prepare to send and begin sending the current message. After calling this,
 * call continueSending repeatedly until it returns false to finish sending
 * the message. See the "speeds" example, which calls startSending and
 * continueSending on two different senders.
 */
void startSending();

/**
 * Switch outputs on and off (and refill the internal timing buffer)
 * as necessary to continue with the sending of the current message.
 * This should be called every few milliseconds (at a significantly
 * smaller interval than a DIT) to produce a legible fist.
 *
 * @see startSending, which must be called first
 * @return false if sending is complete, otherwise true (keep sending)
 */
boolean continueSending();

void *operator new(size_t size);
void operator delete(void* ptr);
};

/**
* Adapt Morse sending to use the Arduino language tone() and noTone()
* functions, for use with a speaker.
*
* If a carrierFrequency is given, instead of calling noTone, call tone
* with a low frequency. This is useful ex. for maintaining radio links.
*/
class SpeakerMorseSender: public MorseSender {
private:
    unsigned int frequency;
    unsigned int carrFrequency;
protected:
    virtual void setOn();
    virtual void setOff();
    virtual void setReady();
    virtual void setComplete();
public:
    // concert A = 440
    // middle C = 261.626; higher octaves = 523.251, 1046.502
    SpeakerMorseSender(
        int outputPin,
        unsigned int toneFrequency=1046,
        unsigned int carrierFrequency=CARRIER_FREQUENCY_NONE,
        float wpm=WPM_DEFAULT);
};

/**
* Sends Morse on a digital output pin.
*/
class LEDMorseSender: public MorseSender {
protected:
    virtual void setOn();
    virtual void setOff();
public:
    LEDMorseSender(int outputPin, float wpm=WPM_DEFAULT);
};

/**
* Sends Morse on an analog output pin (using PWM). The brightness value is
* between 0 and 255 and is passed directly to analogWrite.
*/
class PWMMorseSender: public MorseSender {
private:
    byte brightness;
protected:
    virtual void setOn();
    virtual void setOff();
public:
    PWMMorseSender(int outputPin, float wpm=WPM_DEFAULT, byte brightness=255);
    void setBrightness(byte brightness);
};

morse.cpp
// Morse Code sending library

#include <morse.h>

// MorseSender
int MorseSender::copyTimings(
morseTiming_t *rawOut,
morseBitmask_t definition)
{
int t = 0;
boolean foundSentinel = false;
for(morseBitmask_t mask = MORSE_BITMASK_HIGH_BIT;
    mask > 0; mask = mask >> 1)
{
    boolean isDah = (mask & definition) > 0;
    if(!foundSentinel)
    {
        if (isDah) { foundSentinel = true; }
        continue;
    }
    rawOut[2*t] = isDah ? DAH : DIT;
    rawOut[2*t + 1] = DIT;
    t++;
}
return t;
}
unsigned int MorseSender::fillTimings(char c)
{
int t = 0;
unsigned int start = 0;
if (c >= 'a' && c <= 'z')
{
    t = copyTimings(timingBuffer, MORSE_LETTERS[c-'a']);
}
else if (c >= '0' && c <= '9')
{
    int n = c - '0';
    boolean ditsFirst = (n <= 5);
    if (!ditsFirst)
    {
        n -= 5;
    }
    while(t < 5)
    {
        timingBuffer[2*t] = ((t < n) == ditsFirst) ? DIT : DAH;
        timingBuffer[2*t + 1] = DIT;
        t++;
    }
}
else
{
    int s = 0;
    while(MORSE_PUNCT_ETC[s].c != END)
    {
        if(MORSE_PUNCT_ETC[s].c == c)
        {
            t = copyTimings(timingBuffer,
                MORSE_PUNCT_ETC[s].timing);
            break;
        }
        s++;
    }
    if (MORSE_PUNCT_ETC[s].c == END)
    {
        start = t = 1; // start on a space
    }
}

timingBuffer[2*t - 1] = DAH;
timingBuffer[2*t] = END;

return start;
}

// see note in header about pure-virtual-ness
void MorseSender::setOn() {};
void MorseSender::setOff() {};

// noop defaults
void MorseSender::setReady() {};
void MorseSender::setComplete() {};

MorseSender::MorseSender(unsigned int outputPin, float wpm) :
pin(outputPin)
{
setWPM(wpm);
}

void MorseSender::setup() { pinMode(pin, OUTPUT); }

void MorseSender::setWPM(float wpm)
{
setSpeed((morseTiming_t)(1000.0*60.0/(max(1.0, wpm)*DITS_PER_WORD)));
}

void MorseSender::setSpeed(morseTiming_t duration)
{
DIT = max(1, duration);
DAH = 3*DIT;
}

void MorseSender::setMessage(const String newMessage)
{
message = newMessage;

// Force startSending() before continueSending().
messageIndex = message.length();

// If a different message was in progress, make sure it stops cleanly.
if (timingIndex % 2 == 0) {
    setOff();
}
}

void MorseSender::sendBlocking()
{
//Serial.println("Sending blocking: ");
//Serial.println(message);
startSending();
while(continueSending());
}

void MorseSender::startSending()
{
messageIndex = 0;
if (message.length() == 0) { return; }
timingIndex = fillTimings(message[0]);
setReady();
if (timingIndex % 2 == 0) {
    setOn();
    //Serial.print("Starting with on, duration=");
} else {
    //Serial.print("Starting with off, duration=");
}
lastChangedMillis = millis();
//Serial.println((int)timingBuffer[timingIndex]);
}

boolean MorseSender::continueSending()
{
if(messageIndex >= message.length()) { return false; }

unsigned long elapsedMillis = millis() - lastChangedMillis;
if (elapsedMillis < timingBuffer[timingIndex]) { return true; }

timingIndex++;
if (timingBuffer[timingIndex] == END)
{
    messageIndex++;
    if(messageIndex >= message.length()) {
        setOff();
        setComplete();
        return false;
    }
    timingIndex = fillTimings(message[messageIndex]);
}

lastChangedMillis += elapsedMillis;
//Serial.print("Next is       ");
if (timingIndex % 2 == 0) {
    //Serial.print("(on) ");
    setOn();
} else {
    //Serial.print("(off) ");
    setOff();
}
//Serial.println((int)timingBuffer[timingIndex]);

return true;
}

void *MorseSender::operator new(size_t size) { return malloc(size); }
void MorseSender::operator delete(void* ptr) { if (ptr) free(ptr); }

// SpeakerMorseSender

void SpeakerMorseSender::setOn() { tone(pin, frequency); }
void SpeakerMorseSender::setOff() {
if (carrFrequency == CARRIER_FREQUENCY_NONE) {
    noTone(pin);
} else {
    tone(pin, carrFrequency);
}
}
void SpeakerMorseSender::setReady() { setOff(); }
void SpeakerMorseSender::setComplete() { noTone(pin); }
SpeakerMorseSender::SpeakerMorseSender(
int outputPin,
unsigned int toneFrequency,
unsigned int carrierFrequency,
float wpm)
: MorseSender(outputPin, wpm),
frequency(toneFrequency),
carrFrequency(carrierFrequency) {};

// LEDMorseSender

void LEDMorseSender::setOn() { digitalWrite(pin, HIGH); }
void LEDMorseSender::setOff() { digitalWrite(pin, LOW); }
LEDMorseSender::LEDMorseSender(int outputPin, float wpm)
: MorseSender(outputPin, wpm) {};

// PWMMorseSender

void PWMMorseSender::setOn() { analogWrite(pin, brightness); }
void PWMMorseSender::setOff() { analogWrite(pin, 0); }
void PWMMorseSender::setBrightness(byte bright) {
brightness = bright;
}
PWMMorseSender::PWMMorseSender(
    int outputPin,
    float wpm,
    byte bright)
: MorseSender(outputPin, wpm), brightness(bright) {};

And finally, here is my code:
#include <avr/pgmspace.h>
#include <MorseEnDecoder.h>
#include <stdio.h>
#include <morse.h>
#define PIN_STATUS  13
#define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
#define CPU_RESTART_VAL 0x5FA0004
#define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

// Pin mapping
const byte morseInPin = 7;
const byte morseOutPin = 13;
String check = "";
String origin = "SOS";
const int maxItems = 3;
int x;
char myArray[maxItems], curChar;
char nextChar;
int i;
int y;

// Instantiate Morse objects
morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
morseEncoder morseOutput(morseOutPin);

// Variables dealing with formatting the output somewhat
// by inserting CR's (carriage returns)
long lastTransmissionTime;
long currentTime;
boolean transmissionEnded = true; // Flag to mark old transmission is finished

// Minimum transmission pause time to insert carriage returns (CR)
// Adjust depending on Morse speed. IE 13 wpm = 646 ms between words (no CR).
const long transmissionPaused   = 1000; // Suitable for 13 wpm?

LEDMorseSender sender(PIN_STATUS);

void setup()
{
  Serial.begin(9600);
  Serial.println("Morse EnDecoder Geocache");

  // Setting Morse speed in wpm - words per minute
  // If not set, 13 wpm is default anyway
  morseInput.setspeed(5);
  morseOutput.setspeed(5);

  lastTransmissionTime = (long)millis();
}

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
  currentTime = (long)millis();

  // Need to call these once per loop
  morseInput.decode();
  morseOutput.encode();

  // RECEIVE MORSE (INPUT)
  // If a character is decoded from the input, write it to serial port
  if (morseInput.available())
  {
    char receivedMorse = morseInput.read();
    Serial.print(receivedMorse);
    // A little error checking
    if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
    morseOutput.write('#');
    morseOutput.encode();

    //Create Array out of receivedMorse Chars

    curChar = 0;
    nextChar = receivedMorse;
    curChar += nextChar;
    myArray[i] = curChar;
    check.concat(myArray[i]);
    Serial.println(check);

    //Check input and respond
    if (check == origin)      //GOOD JOB!!  Your reward is as follows
    {
      Serial.println("check = origin");
      Serial.println(check);
      sender.setup();
      sender.setWPM(5);
      sender.setMessage(String("help is coming"));
      sender.startSending();
    }
    else if (check == "S") {}
    else if (check == "SO") {}
    else if (check == " SOS") {}
    else if (check.length() > 4)
    {
      delay(100);
      Serial.println("resetting");
      delay(500);
      resetFunc();  //call reset
      delay(100);
    }
    else {}
  }
  sender.continueSending();
}

I'm not keen on resetFunc();  //call reset - that doesn't actually reset the chip, you know. It just jumps to the reset vector, that is something else (the hardware is not reset).

if I just try to run it plugged into my computer with the serial monitor not open, nothing happens - without trying to understand all your code, what are you expecting to happen, that doesn't happen, if you don't see the serial output?

I want it to run the code, I'm not trying to sound  facetious, but it literally will not run anything unless serial monitor is open.  It is supposed to read in and decode morse code input from a button on digital pin 7 then it is supposed to compare this string of morse code with another string and if they match it is supposed to output morse code to the LED.

An idea occurred to me that could be the culprit.  The code may be sending the character to the serial monitor after it decodes it (turns button pushes into a character).  If this is the case it would not run without the serial monitor, but I have no idea about how to fix this.

Can you please specify the exact board you are using?
As a side note, you might want to use a non invasive approach to system debug, like https://github.com/rlogiacco/MicroDebug.

On both the Mega and the Nano, if you use the serial port for output only, the board does not care, and does even know, whether anyone (serial monitor or other program) is listening.

I am using Mega currently because it is larger and easier to test circuits on, however I plan to transition this project onto a nano, this is why I tagged both boards.

I have used your debug LED library, and have determined that without serial monitor open, it skips lines 71-116, the main if statement which essentially contains all the important bits of code.  I believe this may have something to do with morseInput.available, but I don't know how to fix it.

It is supposed to read in and decode morse code input from a button on digital pin 7 then it is supposed to compare this string of morse code with another string and if they match it is supposed to output morse code to the LED. - you mean it is reading switch presses via an input pin, and then echoing those same patterns to an output pin, via a decode/encode lot of code? Why? What does it achieve to do that?

It would appear that with this code, the serial.print commands were interfering with the code running as strange as that seems.  I was able to delete the offending serial commands and now the code works.  With a few tweaks, it should be flawless.

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


text:
Thunderstorm triggering button press?
So I recently built a small IFTT powered button using an ESP8266 for my boys to play with. Tonight during an intense Thunderstorm, I kept getting alerts that it had been pressed. They weren't in the basement at all. Then I realized, giant crack of lightening === SMS message.
Now I don't think this has anything to do with the button mechanism itself, but the shoddy way I hooked it up, and stuffed it into an enclosure. I'm just curious - is this possible? Could some sort of static electricity from a few nearby lightening strikes do something that would send a 'high' signal to the GPIO Pin on my Espee? I had to use a pull up resistor, and I feel like there's probably a few bare-ish wires in there, but nothing touching, or even close enough to 'arc'. Am I crazy?

You aren't crazy. I had a similar thing happen when an external hot-water system turned on at midnight (someone was having a shower) and one of my systems detected input unexpectedly (and rang a bell right next to my ear while I was trying to sleep).
My solution was to have something like this:

The diodes clamp the input to acceptable ranges, and R1 is a current limit for the diodes. R2 and C1 are a filter that slows down the incoming signal (and thus eliminates sudden spikes). R3 is a pull-up resistor. In my case I had active-low. If you have active-high you could use a pull-down resistor instead.
Also see https://arduino.stackexchange.com/a/13128/10794
Further reference material:

10 Ways to Destroy An Arduino
Protection
Microcontroller Input Protection Techniques


text:
Problem using an array inside a switch statement
I am having a problem when using a switch statement to check for something inside an array. I am using an int as my switch, then I compare the character arrays using strstr. So it reads like this:

void function(char *buffer, uint32_t size){
  char *p=(char*)malloc(compareSize); //compareSize is the size of the text to be compared
  #define TXTCOMPARE1 (char*)"Sample Text 1"
  #define TXTCOMPARE2 (char*)"Sample Text 2"
  #define TXTCOMPARE3 (char*)"Sample Text 3"
  switch(intCompare){
    case COMPARE1 :
      p = strstr(buffer,TXTCOMPARE1); break;
    case COMPARE2 :
      p = strstr(buffer,TXTCOMPARE2); break;
    case COMPARE3 :
      p = strstr(buffer,TXTCOMPARE3); break;
  }
  if(p!=NULL) { Serial.println("Success!"); }
  else { Serial.println("No match"); }
    memset(&p,0,sizeof(p);
}

This method does not work and p is always NULL. However, when I write it out without the switch() it compares just fine:
//using the same p declaration as above
p = strstr(buffer,TXTCOMPARE1);
if(p != NULL) { Serial.print("Success:"); }
else { Serial.print("No Match"); }

Why would the switch statement give me different results for what is basically the same function call?
Edit: Actually it seems to break everywhere when I set more than one call to p = strstr(...). When there is only one strstr it works, when two or more are used, it does not...

Have you defined COMPARE1, COMPARE2 and COMPARE3 ? Where is your value assigning statement for intCompare ?

Yes, I appologize for leaving that out. But that is almost exactly what I'm doing, except that intCompare is being passed into function(char *buffer, uint32_t size, int intCompare). But when I have multiple cases, p is always NULL

I don't understand three things in this code: 1) Why are you doing a malloc() into p, and then overwriting p before doing a free()? That is not what strstr() needs to work. 2) Why do the TXTCOMPARE strings have (char *) before them? This shouldn't be necessary. 3) Why are you doing a memset(&p,0,sizeof(p));? This is an extraordinarily long-winded way of saying p = NULL; - and then p goes out of scope anyway...

Thanks @JohnBurger. 1) I'm trying to put in an expected size for p from the comparison text I am expecting. 2) The compiler was giving me warnings for converting the strings into char* when defining them, so I cast them as char*. Is there a better way to do this? 3)I thought I was trying to clear the p pointer.

One big problem is that you forgot the break statements for those cases.  So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.

I solved this problem, there were a few problems with the code that I found, so thanks for your comments.
Basically, it lies in the #define# statements.
First, in Arduino it's not such great practice to use #define for strings/chars, only for int. This is because the compiler applies the text every time they appear in the code, so it uses up a lot more memory. The problem here is solved by using
static char TXTCOMPARE1 = {"Sample Text 1"};
Another problem was that there was no NULL terminated character at the end of the #define statement, so the program kept looking to the end of the stack when using strstr() and finding no termination, I think I was just getting lucky that it worked occasionally at all.
Furthermore, there is no need to clear p using memset. It needs to be declared as NULL and then reset after the switch by
if(p){p = NULL;}.
And now it works!

Good that you found it - and thank you for the caution about #define and strings. Note that you should have used static const char TXTCOMPARE1[] = "Sample Text 1";, and also that if (p) { p =NULL; } wastes an if. Just do p = NULL; - it's smaller and faster. Oh, and completely unnecessary. p is about to disappear anyway when it goes out of scope: no need to zero it out.

Another problem was that there was no NULL terminated character at the end of the #define statement - that's not true. It's hard to tell from your snippet but a #define just does a textual replacement.

There is no need to malloc memory for p, just declare it as a char *p = NULL; strstr then returns a pointer to the existing strings. All the malloc line is doing is leaking memory.

The statement "This is because the compiler applies the text every time they appear in the code, so it uses up a lot more memory" is wrong. No matter what declaration you use (#define, const char), the memory usage is the same. The C compiler take care of reusing the string when it appears for second time. Wrote a little test program and see how much RAM/program memory it use.


text:
LCD 16x2 Blank Display
I am using the following wiring diagram from a tutorial.  I need to follow this configuration because later tutorials build on this example.  I have looked at other solutions, but they follow a different pattern and I am still learning, so don't have the sophistication to adapt.  I've looked at:
Hacktronics
StackExchange
The picture shows Freeduino, but I am using an Arduino Uno (does that make a difference?)

Here is the code I am using:
#include <LiquidCrystal.h>
int rs = 3;
int enable = 4;
int d4 = 5;
int d5 = 6;
int d6 = 7;
int d7 = 8;

int rows = 2;
int cols = 16;
LiquidCrystal lcd (3, 4, 5, 6, 7, 8);

void setup() {
  // put your setup code here, to run once:
  pinMode (rs, OUTPUT);
  pinMode (enable, OUTPUT);
  pinMode (d4, OUTPUT);
  pinMode (d5, OUTPUT);
  pinMode (d6, OUTPUT);
  pinMode (d7, OUTPUT);
  lcd.begin(cols, rows);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  lcd.setCursor(0,0);
  lcd.print("Hello World");
  delay(1000);
  lcd.setCursor(0,1);
  lcd.print("Goodbye World");
  delay(1000);
}

Unfortunately, I am getting a blank screen (it is lit up, but blank).  So questions:

Is the diagram correct?
Is the code the problem?
What else should I look for?

Change the contrast

Can I change the contrast in the code?  Turning the screw on the pot doesn't seem to have any effect.

Remove all the connections to the display except for power ground and contrast. Then power it on and turn the pot till you see a row of black blocks on the first line and nothing on the second line.

In my experience, contrast can mess pretty bad. I spend days to look for "why my LCD goes blank", thinking there is something wrong with my code. Turns out the characters appear when I change the contrast

1) Diagram seems to be fine. However we don't see pin numbering on LCD. Sometimes pins are like:  15 16 1 2 3 4 ... 14 (at least pin 1 is usualy marked).
2) Library should take care of inputs or outputs. So you can remove pinModes for them. Also change variables to constant variables and use them for lcd initialization: LiquidCrystal lcd(rs, enable, d4, d5, d6, d7);
3) Potentiometer in diagram is contrast setting. You have to preset correct value for it. Start with everything is black and find value where this black is almost invisible. If you've something displayed on LCD, it would be even easier to find right position as text just shows up.
Edit: I've just tested it and it's working fine. With the same wiring and contrast pot adjusted to the right position

Pins are numbered 16...1 left to right.

Check the voltage. your LCD should get 5v to work properly.
if you are powering it through your computer USB, Arduino could be outputting less than 5v.
PS: it happened to me yesterday.


text:
What are the logical errors in this piece of code?
The client always reply with "ThisCodeTurnsTheUnoOnn" or ThisCodeTurnsTheUnoOff" based on some conditions.
This piece of code is inside arduino uno's void loop().
Expected behavior:
The arduino read the reply and turn the digital pin 13 to HIGH if the onCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOnn" and the other way around:
The arduino read the reply and turn the digital pin 13 to LOW if the offCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOff".
and the digital pin 13 should always remain in the previous state if the new client's reply was the same as previous reply. (e.g. if
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state).
Actual behavior:
CASE :
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state but the arduino turns the digital pin 13 HIGH when entering the next loop(void loop()) then turns back to LOW after entered the loop(void loop()).
  // available() will return the number of characters
  // currently in the receive buffer.

  const int solenoidValve = 13;

  char onCode[23] = "ThisCodeTurnsTheUnoOnn";
  char offCode[23] = "ThisCodeTurnsTheUnoOff";

  int onCount = 0;
  int offCount = 0;

  while (client.available())
  {
    char c = client.read();

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

The complete code, in case the logical errors is not within the above piece of code:
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>

//////////////////////////////
// WiFi Network Definitions //
//////////////////////////////
// Replace these two character strings with the name and
// password of your WiFi network.
const char mySSID[] = "SSID";
const char myPSK[] = "PASSWORD";
const int solenoidValve = 13;
char onCode[23] = "ThisCodeTurnsTheUnoOnn";
char offCode[23] = "ThisCodeTurnsTheUnoOff";

//water flow calculation variables
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;

//////////////////
// HTTP Strings //
//////////////////
const char destServer[] = "192.168.0.101"; //private ip //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
const uint16_t port = 8080; // Code ID: 1126 [Kugan] added variable port
const String httpRequest = "GET /aquosdb/getStatus.php HTTP/1.1\n"
                           "Host: 192.168.0.101\n" //private ip [note for myself: dont forget to change IP]
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132

// All functions called from setup() are defined below the
// loop() function. They modularized to make it easier to
// copy/paste into sketches of your own.
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;

  // Serial Monitor is used to control the demo and view
  // debug information.
  Serial.begin(9600);
  //serialTrigger(F("Press any key to begin.")); //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130

  // initializeESP8266() verifies communication with the WiFi
  // shield, and sets it up.
  initializeESP8266();

  // connectESP8266() connects to the defined WiFi network.
  connectESP8266();

  // displayConnectInfo prints the Shield's local IP
  // and the network it's connected to.
  displayConnectInfo();

  //serialTrigger(F("Press any key to connect client."));  //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130
  //valveControl();
}

void loop()
{
  setFlow();
  //delay(500); // [Kugan] 29/7/16 try3 : added delay to debug connection bug Code ID:1131
  valveControl();
}

void initializeESP8266()
{
  // esp8266.begin() verifies that the ESP8266 is operational
  // and sets it up for the rest of the sketch.
  // It returns either true or false -- indicating whether
  // communication was successul or not.
  // true
  int test = esp8266.begin();
  if (test != true)
  {
    Serial.println(F("Error talking to ESP8266."));
    errorLoop(test);
  }
  Serial.println(F("ESP8266 Shield Present"));
}

void connectESP8266()
{
  esp8266.disconnect(); // Code ID:1125 [Kugan] To disconnect from previously connected wifi AP
  delay(100);           // esp8266 has auto-reconnect function to connect previously connected AP

  // The ESP8266 can be set to one of three modes:
  //  1 - ESP8266_MODE_STA - Station only
  //  2 - ESP8266_MODE_AP - Access point only
  //  3 - ESP8266_MODE_STAAP - Station/AP combo
  // Use esp8266.getMode() to check which mode it's in:
  int retVal = esp8266.getMode();
  if (retVal != ESP8266_MODE_STA)
  { // If it's not in station mode.
    // Use esp8266.setMode([mode]) to set it to a specified
    // mode.
    retVal = esp8266.setMode(ESP8266_MODE_STA);
    if (retVal < 0)
    {
      Serial.println(F("Error setting mode."));
      errorLoop(retVal);
    }
  }
  Serial.println(F("Mode set to station"));

  // esp8266.status() indicates the ESP8266's WiFi connect
  // status.
  // A return value of 1 indicates the device is already
  // connected. 0 indicates disconnected. (Negative values
  // equate to communication errors.)
  retVal = esp8266.status();
  if (retVal <= 0)
  {
    Serial.print(F("Connecting to "));
    Serial.println(mySSID);
    // esp8266.connect([ssid], [psk]) connects the ESP8266
    // to a network.
    // On success the connect function returns a value >0
    // On fail, the function will either return:
    //  -1: TIMEOUT - The library has a set 30s timeout
    //  -3: FAIL - Couldn't connect to network.
    retVal = esp8266.connect(mySSID, myPSK);
    delay(60);
    if (retVal < 0)
    {
      Serial.println(F("Error connecting"));
      errorLoop(retVal);
    }
  }
}

void displayConnectInfo()
{
  char connectedSSID[20];
  memset(connectedSSID, 0, 20);
  // esp8266.getAP() can be used to check which AP the
  // ESP8266 is connected to. It returns an error code.
  // The connected AP is returned by reference as a parameter.
  int retVal = esp8266.getAP(connectedSSID);
  if (retVal > 0)
  {
    Serial.print(F("Connected to: "));
    Serial.println(connectedSSID);
  }

  // esp8266.localIP returns an IPAddress variable with the
  // ESP8266's current local IP address.
  IPAddress myIP = esp8266.localIP();
  Serial.print(F("My IP: ")); Serial.println(myIP);
}

void flow() // Interrupt function
{
   flow_frequency++;
}

void setFlow()
{
   // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client1;
  client1.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client1.connect(destServer, port); //Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  //[Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("flow");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
   }

  // print and write can be used to send data to a connected
  // client connection.
  String httpPostRequest = "GET /aquosdb/setFlow.php?data=" + String(l_hour) + " HTTP/1.1\n" //sets the water flow value
                           "Host: 192.168.0.101\n" //private ip
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
  client1.print(httpPostRequest);

  while (client1.available()) // [Kugan] 28/7/16 Code ID: 1128  to clear the buffer
    Serial.write(client1.read()); // read() gets the FIFO char

  if (client1.connected())
    client1.stop(); // stop() closes a TCP connection.
}

void valveControl()
{
  // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client;
  client.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127 stop any existing connections

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client.connect(destServer, port); // Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  // [Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("valve");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

  // print and write can be used to send data to a connected
  // client connection.
  client.print(httpRequest);

  // available() will return the number of characters
  // currently in the receive buffer.
  int onCount = 0;
  int offCount = 0;

  while (client.available())
  {
    char c = client.read();

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

  // connected() is a boolean return value - 1 if the
  // connection is active, 0 if it's closed.
  if (client.connected())
    client.stop(); // stop() closes a TCP connection.
}

// errorLoop prints an error code, then loops forever.
void errorLoop(int error)
{
  Serial.print(F("Error: ")); Serial.println(error);
  Serial.println(F("Looping forever."));
  for (;;)
    ;
}

// serialTrigger prints a message, then waits for something
// to come in from the serial port.
void serialTrigger(String message)
{
  Serial.println();
  Serial.println(message);
  Serial.println();
  while (!Serial.available())
    ;
  while (Serial.available())
    Serial.read();
}

Thanks in advance for your efforts to answer my question.

The sample code looks fine, and shouldn't cause your problem. So my guess is that there is something wrong in the rest of the code. Either that or the board is somehow resetting.

The biggest obstacle to you getting this working is the somewhat bizarre way you are working out what has been sent to you, by counting characters that match and waiting until they reach 22.
Instead you should read the input character by character and place them into an array. Discard anything past the 22nd character so it doesn't overflow the array. Then you can compare what is in that array to strings stored in flash (using the F() macro) and the strcmp_P() function.


text:
How I can use multi sensor in one code in Arduino?
How I can use multi smoke sensor in one code? I mean how can I use more than one sensor, where both sensors has the same purpose, like use smoke sensor in multi room. Similar to this code where one is used only. How I can more than one, in Arduino Uno R3,,
<per>
    int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
 pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

How I can add more than one sensor to get same purpose. check detect 1 and detect2 and detect 3 if one of this detection LED Red ON, Thanks`

just duplicate the parts of the code that handle the sensor.
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeSensor1 = A5;
int smokeSensor2 = A4;
int smokeSensor3 = A3;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeSensor1, INPUT);
  pinMode(smokeSensor2, INPUT);
  pinMode(smokeSensor3, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor1 = analogRead(smokeSensor1);
  int analogSensor2 = analogRead(smokeSensor2);
  int analogSensor3 = analogRead(smokeSensor3);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor1);
  // Checks if it has reached the threshold value
  if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

You haven't mentioned what sensor you are using, so I can't offer any help on how to interface with it. Though you can add 'multi-sensor code' by adding code that will get the state of the sensor at times when you can afford to wait a few ms before checking the state of the other sensors. With the code you provided, you could after the if/else block but before the delay.
Also, it is typically not a good idea to put sensors far away from each other but still connect them to the same controller. You should give each room its own Arduino.

I use Mq2 smoke sensor. I mean use mq2 sensor in many room at least 3 sensor in one Arduino uno.


text:
How to correctly serve a webpage from an SD card
It's been days that I'm trying to figure it out how to edit this perfectly working code in order to load load a webpage from the sd card.
#include <SPI.h>
#include <Ethernet2.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;
boolean L1chk;
boolean L2chk;
boolean L3chk;
boolean L4chk;
boolean L5chk;
boolean L6chk;
boolean L7chk;
boolean L8chk;
int led;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);

pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
         }

         //if HTTP request has ended
         if (c == '\n') {
           Serial.println(readString); //print to serial monitor for debuging

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println();
           client.println("");
           client.println("");
           client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
           client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
           client.println("<TITLE>CONTROLLO LEDS</TITLE>");
           client.println("");
           client.println("");
           client.println("
FLASHATI
");
           client.println("
");
           client.println("LED1");
           client.println("LED2");
           client.println("LED3");
           client.println("LED4");
           client.println("LED5");
           client.println("LED6");
           client.println("LED7");
           client.println("LED8");
           client.println("
");
           client.println("
");
           client.println("
Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!
");
           client.println("
");
           client.println("");
           client.println("");

           delay(1);
           //stopping client
           client.stop();
           //controls the Arduino if you press the buttons
           if (readString.indexOf("?1") >0){
               ledUno();
            }
           if (readString.indexOf("?2") >0){
               ledDue();
            }
            if (readString.indexOf("?3") >0){
               ledTre();
            }
            if (readString.indexOf("?4") >0){
               ledQuattro();
            }
            if (readString.indexOf("?5") >0){
               ledCinque();
            }
            if (readString.indexOf("?6") >0){
               ledSei();
            }
            if (readString.indexOf("?7") >0){
               ledSette();
            }
            if (readString.indexOf("?8") >0){
               ledOtto();
            }
           readString="";
        }

        }
    }
}
}

So I came out with this after a lot of research:
/*
    Created by Rui Santos
    Visit: http://randomnerdtutorials.com for more arduino projects

    Arduino with Ethernet Shield
*/

#include <SPI.h>
#include <Ethernet2.h>
#include <SD.h>
File webFile;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;
boolean L1chk;
boolean L2chk;
boolean L3chk;
boolean L4chk;
boolean L5chk;
boolean L6chk;
boolean L7chk;
boolean L8chk;
int led;

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);

    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    // start the Ethernet connection and the server:
    Ethernet.begin(mac);
    server.begin();
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
}

void loop() {
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println();
                    // send web page
                    webFile = SD.open("index.htm");        // open web page file
                    if (webFile) {
                        while(webFile.available()) {
                            client.write(webFile.read()); // send web page to client
                        }

                        webFile.close();
                    }
                    break;

                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                    if (readString.indexOf("?1") >0){
                        ledUno();
                    }
                    if (readString.indexOf("?2") >0){
                        ledDue();
                    }
                    if (readString.indexOf("?3") >0){
                        ledTre();
                    }
                    if (readString.indexOf("?4") >0){
                        ledQuattro();
                    }
                    if (readString.indexOf("?5") >0){
                        ledCinque();
                    }
                    if (readString.indexOf("?6") >0){
                        ledSei();
                    }
                    if (readString.indexOf("?7") >0){
                        ledSette();
                    }
                    if (readString.indexOf("?8") >0){
                        ledOtto();
                    }
                    readString="";
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
                //controls the Arduino if you press the buttons

            }

        }
        delay(1);      // give the web browser time to receive the data
        client.stop();
        if (readString.indexOf("?1") >0){
            ledUno();
        }
        if (readString.indexOf("?2") >0){
            ledDue();
        }
        if (readString.indexOf("?3") >0){
            ledTre();
        }
        if (readString.indexOf("?4") >0){
            ledQuattro();
        }
        if (readString.indexOf("?5") >0){
            ledCinque();
        }
        if (readString.indexOf("?6") >0){
            ledSei();
        }
        if (readString.indexOf("?7") >0){
            ledSette();
        }
        if (readString.indexOf("?8") >0){
            ledOtto();
        }
        readString="";
    }
}

void ledUno(){
    led = 2;
    if (L1chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L1chk = 1;
        return;                   //Led 1 acceso
    }

    if (L1chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L1chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledDue(){
    led = 3;
    if (L2chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L2chk = 1;
        return;                   //Led 1 acceso
    }

    if (L2chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L2chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledTre(){
    led = 4;
    if (L3chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L3chk = 1;
        return;                   //Led 1 acceso
    }

    if (L3chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L3chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledQuattro(){
    led = 5;
    if (L4chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L4chk = 1;
        return;                   //Led 1 acceso
    }

    if (L4chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L4chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledCinque(){
    led = 6;
    if (L5chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L5chk = 1;
        return;                   //Led 1 acceso
    }

    if (L5chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L5chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledSei(){
    led = 7;
    if (L6chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L6chk = 1;
        return;                   //Led 1 acceso
    }

    if (L6chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L6chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledSette(){
    led = 8;
    if (L7chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L7chk = 1;
        return;                   //Led 1 acceso
    }

    if (L7chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L7chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledOtto(){
    led = 9;
    if (L8chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L8chk = 1;
        return;                   //Led 1 acceso
    }

    if (L8chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L8chk = 0;
        return;                   //Led 1 acceso
    }
}

So far the web page is correctly loaded, but the sketch of the LED light logic seems to not work anymore like it was working correctly before. I thought that maybe someone of you guys could help point me in the right direction.

What happened to the "readString" after your edit?

@MikaelPatel What do you mean?

You removed the section after the comment  //read char by char HTTP request.

@MikaelPatel it was just for debuggin purpose

It looks that I found the solution to my problem, the first skecth was working correctly because  the SD card is using the pin 4  for his purpose, so the sketch was working good becuse the SD card was not used here, in the second code where I used th SD card to serve a webpage was not working anymore not because of the code, but becuse the PIN 4 where I connected a led was used by SDcard and so it messed up by blinking the LED
DON'T USE PIN4 WITH AN ETHERNET SHIELD IF YOU PLAN TO USE THE SD CARD

A pin plan can help. Download http://fritzing.org/download/ and save a plan. You don't need to create a full schema to still document how you are going to use your pins. Very handy when you pick up this project in half a year or so.


text:
Is it possible to power this 12V Wind Speed Sensor with a 5V battery?
I have a battery pack used to charge mobile phones. It's capacity is 13,000mAh and it has two output ports. Both are 5V but one is 1A and the other 2.1A
It also has an Input port of 5V 1A. (To which I will connect a solar panel).
I want to be able to power this Adafruit Feather M0 as well as this Wind Speed Sensor Wind Speed Sensor Voltage Type(0-5V) SKU:SEN0170. Is it possible and if it is how?

Not directly, no. They don't put "9-24V" on it just for fun - specs are specs. They are to be taken note of. You will have to find some way of increasing the 5V to more than 9V (google "Boost Regulator").

If you have a circuit diagram for your 13,000mAh 5V battery, check whether there are internal connections at higher than 5V.  Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit.
An item like a “5V DC to 9V DC Converter DC-DC Isolated Power Supply Module” as in picture below [from ebay seller bidcenter] might do the job.  Also available are less-expensive not-potted adjustable boost regulators.

Because 5V is not a common battery voltage, there probably are cells in a higher-voltage series connection, being converted to 5V output via a step-down (buck) circuit. -- More likely 3.7V LiPoly stepped up through a boost converter. Makes the charging the pack simpler off a 5V USB connectoin.

@Majenko, possibly some  charge packs do it that way.  The teardowns of such units that I've seen usually have at least 2 LiPoly cells in each series string.  Frequently, buck (stepdown) conversion is slightly more efficient than boost.

All the USB charger battery packs I own are boost - that includes solar charged Li-Poly packs and 4xAA batteries (yes, 4xAA boosted - it runs with just 2xAA in there).


text:
How to attach Arduino MKR1000 to a shield meant for Arduino UNO?
I have an Arduino MKR1000 and need to interface it to an Adafruit Music Maker shield, which has pinouts for an Arduino UNO.
Maybe I'll have to attach female headers, and then jumper pins over.
Which pins on MKR go to which pins on Music Maker?
I have to use the MKR1000 because I'm getting the audio from wifi (using MKR1000) and then sending it to Music Maker.

This sort-of sounds like your 1st Arduino project.  The jump from using a Atmel ATmega328P processor to an Atmel ARM processor, in my experience, is not free from problems. Let alone the differences in the boards.  I would suggest you prototype your project using the intended host, the Arduino Uno.  Then try using the MKR1000.  You obviously can't do everything with the Uno.  But I would at least talk to the Music Maker using a Uno then try it with the MKR1000.  Add more features and repeat the test until you have exhausted what you can do on the Uno platform.

The intended host is MKR1000, not UNO.

Yes yes, I'm suggesting, if you are having problems with the MKR1000, to try small parts of your code on the Uno - the intended host of the Adafruit Music Maker PCB.  If the code, Uno and Music Maker board work and switching to the MKR1000 does not, then you know you either have a wiring problem or switching from the ATmega328P processor to the ARM processor is causing unexpected difficulties.  As to which pins go where, if the MKR1000 is touted as 100% Arduino compatible, then the pin labeling should match.  Be sure to check if both boards are designed for the same voltage (5v or 3.3V)!

Wowa, did you read this?: "Warning: Unlike most Arduino & Genuino boards, the MKR1000 runs at 3.3V. The maximum voltage that the I/O pins can tolerate is 3.3V. "   Double check how the Adafruit Music Maker board is put together!  There's some talk on the Adafruit Music Maker product page about level shifting but it sounded a bit vague.  Since both these items are on the Adafruit web site you might post a Music Maker / MKR1000 compatibility question directly to them on one of their forums.


text:
Converting uint8_t to String - unexpected result
I'm working on a remote control code for ESP controller. Using ESPwebserver and Fastled. When I try to return a value of an uint8_t, as a POST response, i got strange result here is the relevant code:
uint8_t PaletteBrightness = 255;

server.on("/Sync", HTTP_POST, []() {
String Sync = "PaletteBrightness:" + PaletteBrightness;
    Sync += ":end";
    Serial.println(Sync);
    server.send(200, "text/plain", Sync);
  });

The code complies, and runs fine but the result of 'Sync' in both serial, and POST response is:
Phase:end

Why? What does even Phase mean?
What I want is:
PaletteBrightness:255:end

Where the 255 is the value of 'uint8_t PaletteBrightness' Also, there will be more values, to add the 'Sync' string. Just trying to get one right.

You should convert your number uint8_t into it's ASCII representation before appending it to your string, otherwise you are appending just one character using it's byte representation.
To do so you can use a standard function itoa() which has a decent documentation available here.
So change line
 String Sync = "PaletteBrightness:" + PaletteBrightness;

into
 char buffer [4];
 String Sync = "PaletteBrightness:" + itoa(PaletteBrightness, buffer, 10);

I've ended up using
String(PaletteBrightness); And it seems to do the trick. Would it be better to use itoa()?

Avoid the use of String at all costs unless there absolutely no alternative. https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Will read this trough. I need to send and receive data from client which is done in http post, effectively plain text. Don't think there is a way around strings there.

Yes, there is at least another way: array of chars. And before you ask, strings are not just array of chars, remember you are dealing with C here, not Java or JavaScript. Also memory is a big constraint, anything that is dynamically allocated must be strictly controlled and memory fragmentation can quickly become an issue.

Okay, I read up on String, and now i understand a bit better why are they bad. However, ESP8266WebServer.h
Uses lots of Strings, and related String object functions. Isnt that also wrong? or I'm missing some key elements here.

Probably the code you are referring to was meant as an introductory or learning (may be both?) resource... As such the author did use strings to make it easier to understand for people coming from other languages (Java, JavaScript,etc...)... Please also note he is using references to, at least, minimize the impact of using strings. Also, ESP8266 has much more SRAM than an ATmega328 (Arduino), which somewhat mitigates the problem. And in any case, the fact somebody else has done something not good does not justify you doing the same mistake...

Make sense, I re wrote the entire code, http://pastebin.com/8aQdhgdQ
Hopefully its better now. Also found reserve(); function, so When i figure out how many byte  is the final string, it should be good enough. Any opinion?


text:
how to get an unofficial WiFi Shield to work?
I just bought these two WiFi Shields -> http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
As they arrived I put one of them onto my Arduino Uno R3 and tried if my LED test sketch still works. It did.
After that I tried this WiFi tutorial (https://www.arduino.cc/en/Tutorial/ConnectWithWPA) to play around with the WiFi API a little bit. Sadly it prints to the serial monitor "WiFi shield not present" which tells me I missed something when setting up the shield.
I just thought the WiFi shield will be already usable without wiring anything. Surely that might be naive somehow, but hey I'm still a noob ;)
Can you guys tell me or simply point out a tutorial where it tells me what wiring I have to do to at least get pass this "WiFi shield not present" check?
Then I just realized that I do not have the "real" Arduino WiFi Shield and therefore the origin WiFi lib won't work for me according to this thread: http://forum.arduino.cc/index.php?topic=371362.0
Sadly I did not received any documenation on how to get this thing to work now. I found A LOT of threads about the "WiFi shield not present" error but none of them solved my specific problem with the shields I bought.

Somewhere it should say this: It is really really difficult to implement enough of the TCP/IP stack on an Uno to handle talking over the Ethernet.  In other words, the shield is doing almost all the work.  As such, if you don't have any documentation, using this Ethernet shield will be difficult.  That said, it looks like this shield is using an ESP8266 which IS widely documented. And if you search around, can even find people creating Arduino / ESP8266 software.