text:
I put some defines into a .h file, and get errors
I'll post the whole code if you really need to see it, but my question is pretty simple.
In my sketch I define some parameters:
#define SSID "Kaywinnet"
#define PASSWORD "806194edb8"
#define MQTT_SERVER { 192, 168, 1, 124 }

And, the sketch compiles just fine.
But, rather than putting my net parameters into every sketch, I wanted to just use a .h file so that if something changes, I only have to change it once.
Here's the problem.  When I put these three lines into a .h file, I get an error when the first parameter is used in the sketch:
expected primary-expression before '.' token

Here is the code where I use the value:
//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

The error is on the .ssid= line.
So, why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??
Here's the ino file:
    /*****

  Projects/esp8266/MQTT nodes/light2.ino
  10/3/2017- Clone of studio.ino

  IDE settings:
  Board: "Generic 8266 Module"
  Flash Mode: "DOUT"

*****/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESPHelper.h>

//#include <Kaywinnet.h>
#define SSID "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

//#define toggle    //Using toggle switch.
#define pushbutton    //Using pushbutton switch

#define NODENAME "light2"
const char *cmdTopic =  NODENAME "/light";
const char *statusTopic = NODENAME "/light/status";
const char *connectName =  NODENAME "lights";
#define OTAPASSWORD "xxxx"

//Defaults to DHCP, if you want a static IP, configure below
//#define STATIC_IP
#ifdef STATIC_IP
IPAddress ip(192, 168, 1, 50);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
#endif

//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

//Declare an object of class WiFiClient
WiFiClient esplight2;
PubSubClient client(esplight2);

#define esp8266-01    //Either sonoff or esp8266-01

//Define the GPIO pins on the 8266-01
#ifdef esp8266-01
const int buttonPin = 0;    //GPIO0
const int relayPin = 2;     //GPIO2
#endif

#ifdef Sonoff
const int buttonPin = 0;     //GPIO0
const int extraPin = 14;
const int ledPin = 13;
const int relayPin = 12;
const bool ledOFF = HIGH;
const bool ledON = LOW;
#endif

int switchVal = 0;
int currentVal = 0;
bool relayState;
String payLoad;

// * *************** RelayControl, remember the state ***************
//
void RelayControl(bool state) {
  //Serial.print("relayState: ");
  //Serial.println(relayState);

  digitalWrite(relayPin, state ? HIGH : LOW);
  relayState = state;

  //Feedback over MQTT
  if (relayState) {
    client.publish(statusTopic, "on");    //Tell Node Red about the current status
    Serial.println(String(statusTopic) + "= on.");
  } else {
    client.publish(statusTopic, "off");
    Serial.println(String(statusTopic) + "= off.");
  }
  Serial.println();
}

void timeLoop (long int startMillis, long int interval) { // the delay function
  while (millis() - startMillis < interval) {}
}

/*
 * ************** blink the LED ************************
   We assume the LED is on after connecting.
*/
void blinkLED() {
#ifdef esp8266-01
  return;   //No led on the esp to blink..
#endif
#ifdef Sonoff
  digitalWrite(ledPin, ledOFF);
  delay(500);
  digitalWrite(ledPin, ledON);
#endif
}

/*
 * ******************** set up WiFi ****************
*/
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(SSID);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}

/*
 * *************** MQTT callback ********************
*/
void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");

  String messageTemp;
  for (int i = 0; i < length; i++) {
    //Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  messageTemp.trim();            // trim the white space off the string

  Serial.println(messageTemp);

  // If a message is received with the topic 'cmdTopic', check if the message is either on or off.
  if (topic == cmdTopic) {
    if (messageTemp == "on") {
      Serial.println("Light2 is ON");
      RelayControl(HIGH);
      blinkLED();

    }
    else if (messageTemp == "off") {
      Serial.println("Light2 is OFF");
      RelayControl(LOW);
      blinkLED();

    }
  }
}

/*
 * **************** Connect to MQTT broker **************
   This functions reconnects your ESP8266 to the MQTT broker and subscribes to topics.
*/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(connectName)) {
      Serial.println("connected");
#ifdef Sonoff
      digitalWrite(ledPin, ledON);
#endif
      // Subscribe or resubscribe to a topic
      client.subscribe(cmdTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

/*
 * *************** SETUP ********************
*/
void setup() {

  //espHelper
  myESP.OTA_enable();
  myESP.OTA_setPassword(OTAPASSWORD);
  myESP.OTA_setHostname(NODENAME);
  myESP.begin();

#ifdef Sonoff
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledOFF);     //The Sonoff LED is low-true.  This starts with it off.
#endif

  pinMode(relayPin, OUTPUT);
  RelayControl(LOW);  //Start with the heat off

  pinMode(buttonPin, INPUT_PULLUP);

  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  //Save the initial switch position.
  currentVal = digitalRead(buttonPin);

  Serial.print("cmdTopic= ");
  Serial.println((String(cmdTopic)));
  Serial.print("statusTopic= ");
  Serial.println((String(statusTopic)));
  Serial.print("connectName= ");
  Serial.println((String(connectName)));
  Serial.println("...............");
}

/*
 * *************** LOOP ***********
   The loop function begins with making sure that your ESP is connected to the broker.
*/
void loop() {
  myESP.loop();  //run the loop() method - this keeps the network services running

  if (!client.connected()) {
    reconnect();
  }
  if (!client.loop())
    client.connect(connectName);

#ifdef toggle
  /*
   * ******** Toggle switch attached **********
  */
  //Has the switch position changed from the last loop?
  //If yes, the save the new setting and toggle the heat.
  switchVal = digitalRead(buttonPin);
  if (switchVal != currentVal) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal != currentVal) {   //debounce
      currentVal = switchVal;
      relayState = !relayState;
      RelayControl(relayState);

      /*    //For simultaneous control over MQTT
            if(relayState){
                client.publish("studio/heat","on");
              }else{
                client.publish("worksgop/light","off");
              }
      */

    }
  }
#endif

#ifdef pushbutton
  /*
   * ***** Momentary pushbuttom switch attached *******
  */
  //When the switch input goes low, toggle the light.
  switchVal = digitalRead(buttonPin);
  if (switchVal == LOW) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal == LOW) {   //debounce
      relayState = !relayState;
      RelayControl(relayState);
      delay(1000);            //Delay if the button is held too long.
    }
  }
#endif

  yield();
}

And here is Kaywinnet.h
#define ssid "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

We need the complete sketch, both .h and .ino. This is a recurrent error with Arduino IDE (and UECIDE sometimes).

Did you #include the .h file in your sketch before you used the macros?

Majenko-  Yes.  The include line is at the same place in he sketch as the internal defines.  If I uncomment the include and comment the three defines right under it, compile fails.

Why is SSID lowercased in Kaywinnet.h?

Yeti and per1234 found the error - DOH! Thanks...

Here's the ino file:
  ...
#define SSID "Kaywinnet"

...
  .ssid = SSID,

...
  And here is Kaywinnet.h
#define ssid "Kaywinnet"

...
  The error is on the .ssid= line.

C++ is case sensitive. You changed the macro name from SSID to ssid when you moved the defines to the .h file.

why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??

easy:
1) go back to the non-fancy version where you put the strings back into the code.
2) get it to compile.
3) then extract the strings to macros.
by going through that, you will know precisely the mistakes you made.

You lost me on this one.  What do you mean to 'extract the strings to macros'?


text:
Save data from an LCD KeyPad Shield to an sd card
I'm developing a project that requires save data from a sensor that is connected in a LCD keypad shield, the information should be save in a file into SD card.
My code

#include <LiquidCrystal.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int buttons;
File myFile;
//name of the file
char nombrefichero[12];
int i = 1;
int exist = LOW ;

void setup() {
Serial.begin(9600);
//check the sd card adapter
  Serial.print("Iniciando SD ...");
  if (!SD.begin(53)) {
    Serial.println("No se pudo inicializar");
    return;
  }
  Serial.println("inicializacion exitosa");
}

void loop() {
// use the buttons of the lcd keypand shield in analog 0
buttons = analogRead(0);

//button right
if(buttons < 50){
  count ++;
  nuevo();
}

//button select
if(buttons < 790){
  capturar();
}

}

void capturar(){
  myFile = SD.open(nombrefichero, FILE_WRITE);//abrimos  el archivo

  if (myFile) {
        Serial.print("Escribiendo SD: ");
        int sensor1 = analogRead(0);
        int sensor2 = analogRead(1);
        int sensor3 = analogRead(2);
        myFile.print(millis());
        myFile.print(",");
        myFile.print(sensor1);
        myFile.print(",");
        myFile.print(sensor2);
        myFile.print(",");
        myFile.println(sensor3);

        myFile.close(); //cerramos el archivo

        Serial.print("Tiempo(ms)=");
        Serial.print(millis());
        Serial.print(",sensor1=");
        Serial.print(sensor1);
        Serial.print(",sensor2=");
        Serial.print(sensor2);
        Serial.print(",sensor3=");
        Serial.println(sensor3);

  } else {
    // if the file didn't open, print an error:
    Serial.println("Error al abrir el archivo");
  }
  delay(1000);
}

void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i); //generate autoincrement number of
file

    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I need capture the information of the sensor when I pressed the select button and when the right button is press create a new file in this method, in this line if(SD.exists(nombrefichero)) if I put the ! before SD.exist the files are created infinite but if I leave it as is without the ! the button does nothing
void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i);
    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I'm use arduino mega 2560 and SD card Adapter

Don't cross post. You already asked this on SO.

source: Stack Exchange

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

sort: votes


text:
CH340 3.3v stability
I want to use the 3.3v on a cheap Arduino Nano clone as my ADC analog reference voltage. The 3.3v comes from a regulator inside the CH340 USB serial chip.
I've measured the voltages (My DMM is NOT calibrated) on seven different Nanos and the voltages vary (2.96-3.38v).
I'm happy to calibrate each board to this voltage, but are there any figures available on how stable this 3.3v supply is? Long term and temperature wise?

Datasheet says?

Very little, just that it's a 3.3v LDO rated to 25mA

The internal analog voltage reference of 1.1V is better. That voltage can be 1.0 to 1.2V so you have to determine it for each board (just once). After setting the analogReference to 1.1V, you can measure the actual voltage at the aref pin: http://www.pighixxx.com/test/portfolio-items/nano/ Why do you need a reference of 3.3V? Is it for a analog sensor running at 3.3V?

I wanted to try the 3.3v as the input voltage from USB (VCC) differs on each host it's plugged into.  I'm wanting to measure an external battery voltage.  It goes through a voltage divider with high precision resistors, but if I divide it down to a max of 1.0 volts, I have to use very high precision resistors for the divider circuit.

@John see my answer; in any case your 3.3V varies not only from host to host, but also during the time. If you want a precise measure, use an external reference, otherwise you'll have to calibrate the internal one. And if you don't want to use a high reducing of the input voltage, use the trick I wrote in the answer (measure the reference and then use that measure to compensate)

Using the VCC as voltage reference is ok only if

you accept poor performances or
you need to measure a ratiometric output.

Case 2 is because the output depends on VCC (so you compensate). For instance, if you want to get the value of position in a potentiometer, you have that the voltage you see is Vo = Vcc * X (where 0<=X<=1 is the position), then the result you have on your ADC is Y = Vi / Vcc * k = X * k (where k is the maximum value of the ADC reading - e.g. 1023). So you actually compensate the Vcc deviation.
If you want to measure an absolute voltage, however (case 1) you will have a lot of uncertainties. For instance, if your current varies during the time (for instance you turn on the LED), the Vcc voltage can vary quite a lot. This is why for precise measurements you always must use a voltage reference.
In your case, you can

Use the internal reference - for the Atmega328 it is nominally 1.1V, but it can range from 1.0V to 1.2V
Use an external reference

You have to keep in mind that the voltage reference is the maximum value you can read. For instance, if you use the internal reference and then try to measure a 2.3V, you will not be able to do it (you will read the maximum value of 1.1V)
In order to fix this, you can use a trick: use Vcc as reference, and then use a voltage reference to get a precise calibration every time you need to measure something. For instance, if you have to read values from ADC1 and ADC3, you can

Read the value of the internal/external reference
Read ADC1
Read ADC3
Use the reading in point 1 to be able to guess what ADC1 and ADC3 readings were

This way you compensate for variations in the supply.
Just note that, even if the internal reference is not very precise (it has a 10% deviation from the standard value), it is indeed stable, while the VCC varies (a lot) during time. So if you have to calibrate, calibrate against the internal reference and not the Vcc.
If you can afford an external voltage reference, these are usually very stable and have very little deviation from sample to sample, so you may assume their value is "fixed"

Thanks, I don't quite understand where the voltage reference connects to - I'm pretty sure I cant connect a voltage reference up to ARef and simultaneously use VCC as the reference.
In your example did you mean to, leave ARef internally connected to VCC, connect the precise reference to ADC1 and my analog input ADC3?

@John In fact it was implicit that you have to attach the reference to another ADC channel, and treat it as another input. Then you can make the measruements relative to that one. If you use the internal reference, you have a special channel (look on the datasheet) used to read the voltage, but of course you will have to use the VCC as reference

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


text:
'TCCR0B' undeclared
I am trying to compile the function in http://playground.arduino.cc/Code/PwmFrequency
This produces a couple of errors
sketch/setPwmFrequency.c:34:3: error: unknown type name 'byte'
   byte mode;
   ^
sketch/setPwmFrequency.c:45:7: error: 'TCCR0B' undeclared (first use in this function)
       TCCR0B = TCCR0B & 0b11111000 | mode;

byte is trivial, but I can't seem to find TCCR0B et al I assume it should be defined somewhere.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

Other that missing setup() and loop(), that code compile OK with Arduino IDE 1.8.5 and UECIDE 0.9.1

@LookAlterno How can a verbatim download of the code from the link to the Arduino site be insufficient?

Insufficient because the link is not the whole picture. It's missing other things that you added. And this kind of problem is all about how do you arrange your sources. Yesterday I had a problems like yours and the solution was ... rename eeprom.ino to Eeprom.ino. Would you believe that? That is why we need your complete sketch.

Your chip doesn't have that register. Find out what the original code does and implement the same functionality on the target chip.

Both errors can be solved by adding the following line to your setPwmFrequency.c:
#include <Arduino.h>

This will include the files that contain the byte typedef and also the register definitions.
You may notice that is not necessary in an .ino file. The reason is that the Arduino IDE automatically adds the Arduino.h include to .ino files during sketch preprocessing before compilation.

The #include partially solved the problem, but still didn't link. Maybe I could have solved with a .h file. I gave in to the dark side, and renamed it .ino. Life would be so much easier if Arduino didn't try to redefine c/c++ - particularly when the language seems to have changed since I last used it.

I assumed you would have a .h file to go with your .c file. I did my testing with that setup and it did indeed compile. The Arduino IDE really doesn't mess with the language much. Pretty much the only thing other than the automatic Arduino.h include in .ino files is it generates function prototypes in .ino files where necessary but you can manually declare them if you like. main() is hidden away in the core library but that's still standard c++.

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


text:
Error with pointer in array
I am currently learning pointers. I am following a book (Says Teach Yourself "Arduino Programming") in which there is an exemple about pointer and array.
void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  char string1[] = "This is my test string";
  char string2[]="This is another string test";
  char *ptr2 = string2;
  char *ptr1 = string1;

  while (*ptr1 != '\0') { // not "\0"
    *prt2 = *prt1;
    ptr1++;
    prt2++;
  }
  Serial.println(string1);
  Serial.println(string2);
}

void loop() {
  // put your main code here, to run repeatedly:

}

I get an error "ptr2 was not declare in this scope."
I don't know what is wrong...
That for your help.

Are you sure the error says ptr2 and not prt2?

"ptr2" != "prt2"
You have a typo there.

the classical ptr vs prt, cmd vs cnd, cnt vs cmt, cmt vs cmd and so on... :)

It's teh typical typo :)

haaa.... Thanks.  I have spent 4 days in a row learning Arduino.... I must be tired. thanks again and sorry for such stupid question. it is working just fine now :-)


text:
How to only detect the opening and closing of door sensor once
im quite new to Arduino coding. Currently im trying to create an alarm and when the alarm ring, the user will just need to remove the door sensor once to stop the alarm and listen for the next alarm. What i have is Real Time clock module to keep track of the time.
So i have tried to code on my own but failed and here's the outcome:
After the alarm ring, and i remove the door sensor from each other, it stopped buzzing (Which is correct partly) but once i put it back together, it continued to ring for the alarm duration (Which was set as 1 min)
Here's the code i had:
#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
DS3231  rtc(SDA, SCL);
Time  t;
#define buz 11      //This is Buzzer that is plug into pin 11 (Change it accordingly to what you will be putting it in the arduino)
int Hor;            // This is declaring the alarm in Hours
int Min;            // This is declaring the alarm in Minutes
int Sec;            // This is declaring the alarm in Seconds
const int sensor = 10;    // Door sensor connected to Pin 10
int state; // 0 close - 1 open switch

void setup()
{
  Wire.begin();
  rtc.begin();
  Serial.begin(9600);
  pinMode(buz, OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Alarm");
  lcd.setCursor(0,1);
  lcd.print("Test");
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
  delay(2000);
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());

  alarm1();
  alarm2();
  delay(1000);
}

void Buzzer()
{
  digitalWrite(buz,HIGH);
  delay(500);
  digitalWrite(buz, LOW);
  delay(500);
}

void alarm1() //E.g. This is the first alarm for the medicine
{
  state = digitalRead(sensor);
  if( Hor == 20 && (Min == 11 || Min == 12) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else if ( Hor == 20 && (Min == 11 || Min == 12) && state == 1)
  {
    noTone(buz);
  }
  delay(200);
}

void alarm2()
{
  if( Hor == 19 && (Min == 48 || Min == 49) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else
  {         //Once user open the door sensor, the alarm will stop buzzing
    noTone(buz);
    alarm1();
  }
  delay(200);
}

Just to clarify that the variable state i took from
http://www.instructables.com/id/How-to-Use-a-Magnetic-Door-Switch-Sensor-With-Ardu/
So to summarised my problem, i am trying to get the system to read the opening of the door sensor once so that the alarm will stop and listen to the next alarm regardless if i put it back the door sensor or not
Really hope someone can help me thanks for you kind attention

Please, provide a link to the libraries you are using. There are tons of libraries called “DS3231”, which are not compatible with one another.

As often, the answer to this question is “Implement a ‘Finite State
Machine.’”. In this instance, you need at least three distinct
states:

ARMED: the buzzer is not active, but it is only a matter of time...
ON: bzzzz... bzzzz... bzzzz...
STOPPED: the user has stopped the alarm.

Each of your alarms should have a start time and a stop time (say, two
minutes after the start time). Then, the possible state transitions are:

ARMED → ON: when we hit the start time of an alarm
ON → STOPPED: when the user stops the alarm
ON → ARMED: when we hit the stop time of the alarm
STOPPED → ARMED: when we hit the stop time of the alarm

Notice that, once the user stops the alarm, the only way for the buzzer
to start buzzing again is by going through the transitions STOPPED →
ARMED → ON. The first transition happens at the alarm's stop time,
whereas the second one happens at the next alarm's start time.
You did use a kind of state variable in your code, but the problem is
you failed to realize that ARMED and STOPPED should be distinct
states. If you fuse these states together then, when the user stops
actively “stopping” the alarm, and if it's still start time, the
system transitions immediately back to the ON state.


text:
Can I change Arduino program on-the-fly?
I have Arduino which is programmed to do something. Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.
What I need is to send the message via MQTT which will Arduino receive and change its behaviour by it. I managed to change the frequency of messages published or to add some new data, but what if I want to change how decisions are made. What if I want to change some Arduino code, to add some if or another state, can that be done on the fly?
Update: Changing device behaviour on the fly or after restart is acceptable. I am not strict with using arduino, nodemcu is and option. I just need a way to add new functionality to device if I need.

On NodeMCU you can upload a sketch OTA (Over The Air) using WiFi.

But that is using Arduino IDE, isn't it? Is it possible to change some code without need to reprogram it?

No, you have to replace the whole sketch.

Your code in stored in flash memory. Your code can't change the content of the flash memory. You must understand Arduino is NOT a computer. On a computer (Von Neumann architecture) we store code and data in RAM and we can change content of RAM. So a code can change itseof on the fly. Arduino has an Harvard architecture: code is in one memory, data inside another memory. Not possible for code to perform "self modification". On the other side you can have a code using a "script" and yuo can update this script (in RAM or EEPROM)

@Peter - you are mistaken.  Harvard architecture machines are very much "computers" as well.  The arduino is most definitely a "computer".  Additionally, although by no means a requirement for being a "computer", the Arduino can alter its own flash, though the process is a bit tricky, and one shouldn't design a scheme to do it repeatedly on an ongoing basis or the flash will wear out.

@Peter suggested: “you can have a code using a ‘script’”. I second that suggestion. See Interpreted Languages on Arduino playground.

@Chris Stratton  The fact of talking about Harvard had the main purpose of giving a better view of the problem. I played a lot with ASM and Self-modifying code (in the 80') and I see many people struggling, at basic level, with memory problem on the Arduino, because they think of it as a "small computer" when in fact, the principle is different. I agree we can have Harvard or Von Neumann computer, of course :) Cheers.

@Peter well, the fact that there is a bootloader able to reprogram the Arduino without an external programmer may tell you that the AVR is indeed capable of writing on its own flash ;)

@emir can you just clarify if you need the arduino to reprogram it "runtime", so without resetting, or just like you'd do if you connected to the USB port (but through the net)? If the former than the suggestion is to change the logic of the algorithm like JRobert suggests in his answer; if the latter, you can modify the bootloader to accept data from the network connection, then when you want to flash you have to reset the board and then connect to the bootloader (not so easy, but doable)

@frarugi87 restarting device is no problem. It would work in any way

@emir then it is possible, even if it is rather difficult. You will have to modify the bootloader so that it gets the program somewhere (e.g. a direct TCP connection). Note that the bootloader has a very limited space available. Then from the application when you receive the MQTT request you save a flag in eeprom and then reset the board; in the bootloader if the flag is present download the FW and write it in the flash, then clear the flag and reboot. When the flag is not present, launch the application. Even if... Again, if you can do what JRobert suggests it is MUCH better

@farugi87. Every thing is possible. But I think we must clarify a point: some tips and tricks are possible and can be used in coding party. But using them in real app is not the same story. ;)

Replacing or modifying the existing code during run-time will require some form of uploading and over-writing the old code. This is deliberately not made straightforward or easy for these kinds of micro-controllers.
But you can change the program's strategy on the fly, if you anticipate the potential changes and include the code for each of the possibilities.
For example, write a set of functions that each embody one of the various ways of operating, and, at run-time, select which function the program should use. You can change the selection by setting a value from the keyboard or the program could sense some external trigger such as a button-press, or a temperature reading and respond by changing the selection - the value of an int, perhaps. A switch statement can use that value to call the appropriate function at the appropriate time:
uint8_t strategy = 0;           // init to the default strategy

switch( selector ){
case(1):                // has event 1 happened?
   func1();
   break;

case(2):                // has event 2 happened?
   func2();
   break;

case(3):                // has event 3 happened?
   func3();
   break;

default:                // none of the above or undefined selector value
   funcDefault();
   break;
}

This does mean that all of the code for the possible operating strategies must be included at upload-time and share the program-memory space, but unless your job is very complex, even an Uno should be capable enough.
Update:

I need to be able to update the device with some new functionality.

There is another approach which may or may not fit in an Uno but would be doable with a Mega 2560 or other larger-RAMmed machine: interpreted code.

Define a set of operations that includes whatever you'll need to operate your external device(s): the necessary I/O operations to read your sensors and control your hardware; to make logical and/or arithmetic tests and conditionally branch or call a function based on the test result; to listen for a user-signal from the terminal (for example) and return to the arduino program. This will be the "language" in which you write your control program.
Define a concise coding scheme to specify each operation and whatever data it needs, such as reading a temperature sensor and storing the result in a named place. If your control programs won't be too complex, you can get away with pre-defining A, B, ..., Z to be data registers of some appropriate type.
In C++, write an interpreter for this new language. It's program will consist of the codes you just defined. But this code will be seen as data by the interpreter. This is the key - this pseudo-code will live in RAM, where your interpreter - a collection of C++ functions - can read and execute it, and the Arduino program can download a new one, over-write the old one, and run the interpreter again.

Caveat: Like the Greek mythological Hydra, this is a job that can grow new challenges as you address the current ones, but it is doable if you keep it simple as possible and include only what you must have to make it work.
Run-time-interpreted code can take 10 - 50 times as long to execute as a natively coded application, so anything that can be pre-coded in C++ should be. The finer and more flexible your interpreted instructions, the more expressive you can be when writing the control program, but the interpreter will be more complex to write, slower to execute, and harder to debug. Design your language to be only as flexible as it must be to allow you to write new control algorithms.
If you try to invent an entire pseudo-computer, completely flexible and capable of being programmed for any and all purposes, you'll drive yourself crazy. Whole businesses have folded after sinking money and time into inventing a new and better computer and got so bogged down they couldn't recover. Don't go that route.
Start with the grossest, least flexible operations you can live with and get that much working. Discover its limitations and address those, and only those, one at a time, until you have a sufficiently flexible system in which to control your device.

I am aware of this approach, but this would require knowing in advance about what device could do. I need to be able to update the device with some new functionality.

Code that writes to flash has to reside in the bootloader section.
The only way I know how to execute code in the bootloader section is
after a reset. However, even if you could transfer execution to the bootloader section and get something to work, it would
have to contend with the fact that flash has limited write cycles and
will reduce the life of the device. Possibly to the point of being
useless for a practical application.
Executing code from RAM. Self explanatory, modify code all you want.
There is an application note for AVR that discusses this.
Write an interpreter for your needs. yuk!

EDIT: There is some GCC code example here.

You should be able to jump to locations in the bootloader section provided that you know the assumptions of the code you placed there.  You can also do a soft reset.  But yes, the flash endurance is an issue.

I was not aware of limitation with a number of flashing. Do you refer to firmware flashing or updating a device with code using IDE or over OTA?

Write/Erase Cycles: 10,000 Flash/100,000 EEPROM

The claim about "executing code from RAM" is erronous.  That is not supported on an AVR, your link is to a document for an Atmel SAM-series ARM processor, not an AVR.

Sorry. Wrong application note. I was wondering why I wrote AVR. It came from this application note for AVR32825: Executing code from external
SDRAM Specifically for the AVR 32 UC3A and UC3C series.

You can change the behaviour of Arduino on-the-fly but it's not necessary to reprogram, just design your code to change behaviour with some variables you get form outsite e.g. a server, but this new changes must be defined previously in your code.
If you have a list of states and want to add more, use a dynamic array or use an array with enough space and when send a MQTT message that Arduino parses adding tha new state or even deleting a state.

I need to see how I can update the device with new functionality which was not previously planned.

Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.

(emphasis added by me).
As some answers pointed out, you can change the behaviour if you allow for it in advance. For example, store in EEPROM some setting (like how often something happens) and have a method of changing that setting.

Different bootloader
However if you want to change the behaviour completely then you need to upload new code (whether the code is in RAM or program memory doesn't really change this part).
The bootloader installed as a standard on the Arduinos allows for code to be uploaded via a protocol which arrives at the serial port shortly after reset. There is nothing to stop you writing your own protocol (eg. using MQTT) and make your own bootloader which uses that - assuming it is small enough to fit into bootloader space (the largest bootloader the Atmega328P can hold is 4096 bytes).

Stand-alone programmer
Since you asked about uploading new code without needing to have the computer, an alternative is to program it in the field using a stand-alone programmer. There are various ones around, including one developed by user Crossroads from the Arduino Forum:

I wrote the code for that one. The basic approach is to write your new code using the IDE (something you would have to do anyway) and then copy the .hex file to a SD or micro-SD card which is then inserted into the programmer as you can see in the photo. The programmer then connects to the target board via a ICSP interface using a 6-core cable as shown. This reprograms the target in about a second. This makes it practical to reprogram a device "in the field" without having to return it to your base, or carry a laptop around with you.

What you need is not a “one trick pony” (arduino) but an actual “horse” - Raspberry Pi. You have no reason not to such as:

Price - RPi Zero - $10
Size - ditto -about the size of a Nano
Functionality::
Pi . . . . . . . . . . . . . . . .  Arduino

wifi           . . . . . . . . . . . . . . . .  no (wifly /Zigbee now you violate #2)
bluetooth   . . . . . . . . . . . . . . . .  no
web server . . . . . . . . . . . . . . . .  no
mysql database . . . . . . . . . . . ..  no
any linux multithreaded
  apps. . . . . . . .. . . . . . . . . . . . .  no
etc etc etc
Did i miss anything? being a technology architect begins with knowing what hardware and software to apply in any given situation. I. E. avoid square pegs in round holes.

You forgot to mention the RPi Zero won't work without a good quality 4 to 8GB micro SD card for storage (OS, libraries and user programs). You also need a "USB OTG Cable", a 1 amp power supply with Micro USB connector, and if you want to connect it using HDMI, there an adapter required for that too. It would cost me $51.46 CDN plus $5 to $10 for shipping, just to get started with the RPi Zero.

Another thing to consider, is whether or not your project needs WiFi, and Bluetooth, and a web server, and MySQL. Why pay for all of this "horse power" if you're not going to use it. The RPi Zero is a computer, and needs to be treated as such. If the power drops on the Arduino, you won’t end up with a corrupt operating system or other software errors: it will just start running code when it’s plugged back in. For Raspberry Pi, you must shut it down within the operating system like any other computer, or else risk corruption and software problems.

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


text:
Speed measurement from lidar sensor for automatic braking system
For a school project I have been working on a system that will automatically brake when there is danger. Only the requirements are more strict (safety) than just using a ping sensor and detecting a fixed distance. I am going to implement the speed of an incoming object a swell.
On the internet I found this awesome 100Hz sample Lidar module that's very cheap. It uses UART with 2 header frames (0x59), after that a data Lowbyte and a data Highbyte.
So I've started inputting coffee and outputting code (in C) on the atmega328P (Arduino). Only I'm stuck for a few days now.
As you can see here I've set up the code to read the sensor and process the data. The problem is that it gives back weird readings, like a distance difference when I'm moving further away AND when moving closer even though I stated it not to.
Does anyone have experience using this module? Or maybe I misread something of the datasheet.
//Includes
//============================================================================================//
#include <avr/io.h>
#include <avr/interrupt.h>
#include <math.h>
//============================================================================================//

//Defines
//============================================================================================//
#define F_CPU 16000000                                          //CPU frequency
#define Baudrate 115200                                         //UART Baudrate
#define UBRR_VALUE (((F_CPU / (Baudrate * 8))) - 1)             //UART Baudrate set in Arduino
// #define SafetyRating 8
// #define sampleTime 0x65                                          //Time between 2 samples in 10^-4. This value comes from testing (its 1,01ms)
//============================================================================================//

//Enums
//============================================================================================//
enum {Safe, Warning, Danger}State;                              //Possible States
//============================================================================================//

//Global variables
//============================================================================================//
uint8_t distanceL;                                              //Distance (low value) data taken from the UART buffer coming from Lidar
uint8_t distanceH;                                              //Distance (high value) data taken from the UART buffer coming from Lidar
uint16_t Distance;                                              //Distance combined
uint8_t frameByteCount = 0;                                     //To count which byte in the frame is current
uint16_t Speed;                                                 //Speed variable
//volatile uint8_t DangerLevel;                                 //Danger indicator

//Function prototypes
//============================================================================================//
void calcSpeed(uint16_t Measurement);                       //Function to calculate the speed out of distance readings
void UART_Transmit(uint8_t data);                               //Funtion to send data via uart
//============================================================================================//

//Interrupts
//============================================================================================//
/*UART receive complete interrupt*/
ISR(USART_RX_vect)                                              //Data taken from the UART buffer
{
    uint8_t sample;

    sample = UDR0;                                              //Read a sample from the receiver buffer

    if(frameByteCount == 3)                                     //If its the 4th byte of the frame
    {
        frameByteCount = 0;                                     //Reset the counter
        distanceH = sample;                                     //Read the distance data high byte
        Distance = (8 << distanceH);                            //Combine the data low and data high
        Distance |= distanceL;

        calcSpeed(Distance);                                //Send the data to laptop for debugging purposes

    }

    if(frameByteCount == 2)                                     //If its the 3rd byte in the frame read the distance data low byte
    {
        distanceL = sample;
        frameByteCount++;                                       //Increment the counter
    }

    if (sample == 0x59)                                         //If a sample is a header increment a counter
    {
        frameByteCount++;
    }
    else if (frameByteCount != 2 && frameByteCount != 3)        //If its not a header or distance data byte reset counter
    {
        frameByteCount = 0;
    }
}
//============================================================================================//

//Timers and Counters
//============================================================================================//
/*Timer0 Counter, this decreases the danger level periodically so a really slow approach will not keep incrementing the danger level*/
ISR(TIMER0_OVF_vect)
{
//  if (DangerLevel > 0)
//  {
//      DangerLevel--;
//  }
}
//============================================================================================//

//Main
//============================================================================================//
int main(void)
{
    DDRB    |=      0x02;                                       //For debugging purposes LED pin PB1 (pin 9) as output

    UBRR0H = (UBRR_VALUE >> 8);                                 //Setting the Baudrate register high value
    UBRR0L =  UBRR_VALUE;                                       //Setting the Baudrate register low value
    UCSR0A |= (1<<U2X0);                                        //Setting the data sample to double speed to make Baudrate error less
    UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00);                        //Initializing UART, setting frame to 8 data bits
    UCSR0B |= (1<<RXCIE0) | (1<<TXEN0) | (1<<RXEN0);            //Setting receiver interrupt enable, transmitter enable and receiver enable... Transmitter for debugging purposes

    TCCR0A = 0x00;                                              //Timer0 Setup
    TCCR0B |= 0x05;                                             //Timer0 clock prescaler to 1024
    TIMSK0 |= 0x01;                                             //Timer0 overflow interrupt enable

    sei();                                                      //Set interrupts

    State = Safe;                                               //Set state to safe

    while (1)
    {
        //checkState(DangerLevel);
    }
}
//============================================================================================//

//Functions
//============================================================================================//
/*Calculate the danger level out of distance readings*/
void calcSpeed(uint16_t Measurement)
{
    static uint8_t samplenumber = 0;                                //Sample tracker
    static uint16_t value0 = 0;                                         //First sample
    static uint16_t value1 = 0;                                         //Second sample

    switch(samplenumber)                                            //To store the measurements alternately
    {
        case 0:
            value0 = Measurement;                                   //Store first measurement
            samplenumber = 1;                                       //So next measurement goes to a different variable
        break;
        case 1:
            value1 = Measurement;                                   //Store 2nd measurement
            samplenumber = 0;                                       //So next measurement goes to a different variable
        break;
        default:
        break;
    }

    if (samplenumber == 0 && value1 < value0)                       //When value0 is first and value1 is second and the object is closing in
    {
        Speed = value0 - value1;
    }
    else if (samplenumber == 1 && value0 < value1)                  //When value1 is first and value0 is second and the object is closing in
    {
        Speed = value1 - value0;
    }
    else
    {
        Speed = 0;
    }
    UART_Transmit(Speed);       //I think sending an uint16_t over uint8_t uart is possible because 'Speed' is never greater than 255 when i'm testing it
}

/*Send data over UART when buffer is empty*/
void UART_Transmit(uint8_t data)
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    ;
    /* Put data into buffer, sends the data */
    UDR0 = data;
}
//============================================================================================//

The datasheet for the module: Datasheet Lidar module

Where is the datasheet?

I forgot to add the link to datasheet Datasheet Lidar Module

First. Make volatile all global variables touched inside the ISR. Otherwise, it can be changed while loop() is using them. And as assignment is not atomic in Arduino, you can get weird values.

All #defined numbers should be enclosed in brackets to prevent against misunderstandings as a result of precedence rules.  i.e. #define Baudrate (115200)

I found it!
Can't believe I was stuck for two days on this.
Distance = (8 << distanceH);                            //Combine the data low and data high
Distance |= distanceL;

Should be:
Distance = (distanceH << 8);                            //Combine the data low and data high
Distance |= distanceL;

Thanks all for taking the effort, and i'm definately going to do the experiment above to test the accuracy.

Don't forget to accept your own answer to close this question.

I don't know how, because I asked the question with an guest account. And I made an account right after.

You have to wait 24 hrs (not sure) and then click the tick that appear at the left side of your answer.

I think you are either getting interference that is corrupting the serial data or reflections from the scattering of the light off the object.
If you are certain that your code is right, which it seems to be, then I think you need to ascertain if the unit is giving you constant readings or not.  Can you set up a test that puts the unit at a fixed distance from a reflector and get readings for a minute.  The raw readings should all be identical, absolutely no variation.  They won't be they will waver around a tiny amount so work out what the percentage variation is for this distance.
Now repeat the test but at double the distance, you should get the same accuracy. Now again at double the distance again and you should have the same level of accuracy.
If the accuracy is varying "significantly" then you will need to generate a calibration table.  'At distance x the accuracy is y', etc.
Reflections will give you intermittent wildly inaccurate results. To combat this you might want to filter the data to remove any data that is more than n times the accuracy away from the previous reading.  n has to be a value large enough to cover the maximum distance the reflector (car) can cover in the time between samples.  I would guess assuming a maximum speed of 300MPH would be enough for most cases.


text:
Use an L293D with Arduino
I am making a 2-wheeled Arduino car controlled by T.V. remote for a science fair tomorrow. I have found a tutorial for the IR part. I brought this  L293D motor driver to control a 2-wheeled car. I am facing a problem. I know where to connect the motors (because there are indications stating M1 and M2) but I don't know where to connect the motor driver to the Arduino and to the batteries.
I checked over the net but couldn't find any tutorial for this kind of board. Also I have no experience in all this so I don't want to risk it. I don't want any code or anything, just where to connect what.
Any help is appreciated.

Welcome to Arduino SE. Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't. Please revise your question showing your work and findings so far. Or delete the question if Internet searches give you your answer anyway.

I searched all over the net for any documentation but i didn't find any. That's why i turned here

What have you done already? (Beside having various hardware pieces)

@LookAlterno I connected the 2 wires of motor 1 to the two headers stating M1 and connected the 2 wires of motor 2 to the two headers stating M2. I found the hex values of the Buttons of the I.R. remote and have connected the I.R.(TSOP 1738) receiver to the Arduino. I also found a tutorial but am yet to program the chip cause i want to finish the joining of the components first.

All the inputs are clearly marked.
The battery connects to +12V and GND
The Arduino's 5V and GND connect to 5V and GND.
The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.
The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.

Thanks a lot. Now I have a question. Can I power the Arduino with a 1.5 volt and the motor driver with two 9 volts battery.

No, and maybe. If the motor is 18V then yes. The Arduino can never run from 1.5V. It needs 5V minimum.


text:
Strings from serial are not equal
In my code I have that string:String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017 It means that code = "034000017". But if I run if (code.equals("034000017")) Serial.println("OK"); There is nothing in serial monitor. Here is full code:
String code, rs1, rs2, rs3, readString;
void setup() {
    Serial.begin(9600);
    Serial.println("Serial ready!");
}

void loop() {
    if (Serial.available()) {
        while (Serial.available()) {
          delay(10);
          if (Serial.available() >0) {
            char c = Serial.read();
            readString += c;
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
          }
        }
    }
}

Why do you read just one character and add it to the string then split the string up as if it had at least 9 characters in it? You need to read the entire string first before splitting it.

@Majenko Why one character? I write 034000017 to serial.

No, you write "0" to the serial. Then you write "3" to the serial. Etc.

This may be of use to you: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

@Majenko And how i can fix it?

You need (a) some way of knowing the start and end of your data in the anonymous serial data stream, and (b) some way of reading that data into memory. The link I provided gives a good example.

What's the point in spitting the string and then combing it back again into the same string?

Lots of errors in your code. Mine is basically the same that @frarugi87's answer.
I only have to add: when reading serial, wait for the end of line ('\r' and/or '\n') to know when you have all your data, so you don't depend on length (which can be corrupted).
Edit (on Majeko's comment)
String code, rs1, rs2, rs3, readString;
void setup()
{
  Serial.begin(9600);
  Serial.println("Serial ready!");
}

void loop()
{
  static bool inData = true;

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

    if (c != '\r' && c != '\n') {
      readString += c;
      inData = true;
    }
    else {
      if (inData) {
        rs1 = readString.substring(0, 3); //034
        rs2 = readString.substring(3, 6); //000
        rs3 = readString.substring(6, 9); //017
        code = rs1 + rs2 + rs3;
        Serial.println(code);

        if (code.equals("034000017")) {
          Serial.println("OK");
        }
        readString = "";
        inData = false;
      }
    }
  }
}

This code works for any configuration of line ending ('\r', '\n' or '\r\n').
It doesn't test for length (or validity or timeout); it's left as an exercise to the reader :-)
I hope it shows how code grows when making it robust in all scenarios.

The only failing with your code is if the string is terminated with \r\n - in that case, the \r will trigger a parsing, and then straight after the \n will trigger another with an empty string. You should decide on just one to use, not either/or. Discard the one you're not using. A switch/case can be good for that. Also checking the length of the string can be useful to make sure you got all the data.

@Majenko. You are right; I edited it.

...but why are you retaining the absurd splitting of the String into parts only to expensively concatenate them right back together in the same order?

@ChrisStratton. Because that is not what the OP asked. I took his code and made it better. He will learn by comparing his version with mine. If I were to post the way I program, he will understand nothing and my answer will be useless to him. If you are so brilliant, go and post a better (in your opinion) answer.

The point you are making in your text isn't an important one - it's not actually necessary to wait for the end of the line, you can keep checking and failing.  It is wasteful to do that, but it's also wasteful to keep in the pointless things you kept in.  The only thing you're proposing that actually has a chance of helping with the actual problem is clearing the accumulated string, but you call no attention to that fact.

@ChrisStratton. Where is your code? Too much talk, too little coding.

In your code there is a trivial error and a conceptual error.
The trivial error is in line 16, you wrote
rs2 = readString.substring(6, 9); //017

but it should have been
rs3 = readString.substring(6, 9); //017

(3 instead of 2)
The conceptual one is that you do not have to check the string every time; if you know that the string must be 9 chars long, check for it:
void loop() {
    while (Serial.available()) {
        readString += (char)Serial.read();
        if (readString.length() >= 9) {
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
            readString = "";
        }
    }
}

Note that in this code I cleaned up a bit your code, and MOST IMPORTANT I reset the readstring to nothing after the check (otherwise only the first string is accepted)
I left a lot of things as they were (for instance in my opinion using a string in this case is pointless - better use a byte array; or splitting the string in three for joining it again later), since I think this is part of a larger program

This is much closer to being a correct answer.


text:
checking if user is opening root entry point of the IP address on esp8266 webserver
I am trying to open load a webpage from ESP8266 that displays temperature and humidity of my room if I only type root URL:192.168.1.89
GET / HTTP/1.1
Host: 192.168.1.89
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Safari/602.1.50
Accept-Language: en-us
DNT: 1
Accept-Encoding: gzip, deflate

to do that in my esp8266 sketch I am trying this logic:
bool readRequest(WiFiClient& client) {
  bool currentLineIsBlank = true;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();
      if (c == "GET / HTTP/1.1"){
        Serial.println("Got root");
        client.println(handleRoot()); // where handle root contains web page
      }
      else{
        Serial.println("Did not got root.");
      }
      if (c == '\n' && currentLineIsBlank) {

        return true;
      } else if (c == '\n') {
        currentLineIsBlank = true;
      } else if (c != '\r') {
        currentLineIsBlank = false;
      }
    }
  }
  return false;
}

but the condition to check if it met GET / HTTP/1.1 never validates.

c is a char. You can't compare a char to a string. And c == "GET... is not how you compare string in C, anyway.

Just use a HTTP server library.

@gre_gor in a different project I am using ESP8266WebServer  but I want ed to give a try to WiFiServer server(80); while sticking with ArduinoJson.h library as well.

This applies to networking as well as serial. Also this may be of use to you, along with this.

@gre_gor I switched back to ESP8266WebServer.h however I cannot pass ArduinoJson.h's jsonObject to server.send(...) https://arduino.stackexchange.com/q/46961/27363


text:
Arduino GSM module + SMS string sending garbage value
I want to check the water level and have an SMS sent via a GSM module. Reed switches are connected to four Arduino analog inputs.
I am unable to add a string and tank level (TKLVL) in program.
The program is sending some garbage value via SMS. But TKLVL variable prints the right value.
What is wrong with my code?
    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(10, 11);
    String textMessage;
    #define LED1 2
    #define IRLED 3
    //#define rf433DATA 4
    //D4 IS CONNECTED TO RF433MHZ RECEIVER CHANGE ACC TO LIBRARY
    #define PIRpower 5
    int receiver = 6;
    #define VALVE1 7
    #define GSMRESET 8
    #define pumpONdetect 9
    #define VALVE2 12
    //#define TANK_SENSPOWER 13 //
    #define TANK_SENS4 A0  //full tank wigh buzzer
    #define TANK_SENS3 A1
    #define TANK_SENS2 A2
    #define TANK_SENS1 A3  //low tank
    int TKLVL= 0;
    int LEVEL;

    void setup()
    { pinMode(LED1, OUTPUT);
      pinMode(IRLED, OUTPUT);
      pinMode(PIRpower, OUTPUT);
      //CHECK RECEIVER PIN
      pinMode(GSMRESET, OUTPUT);
      pinMode(VALVE2, OUTPUT);
      // pinMode(TANK_SENSPOWER, OUTPUT); //DRIVE THIS PIN LOW TO ON TANK POWER(PNP TRANSISTOR)
      pinMode(TANK_SENS4, INPUT); //FULL TANK WITH BEEP BUZZER
      pinMode(TANK_SENS3, INPUT);
      pinMode(TANK_SENS2, INPUT);
      pinMode(TANK_SENS1, INPUT); //LOW TANK WATER
      // digitalWrite(TANK_SENSPOWER, HIGH); //turns OFF tanksenspower OFFvia PNP transistor..
      Serial.begin(9600);
      SIM900.begin(9600);
      Serial.print("SIM900 ready...");
      SIM900.println("AT+CMGD=1,4\r");
      delay(1000);
      // AT command to set SIM900 to SMS mode
      SIM900.println("AT+CMGF=1\r");
      delay(400);
      // Set module to send SMS data to serial out upon receipt
      SIM900.println("AT+CNMI=2,2,0,0,0\r");
      delay(400);
      digitalWrite(VALVE1, LOW);

    }

    void loop()
    {
      if (SIM900.available() > 0) {
        textMessage = SIM900.readString();
        Serial.print(textMessage);
        delay(10);
      }
      if (textMessage.indexOf("Von") >= 0)
      {
        G_valve1On();
        Serial.println("on loop");
        textMessage = "";
      }
      if (textMessage.indexOf("Voff") >= 0)
      {
        G_valve1Off();
        Serial.println("off loop");
        textMessage = "";
      }

      if (textMessage.indexOf("Tanklvl") >= 0)
      {
        Tanklvl_calc();
         Serial.print("TKLVL is=");
         Serial.println(TKLVL);
        //  TKLVL=LEVEL;
        // Serial.print("level is=");
        //Serial.println(LEVEL);
        String msg ="TANK IS " + TKLVL;
        Serial.println(msg);
        sendSMS(msg);
        textMessage = "";
      }

    }
    //SEND SMS function
    void sendSMS(String lvlmsg)
    {
      SIM900.print("AT+CMGF=1\r");
      delay(1000);
      SIM900.println("AT+CMGS=\"+9182375*****\"\r");
      delay(100);
      SIM900.println(lvlmsg);
      delay(100);
      SIM900.println((char)26);
      delay(1000);
      SIM900.println();
      delay(5000);
    }

    void G_valve1On()
    {
      digitalWrite(VALVE1, HIGH);
      Serial.println("...turning valve1 on...");
    }
    void G_valve1Off()
    {
      digitalWrite(VALVE1, LOW);
      Serial.println("...turningvalve1 off...");
    }

    int Tanklvl_calc()
    {
      if (digitalRead(TANK_SENS4) == HIGH)
      {
        TKLVL = 100;
        Serial.println("TANK LEVEL 100%");
      }
      else if (digitalRead(TANK_SENS3) == HIGH)
      {
        TKLVL = 75;
        Serial.println("TANL LEVEL 75%");
      }
      else if (digitalRead(TANK_SENS2) == HIGH)
      {
        TKLVL = 50;
        Serial.println("TANK LEVEL 50%");
      }
      else if (digitalRead(TANK_SENS1) == HIGH)
      {
        TKLVL = 25;
        Serial.println("TANK LEVEL 25%");
      }
      else
      {
        TKLVL = 0;
        Serial.println("TANK LEVEL IS LESS THAN 25%");
      }
      return(TKLVL);
    }

Are you receiving some sms from UNO ? Did serial monitor print correct value?

Garbage values received in sms

@MITURAJ  plz chk string msg command,I think it nor combining statement +level variable.

Serial.println(msg); <-- Did this work? I doubt if it prints junk value cz TKLVL is int type. Convert it to string using --->
String msg = "TANK IS " + String(TKLVL)

@MITURAJ No this line doesnt print any value.

Try
String msg = "TANK IS " + String(TKLVL)

String msg= "led is" + ledstate this line works.but ledstate is boolean variable.

Any other way by which I can send tank level variable valve as sms??

if (textMessage.indexOf("Tanklvl") >= 0) <--- sms is sent ONLY if this condition is satisfied. Did you check if this worked first ?

Yes I ve checked this condition.

String msg = "TANK IS " + String(TKLVL) <-- did this work?

Step by step: send hardcoded string in SMS. If the SMS is OK->problem came for the way you build the msg. If the SMS is wrong-> problem came from the sending. Notice one detail: seems you can't send all kind of character in SMS. I've made Android App exchanging SMS and I' ve had to avoid some char which were received as garbage.

Using Strings in a microcontroller is a no-no.
First, try to send a test SMS, to see if everything works OK on SIM800-Arduino etc.
If you receive it correctly, then try to play with char arrays.
First, declare a char array big enough for your data to fit in. Let's use a demo array, but keep in mind that it's your responsibility to keep things tidy.
byte sizeOfBuffer = 10;
char smsString[sizeOfBuffer] = {'\0'};

What we did is create an smsString array of 10 bytes, 9 bytes for data and 1 byte for our special end of sting character. Since we don't want Arduino to handle things with Strings, we have to tell our microcontroller where does that String end. That's what '\0' does.
Then, modify the send function to accept that data type.
//SEND SMS function with char array
void send_SMS_charArray(char *lvlmsg, byte sizeOfsms)
{
  SIM900.print("AT+CMGF=1\r");
  delay(1000);
  SIM900.println("AT+CMGS=\"+918237504767\"\r");
  delay(100);
  for (byte i=0; i<sizeof(sizeOfsms); i++){
    SIM900.print(lvlmsg[i]);
  }
  Serial.println();
  delay(100);
  SIM900.println((char)26);
  delay(1000);
  SIM900.println();
  delay(5000);
}

Finally, to call the new function you would do something like
sprintf_P(smsString, PSTR("TANK IS: %i"), TKLVL);
send_SMS_charArray(smsString, sizeOfBuffer);

Notice sprintf_P when using static messages such as "TANK IS". It will save your life in a few months.

TKLVL is integer type. Convert it to String object and add :-
String msg = "TANK IS " + String(TKLVL)


text:
How to pass JsonObject from ArduinoJson to ESP8266WebServer object?
I am learning the ArduinoJson.h library and creating jsonOject:
JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  JsonObject& root = jsonBuffer.createObject();
  JsonArray& tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray& humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray& dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray& EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);
  return root;
}

As per the example given here. However since I am using an ESP8266WebServer to create a server object from ESP8266WebServer.h, I cannot pass a JsonObject to server.send(.....).

no matching function for call to 'ESP8266WebServer::send(int, const
  char [10], ArduinoJson::JsonObject&)'

void outputJson() {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& json = prepareResponse(jsonBuffer);
  writeResponse(client, json);
  server.send ( 200, "text/json", json );
}

void writeResponse(WiFiClient& clnt, JsonObject& json) {
  clnt.println("HTTP/1.1 200 OK");
  clnt.println("Content-Type: application/json");
  clnt.println("Access-Control-Allow-Origin: *");
  clnt.println("Connection: close");
  clnt.println();
  json.prettyPrintTo(clnt);
}

As far as I know, the only way is to serialize the JsonObject to a String:
String createJsonResponse() {
  StaticJsonBuffer<500> jsonBuffer;

  JsonObject &root = jsonBuffer.createObject();
  JsonArray &tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray &humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray &dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray &EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);

  String json;
  root.prettyPrintTo(json);
  return json;
}

void outputJson() {
    server.send(200, "text/json", createJsonResponse());
}

By the way, I recommend that you use the ArduinoJson Assistant to compute the size of the JsonBuffer.

thanks I did tried the suggested already but forgot to get rid of the other stuff from outputJson. Thank you very much . greatly appreciated (y)


text:
Arduino : LCD / POT
how can I make the repetitions stop at 10 ? Also how can I get the lcd to reset when its off/low ?
#include <LiquidCrystal.h>

LiquidCrystal lcd(12,11,5,4,3,2);
const int tiltSensor = 8;
int reps = 0;
int switchState = HIGH;
int prevSwitchState = LOW;

void setup() {
  lcd.begin(16,2); // type of lcd(16 columns and 2 rows)
  pinMode(tiltSensor,INPUT);
  lcd.clear();
  lcd.setCursor(0,0); // the cursor is where on the
  lcd the characters will be placed
  lcd.print("Workout Time"); // print is the characters on the screen
  lcd.setCursor(0,1);
  lcd.print("Lets GO ! ");
}

void loop() {
  switchState = digitalRead(tiltSensor);
  if (switchState != prevSwitchState) {
    if (switchState == LOW) {
      reps = reps + 1;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Reps:");
      lcd.setCursor(0,1);
      lcd.print(reps/10);
    }
  }
  prevSwitchState = switchState;
}

... how can I get the lcd to reset when the potentiometer is turned off /low ?

Please edit your question and add the code as text and not as an image. It is important that your question incl. the code can be proplery indexed for search. Also see https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors

if (reps < 10)?

Learn to program.

how can I make the repetitions stop at 10 ?

use a loop counter:
  if (loop_cnt++ < 10) do_mything();

Would it be possible for you to elaborate as to where in the loop its to be placed ? as I am new to this...


text:
Hall effect sensor and water sensor
I'm working on a project based on the two sensor above but I keep getting this error:
'liquid_level does not name a type'
This is my sketch:
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
const int sensorPin= 0; //sensor pin connected to analog pin A0
int liquid_level;
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;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{

   pinMode(flowsensor, INPUT);
   pinMode(sensorPin, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   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
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");

   }
}

liquid_level= analogRead(sensorPin); //arduino reads the value from the liquid level sensor
Serial.println(liquid_level);//prints out liquid level sensor reading
delay(100);//delays 100ms
}

I suggest you to re-write your post in order to have more readable code. :)

The last 4 lines are outside any function. They aren’t in the loop() function. You can’t put plain statements outside of any function. Check your brackets.


text:
How can I have 2 differents frequency on the 2 DAC outputs on an Arduino Due?
I would like to blink, using specific waveforms, 2 LED controlled by the 2 DAC output of the Arduino Due.
I wrote this :
    #include "Waveforms.h"

    int i = 0;
    int sample;

    void setup()
{
      analogWriteResolution(12);
}

    void test(float fq, int wave1, int wave2)
{

      sample = ((1/fq)*1000000)/120;

      analogWrite(DAC0, waveformsTable[wave1][i]);
      analogWrite(DAC1, waveformsTable[wave2][i]);

      i++;

      if(i == maxSamplesNum)
          {
            i = 0;
          }

      delayMicroseconds(sample);

}

    void loop() {
    // 10 Hz, 0 is a sine wave on DAC0, 3 is a square wave on DAC1

      test(10, 0, 3);

I would like to be able to change the frequency of each output (1Hz - 100 Hz) using differents waveforms. Changing waveforms is ok and it works, but is it possible to also change the frequency so to have two differents output frequency on each DAC output ?
The goal is to have, for example, simultaneously :

1 Hz, sine wave on DAC0.
10Hz, square wave on DAC1.

Thanks a lot.

Properly format the code. It's hard to read.

I don't have experience with this, but what you can do is:

If the frequency of DAC1 is x times faster than DAC2 to calculate the delay time based on the fastest and for DAC1 changing in every loop, while changing DAC2 only every DAC1/DAC2 times.
Vice versa if DAC2 is x times faster than DAC1
However, if there is not a simple ratio between DAC1 and DAC2 than you have to use the fastest speed of the two and use for the slowest an approximation...
Or use a higher significant fixed speed for i use a simple linear approximation between two points of the wavetable.

E.g. assume the speed is 10 times too fast for DAC1.
Suppose i = 100.. you should use the following points in the waveform: wave[100/10] and wave[100/10 + 1], so two consecutive points.
Assume the first is 10.0 and the second is 20.0... for the 10 increases of i (because i is running 10 times too fast) you can calculate for values of
 i     : 10.0 +   0% of (20.0 - 10.0)
 i + 1 : 10.0 +  10% of (20.0 - 10.0)
 ...
 i + 10: 10.0 + 100% of (20.0 - 10.0)

etc.
Note this is called linear interpolation.
You would have to check how many numbers per wave form table you need to get good values for different frequencies/speeds and what 'fixed' frequency you need to use for the delay.


text:
No data in text file
Data can be seen in the console but the data is not being written in the text file. The file is created but there is no data in it.
Here is my code in Processing,
import processing.serial.*;
Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
PrintWriter output;
void setup()
{

   String portName = Serial.list()[0];
   myPort = new Serial(this, portName, 9600);
   output = createWriter( "my.txt" );
}
void draw()
{
    if ( myPort.available() > 0)
     {  // If data is available,
         val = myPort.readStringUntil('\n');
       output.print( val );
     }
    println(val); //print it out in the console

 }

and in Arduino,
  int potPin = 0; // initialize analog pin 0 for LM35 temperature sensor
  void setup()
  {
     Serial.begin(9600);// set baud rate at”9600”
  }
  void loop()
  {
     int val;// define variable
     int dat;// define variable
     val=analogRead(0);
     dat=(125*val)>>8;// temperature calculation formula
     Serial.print("Tep:");//
     Serial.print(dat);// output and display value of dat
     Serial.println("C");// display “C” characters
     delay(500);// wait for 0.5 second
   }

Any answers are appreciated. Thank you!

Don't know "processing" but do you close the file at the end? Because if you open it, write and then let it open, the file size stay at 0 and you can't read data. So maybe you really write data but they stay invisible because of the fact you don't close the file.

Don't post images of text; post the text itself. No one is going to retype your code to test it and you will get no help. And, what is your question?

The Arduino has simple task of sending data to your computer, and does not create any files. Check your Processing script. As mentioned by Peter, be sure you closing file after storing anything into it.

@LookAlterno my question was how to write arduino data to text file using Processing

Processing questions are off-topic.

I'm voting to close this question as off-topic because it is about Processing and not about Arduino.  While similar in heritage, writing files on the development machine with Processing is not an Arduino question.

createWriter description says:

"For the file to be made correctly, it should be flushed and must be
  closed with its flush() and close() methods"

Source: https://processing.org/reference/createWriter_.html
This question is not about Arduino, but Processing language.


text:
Yellow LED got burned, green LED didn't

I'm not talking about the onboard LED at the Arduino board here.  What those LED's mean, is the LED's we usually plug at the breadboard.

I plugged in a yellow LED and a green LED onto a breadboard.  I wired it up, and noticed something.  Green LED lights up at its full brightness, while yellow LED didn't emit any light.  Tried in another yellow LED, and it seems like it's smoking, which means it's burned.
I'm not using a 220 Ohm resistor or any kind of resistor that time.  I also have no idea why the green LED didn't burn itself, when you plug it directly on 5V and GND.  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.
When I plugged the green LED into a 220 Ohm resistor, it did as expected.  It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the question is?

I don't see the Arduino connection here. Or a question.

The Arduino Uno can give 40mA shortcut current with a digital output pin. Maybe that was not enough to burn the led. I think that somewhere along the line from the computer via the usb cable, the Arduino board and the output pin, the current or voltage was lowered or the internal resistance of the led is higher or became higher during burning. Try a power supply of 5V 2A and connect all the leds to burn them all. What is the point of this? If you want to know about leds then measure the voltage and the current of the led. Can you get rid of that Arduino board, it might no longer be reliable.

@LookAlterno Oh, sorry.  I forgot to include the question. The question is, "Why is the yellow LED burning, while the green LED is not?"

@sempaiscuba I'm just new to the community.  If you like, then you can move this question / post to a different Q&A site.

@Jot I will burn all the LED's?  Why would I do that?

@LloydDominic You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

You probably didn't have it connected to 5V for long enough. When I purposely applied too high a voltage to a led, it took around 10 seconds to fail. It changed color before that, which was funny.

I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.
Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.

Majenko already mentioned the reason. Maybe it's good to add that different colored LEDs (and even each type/model) should have its 'calculated' resistor.
Find the forward voltage of the LED (differs per type/color), and use the following formula :
V - Vfv = I * R  <=> R = (V - Vfv) / I

E.g. if the forward voltage is 2V and you use a 5V Arduino and want 20 mA:
R = (5 - 2) / 0.02 = 150 ohm

The maximum mA you can find also in the data sheet of the LED.

Would be much better if you give the meaning behind those acronyms.  (What is "V" ?, what is "Vfv" ?, etc. ...)

@LloydDominic If you don't know what V (voltage) means, or what Vfv (Forward Voltage) means, your better stop playing with electricity before you kill yourself or burn down your house.

If someone does not know what V or Vfv (forward voltage) means, I think he should either google it or ask a new question.

I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

LEDs get burned from excessive heat that is the result of excessive current. Green LEDs have higher forward voltage than yellow LEDs so, if everything else is equal, the "excessive" current through the green LED is smaller than the one through the yellow LED, thus causing the yellow LED to warm up faster and thus burn out faster.
Other factors may still attribute to the yellow's burn-out.


text:
Arduino Uno + MSD-11-EM stepdriver + NEMA 17
I am working on Arduino code for stepper motor rotations control. I want to rotate a stepper for only 4 rotations.
The code is working fine but that will run only once as I have put that in setup().
I want to know if there will be any reverse current flowing in the circuit that would damage the Arduino or stepper. What if I want to run the stepper in the loop()? I tried but that will force the stepper to run continuously.
How can I run stepper for only 4 rotations and then stop?
I want to run it in loop().

Below is the code I am using:
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(110);
  // initialize the serial port:
  Serial.begin(9600);
  for(int i=0;i<25;i++) {
    Serial.println("Anti-clockwise");
    myStepper.step(stepsPerRevolution);
    delay(50);
  }
}

In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
bool flag = true;

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(110);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop {
 if (flag) {
   for(int i=0;i<25;i++) {
     Serial.println("Anti-clockwise");
     myStepper.step(stepsPerRevolution);
     delay(50);
   }
   flag = false;
 }
}

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.

I still wonder how code which I have posted earlier worked but no worries code below is working as expected.
int dirpin_T1 = 7;
int dirH_T1 = 8;
int steppin_T1 = 9;
void setup() {
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
}

void loop() {
  static int count = 0;
  if(count < 4) {
    count++;
    digitalWrite(dirpin_T1, LOW); // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);
    for (int i = 0; i<3193; i++) {
      // Iterate for 4000 microsteps.(32767)
      digitalWrite(steppin_T1, LOW);
      // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH);
      // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(500);
    }
  }
}

please make sure you reset the arduino everytime you power it on to run the stepper because it won't run the loop again, just four rotations and it will stop.

Learn to properly indent your code. Press cmd/ctrl-T in the Arduino IDE regularly to clean up your code.

I can't validate what you are doing in the for statement, but if you want to execute that only 4 times, this sketch will do
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup()
{
    // set the speed at 60 rpm:
    myStepper.setSpeed(110);
// initialize the serial port:
    Serial.begin(9600);
}

void loop() {
    static int count = 0;

    if(count < 4)
    {
        count++;

        for(int i=0; i<25; i++) {
            Serial.println("Anti-clockwise");
            myStepper.step(stepsPerRevolution);
            delay(50);
        }
    }
}

count keeps the count of how many times you execute the for loop. It's declared static to keep his value between loop() executions; otherwise, it will be zero on each loop

I have used for loop to rotate the stepper four times.If I would remove for loop stepper will keep rotating continuously. The command "myStepper.step(stepsPerRevolution)" will force the stepper until it completes the count of "stepsPerRevolution" and increasing and decreasing the count just affect the speed of stepper that is not what I want. I want four times rotation of stepper and for loop makes it easier.


text:
How can I use PWM in power saving mode (ATmega328)?
I fail to use PWM in power saving mode.  The output behaves erratically.  This should be possible, I guess.  The following is a minimal working example:
/* MWE: Cannot use PWM in any power saving mode.

   A minimal working example (MWE) demonstrating my trouble in using
   PWM while saving power.

   Intention: Control one load to be on or off for longer periods of
   time (hours, that is).  The brightness of the load is set by PWM.

   Wiring:

                                              +5V
                                               |
           +------------------+                |
     +5V---|Vin               |                |
           |     Arduino      |                C
           |     Pro Mini    9|-----/\/\/----B|<  PN2222
           |     compatible   |      1k        E
           |     (ATmega328)  |                |
     GND---|GND               |                | +
           +------------------+               LED
                                               | -
                                               |
                                               >
                                               < 1k
                                               >
                                               |
                                               |
                                              GND

   Implementation:

     * Set watchdog to cause an interrupt in regular intervals (in
       this MWE: 2s).  Count down `cycles` (MWE: 2 or 3) on each
       watchdog interrupt.

     * If `cycles` is 0, toggle the output, set new `cycles` value.
       The real program uses 7200 8s cycles for 16h before the next
       toggle.

     * Go to SLEEP_MODE_PWR_DOWN.

   Expected: attached load is on for 4s, dimmed at 32/256.  Then off
             for 6s.  Then repeat.

   Observed: In most cases, there's no output in sleep mode, the LED
             only blinks before sleeping.  But sometimes it is on, so
             PWM seems to be possible while sleeping!

   The real program (from which this MWE is derived) uses adjustable
   brightness, wakes up from sleep by external interrupts, stores
   brightnes to EEPROM, ...
*/

/* Setting the following to 0 uses `digitalWrite` instead of
   `analogWrite` to demonstrate that the watchdog and interrupt logic
   do actually work. */
#define USE_PWM 1

#include <avr/sleep.h>
#include <avr/wdt.h>

#define outputPin 9    // where the PWM load is connected
#define onCycles 2     // num of watchdog cycles to stay on
#define offCycles 3    // num of watchdog cycles to stay off

int brightness = 32;  // PWM duty cycle in 1/256, if the load is on
int toggle = 1; // current on/off state of PWM load

/* Number watchdog cycles until next toggle.  This will be modified in
   the watchdog interrupt handler. */
volatile unsigned long wdt_cycles = onCycles;

/* Watchdog interrupt handler called when watchdog expires, count down
   remaining cycles.  Does not underflow. */
ISR(WDT_vect) {
    if (wdt_cycles > 0)
        wdt_cycles--;
}

void setup(void) {

    /* Setup watchdog.  See [1] p54, [2] */
    cli(); // BEGIN disable interrupts

    MCUSR &= ~(1<<WDRF); // no system reset on watchdog timeout

    WDTCSR |= 1<<WDCE | 1<<WDE; // allow watchdog configuration

    WDTCSR
        = 1<<WDIE // enable interrupts
        | 1<<WDP2 | 1<<WDP1 | 1<<WDP0 // 2.0 seconds
        ;

    wdt_reset(); // reset timer

    sei(); // END disable interrupts

    /* Setup output pins */

    pinMode(outputPin, OUTPUT);

#if USE_PWM
    analogWrite(outputPin, brightness);
#else
    digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif

}

void loop(void) {

    if (wdt_cycles < 1) {
        toggle = !toggle;
        wdt_cycles = toggle ? onCycles : offCycles;
#if USE_PWM
        analogWrite(outputPin, toggle ? brightness : 0);
#else
        digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif
    }

    /* Heartbeat: Short blink of builtin led.  This verifies that we
       are actually sleeping and waking up. */
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    /* Got to sleep, see [3].  I want `SLEEP_MODE_PWR_DOWN`, but also
       none of the others works. */
    set_sleep_mode(
                   //SLEEP_MODE_IDLE
                   //SLEEP_MODE_ADC
                   //SLEEP_MODE_PWR_SAVE
                   //SLEEP_MODE_STANDBY
                   SLEEP_MODE_PWR_DOWN
                   );
    sleep_mode();
}

/* References
   [1] https://cdn.sparkfun.com/datasheets/Kits/doc8161.pdf
   [2] https://forum.arduino.cc/index.php?topic=63651.0
   [3] https://playground.arduino.cc/Learning/ArduinoSleepCode
 */

The timers are disabled during SLEEP_MODE_PWR_DOWN, so PWM doesn't work during SLEEP_MODE_PWR_DOWN. You could instead use SLEEP_MODE_IDLE, but that only saves a bit of current.
When you put the MCU to sleep, the led will keep the state it was in during PWM. So around 12.5% if the time the leds will be on, and the other times it will be off (during those 2s PWM periods).

Your second comment explains why I have seen light-on in sleep mode, and also why this is difficult to reproduce.

Just as a complement to Gerben's answer:

You could use SLEEP_MODE_PWR_DOWN during the off period, but
SLEEP_MODE_IDLE is the only way to do PWM while sleeping.
When in SLEEP_MODE_IDLE, you can use the power_*_disable()
function defined in <avr/power.h> in order to further
reduce the power consumption.

Really good info: “SLEEP_MODE_IDLE is the only way to do PWM while sleeping”.  I failed to find this in the ATmega docs.  I'm using what you suggested, thanks!


text:
connecting 4 wire camera to esp8266
I am looking for the arduino code to stream video to a webpage using the ESP8266.
here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793
The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.
Any help or pointers would be most appreciated.

As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series).
The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.

Welcome to Arduino SE. Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't. Please revise your question showing your work and findings so far. Or delete the question if Internet searches give you your answer anyway.

Google first, ask latter. This had been asked several times in Arduino SE.

Questions may not rely on external links for basic information.  "Four wire camera" does not capture the key fact that this is an analog NTSC camera.

No.  Your link is to an analog NTSC camera.   Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.
It is simply not compatible to use this with a small embedded system.
If you really want a camera for a resource constrained embedded system, seek a still camera with a serial or SPI output.
Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.

So if I understand you correctly if I can find a digital camera with a serial output then it would be compatible for the esp8266?

Yes but it's likely a terribly bad idea as a project.


text:
Linux IDE 1.0.6 & Nano: Problem with if statement
This is a basic battery monitor for a solar-powered control box.  It keeps the solar panels tracking the sun.
The Arduino monitors the voltage on the battery and turns on an AC-powered battery charger if the voltage drops too low.
It works, but there is an odd quirk.

Actual code is posted here. Too long to post and it does a bunch of other stuff that can be distracting.

One simple if statement isn't executing, as described below and shown on the plot.

HERE IS THE KEY CODE SEGMENT WHERE THE FAILURE OCCURS:
if (vind < vTriggerOn) {    // Batt low, turn on charger
  digitalWrite(powerPin,LOW);
  digitalWrite(powerPin2,LOW);
  vAC=17.0;
  }
if (vind > vTriggerOff) {   // Solar panels on, turn off charger
  digitalWrite(powerPin,HIGH);
  digitalWrite(powerPin2,HIGH);
  }

//  HERE IS THE PROBLEM :  THIS ONE DOESN'T EXECUTE
if (vind > 15.5) {vind=15.48; vin=15.48;}

This is followed by yet another if statement that works.
Problem:  That if statement in question is supposed to keep it from going off-scale above the top of the plot.  Yet it is not executing.

The two gray lines show that it is detecting the on and off triggers, but the voltage is going off the top.  This should be impossible.
The first two if statements are executing but the third one is not.

Considered the fact that I hadn't upgraded the Arduino IDE since first installation.  It is "Arduino 2:1.0.6:dpsg2-4"
Tried this:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install arduino

and it told me I had the latest version.

Question:  How can I make it execute that third if statement?

Still don't compile.

Not sure why about that.  But the plot tells the story.  You can see it trigger at the voltage points by drawing vertical gray lines, and the voltage runs off the top of the plot even though that one statement should hold it to just under the plot boundaries.  I know this is not a big deal, but it is worrisome..

There is absolutely no problem with multiple if statements. How do you know that the third one doesn't "execute"? Maybe "other stuff..." is the problem.

I've noticed that when I have too many if statements, they may or may not work.  absolutely not. You have a bug in code you haven't shown us. If the gcc compiler sometimes didn't execute "if" statements the world would grind to a standstill because of the amount of code that uses it.

And 3 is hardly too many. Try 100,000.

This is hard to believe, and it would be a very serious bug. Could you please post somewhere the exact source code that causes the problem, together with the generated .elf file? And also tell us what versions are you using. Raspbian Stretch? The Arduino IDE that comes packaged with it? Version of avr-gcc? I would like to disassemble your .elf and compare with what I compile myself on Raspbian Stretch.

Nick, you are right.  It was indeed "other stuff" - having nothing to do with my source code.

The program you posted does not compile. I did the minimal fixes to make it compilable, then compiled it on an up-to-date Raspbian stretch (arduino-core 1.0.5, gcc-avr 4.9.2) and ran it on an Uno. It works as expected. It seems you misdiagnosed your problem. My guess is you had some issue in your code, which is not in the part you showed us. Either you fixed the bug when upgrading the IDE, or it just stopped manifesting itself (this can happen when you have undefined behavior). Then you wrongly blamed the Arduino IDE.

If the version packaged with Raspbian miscompiled code, that would certainly matter. But you show no evidence of such a thing.

This a new answer, upon the complete, original sketch as posted here by OP.
I deleted all the code that doesn't affect vind directly. Also, I replaced the value=analogRead(A2) with worst case scenario value=1023. Also tested with 781 and 782, which produces values for vind around 15.5.
Reduced sketch
const float R1 = 147000.0;
const float R2 =  47000.0;
const float constADC = 5.0;
const float offsetADC = -0.25; //
const float convADC = constADC / 1024.0;
const float numReadings = 10.0;
const float vTrigAlertLow = 12.1;

float nReadings = 0.0;
float tReadings = 0.0;

int value = 0;
float vout, vin, vind;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println("");
}

void loop() {
  int value = 1023;
  vout = value * convADC;
  vin = vout / (R2 / (R1 + R2));
  vind = vin + offsetADC;
  tReadings = tReadings + vind;
  nReadings = nReadings + 1.0;

  Serial.print(nReadings); Serial.print(" "); Serial.print(tReadings); Serial.print(" ");   Serial.println(vind);

  if (nReadings >= numReadings) {
    vind = tReadings / numReadings;
    tReadings = 0.0;
    nReadings = 0;

    Serial.print("Before "); Serial.print(vind);
    if (vind > 15.5) vind = 15.48; // <----  PROBLEM - not executing
    Serial.print(" After "); Serial.println(vind);

    if (vind > vTrigAlertLow) { // Normal, otherwise below vTrigAlertLow it will send alerts in the 'else' below
      Serial.println(vind);
    }
    else {
      Serial.println("LOW VOLTAGE");  // send Texts
    }
    Serial.println("----");
  }
}

The output is
1 20.37 20.37
2 40.74 20.37
3 61.10 20.37
4 81.47 20.37
5 101.84 20.37
6 122.21 20.37
7 142.58 20.37
8 162.95 20.37
9 183.31 20.37
10 203.68 20.37
Before=20.37 After=15.48
Send to PI 15.48
----

The if works as intended. It must be something else.

Thanks for going to the trouble of testing it.  It did indeed turn out to be something else.