text:
How to exit a function if conditions are met
Hello I want to exit a function if conditions are meet .
I have this code inside the loop()
if (t.hour == 7 && t.min == 16) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();
  }
}

If its true it will call the RelayOne() function and open the solenoid valve
inside the relayOne() fucntion i have also code for waterflow sensor
below is the relayOne function code for opening the valve and getting data from waterflow
 void RelayOne(){

//Serial.println("Valve Open");
digitalWrite(RELAY1, 0); //OPEN VALVE
digitalWrite(WATERFLOW1, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres = (flowRate / 60) * 1000;

    // Serial.print(flowMilliLitres);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");

    //setPointForN1 = EEPROM.get(0, WATEREQFORN1) / 2;

   if(totalMilliLitres >= setPointForN1 ){
       closeSolenoidValve();

      }

     // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }

  if(flowMilliLitres == 0){
     totalMilliLitres = 0;
  }

}

this line of code will supposedly close the valve but its not working
`if(totalMilliLitres >= setPointForN1 ){
           closeSolenoidValve();

          }`

the problem is that it will wait for 1 minute before closing the valve even tho the set point already reach .
Below is My full code
#include <EEPROM.h>

#include <TimeAlarms.h>
#include <Wire.h>
#include <dht.h>
#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);
//RTC_DS1307 rtc;

Time  t;

dht DHT;

//PINS
#define MOISTURE1 A15
#define MOISTURE2 A14

#define RELAY1 7
#define RELAY2 6
#define ALARM 13
#define DHT11_PIN A11

int relayState1 = 1;
int relayState2 = 1;
//WATER FLOW VARIABLES

byte sensorInterrupt = 0;  // 0 = digital pin 2
byte sensorInterrupt2 = 1;  // 0 = digital pin 3
byte  WATERFLOW1 = 2;
byte  WATERFLOW2 = 3;

// The hall-effect flow sensor outputs approximately 4.5 pulses per second per
// litre/minute of flow.
float calibrationFactor = 4.5;

volatile byte pulseCount;
volatile byte pulseCount2;
//For Waterflow sensor pin 13
float flowRate;
float frac;
unsigned int flowMilliLitres;
unsigned long totalMilliLitres;

//For Waterflow sensor pin 12
float flowRate2;
float frac2;
unsigned int flowMilliLitres2;
unsigned long totalMilliLitres2;

unsigned long setPointForN1;
unsigned long setPointForN2;

unsigned long oldTime;

unsigned long oldTime2;

///END OF WATER FLOW VARIABLES

unsigned int val;
int DELAYNI = 1000;

//Sensor Variables

int  moistureOneSensorValue;
int  moistureTwoSensorValue;
int  waterLevelSensorValue;
int  humiditySensorValue;
int  tempSensorValue;

//FOR EEPROM
unsigned int WATEREQFORN1;
unsigned int WATEREQFORN2;
unsigned long DELAYINTERVALOFDATA;
unsigned long prevMillis = 0;

unsigned long interval;

// -------------------------------------------------------------------
// SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP
// -------------------------------------------------------------------

void setup() {

  // put your setup code here, to run once:

  // Setup Serial connection
  Serial.begin(9600);
  rtc.begin();
  Wire.begin();

   //EEPROM

  //int eepromSize=EEPROM.length();
  //Serial.print("EEPROM found, size=");
 // Serial.println(eepromSize);
    // Get the last fade value (as an integer)
  //EEPROM.get(0, WATEREQFORN1);
  //Serial.print("Last Value N1: ");
 // Serial.println(WATEREQFORN1);

 // EEPROM.get(3, WATEREQFORN2);
 // Serial.print("Last Value N2: ");
 // Serial.println(WATEREQFORN2);

pinMode(MOISTURE1, INPUT);
pinMode(MOISTURE2, INPUT);
pinMode(WATERFLOW1, INPUT);
pinMode(WATERFLOW2, INPUT);
pinMode(DHT11_PIN, INPUT);
pinMode(RELAY1, OUTPUT);
pinMode(RELAY2, OUTPUT);

//WATER FLOW
  pulseCount        = 0;
  flowRate          = 0.0;
  flowMilliLitres   = 0;
  totalMilliLitres  = 0;

  oldTime           = 0;
   attachInterrupt(sensorInterrupt, pulseCounter, FALLING);

  pulseCount2        = 0;
  flowRate2          = 0.0;
  flowMilliLitres2   = 0;
  totalMilliLitres2  = 0;

  oldTime2           = 0;
  attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING);

  digitalWrite(RELAY1, 1);
  digitalWrite(RELAY2, 1);
}

void loop() {

  // put your main code here, to run repeatedly:
  t = rtc.getTime();
//DateTime now = rtc.now();
//This will get data send from the Desktop Application
char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        WATEREQFORN1 = val;

            EEPROM.put(0, WATEREQFORN1);
            //Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
         WATEREQFORN2 = val;
         EEPROM.put(5, WATEREQFORN2);
         //Serial.print("DATA SAVE TO EEPROM");

        break;
      case 'D':
        Serial.print("Case D got ");
        Serial.println(val);
        DELAYINTERVALOFDATA = val;
        EEPROM.put(10,DELAYINTERVALOFDATA);
        break;

      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }//END of SWITCH
  }//END of WHILE

   moistureOneSensorValue = analogRead(MOISTURE1);
   moistureTwoSensorValue = analogRead(MOISTURE2);

 // -------------------------------------------------------------------
 // Alarm Every Morning 7 AM Check If The Soil is DRY if DRY it will water
 // -------------------------------------------------------------------
if (t.hour == 0 && t.min == 49) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();

  }
  //if(moistureTwoSensorValue >= 700 ){
  //  RelayTwo();
 // }
}else{
   digitalWrite(RELAY1, 1); //CLOSE VALVE

}
// -------------------------------------------------------------------
// Alarm Every Afternoon 4 PM and Check if the soil is DRY if DRY it will water
// -------------------------------------------------------------------

if (t.hour == 16 && t.min == 00 && moistureOneSensorValue >= 700 ) {
  if(moistureOneSensorValue >= 700 ){
     RelayOne();
     digitalWrite(RELAY1, 1);
  }
  if(moistureTwoSensorValue >= 700 ){
     RelayOne();
  }
}
 readAllSensorStatus();

//Setting alarm/timer at every 2:32:53pm,
//in other words you can insert t.dow for every Thursday?, t.date for specific date?
//  {Serial.println("RELAY ON");

//Lets say that your component is wired to pin 99 and be switched on for 5 seconds,
//whatever you want to do with it

  // Wait one second before repeating :)
 // delay (1000);
 if(RELAY1 == LOW){
      digitalWrite(RELAY1, 1);
 }
}

void readAllSensorStatus(){
   unsigned long currentMillis = millis();

   interval = EEPROM.get(10,DELAYINTERVALOFDATA);
   if(currentMillis - prevMillis > interval) {
        prevMillis = currentMillis;
  //moistureSensorValue >= 700 DRY
  //
  //moistureSensorValue < 700 && moistuteSensorValue >= 300 Moist soil
  //
  //moistureSensorValue < 300 soggy soil
  //
  //Moisture
 moistureOneSensorValue = analogRead(MOISTURE1);
 moistureTwoSensorValue = analogRead(MOISTURE2);
 //Humidity and Temperature
 int chk = DHT.read11(DHT11_PIN);

 humiditySensorValue = DHT.humidity;
 tempSensorValue = DHT.temperature;
 //Water LEvel

  String LineOne = "-";
  String SensorValue = moistureOneSensorValue + LineOne + moistureOneSensorValue + LineOne + humiditySensorValue + LineOne + tempSensorValue;

  Serial.println(SensorValue);
  Serial.println(t.hour+LineOne+t.min);
   }

}
void closeSolenoidValve(){
   digitalWrite(RELAY1, 1); //Close

}
void RelayOne(){

//Serial.println("Valve Open");
digitalWrite(RELAY1, 0); //OPEN VALVE
digitalWrite(WATERFLOW1, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres = (flowRate / 60) * 1000;

    // Serial.print(flowMilliLitres);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the cumulative total of litres flowed since starting
    Serial.print("  Output Liquid Quantity: ");             // Output separator
    Serial.print(totalMilliLitres);
    Serial.println("mL");

    setPointForN1 = EEPROM.get(0, WATEREQFORN1) / 2;

   if(totalMilliLitres >= setPointForN1 ){
       //closeSolenoidValve();
        digitalWrite(RELAY1, 1); //OPEN VALVE
      return loop();
      }

     // Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }

  if(flowMilliLitres == 0){
     totalMilliLitres = 0;
  }

}

void RelayTwo(){

digitalWrite(RELAY2, 0);
digitalWrite(WATERFLOW2, HIGH);//READY WATER FLOW FOR SENSING
//WATER FLOW

if((millis() - oldTime2) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to
    // the host
    detachInterrupt(sensorInterrupt2);

    // Because this loop may not complete in exactly 1 second intervals we calculate
    // the number of milliseconds that have passed since the last execution and use
    // that to scale the output. We also apply the calibrationFactor to scale the output
    // based on the number of pulses per second per units of measure (litres/minute in
    // this case) coming from the sensor.

    flowRate2 = ((1000.0 / (millis() - oldTime2)) * pulseCount2) / calibrationFactor;

    //Serial.print(pulseCount);

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.

    oldTime2 = millis();

   //  Serial.print("::");
    // Serial.print(oldTime);
    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.

    flowMilliLitres2 = (flowRate2 / 60) * 1000;

    // Serial.print(flowMilliLitres2);
    // Add the millilitres passed in this second to the cumulative total

    totalMilliLitres2 += flowMilliLitres2;

    unsigned int frac2;

    // Print the cumulative total of litres flowed since starting
    //Serial.print("  Output Liquid Quantity: ");             // Output separator
    //Serial.print(totalMilliLitres2);
    //Serial.println("mL");

   setPointForN2 = EEPROM.get(5, WATEREQFORN2) / 2;

   if(totalMilliLitres >= setPointForN2 ){
       Serial.println("Solenoid Close Set Point Reach");
       digitalWrite(RELAY2, 1); //CLOSE VALVE
    }

     // Reset the pulse counter so we can start incrementing again
    pulseCount2 = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING);
  }

  if(flowMilliLitres2 == 0){
     totalMilliLitres2 = 0;
  }

}

/*
Insterrupt Service Routine
 */
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void pulseCounter2()
{
  // Increment the pulse counter
  pulseCount2++;
}

You'll need to show the complete code.  It isn't clear from just this snippet what is going on.

@Delta_G see edit

That's still not complete code.  My guess is either that the closeSolenoidValve function doesn't do what you expect or that the solenoid is being closed and thenimmediately reopened again because whatever condition got you into that state is still true.

The code you've shown is incomplete. Complete means in addition to logic, 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.   In particular, the datatype of flowRate isn't shown; if it's an integer, the flowRate / 60 divide will truncate.

Im posting my whole code ..

return loop();  That line is pretty useless.  You can't return the value of a function that returns nothing.  It also causes a recursion in your code, you're calling loop before the previous call to loop has finished.  Do that too many times and the whole thing crashes.

Try printing the setpoint right before the if statement that closes the valve and make sure it has the value you expect.

Its already printing , I set the set point into 100ml if I print something inside the condition like Serial.println("Set Point Reach"); it will print without problem but when I try digitalWrite(RELAY1, 1);//CLose it just dont work

What if you kill all the other code and write just a program that opens and closes the solenoid like the blink example.  Will that work to open and close it?  How are things wired?  Do you have a separate power supply for the relay?  Do you have flyback diodes for the relay?

I think I need to exit the Alarm if the condition is meet .

OK, if you're not into answering my questions then I'm done helping.

I have separate power for the solenoid and use relay to control it

OK.  There were more.  And a suggestion for something to try.  How did that work out?

Let us continue this discussion in chat.

It works fine , just exiting the alarm after the conditions is meet is the problem , even if it reach the set point the relay is stil on and water still flowing .

This may not be a direct answer to the question, in the sense that I
cannot tell you where exactly is the bug in your program. But hopefully
it will help you getting a program that does work. I tried to find the
bug, but it's quite hard. When reading your code, I could not stop
asking myself “Why is this so convoluted?”. As a general rule, a simple
program is easier to get working than a complex program. So I would ask
you: why don't you try something simple instead?
The first thing that stroke me is that it seems you did not realize that
the pulse count from the flow sensor is a direct measurement of the
volume that went through it. You are timing the pulses in order to
convert a pulse count into a pulse rate, then you convert that into a
flow rate, then you integrate the flow rate rate to get the volume. All
this is unnecessary complication: just count the pulses, the count
is a water volume, albeit in an unusual unit.
Second thing is the logic of the whole program. It should be clear at
first sight under what conditions the watering starts and under what
conditions it stops. This is best done with a finite state machine
with two state: either we are watering the plants or we are not. The
state variable is then a boolean, and the logic could written along
those lines:
void loop()
{
    // Should we start watering?
    if (!watering) {
        if (some_condition()) {
            start_watering();
            watering = true;
        }
    }

    // Should we stop watering?
    else {
        if (some_other_condition()) {
            stop_watering();
            watering = false;
        }
    }
}

Something explicit like this is generally easier to read, to understand
and to debug. And likely to be less buggy in the first place.
Third thing, you seems to be doing too much stuff at once: controlling
two different pumps, monitoring a DHT sensor, updating the setpoints...
You should try to get a minimal program working, and only then start
to add more stuff. The more functionality you add, the more complex the
program gets. Don't expect something complex to just work: you should
really get a simple version working first, and only then build on that.
Here is a proposed simplified version for your program. Absolutely not
tested: it is just meant to get you started.
#include <EEPROM.h>
#include <DS3231.h>

const uint8_t RELAY_PIN = 7;
const uint8_t MOISTURE_PIN = A15;
const uint8_t FLOW_SENSOR_PIN = 2;
const uint8_t SENSOR_INTERRUPT = 0;
const float PULSES_PER_ML = (4.5*60)/1e3;  // 0.27 pulses/mL
const int MOISTURE_THRESHOLD = 700;

uint16_t wateringPulseCount;  // required pulses of water to deliver
DS3231  rtc(SDA, SCL);

/***********************************************************************
 * Handling of pulse counts.
 */

volatile uint16_t pulseCount;

// Interrupt handler.
void pulseCounter()
{
    pulseCount++;
}

// Safely read the current pulse count.
static inline uint16_t getPulseCount()
{
    noInterrupts();
    uint16_t pulseCountCopy = pulseCount;
    interrupts();
    return pulseCountCopy;
}

/***********************************************************************
 * Main program.
 */

void setup()
{
    pinMode(RELAY_PIN, OUTPUT);
    pinMode(MOISTURE_PIN, INPUT);
    pinMode(FLOW_SENSOR_PIN, INPUT);

    // Initialize the watering limit as a pulse count.
    uint16_t wateringVolume;
    wateringPulseCount = EEPROM.get(0, wateringVolume) * PULSES_PER_ML;
}

void loop()
{
    static bool watering;  // are we watering now?

    // Start watering at 07:00 if the soil is dry.
    Time t = rtc.getTime();
    if (!watering && t.hour == 7 && t.min == 0) {
        if (analogRead(MOISTURE_PIN) > MOISTURE_THRESHOLD) {
            pulseCount = 0;
            attachInterrupt(SENSOR_INTERRUPT, pulseCounter, FALLING);
            digitalWrite(RELAY_PIN, LOW);  // open valve
            watering = true;
        }
    }

    // Stop watering after the required volume.
    if (watering) {
        if (getPulseCount() >= wateringPulseCount) {
            digitalWrite(RELAY_PIN, HIGH);  // close valve
            detachInterrupt(SENSOR_INTERRUPT);
            watering = false;
        }
    }
}

Note that the pulse count has to be read with interrupts disabled, but
you should not detach the interrupt handler. Detaching the handler
means you will miss pulses, wheres disabling the interrupts only delays
their handling until you enable them again. You won't miss pulses unless
to keep the interrupts disabled for too long (which you shouldn't do).


text:
How to set alarm on DS3231 sensor?
I want to know if it is possible to set an alarm in DS3231.
I want to set the alarm every 6 AM in the morning. Is this possible?

Yes it is (see datasheet datasheet) ... the DS3231 has 2 alarms.
There is also a library for the Arduino, see: library.
The alarm(s) can be set (repeatedly) via one of the following functions:
Alarm.alarmRepeat(hours, minutes, seconds, function);
Create an alarm that will call a function every day at a particular time.

Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
Create an alarm that will call a function every week on a specific day at
a particular time.

 "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
 dowThursday, dowFriday, or dowSaturday.

Detailed info and more functions: link

is it okay that i used the SDA SCL pins ? for ds3231 although I use the timelib.h and timealarm library?

I'm not sure, I never played with I2C so far, I see the DS3231 uses I2C, so I assume the library uses I2C to interact with the DS3231. Probably it needs to be connected via I2c (thus SDA/SCL).

When I try this Alarm.alarmRepeat(8,30,0, MorningAlarm);  // 8:30am every day   Alarm.alarmRepeat(17,45,0,EveningAlarm);  // 5:45pm every day using the timelib.h and timerAlarm.h library , when i close the serial monitor it restart counting ..

What do you mean exactly with 'restarts counting' ? I assume when the alarm(s) set is equal to the time of the IC, the alarm callback function is fired.

In the TimeAlarmExample ..
setTime(9,21,0,05,03,17); // set time to Saturday 8:29:00am Jan 1 2011 time is set to 8:29 am .. and then Alarm.alarmRepeat(8,30,0, MorningAlarm); // 8:30am every day  when i close the serial monitor it restart counting back to 8:29 am ..

Is it possible to achieve alarm using DS3231.h library ?

I think it is, but I never tried.

But if you first set the time (to 8:29) and than the alarm (to 8:30), the time will not change; it should continue counting from the time it was set (8:29), and never reset back to 8:29 or counting backwards.

I find the answer to my question .
I just add Time  t; and t = rtc.getTime(); into my code then an if statement like this if (t.hour == 11 && t.min == 59 && t.sec == 00)
ref http://www.instructables.com/id/Setup-for-DS3231-AlarmTimer-Function/

The correct way to use RTC alarms is to setup them to fire an interrupt when alarm date/time occurs. This way MCU doesn't have to poll RTC frequently. The configuration is described in "Alarms" paragraph of the datasheet.

source: Stack Exchange

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

sort: votes


text:
Ethernet shield programming
This is first time programming with Ethernet shield . I want to test the web server application with my Arduino. I have an Arduino Uno, Ethernet shield, and a potentiometer. Below code being uploaded.
Question are:

Currently I am using LAN connection to configure. How to configure it? Is internet required for below application?
How do I check the output?
Is there any software where i can make customized tags?
I have values coming from the serial port to be monitored on webserver. Can someone share how to monitor it?

Ethernet shield
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
      client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("
");
          }
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.
The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.
To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.

I have manually configured ip address as above . Let me know what problem i have made

It looks as though your network address is 192.168.7.0 with a subnet mast of 255.255.255.0. Therefore you would need to assign the Arduino an IP address is the range of 192.168.7.1 - 192.168.7.254. You need to make sure however that the IP address has not already been used by a device that is already on your network. e.g. 192.168.7.12 is already being used by your computer.

I have already  tried it but didn't worked . Is internet connect needed  for this application?? i have assigne d my network as 192.168.7.0 and arduino as you told it to 192.168.7.50. but nothing being changed

It is not clear what you mean by nothing has changed. Can you clarify? Are you seeing the server is at xxx serial output?

authors: 032 Pipat S. พิพัฒน์ ศาสนา

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


text:
How to control a Nema 17 stepper motor with an arduino? (too much current / heat)
I am trying to control a Nema 17 motor with a L298n dual bridge and an Arduino Mega.
My wiring is from this Instructable:
http://www.instructables.com/id/Control-DC-and-stepper-motors-with-L298N-Dual-Moto/?ALLSTEPS
When I connect it to my laboratory power supply the current limitation blinks. Normally when there is too much current needed the LED is all the time on and not blinking.
So I increase the current limit and the motor just starts moving on 3.1A @ 12V (doesn't move if less current) and in the description of the motor on amazon
they say "Rated Current/Phase:1.2A" so I am wondering what did I do wrong here?
From my understanding "Rated Current/Phase:1.2A" means that I should run this motor (it's a bipolar stepper motor with 2 phases) not higher than 2.4A?
These are the informations from amazon about this motor:
Specifications:

Led screw diameter: 8mm
Lead screw length: 300mm
Step angle :1.8 degree
Nut material: Brass
Holding Torque: 400mN*m
Thrust(full step): 12.5kg
Rated Current/Phase:1.2A
Rate Voltage: 3.3v
Rated Resistance/Phase:2.2±10%ohm

What would be a good voltage to run this motor? I thought 12V is a good idea with.
The motor L298n gets really hot when I run it at 3.2A or more so I think my setup will destroy the dual bridge and / or the motor.
I really appreciate help on this! :-)

one thing i can think of is that your PSU is too fast/good. Motors often need "infinite" amps to start moving, then they drop-off quickly. If your supply limits those high-voltage startup impulses, it might not be able to get off the ground. Read https://learn.adafruit.com/all-about-stepper-motors/matching-the-driver-to-the-stepper for info about avg current. I suspect your high heat is because the motor is not turning when consuming power.

Do you think my motor will get destroyed or can I use it with high amp?

i think the motor is more likely to get damage if there's not enough current, not from having too much. current limiting causes the volts to drop, and the motor need a certain voltage to turn. if it can turn, heat will build-up on the coils. if it does turn, it consumes less power and can self-cool.

I was running the motor for a while (few minutes) and the motor driver was getting hotter and hotter and already smelled a bit. The current was jumping from 3.2A (was the current limitation) to 2.6A and again to 3.2A from time to time. My sketch loaded on the arduino is just a non stop stepping, will my current decrease if I put in some delays?

you could be over stepping, or smearing microsteps, but it's hard to say without knowing virtually everything about your code, gear, internal wiring, etc. instant amps can jump around a lot and mislead humans and meters, don't use current limiting. excess heat is more important, and you might need to adjust your driving hardware/software in order to avoid that. if the extra heat is happening under no-load, i strongly suspect some software timing issues are in play.

I replaced my L298 with a easy driver A3967 and it works perfectly with just 0.2A. Maybe the L298 was broken or something. I still can't  understand that.

if it's not being controlled correctly, that explains the heat for sure, good to hear.

What voltage are you running it at? The motor is rated for 3.3V so you should probably be running it at 3.3V.

The stepper motor does not directly control or limit its own current.  When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin.  If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage.  Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.
To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point).  Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.
EDIT: I reviewed the info at the link, and this is the relevant area of the code:
// set speed to 200 out of possible range 0~255
analogWrite(enA, 200);
// set speed to 200 out of possible range 0~255
analogWrite(enB, 200);

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle).  Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue.  Reading further still, even the author gives you your first hint at what is happening:

This is not a speed value, instead power is applied for 200/255 of an
  amount of time at once.


text:
Two outputs: which one "leads" the other?
I have a problem with my Arduino Uno and my AS5311 position sensor
I am trying to get incremental output as described in Section 7 but I don't really know how to do it. It says that there are three outputs: A, B, and index. A and B will change states 512 times per 2mm of magnetic band (256 pulses) and index will produce a pulse every 2mm. It says that A "leads" B when the magnet is moving from right to left and B "leads" A when the magnet is moving from left to right.
What is the right way to get this information? I suppose it's using interrupts on A, B, and index but I'm not sure how.
Here is what I have so far (absolute position works fine):
const int A_Pin = 2;
const int B_Pin = 3;
const int Index_Pin = 8;
const int CSn_Pin = 5;
const int CLK_Pin = 6;
const int DO_Pin = 7;
int Bit;
int Position;
int Pow2[12] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
int OCF, COF, LIN, MagINC, MagDEC, EvenPAR;
volatile int ACount = 0;
volatile int BCount = 0;
volatile int IndexCount = 0;

void fA(){
  ACount++;
  //What should I do here?
}

void fB(){
  BCount++;
  //What should I do here?
}

ISR(PCINT0_vect){
  if(digitalRead(Index_Pin) == 1) IndexCount++;
}

void setup(){
  //For incremental output
  pinMode(A_Pin, INPUT_PULLUP);
  pinMode(B_Pin, INPUT_PULLUP);
  pinMode(Index_Pin, INPUT);
  attachInterrupt(digitalPinToInterrupt(A_Pin), fA, RISING);
  attachInterrupt(digitalPinToInterrupt(B_Pin), fB, RISING);
  digitalWrite(Index_Pin, HIGH);

  //For absolute position
  pinMode(CSn_Pin, OUTPUT);
  pinMode(CLK_Pin, OUTPUT);
  pinMode(DO_Pin, INPUT);
  digitalWrite(CSn_Pin, HIGH);
  digitalWrite(CLK_Pin, HIGH);

  Serial.begin(9600);

  cli();
  PCICR = 1;
  PCMSK0 = Pow2[Index_Pin - 8];
  sei();
}

void loop(){
  //Absolute position
  //delay(1);
  digitalWrite(CSn_Pin, LOW);
  //delay(1);

  Position = 0;
  for(int z0 = 0; z0 < 12; z0++){
    digitalWrite(CLK_Pin, LOW);
    //delay(1);
    digitalWrite(CLK_Pin, HIGH);
    //delay(1);
    Bit = digitalRead(DO_Pin);
    Position += Bit * Pow2[11 - z0];
  }

  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  OCF = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  COF = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  LIN = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  MagINC = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  MagDEC = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  EvenPAR = digitalRead(DO_Pin);

  digitalWrite(CSn_Pin, HIGH);

  Serial.print(Position);
  Serial.print(", ");
  Serial.print(OCF);
  Serial.print(", ");
  Serial.print(COF);
  Serial.print(", ");
  Serial.print(LIN);
  Serial.print(", ");
  Serial.print(MagINC);
  Serial.print(", ");
  Serial.print(MagDEC);
  Serial.print(", ");
  Serial.print(EvenPAR);
  Serial.print(", ");

  //Incremental output
  Serial.print(ACount);
  Serial.print(", ");
  Serial.print(BCount);
  Serial.print(", ");
  Serial.println(IndexCount);
}

The first problem is that after a while ACount and BCount drift apart so sometimes interrupts appear to be overlooked. The second problem is that I don't know how to tell which output "leads" the other one. How can I get this information (direction of movement) consistently?
Update:
I tried what was suggested in the comments and it works most of the time. The problem is that sometimes I seem to get a false reading. When A goes up I check the state of B to see if I have left or right movement. I save the movement into a boolean variable (Left) which I then use in the function that is called when index is up. If Left is true I decrease the index counter, otherwise I increase it. But after some time the index counter differs by two from its true value which means that I had a false direction of movement when index is up. Here is my new code:
const int A_Pin = 2;
const int B_Pin = 3;
const int Index_Pin = 8;
const int CSn_Pin = 5;
const int CLK_Pin = 6;
const int DO_Pin = 7;
int Bit;
int Position;
int Pow2[12] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
int OCF, COF, LIN, MagINC, MagDEC, EvenPAR;
bool Error = false;
volatile int ACount = 0;
//volatile int BCount = 0;
volatile bool Left = true;
volatile int IndexCount = 0;

void fA(){
  if(digitalRead(B_Pin) == HIGH){
    Left = true;
    ACount--;
  }
  else{
    Left = false;
    ACount++;
  }
}

//void fB(){
//  BCount++;
//}

ISR(PCINT0_vect){
  if(digitalRead(Index_Pin) == 1){
    if(Left) IndexCount--;
    else IndexCount++;
  }
}

void setup(){
  pinMode(A_Pin, INPUT_PULLUP);
  pinMode(B_Pin, INPUT_PULLUP);
  pinMode(Index_Pin, INPUT);
  attachInterrupt(digitalPinToInterrupt(A_Pin), fA, RISING);
  //attachInterrupt(digitalPinToInterrupt(B_Pin), fB, RISING);
  digitalWrite(Index_Pin, HIGH);
  pinMode(CSn_Pin, OUTPUT);
  pinMode(CLK_Pin, OUTPUT);
  pinMode(DO_Pin, INPUT);
  digitalWrite(CSn_Pin, HIGH);
  digitalWrite(CLK_Pin, HIGH);

  Serial.begin(4800);

  cli();
  PCICR = 1;
  PCMSK0 = Pow2[Index_Pin - 8];
  sei();
}

void loop(){
  //delay(1);
  digitalWrite(CSn_Pin, LOW);
  //delay(1);

  Position = 0;
  for(int z0 = 0; z0 < 12; z0++){
    digitalWrite(CLK_Pin, LOW);
    //delay(1);
    digitalWrite(CLK_Pin, HIGH);
    //delay(1);
    Bit = digitalRead(DO_Pin);
    Position += Bit * Pow2[11 - z0];
  }

  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  OCF = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  COF = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  LIN = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  MagINC = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  MagDEC = digitalRead(DO_Pin);
  digitalWrite(CLK_Pin, LOW); //delay(1);
  digitalWrite(CLK_Pin, HIGH); //delay(1);
  EvenPAR = digitalRead(DO_Pin);

  digitalWrite(CSn_Pin, HIGH);

  if(LIN == HIGH || MagINC == HIGH || MagDEC == HIGH) Error = true;

  Serial.print(Position);
  Serial.print(", ");
  Serial.print(OCF);
  Serial.print(", ");
  Serial.print(COF);
  Serial.print(", ");
  Serial.print(LIN);
  Serial.print(", ");
  Serial.print(MagINC);
  Serial.print(", ");
  Serial.print(MagDEC);
  Serial.print(", ");
  Serial.print(EvenPAR);
  Serial.print(", ");

  Serial.print(ACount);
  Serial.print(", ");
  Serial.print(Left);
  Serial.print(", ");
  //Serial.print(BCount);
  //Serial.print(", ");
  Serial.print(IndexCount);
  Serial.print(", ");
  Serial.println(Error);
}

Update 2: Maybe the problem comes from the hysteresis described in section 7.2? If the change of direction is directly at the index pulse, wouldn't I get a false direction of movement?

Search this site for “rotary encoder”. Even though yours may not be rotary, it's exactly the same problem.

On a rising edge of A check the state of B, if it's high B is leading A, if it's low A is leading B.

Thanks for your helpful comments. I updated my question accordingly.

Using ad hoc methods to handle quadrature inputs (ie, the kind of signals you have) can lead to missed pulses and accumulated error.  However, it's possible to handle fairly fast quadrature input pulse trains using pin-change-interrupts on an Arduino.
In my answer to the question How to read RPS for fast rotation with status change method in Arduino?, you will find links to several previous answers that include code to process quadrature inputs at reasonable data rates; for example, Reading from a KY-040 rotary encoder with Digispark.

Edit 1, part 1: Ad hoc methods (such as just checking the state of input B whenever input A has a rising edge), while often simple to implement, can cause extra counts or missing counts.  Extra counts may occur if A bounces and has several rising edges in a short interval.  Missing counts may occur if rising edges of A occur faster than they are handled, particularly if the ad hoc code includes delays to deal with contact bounce.
Typical finite state machine methods for  handling quadrature inputs, by contrast, automatically debounce A and B inputs, either by ignoring cases where a set of inputs repeats, or by counting an equal number down and up transitions as bouncing occurs.  See for example the diagrams in reply #17 in “easy rotary encoder implementation” at eevblog.com – from which the first diagram below is taken – and in Omapl137 linux eqep driver at ti.com, where the second diagram is from.  Both those sources provide substantial detail about processing quadrature inputs.

Edit 1, part 2: Besides using a correct model of the quadrature process, encoder software should be fast, delay free, and asynchronous to other processing.
Slow handling of events (that is, of changes on encoder inputs) is caused by lengthy code or indirect IO, inter alia.  Slow event handling cannot keep up with as many events per second as fast event handling; if code is really slow, users will notice that they have to turn or move an encoder at a snail's pace to avoid missing menu items or location steps.
Trying to handle events synchronously, eg via polling, also limits the rate at which software processes events.  Unless a processor is quite fast or is dedicated to quadrature input, it is likely to miss occasional transitions on inputs.  Using interrupts usually is a better choice when dealing with asynchronous transitions like encoder inputs.
By “indirect IO” I mean use of functions like digitalRead() and attachInterrupt() which result in massive overhead for IO processing.
digitalRead() takes between 3 and 4 μs to read one bit of input.  Directly reading a port takes one instruction cycle, 62.5 ns (1/16 μs) on a typical Uno or Nano.  If two encoder inputs are wired to the same port, one port read is enough, vs two digitalRead() calls.  Note, this comparison assumes encoder pin numbers are known at compile time, that the target MCU is known, etc.  With direct port IO, the programmer is responsible for making the software conform to the MCU, instead of having digitalRead() taking care of details like which port bit corresponds to which Arduino digital input.
attachInterrupt() adds about 5 μs of overhead to interrupt processing.  [See the section  “How long does it take to execute an ISR?” in Nick Gammon's interrupts page.]  This is on top of about 2.6 μs of ordinary software overhead (for interrupts on Arduino Uno, Nano, etc.).
Note, some of the example code in previous answers uses attachInterrupt() and digitalRead(), but is concise enough to still get reasonable input rates.  Using those functions leads to better code readability and portability.   However, for faster input rates, you might use code as shown below.  This code probably could be improved (shortened, made faster, made more clear) but anyhow functions ok for up to a few hundred counts per second.  To adapt this code for other input pins, replace abNew = PINC & 3; by code to set the low two bits of abNew equal to the input bits; and adapt setup_rotocoder() accordingly.  See (eg) Arduino Pin Change Interrupts and Simple Pin Change Interrupt on all pins for further information about setting up pin change interrupts.
// The following three vars should be visible to loop(), which
// can find out if an encoder changed by testing rotoInt.
static   byte roABold;          // A,B states for rotor
volatile uint16_t roCount;      // current rotary count
volatile byte rotoInt;          // Rotary-interrupt flag (change flag)

// jiw (c) 2015  Offered without warranty under GPL v3 terms as at http://www.gnu.org/licenses/gpl.html

ISR(PCINT1_vect) {  // This plus Arduino overhead of 2.6 us probably takes ca 5 us total per interrupt
  enum { upMask = 0x66, downMask = 0x99 };// up & down are complements
  byte roABnew = PINC & 3;  // Read pins  14, 15, which are A0, A1
  byte criterion = roABnew ^ roABold;
  if (criterion==1 || criterion==2) {
    if (upMask & (1 << (2*roABold + roABnew/2))) // Embeds state transition rules
      ++roCount;
    else --roCount;             // upMask = ~downMask
  }
  roABold = roABnew;            // Save new state
  rotoInt = 1;                  // Say something happened
}

// For rotary encoder initialization, in setup(), say:   setup_rotocoder();
void setup_rotocoder() {
  rotoInt = roABold = 0;
  roCount = 32768;              // Start with a middle count
  pinMode(A0, INPUT_PULLUP);    // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT_PULLUP);    // pin 15, A1, PC1, for pin-change interrupt
  PCMSK1 |= 0x03;
  PCIFR  |= 0x02;             // clear pin-change interrupts if any
  PCICR  |= 0x02;             // enable pin-change interrupts
}

Could you please elaborate on why rotary encoders tend to lose count and how the solutions you suggested solve the problem? I don't only want it to work, I would also like to understand. I should mention that this is the first time I've ever used a microcontroller so I am a total beginner (know a thing or two about C++ though).

@Mario, see edit

In addition to this excellent answer I have a page about rotary encoders.


text:
How to use analogWrite() on multiple pins at the same time?
I would like to do,
analogWrite(100,3);
 analogWrite(200,6);
at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for digitalWrite() but I couldn't find one for analogWrite(). Can someone please help me with just a simple example on just how to do the above operation?
I'm using arduino uno.

You have your parameters the wrong way round:
analogWrite(2, 100);
analogWrite(6, 200);

However: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with ~ - they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.

yeah I'm sorry it's pin 3. Now how to i turn both on at the same time?

Just like that. When you run analogWrite() it starts PWM on that pin and it keeps going until you tell it otherwise. If you aren't getting anything out then you have probably broken that pin through misuse or doing something else in your code that's stopping PWM.

No. if i use pin 6 first, then pin 3. The pin 6 lights up and not pin 3

And if you do it the other way around? And NOT PIN 2.

analogWrite(6, 100);
analogWrite(3, 200); This turns on pin 6

NOT PIN 2

I think you have blown the LED on pin 3.  You haven't said that you have a resistor between the LEDs and the Uno.  If this is the case you might have fried the LED on pin 3.  If its good then try doing (3, 100) not 200 and see if that works.

I guess someone has to introduce multiplexing here...


text:
Enter timing value via keypad for bldc motor spin
I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?
The idea for this code is to enter the speed and timing via keypad.  After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?
Here is my code so far...
#include "Keypad.h"
#include "LiquidCrystal.h"
#include "Servo.h"

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

Servo myservo;

const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("S:");
  lcd.setCursor (0,1);
  lcd.print ("T:");

  myservo.attach(11);
}

void loop()
{
    static char buffer[4], spintime[4];
    static byte i = 0, a = 0;
    char key = keypad.getKey();

    // i < 3: prevent buffer overflow
    if  ('0' <= key && key <= '9')   // this is for speed entry
    {
        buffer[i] = key;
        ++i;
        buffer[i] =0;  // null-terminate buffer
        lcd.setCursor (2,0);
        lcd.print(buffer);
    }

     if  ('0' <= key && key <= '9') // this is for timing entry
     {
        spintime[a] = key;
        ++a;
        spintime[a] =0;  // null-terminate buffer
        lcd.setCursor (2,1);
        lcd.print(spintime);
    }
    else if (key == '#')            // this is to run the motor after speed and timing are entered
    {
        int value = atoi(buffer);
        myservo.write(value);       //speed of motor
        int timing = atoi(spintime);
        delay (timing*1000);        // keep the motor spin for ( timing entered) second
        myservo.write(0);
        i = 0;
    }
}

As I understand it, you want to enter the speed, then the time, then '#'.
Let's imagine you want a speed of 22 and a time of 3.  The device will see 2, 2, 3, #.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.
My suggestion: we'll enter speed followed by *, and time followed by #.  (There are other possible solutions to this.)
We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter 123456789#, we will register 123#.  (Again, there are other solutions.)
There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.
Lastly, I am assuming your code to drive the motor and read keys is correct.
Here's some loop code which I hope will do the above.  It will read numbers until it finds either a * or a #, convert the number to an integer, and store it as either time or speed.  When it has both speed and time, it will spin the motor and reset the values.
void loop()
{
    // Where we will store the number as we type it.
    // This buffer is large enough for a 3-digit number, pull a null terminator
    char buffer[4];

    // The speed of the motor
    static int speed = 0;

    // The time to spin for
    static int time = 0;

    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i<3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key || '*' == key)
        {
            // Null terminate
            buffer[i] = 0;

            // Convert to an integer
            int value = atoi(buffer);

            // Set the appropriate value
            if ('#' == key) time = value;
            if ('*' == key) speed = value;
            break;
        }
    }

    // If we have both speed and time...
    if (speed > 0 && time > 0)
    {
        // ...spin the motor at the required speed
        myservo.write(speed);
        // ...and for the required time
        delay(time*1000);
        // ...then stop it
        myservo.write(0);

        // Reset the values for next time
        time = 0;
        speed = 0;
    }
}

thanks for the insight mark smith... but I wanted it to do like this (code below) how to I  enter the speed first, then enter the timing second... after that... pressed #  for the motor to move to the desired speed according to the timing... how do I combine the speed entry and time entry...

Could you edit your question to state the actual question, please? Also please include code to set the speed, if you have it, because I don't know how to control your motor. I'll try to help with getting input.

i have change it mr. Mark... i hope you can really help me with this.

Answer updated.

Mr Mark... i have tried your code... I enter speed of 123 then pressed #... after that I enter 10  then pressed *... after entering all the entries... the motor suppose to spin according to the time given...however nothing seem to happen... your code seems right tho...does pressing *  after to time entry suppose to activate the motor??

Read my answer again, more carefully.

thank you so much Mr Mark Smith.... it worked!!!!... i appreciate it... God bless you Sir... :)

Mr. smith... how do i make the timing displayed on the lcd to be counted down... let just say... i want 10 second... then the display show 10,9,8,7,6.... 1... is it possible with delay()??

That's an entirely separate question. Please post it as a new question, complete with a minimal, complete, verifiable example. Remember to tell us how much of the problem you have already been able to solve - for example, can you display anything on the LCD?


text:
Controlling servo with IR led and photodiode
I have found myself a really nice scheme of a buzzer that is controled by the IR led and photodiode by I want to upgrade it so it can be used for controlling a servo. What I have in mind is that when there is no object the servo whould stand still and when object comes by it will go to 90 degrees, wait for 5 sec and go back to 0 position. I just want to know is that possible for an Arduino starter and where should I look for help. Thanks.

Yes that is possible.
Start by googling for the two halves of your project separately. Find a project, example or tutorial which controls a servo. Get it working. Understand it.  Then find one which deals with a sensor similar to the one you want to use, get it working, understand it.
Then you'll have everything you need to get your project up and running.

Feel free to post a new question if you have a specific problem. Accepting one of the answers to this question, if one helped you, will encourage people to keep helping you.

The convenience of the Arduio development paradigm is that most common hardware projects have been abstracted by software libraries to simple software interfaces.  This is the case for controlling common servos motors.
If you find it sufficient, use the Arduino servo library to control servo motors.  There are only 6 method to understand and in most cases you only need 2 or 3 of them.  This example appears to satisfy your requirements for a sweeping servo.


text:
Use Female USB Type A as Power Supply for external device
I bought a female USB Type A Breakout, like this (https://www.sparkfun.com/products/12700). I thought I could use this one to simply power a USB 5v water pump. Therefore I use an external USB power supply that is regulated by a relay, that I regulate with my Arduino. But I'm wondering if it is possible to get that USB Breakout to "give out" power to my water pump.

Yes. Just connect VCC to +5V and GND to GND and you can plug a 5V device into it.
If you need to use it as a charge port (for charging a phone) you will need to connect the D+ and D- pins together.

I thought that too, but it's not working. Whats the difference between a charge port and my case?

A charge port tells the device how much current it can supply. A dumb device like a pump won't need it.

But do you have an idea, why it's not working? I use a FTDI USB plug, that I stick into a USB  Power Adaptor(with direct link to usb pump works). Then I connect VCC and GND to the usb female breakout.

ok simple as it is sometimes... there was a bad manufactoring soldier. i fixed it and now its running. thanks a lot!


text:
RadioHead and Servo compile problems
I am having this problem when trying to compile my sketch. I am using RF frequency modules to send data between devices and a servo motor to control the tilt of a ramp. I understand that both libraries use TIMER 1 but I am unsure how to change one of them to use TIMER 2 thanks.
Arduino: 1.8.7 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\Servo\avr\Servo.cpp.o (symbol from plugin): In function `ServoCount':

(.text+0x0): multiple definition of `__vector_11'

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.
Board at COM4 is not available

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Mikael Patel pretty much gave the answer but I want to be more precise with it.
In your Arduino libraries folder (C:\Users[USER_NAME]\Documents\Arduino\libraries\RadioHead) there is a file called "RH_ASK.cpp" where you have to insert this line:
#define RH_ASK_ARDUINO_USE_TIMER2
You can open the cpp file with Notepad. I added the line between "include <RHCRC.h>" and
"#ifndef SAMD51" and it worked for me.
I know it's an old post, but the previous answer didn't help me yesterday, so I hope this help someone in the future as well.

You can force the RadioHead library to use Timer 2 instead. This can be done by enabling the define RH_ASK_ARDUINO_USE_TIMER2 near the top of RH_ASK.cpp.
More details about how to do this may be found in the RadioHead library documentation. Please see https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html.
Cheers!

You can also use the ServoTimer2 library to move the servos to timer 2 if you'd prefer that.
https://github.com/nabontra/ServoTimer2

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


text:
I keep getting stray '/302'.
I even rewrote the code and it still didn't work. How can I fix this?
#include "pitches.h"
void setup() {
    // put your setup code here, to run once:
    pinMode(4, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
  tone(4, NOTE_D4, 500);
  digitalWrite(dayOne, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, LOW);
  digitalWrite(Shamash, LOW);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(Shamash, HIGH);
  tone(4, NOTE_A4, 250);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(Shamash, LOW);
  tone(4, NOTE_D5, 500);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250); //Oh chanukah oh chanuka come light the meora
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(Shamash, LOW);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay(350);
  tone(4, NOTE_D5, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(Shamash, LOW);
  delay(700);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(daySeven, HIGH);
  digitalWrite(Shamash, HIGH);
  delay(350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_A4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(daySeven, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  digitalWrite(dayTwo, HIGH);
  digitalWrite(dayThree, HIGH);
  digitalWrite(dayFour, HIGH);
  digitalWrite(dayFive, HIGH);
  digitalWrite(daySix, HIGH);
  digitalWrite(daySeven, HIGH);
  digitalWrite(dayEight, HIGH);
  digitalWrite(Shamash, HIGH);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  digitalWrite(dayOne, LOW);
  digitalWrite(dayTwo, LOW);
  digitalWrite(dayThree, LOW);
  digitalWrite(dayFour, LOW);
  digitalWrite(dayFive, LOW);
  digitalWrite(daySix, LOW);
  digitalWrite(daySeven, LOW);
  digitalWrite(dayEight, LOW);
  digitalWrite(Shamash, LOW);
  delay (700);
  tone(4, NOTE_F4, 500); //Oh chanukah oh chanuka come light the meora
  delay (700);

  tone(4, NOTE_F4, 250);
  digitalWrite(dayOne, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayTwo, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayThree, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayFour, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(Shamash, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(dayFive, HIGH);
  delay (50);
  tone(4, NOTE_F4, 250);
  digitalWrite(daySix, HIGH);
  delay (50);

  tone(4, NOTE_G4, 250);
  digitalWrite(daySEVEN, HIGH);
  delay (50);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayEIGHT, HIGH);
  delay (50);
  tone(4, NOTE_G4, 250);
  delay(250);

  tone(4, NOTE_A4, 250);
  digitalWrite(dayEight, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(daySeven, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(daySix, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayFive, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(Shamash, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayFour, HIGH);
  delay (50);
  tone(4, NOTE_A4, 250);
  digitalWrite(dayThree, HIGH);
  delay (50);

  tone(4, NOTE_G4, 250);
  digitalWrite(dayTwo, HIGH);
  delay(50);
  tone(4, NOTE_G4, 250);
  digitalWrite(dayOne, HIGH);
  delay(50);
  tone(4, NOTE_G4, 250);
  delay(250);

  delay (300);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_E4, 250);
  delay (350);
  tone(4, NOTE_F4, 750);
  delay (1000);

  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_G4, 250);
  delay (350);
  tone(4, NOTE_A4, 250);
  delay (350);
  tone(4, NOTE_G4, 250);
  delay (350);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_F4, 500);
  delay (700);
  tone(4, NOTE_G4, 500);
  delay (700);
  tone(4, NOTE_F4, 250);
  delay (350);
  tone(4, NOTE_E4, 250);
  delay (350);
  tone(4, NOTE_D4, 500);
  delay (700);
  delay (2000);
}

Edit your post to contain the full error message, in a code block.

The Stray /302 is saying that the compiler found some random unicode character that it didn't understand.  You should put your code into some text editor that will allow you to see the unicode characters and go find it.  It will probably be a lot easier if you'll format that code instead of trying to cram it all in one line.


text:
Arduino Servo with Serial
I have an interesting problem. I want to control ESC and servo with Arduino. I'm using HC-12 to communicate with 2 Arduino and I'm using SoftwareSerial on the nano.

#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial mySerial(2, 3); // RX, TX
Servo esc,servo1;

String okunan;
int escval;

void setup() {
  okunan="";
  esc.attach(9);
  servo1.attach(10);
  mySerial.begin(2400);
  Serial.begin(9600);
}

void loop() {
   while (mySerial.available()) {
    delay(3);  //delay to allow buffer to fill
      char c = mySerial.read();  //gets one byte from serial buffer
      okunan += c; //makes the string readString
   }

  if(okunan.length()>0)
  {
    Serial.println(okunan);
    //escval= map(okunan.substring(0,okunan.indexOf(',')).toInt(),0,1023,,2000);

    servo1.writeMicroseconds(map(okunan.toInt(),0,179,1000,2000));

    okunan="";

mySerial.flush();
  }
  delay(20);
  }

When I use a potentiometer, It works successfully. But When I use with serial and if three digit value(between 0-179, for example, 120) comes from serial(HC-12), motor works and stops continuous and irregular. If the value is under three digit there is no problem.
Also, if I delete the ESC variable(servo) or add a new servo to code, it always starts and stops interestingly(Using or not it doesn't matter. If I add Servo servo2 etc., it is going crazy.
I've tried on Uno. That is the same.
Thanks in advance...

Did you look at the source code for SoftwareSerial and Servo? What does SoftwareSerial do when it detects a start bit? Receives the character in the ISR. And how does that affect Servo? It blocks the Servo ISR and delays pulse generation.

Like Mikael Patel said, SoftwareSerial disables interrupts for the entire character receive time.  Bad juju.
This answer lists the alternatives:

HardwareSerial is always the best.  Simply connect the device to pins 0 & 1 and use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The UNO only has Serial.  Serial would not interfere with the Servo.
AltSoftSerial is the best of the software serial libraries.  Only one instance is allowed, and it is must be used on the Input Capture pins (pins 8 & 9 for a Nano).  It would not interfere with the Servo.
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.  Receiving characters does not disable interrupts, but transmitting does (i.e., TX would interfere with the Servo).
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot transmit and receive at the same time (unlike all other choices).  This can interfere with other parts of your sketch, other device communications, or with libraries (e.g., Servo).

In your case, I would suggest connecting the HC-12 to pins 0/1 and use Serial.  No software serial library required, but you will have to disconnect pin 0 to upload new sketches over USB.  Some people put a switch in that wire so it's easy to upload a new sketch.
If you need debug prints, I would suggest using AltSoftSerial and an extra TTL Serial-to-USB adapter (aka FTDI module) to your PC.  Then print your debug messages to the AltSoftSerial variable:
#include <AltSoftSerial.h>
AltSoftSerial debugPort; // always pins 8 & 9

   ...

void loop()
{
  if (something) {
    debugPort.println( F("something happened!") );

Or, if the HC-12 connection is receive only, don't connect pin 1 (TX).  Then your debug prints won't go to the HC-12.
BTW, don't use delay and don't use String.  They will get you into trouble sooner or later.

Thank you very much. Can I hardware serial on nano or uno? Do I have to eject USB?

Yes, you can use HardwareSerial (0 & 1) on a Nano or UNO.  You only have to disconnect pin 0 from the HC-12 when you upload a new sketch over USB.  You do not have to disconnect the USB cable when running the sketch (reconnect pin 0 after the upload completes).


text:
Arduino cluster functionality - feasibility advice for arduinos to communicate using variable-length long strings?
My apologies. This is my first time on this site and I wasn't even aware that it wasn't some sort of discussion forum until receiving the automated response message to my already submitted vague and open-ended question.
Thank you Nick Gammon for pointing out Wanago's very interesting project, and I am sorry I did not provide enough information to show the difference in requirements. His solution is quite strictly structured and rigid (not just physically). But I wish to provide a solution that might allow anyone to fairly easily create an ad-hoc collection of any available arduino compatible hardware - which could also allow use of ESP devices for additional functionality if wished, but would not require ESPs as a means of connecting nodes. There may be a better solution than your RS485 Rolling Master for connecting nodes, but yours is the best solution I have yet seen so far, and not least because of the minimal resources required.
Thank you JBulmer for your clear overview and assessment, which does now give me a point of focus. In order to pursue this, I must try to aquire sufficient skills to add some form of multiple-chunk protocol layer on top of Nick Gammons Rolling Master protocol. I don't know if I'll manage it because I'm a hacker not a programmer, therefore I would appreciate  if I could give my reasons for trying, because I would very much value your opinion as to whether you think it would be worth my efforts or not.
Nicks protocol already provides auto-negotiating of nodes and takes care of most fault-tolerance type issues. I believe it auto-detects nodes and assigns them IDs which are stored in each individuals EEPROM, so he has already taken care of most of the connectivity side of things.
And I think the main reason for him using a defined message length was in order for all nodes to be able to poll in timeslot sequence for opportunity to transmit as master, which means it ought to be possible to somehow sync up re-constitution of split message blocks.
So apart from the protocol extension for handling of long strings, I don't see any other major obstacles which I can't imagine a solution for in principle even if not yet aware of how. I hasten to add that I am pushing myself way out of my comfort zone to try to achieve this because I think (though perhaps wrongly) that it might offer much benefit to ordinary arduino amateurs (such as myself) who I feel arduino is mainly aimed at. So the following example is not any specific requirement of mine, just something to illustrate some of the potential that could be offered to non-professionals - hopefully after the initial scene-setting, things can become more apparent...
The majority of arduino project examples use the serial monitor as a quick and easy way for user interaction, which can then be expected to need customising for more practical methods of input and output - but clustered nodes communicating serially might allow many project examples to be used almost as is.
An Infra-Red sender makes a good starting point. The IRremote library IRsendDemo.ino monitors the serial port for a keypress then calls a send routine, eg: irsend.sendSony. The incoming serial trigger could be made to be anything the user wished to use as a command, such as MyIRblaster, and could also include an equivalent text string of any required parameters for appropriate data conversion before use, ie:  MyIRblaster Sony(0xa90, 12)
All this can be developed and tested in independent isolation using the serial monitor, then when happy, add a 'common' block of RS485-based cluster-talk code, allowing any other node the ability to then send it a MyIRblaster command and parameter to action when needed.
As the IR arduino is using the IRremote library anyway, we may as well also give it an IRread capability, which wouldn't even require any associated trigger command.
It would be an advantage to be able to save IR signals somewhere though, but trying to squeeze on additional SD and FAT libraries as well as IRremote might be a step too far, so perhaps better just to add a separate SD node for storage. The SD node could have a file of saved IR codes, perhaps each with an asscociated corresponding simple text description such as TVmute, and have a suitable command+parameter capability added such as "SendBlaster (name)". This would allow any node to issue eg: "SendBlaster TVmute" to the SD node which in turn could issue a corresponding MyIRblaster Sony(0xa90, 12) command to the IR node.
And similarly to action any other types of node functionality for that matter - it would be relatively trivial to add some relays to the IR node if wished, and make the node recognise a "Relay (name)" command+parameter for instructing it to control any relay as required.
But it would also be just as easy (if not easier from a software point of view) to add a separate Relay node if wished. And similarly, even a Trigger node perhaps offering 64 channels of interupt-driven inputs - which also wouldn't need to recognise any incoming command, just simply be able to issue perhaps a 'Triggered' command plus appropriate triggered channel number as a lookup instruction to the SD node. Every trigger input could be assigned its own corresponding list of responses in its config file entry, which could include any of the functionality that any of the nodes could respond to.
Adding new functionality to the cluster would be as simple as adding another command keyword to a relevent nodes list of commands to be parsed for, which when matched would branch to an appropriate internal function.
So adding a "WriteLOG" command to the SD node (and having it parse for an accompanying "Details" parameter) could provide a facility for every node to be able to record events to an event log just by sending the serial command "WriteLOG (details)"to the SD node.
Commands don't have to be external, they could include any locally recognised macro-type commands for accessing any of the internal capability. So for instance the SD node could recognise a "Pause (duration)" instruction to invoke a non-blocking delay if wished. This could allow the SD node to send multiple IR code commands with pauses between each transmission. It might also recognise a 'No_Retrigger (duration)' timer to prevent unwanted repeat triggering of PIRs etc.
To better appreciate the potential now, we could create a config file on SD that contains an appropriate channel entry # for every trigger input we might wish, be it IR receives, PIRs, switch contacts or whatever.
The channel #3 doorbell entry could be something like this...
3  Doorbell,  No_Retrigger (3mins),  MyIRblaster (TVmute),  Relay (Porchlight) (ON),  Relay (Doorbell) (ON),  Pause (3secs),  Relay (Doorbell) (OFF),   MyIRblaster (TVun_mute),  Pause (5mins), Relay (Porchlight) (OFF).
If the SD node receives a 'Triggered Doorbell' instruction it simply parses the corresponding #3 entry and sends any extracted commands out for the other nodes to action as appropriate. In this case it would ignore subsequent PIR retriggering for 3 minutes, send commands to mute the TV, turn on the porch light, ring the doorbell for 3 seconds, unmute the TV, then turn the porch light off after 5 minutes.
It could also easily include simple local conditional logic to only turn the Porchlight when dark etc, which could allow option for appropriate qualifiers to a commands parameters, ie: Porchlight (ON) (IF_dark).
PIR sensors could select CCTV cameras, or even send IR commands to point a PTZ cam to preset positions, and all using just the same cluster functionality being used above.
A voice node might be added to givie an "Announce (message)" command, then add appropriate config entries to provide appropriate voice announcements for any triggered events.
Even amateurs could evolve quite sophisticated flexible ad-hoc systems without needing any rocket science, and without hardware constraints other than needing cheap RS485 adapters and sufficient memory for running the protocol and parsing out any commands plus conversion of any parameters.
Although the SD node in the example above is tending towards becoming a systems co-ordinator, it is still just essentially another cluster peer node. But perhaps there could be good grounds for trying to modify Nicks Rolling Master to take advantage of what benefits an SD intelligent controller might offer, such as newly connecting nodes automatically obtaining assigned IDs plus other 'characteristics' and 'behaviour' from the centrally managed SD config file.
I'm willing to roll up my sleeves and prepare for the long slog if the concept is considered realistic and worthwhile, but I would certainly welcome informed opinion as to whether it might be or not.
-------Original---------
I am looking into the feasibility of linking multiple Arduinos together to form a cluster of Arduino and ESP8266 nodes capable of sending sequences of plain text commands plus optional parameters to each other.
This could offer a mechanism for any node to be able to access the functionality of any other node without having local burden of that functionality.
For instance, only the SDcard node would require the libraries and overheads for accessing a centralised config file on SD card, but any of the other nodes could request appropriate entries from the config file whenever needed, or have ability to write event entries to a log file.
Similarly for an InfraRed node and its IR libraries, allowing any other node to send it plain text commands and parameters to transmit any required IR code even though the other nodes don't have local IR functionality themselves.
Basically, each individual arduino might just be considered a black box that does something useful and can be programmed to respond to certain external text commands (so in fact any other platforms with similar blackbox functionality could also easily be integrated to the cluster if wished).
Each node would parse an incoming string for a command that matched any of it's own local list of recognisable commands (ie: IRsend [code]) then branch as appropriate with any extracted accompanying parameters.
A cluster could be built up to include any and all required arduino functionality even though all of that functionality could never be squeezed onto any single arduino.
So an automation cluster could include things like voice announcements, web access, X-10 firecracker control etc just by including the appropriate nodes. Then tomorrow a voice recognition node might be easily added - needing to do nothing more than just issue appropriate text commands to also invoke any already existing functionality.
In principle, anyone could have the capability for doing almost anything they might wish, so although I don't know if this cluster functionality idea can be practically achieved or not, but the possible potential offers much incentive for trying.
And Nick Gammons excellent RS485 Rolling Master article brings the possibility so tantalisingly close... but it uses fixed-length messages to achieve it's clever self-negotiating fault-tolerance, and I'm afraid I don't know enough to be able to merge variable-length long string capability with his enticing communications system.
So I would appreciate any suggestions, even just informed advice telling me to forget it because it cannot be done (cos at least then I'd be able to get some sleep!).
Thanks,
Robin Baker.

Many communication systems use fixed-length, or limited-length, data exchange at the lower levels. For example, the ethernet network, under TCP/IP, has a maximum package size of 1526 bytes.
However, that doesn't prevent us moving large chunks of data, e.g. a DVD across the Internet.
A common approach is to use a layered protocol suite. Each layer is responsible for providing a service to the higher layer by using the service of the lower layers.
We talk about layered protocols because it provides a powerful, yet simplified way of thinking about communication problems. Rather than get bogged down in lots of detailed issues which need to be solved to work, we try to organise the problem into simpler and simpler solutions. Eventually things which we can implement without too much difficulty can be built, then higher layers are built from the simpler capabilities of lower layers.
The highest level of your protocol would provide the sort of service you need. In this case, you want to be able to send long-ish string messages, so the highest level would do that by using a mid-level fixed-length service.
In its turn the mid-level fixed-length service might provide error-free fixed-length messages using a still-lower-level service which can move fixed-length messages, but can't correct some types of errors.
(This is just an illustration of the idea, please don't take this as a concrete suggestion on how to implement anything.)
So, don't think "I don't know enough to be able to merge variable-length long string capability with his enticing communications system"
Instead, ask the simpler question, "how could I use that existing fixed-length communication system to send variable length strings?"
The answer might be pretty simple if the underlying system guarantees the order that messages are received. For example, send a count of the message length (in one or more messages) then send that number of bytes. The receiver knows how much to expect, and needn't act to interpret the data until it is received.
Then how to tell the difference between the command and its parameters? The command might be the first 'parameter' in the string, and parameters come after it.
The way I interpret your question, there may be several problems beyond sending variable length strings. There are potential problems like: adding or removing nodes, nodes failing, allocating 'names' to services on nodes (so commands can be sent to the appropriate node), etc.
However, the fundamental problem of sending long strings over a fixed-length communication channel is straightforward, and can be solved in a few different ways (I mentioned one, above).

Someone (Wanago) has done a similar project here. However instead of ESP8266 he used I2C which sounds more practical to me.
See images:

He had the same basic idea - each board has a specific task, and the work is shared between them.


text:
Bad LCD? Bad microcontroller? Or what?
So I recently bought an Arduino along with an LCD module and two extra ATmega328P-PU ICs. Yesterday it was working just fine then I disconnected everything and reconnected it and this happened.
What could possibly go wrong?
Setup:

with microcontroller that came with the board:

with the microcontroller that a purchase separately:
http://s1072.photobucket.com/user/Tonny_Cassidy/media/Mobile%20Uploads/20160128_012325_zpslavooxa2.jpg.html?filters[user]=143082917&filters[recent]=1&sort=1&o=1

Try wiggling all connections to make sure they are all properly seated in the breadboard and arduino-headers.

Also make sure that you actually connected all the wires up again properly to the right places. And then double check.

Are the wires soldered in place, or pushed into place? Instead of sending people off to PhotoBucket, how about posting the photos here as part of the question? You can embed photos into questions.

These 16x2 LCDs are fairly sensitive about their power requirements.
As a first step, I would check the VCC and GND wires are well connected, and closely connected on the breadboard near the LCD.
If your LCD display shows rubbish characters, check the 4 data lines are connected in the correct order.
Also it looks like the contrast is at minimum (or LED backlight at maximum).  It could just be the photo, but best check both of these.

it turns out that my board have dead pin(pin5),but even with new microcontroller ,only half of the display works as shown here http://s1072.photobucket.com/user/Tonny_Cassidy/media/Mobile%20Uploads/20160128_012325_zpslavooxa2.jpg.html?filters[user]=143082917&filters[recent]=1&sort=1&o=1

Is it a simple bad solder joint?  Maybe just re-melting the solder will re-connect it.

So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.
My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".
From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.
Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.
Cheers!

reconnected all the wires like 5 times,still the same,even tried changing the pin number that was connected to lcd on arduino,i find that my pin5 was dead so i change it to pin7,only half of the lcd working correctly ,and i have tried changing the contrast


text:
2.8" tft screen arduino all pins used
I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: 2.8" TFT Touchscreen Prohibits Access to Unused Pins)
However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)
However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?
Thanks!

You're confusing the idea of using all the pins to that of plugging into all the pins.
Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.
The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.
You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


text:
Accessing a C++ static variable from gcc inline asm
For some reason I want to mix a bit of assembly with C++ (not C).
To allow the code to be compilable using the standard Arduino IDE, I don't want to use direct assembly source.
I don't want to use a wrapper C file either.
My problem is as follows:
I have a class with a single instance (implementing some kind of driver) that looks like this:
class cDriver {
public:
    char ISR_param;
    // ...
};

cDriver Driver;

If I want to access the ISR_param of this single instance from within an ISR, I can do something like:
ISR (TIMER2_COMPA_Vect) {
    do_something_with (Driver.ISR_param);
}

This works like a charm: the address of Driver.ISR_param beign a constant, the compiler simply generates an lds r24, &Driver.ISR_param instruction to load the proper byte as a parameter for do_something_with.
Now when I try to replicate the same mechanism with inline assembler, things get a lot more complicated.
The address of Driver.ISR_param is only known to the C++ compiler as an mangled label, and I can't find a way to pass it to the inline assembler to generate the equivalent lds r24, <&Driver.ISR_param>.
trying to remane the variable
The renaming of variables for assembly like so:
char global_var asm("my_var");

and an attempt to use it like so:
asm ("lds r24, my_var\n");

will compile, but produce a linker error (my_var is undefined).
Looking at the object symbol table, the only label for global_var is a C++-like mangled name.
However hard I tried this renaming trick, I could not bring the compiler to generate a my_var label.
trying to use asm constraints
A constraint like
asm (lds r24, %0\n" : : "I"(&global_var));

will simply not compile. I scoured the possible parameter types and could not find a way to let the assembler know about this bloody address.
a terribly awkward workaround
The only way I found to make the compiler generate this dreaded lds r24,... instruction is to perform an actual function call.
So you can do something like:
__attribute__((always_inline)) give_me_my_friggin_variable(char data)
{
    asm volatile ("cmp  %0,%0\n"::"r"(data));
}

ISR (TIMER2_COMPA_Vect, ISR_NAKED) {

    <some prologue to save SREG and all needed registers>

    //...

    give_me_my_friggin_variable(Driver.ISR_param);

    // continue assembly code with r24 properly initialized
}

That will generate:
    lds r24, <the proper address> // added by the compiler...
    cmp r24,r24                   // ...because of the register constraint here

Well, that sort of works, but at the cost of generating a totally useless instruction.
so my question is...
Is there a simpler way to let the assembler know about addresses of C++ static variables?

Try this:
asm volatile("lds r24, %0" : : "i" (&Driver.ISR_param));

The "i" constraint means you provide an integer constant. It can be
any integer, unlike the uppercase "I" constraint which is limited to
6-bit positive integers.
Addendum:
The constraints supported by gcc are listed in the gcc documentation,
section Constraints for asm Operands:

The "i" constraint is listed in the subsection “Simple Constraints”
and is described as:

An immediate integer operand (one with constant value) is allowed.
  This includes symbolic constants whose values will be known only at
  assembly time or later.

The "I" constraint is in the subsection “Machine Constraints” and,
for the AVR architecture, is defined as

Constant greater than -1, less than 64.

Dang... And thanks :). This "i" type was not listed in the online manuals I found. For completeness, could you add a link to an up to date documentation? Btw. I wonder why an example of such an obvious use of the inline assembler is so hard to come by.

@kuroineko: The "i" constraint is indeed missing from the avr-libc's Inline Assembler Cookbook. I added a link to the gcc documentation that lists it.

Thanks a lot. That sort of cooking is pretty confidential I guess :).

The "i" constraint does not mean "integer". "i" specifies an immediate operand, which is the union of "n" (integral operand known at compile-time) and "s" symbolic operand known at link time. For example, addresses of variables in static storage are known at link time, thus "i" will work for them.

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


text:
Take the program from the arduino board
How to remove the program from arduino board which is already there in it.?And I need that program in my arduino IDE how to take it please help me?

You remove an existing sketch by uploading a new sketch.

That's a somewhat advanced question. And you shouldn't be "stealing" code for no reason. But you can have a look at this: https://ucexperiment.wordpress.com/2015/01/04/dump-and-disassemble-avr-%C2%B5c-flash-memory/

You can retrieve the program currently in your Arduino with the
avrdude tool. This tool comes with the Arduino installation. The way
to call it is somewhat OS-dependent. On Ubuntu, for an Arduino Uno, I
type:
avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:r:prog.hex:i

This creates the file prog.hex with your program in Intel
HEX format. You can save this
file if you want to re-install it on the Arduino later. You can also
turn this file into an assembly listing with avr-objdump:
avr-objdump -m avr -Dz prog.hex > prog.lst

You may be able to make some sense of this listing if

you are well versed in AVR assembly language
you have lots of spare time

As others have said, you cannot expect to get the original C++ source
back.

You can't. The program in the Arduino IDE is compiled to machine code (bits and bytes basically) and that's what is uploaded to the Arduino.

It's a bit like baking a cake. Or brewing cider. Once you have baked your cake can you get the eggs, flour and sugar back again? Can you make apples from cider? No. And it's the same with compiling. Once you have compiled your source code you can't turn it back into source code again.


text:
How to change input pin of FreqCounter Arduino Uno/Dumilanove library?
The following link to the library defines arduino pin 5 for input pin for signal.
https://www.pjrc.com/teensy/td_libs_FreqCount.html
But the problem is I'm using an 16x2 LCD display with the arduino pin 5. The display needs pin 5 to work. So the question can solved in two ways,to both of which I don't know the answer.
1. Change LCD pin number to other pin. (Tried it was a failure. I've probably done it wrong)
2. Change the input pin for the freqcount library.
Any idea how to get past this bottleneck?

I've used this to try changing pins. LiquidCrystal lcd(12, 11, 4,3 , 2, 1); in place of LiquidCrystal lcd(12, 11, 5,4 , 3, 2); This fails for some reason. Nothing appears on the screen.

The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.
It can't be changed.  You have no choice in that.
You will have to move the LCD to another pin instead.

any idea how to do that?

Like you tried before, but don't use pins 0 or 1 - they are shared with Serial and sometimes that gets in the way - especially if you're also using Serial for communication with a PC at the same time.