text:
Is it possible to connect NRF24L01 to localhost in laptop without wifi router?
I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that?
Thank  you...

It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.
However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.
You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.
(By the way you won't be able to call you laptop localhost)


text:
How to select which resistor is required for my curcuit to reduce voltage
I am trying to connect arduino and esp8266 as like this

I know arduino runs at 5V and RX of ESP8266 should not have voltage more than 3.5V. If you see my diagram there voltage is large than need on RX of ESP8266. I know resistor can help me for this and ohm law.
V = R.I => R = V/I

So I want to understand how should I select what ohm resistor for this cuicuit ? Can anyone explain with some calculation using ohm law ?

A voltage divider made with a 4.7KOhm between your +5V and input and a 10Kohm between your input and ground will result in a 10/14.7 ratio, giving you 3.4V on your input.
If you use a 5.6KOhm to +5V instead, your voltage will be 3.2V which may be a bit easier on the ESP8266.
The trick here is not the specific value of any resistor, but the relationship between two resistors.  You need to find a divider that will change 5 into 3.3 volts, a ratio of 0.66.  Thus, any resistor values where the value of the bottom one in the diagram below divided by the value of both resistors is close to 0.66 will work.  My suggestion would work equally well if you chose 1K Ohm and 470 Ohm.

Note that a voltage divider should only be used for signals and not for powering the ESP.

Well, yes this is my question how to decide what ohm is best for my circuit ? how did you decide 10Kohm will give 3.4 V ?

For a voltage divider, the trick is to find the right ratio between the two resistors.  In your case, the 5V potential to ground is split between the two resistors, let's call the one between 5V and your input R1, and the one between your input and ground R2.  The current reaching your input has passed through R1, so the potential between your input and ground is determined by the resistance of R2 divided by the sum of R1 and R2.  The Wikipedia page explains it better than what I can: https://en.wikipedia.org/wiki/Voltage_divider

To follow on from my other reply (ran out of space), you need to find a combination of resistor values that gives you R2/(R1+R2) similar to the ratio of your desired voltage (3.3V) and your original voltage (5V)  3.3/5 is 0.66.
any combination of resistors that give this ratio will give you 3.3V, given 5V in.

Well. "A voltage divider made with a 4.7KOhm between your +5V and input" - Do you mean "input" as RX of ESP8266 ?

Alright "ratio of your desired voltage (3.3V) and your original voltage (5V) 3.3/5 is 0.66." what .66 ? Do I need .66Kohm resitor ?

Yes that would be it.  (RX)
As for the resistor value, no, 0.66 is the ratio of the value of one resistor and both resistors.  Have a look at the Wikipedia page I linked to, it may be clearer then.

Let us continue this discussion in chat.

A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law.  If you have resistance R and current I the voltage dropped is R×I.
So if the current changes the voltage changes - and if the voltage changes the current changes.
So what do we do? Well, we have one known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?
So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
It doesn't create too high an output impedance, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

simulate this circuit – Schematic created using CircuitLab
When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).
Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look like this:

simulate this circuit
Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to each one to find the voltage drop across it.
So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V.  That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.
If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.
But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

simulate this circuit
The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).
So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.
But as I say you may not have one. So you pick resistor values that you do have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a roughly 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).
Now - we get onto that mysterious phrase I mentioned earlier: Output Impedance. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.
The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors.
Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.
Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.
This output impedance, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).
For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.
You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a low pass filter which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

simulate this circuit
I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.
Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.
By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).
The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:
Vout = R2 ÷ (R1 + R2) × Vin
I can never remember it, though, and usually use an online voltage divider calculator.

Bravo.  If only I was able to explain as clearly I would have been happy as can be.

@ErikHB The trick is to read the question on your phone in bed when you wake up, then get up (a while later), have bacon and eggs, followed by a big mug of strong black coffee, and then write an answer ;)

@Majenko Awesome!! Thanks a lot :) +1

You made my day @Majenko :) Too much useful I went to have cofee and read it while have it :) I will try it once I resolve some issues which I am facing right now.

This is the best anwer I've seen in a long time. With this simple and easily explained example, we went through many of the basic concepts of the electronics. Super helpful.

source: Stack Exchange

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

sort: votes


text:
Arduino Micro vs. Pro Micro
What are the differences between the Arduino Micro and Pro Micro?

Looking at their schematics, the pro micro is a bit smaller (with less available pins) and can come in 5V or 3.3V variants, while the micro is bigger (with some more pins) and only 5V. Apart from this, the micro is the same, and I guess also the bootloader, so from a software point of view they are the same

@LookAlterno The proposed dupe is about Pro Mini and Pro Micro which use a different chip, but this question is about Micro and Pro Micro which use the same chip.

I actually think you are meaning what is the difference between the Arduino Mini and the Arduino Pro Mini, since there is no such board as the Arduino Pro Micro. However there is a board called the Arduino Micro and also the Sparkfun Pro Micro, so this answer will look at all four.
Arduino Mini

Arduino Pro Mini

Arduino Micro

(Sparkfun) Pro Micro

Microcontroller
Arduino Mini: ATmega328
Arduino Pro Mini: ATmega328 (ATmega168 on older boards)
Arduino Micro: ATmega32U4
Pro Micro: ATmega32U4
Memory
All four have 32KB of Flash and 1KB of EEPROM
Both Minis have 2KB of SRAM where as both Micro boards have 2.5KB
Digital I/O
Both Minis have 14 (of which 6 provide PWM output)
The Arduino Micro has 14 also (of which 7 provide PWM output)
Some of the analog pins can also be used as digital I/O
The Pro Micro has 12 (5 PWM pins)
Analog Inputs
Arduino Mini/Pro Mini: 8 (some boards only break out 6 analog inputs)
Arduino Micro: 12 (6 dedicated and 6 from digital I/O pins)
Pro Micro: 9 channels of 10-bit ADC
USB
Arduino Mini/Pro Mini: Requires FTDI cable or Sparkfun breakout board to provide USB power and communication to the board.
Arduino Micro / Pro Micro: Native USB
Clock
All 16 MHz
(Some 3V3 variants run at 8MHz)
Power
Arduino Mini: 7-9 V
Arduino Pro Mini: There are two version of the Pro Mini. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz. VRAW  can accept voltage up to 12VDC.
Arduino Micro: USB or external supply of 6 to 20 volts (recommended range is 7 to 12 volts)
Pro Micro: can accept voltage up to 12VDC
Interrupts
Arduino Pro Mini: The Atmega328 has 2 hardware interrupts available
Arduino Micro / Pro Micro: The ATMega32u4 has 5 hardware interrupts available
credit: Enric Blanco

You're correct there is no board (legitimately) named "Arduino Pro Micro" but the question was not about "Arduino Pro Micro", it was about "Pro Micro" which certainly does exist and is a very nice board. You can see the original here: https://www.sparkfun.com/products/12640. Also, the clones (with blue solder mask) are available from all the usual places and may be advertised as "Arduino Pro Micro" some places, though they do not have permission from Arduino to use their tradmark.

Most of my answer is still relevant. I will update my answer shortly.

Maybe you could compare Arduino Leonardo too since it uses the same chip that Arduino Micro and Sparkfun's Pro Micro.

sa_leinad gave a detailed answer.
a simplified version would be on the chips used: 328 vs. 32u4.
the 32u4 is a superb chip if you are into mixed signal mcu. the ability to put a programmable gain and differential analog input into the adc module at such a low price point is simply superb.
unfortunately, not many boards route out AIN0/AIN1 pins.

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

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


text:
Alternative ways for read Serial Output
its possible to read serial ouput from ICSP or Tx Rx pin instead from USB port? If it's possible how? thanks for reply

You can connect directly to the tx and rx pins to get UART communication

The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.
You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.


text:
Accessing two MPU-9250 DMP
I want to use both IMU at the same time using the Sparkfun Library on a SAMD21 mini breakout board. Can anyone help?
The begin function is :
inv_error_t MPU9250_DMP::begin(void) {
  inv_error_t result;
  struct int_param_s int_param;
  Wire.begin();
  result = mpu_init(&int_param);
  if (result)
    return result;
  mpu_set_bypass(1); // Place all slaves (including compass) on primary bus
  setSensors(INV_XYZ_GYRO | INV_XYZ_ACCEL | INV_XYZ_COMPASS);
  _gSense = getGyroSens();
  _aSense = getAccelSens();
  return result;
}

Have you tried to do it?

yes i tried but when connecting them togher i got the same data for both,actually i'm trying to modify the library to have to imu with two adresse 0x68 and 0x69

I have the same problem now. the function is burried in 3rd lvl of libraries..
Where did you change the code?

Sorry, but I'm not 100% sure of what you are trying to do, I don't understand 'both imu the' in your question.  I think you are trying to use two identical boards at the same time.  (If not tell me so I can edit my answer)
You will need to modify the library so the begin function takes a parameter.
That parameter for MPU9250_DMP::begin then identifies the address of the device, this will need passing to Wire.begin() I think (you'll need to check the Wire.begin() function, I can't).
That should let you create two different instances of the class.
MPU9250_DMP apple;
MPU9250_DMP banana;
apple.begin(0x68);
banana.begin(0x69);

yes i want to use this but in the begin function there is no parameter to pass

Erm, whoops, I missed a line out of the answer.  You need to change the library so begin() takes a parameter.  Sorry for the confusion.

thank you, i'm trying to modify it, now i'll test it and i'll give you the response

i changed the library,the problem is there is no data displayed ,when debugging even when i Print Something in the serial nothing displayed


text:
'[Class name]' does not name a type in C++ Error
    #include <Servo.h>
Servo tilt, pan;

// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output
int x, y;

// Second joystick pin numbers

const int SW_pinn = 4;
const int X_pinn = 3;
const int Y_pinn = 5;

void setup() {
  pinMode(SW_pin, INPUT);
  digitalWrite(SW_pin, HIGH);
  Serial.begin(115200); // setting serial baud rate tp 115200
  tilt.attach(7);
}

void loop() {
  x = X_pin; // defining the variable
  y = Y_pin;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pin));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pin));
  Serial.print("\n\n");
  x = map(analogRead(X_pin), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pin), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);

}

  x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));
  Serial.print("\n");
  Serial.print("Y-axis: ");
  Serial.println(analogRead(Y_pinn));
  Serial.print("\n\n");
  x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec
  y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);
  tilt.write(x); // sets the servo position according to the scaled value
  pan.write(y);
  delay(5);
}

When I compile this code in the Arduino IDE it gives me the error
   arduino-builder/arduino-builder -compile -core-api-version 10611 -build-path /tmp/166416428 -hardware arduino-builder/hardware -hardware arduino-builder/packages/cores -tools arduino-builder/tools -tools arduino-builder/packages/tools -built-in-libraries arduino-builder/latest -libraries /tmp/358566849/pinned -libraries /tmp/358566849/custom -fqbn arduino:avr:uno -build-cache /tmp -verbose=false /tmp/358566849/sketch_may12a

Multiple libraries were found for "Servo.h"

Used: /home/admin/builder/arduino-builder/latest/Servo-1.1.2

Not used: /home/admin/builder/arduino-builder/latest/Printoo_Library-1.0.2

/tmp/358566849/sketch_may12a/sketch_may12a.ino:40:3: error: 'x' does not name a type

x = X_pinn; // defining the variable

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:41:3: error: 'y' does not name a type

y = Y_pinn;

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:42:3: error: 'Serial' does not name a type

Serial.print("X-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:43:3: error: 'Serial' does not name a type

Serial.print(analogRead(X_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:44:3: error: 'Serial' does not name a type

Serial.print("\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:45:3: error: 'Serial' does not name a type

Serial.print("Y-axis: ");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:46:3: error: 'Serial' does not name a type

Serial.println(analogRead(Y_pinn));

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:47:3: error: 'Serial' does not name a type

Serial.print("\n\n");

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:48:3: error: 'x' does not name a type

x = map(analogRead(X_pinn), 0, 1023, 900, 2100); // scale it to use with the servo b/w 900 usec to 2100 usec

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:49:3: error: 'y' does not name a type

y = map(analogRead(Y_pinn), 0, 1023, 900, 2100);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:50:3: error: 'tilt' does not name a type

tilt.write(x); // sets the servo position according to the scaled value

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:51:3: error: 'pan' does not name a type

pan.write(y);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:52:8: error: expected constructor, destructor, or type conversion before '(' token

delay(5);

^

/tmp/358566849/sketch_may12a/sketch_may12a.ino:53:1: error: expected declaration before '}' token

}

^

exit status 1

In short, it saying that x does not name a type in this part of the code
x = X_pinn; // defining the variable
  y = Y_pinn;
  Serial.print("X-axis: ");
  Serial.print(analogRead(X_pinn));

Even though I defined it as a variable at the beginning... Any ideas?

You seem to have a chunk of your code twice.

The error is due to that the code is outside a function block e.g. loop().

If that is really your code then the errors are caused by one error.
As Majenko says lines 58 through to 71 should not be there.  It could be a cut and paste error when you wrote the post, but if it isn't that will cause a problem.
Some tips regarding your style that might help spot these faults in future.

Don't give variables a larger scope than they need.  See x and y, these don't need to be global variables.  You only use them within the loop() and you don't store the value between loops.  In fact lines (42 and 43) aren't needed which means you could define them as const int values on line 50 and 51.
Braces {} - I know people like to write braces in the java style now, because it saves a line of text and all those 2 bytes will eventually add up, but If you had always put braces on line on there own you would have seen the error because line 57 doesn't have an opening brace.
Encapsulate related data - I appreciate its only a little scrap program, but I would have placed the pin information in a class.  This would have let you have better variable names.

const PinInfo joystick1 (2, 0, 1);
const PinInfo joystick2 (4, 3, 5);


text:
How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?
Okay so I did this project from Fritzing first in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.
But here is what I wanted to add, as you can see when you plug the arduino in it will set the time to 00:00 and you can adjust it yourself to the time right now, let's say 12:57. Then you put in the alarm so let's say you want to sleep an hour u put the alarm on 13:57.
Is there a way to automatically get the time from the computer? So you don't have to adjust it yourself everytime and start from 00:00.
Thanks for all the help!

Two ways: 1. Add a network interface to get the time from an internet time server (for example). 2. Write some software for your PC that gets the time and have the Arduino communicate with that through serial.

Alternatively add an RTC so it remembers the time while it's turned off.

But be careful some popular/cheap RTC modules claim to have recharge circuits when they don't and vice versa. (+1 for a good first question, BTW)

There are also atomic clock and GPS options Reading atomic radio clock

There are several ways, and they are covered in the comments above.

The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:
@echo off
set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%
echo %datetimef% > COM5

COM5 is used as a example, your serial port can be another number.
The format in the example is hour.minute:second

And you can have your batch running in a loop every n minutes, and presto! you have your own NTP "serial" server. Brilliant!

And you may also need to set the COM port to correct speed: mode COM5 BAUD=9600 PARITY=n DATA=8


text:
Choosing the right mosfet to switch on-off a neopixel strip
I,m trying to find the right mosfet or transistor to switch on-off a neopixel strip to safe battery power on a Lipo 3.7v using a pro mini 3.3v.
My Animation-Setup and Power Comsumption with 35 Neopixels is :

Sparkel      : 20mA
Knight Rider : 80mA
Pulse        : 600mA

So the maximum  current for the ledstrip is 600mA @ 3.7v
My first thought was to use the 2N 2222 - Transistor NPN TO-18 60V 0,8A 0,5W.
But then i realize the worst case:
What happens if the all 35 Neopixels turn full white caused by a software glitch or a bug in the code. Full white means every neopixles consumes 60mA.
Total power comsumption: 35 X 60mA = 2.1A
Would be destroyed the 2N2222? Because it could handle only 800mA drain current?
How can I avoid this situation. So I read about Mosfet like this one FQP30N06L :
N channel power MOSFET
TO-220 Package
Vds = 30V max
Max current = 62A
Vgs = 2.35V max
Rds_on = as low as 8.7 milliohm - depending on Vgs

What do you think will it work to switch on/off the led if:

the drain current is between 20mA - 600mA - 2.1A
ledstrip Vcc is 3.7v
pro mini out 3.3V at max 40mA

Or is there an other suitable Mosfet for this problem than the FQP30N06L with 62 Ampere for these hardware setup with only 2.1 Ampere Peak @ 3.7v ?

Any reason why you don't want to use this mosfet? It looks to me like it will do the job. (PS make sure you set the data-pin for the neopixels to an input, before turning off the mosfet)

You refer to a 2N2222 handling 800 mA.  However, the 2N2222 datasheet shows 600 mA as its maximum rating for Collector Current – Continuous.  Moreover, from the On Characteristics table, Collector – Emitter Saturation Voltage at 500 mA current could be as high as 1 V.  In typical circuits with high base drive it usually is less, eg about 0.2 V typical with 50 mA base drive, which is more current than a typical AVR output is rated for.  Anyhow, the Neopixels won't operate if your switch drops any significant voltage from the supply.  Using a 2N2222 might work ok, or briefly, or intermittently, or not at all  – depending on the quality of the  2N2222 and the amount of base drive.
You refer to a FQP30N06L handling 62 Amperes.  However, the FQP30N06L datasheet shows 32 A as its rating for Drain Current - Continuous (vs 128 A for Drain Current - Pulsed, which is irrelevant here).
Using a FQP30N06L at its maximum 32 A continuous drain current would require careful heatsinking and perhaps 10 V of VGS drive to achieve low RDS(on), like 27 mΩ. With low VGS of say 3.3 V, RDS(on) might be twice as much.  For example, if it were 45 mΩ, going above 4 or 5 A current would be problematic without careful heatsinking:  4 A → P = 4²·0.045 = 0.72 W, enough to heat up a not-heatsinked unit's junction by about 45℃ or 80℉.
But the FQP30N06L should work ok for your 600 mA typical-case scenario, and also should be ok with the 2 A worst-case as well.


text:
AT command is not responding on serial monitor
I am trying to send AT commands to ESP8266. I re-flashed ESP8266 https://i.stack.imgur.com/z0hoc.jpg I followed this tutorial http://remotexy.com/en/help/esp8266-firmware-update/ and I hope it re-flashed successfully as there was no error.
When I uploaded this program http://www.pastebin.com/frhZY7tD I am trying to run AT command at 9600 baud rate on serial monitor then no response..
Below is how my circuit looks like

#include "SoftwareSerial.h"

SoftwareSerial esp8266(2, 3); // RX, TX

void setup()
{
  Serial.begin(9600); // serial port used for debugging
  esp8266.begin(9600);  // your ESP's baud rate might be different
}

void loop()
{
  if(esp8266.available())  // check if the ESP is sending a message
  {
    while(esp8266.available())
    {
      char c = esp8266.read();  // read the next character.

      Serial.write(c);  // writes data to the serial monitor
    }
  }

  if(Serial.available())
  {
    delay(10);  // wait to let all the input command in the serial buffer
    // read the input command in a string
    String cmd = "";
    while(Serial.available())
    {
      cmd += (char)Serial.read();
    }
    // send to the esp8266
    esp8266.println(cmd);
  }
}

Trying to execute AT command -

On clicking on send button then it shows empty response like below -

When I unplug power wire and plug it back then it prints some garbled message on serial monitor. I checked voltage on RX also, it was around 3.5V that seems also OK.

I am facing this issue after I flashed WiFi firmware to ESP8266 then back AT firmware. It seems that AT firmware was not flashed successfully so I tried to erase everything using below command.

esptool.py --port /dev/ttyUSB0 erase_flash

C:\Users\williams>esptool.py --port COM4 -b 9600 erase_flash
esptool.py v1.3
Connecting...................

A fatal error occurred: Failed to connect to ESP8266: Timed out waiting for pack
et header

Before execute above command, I made changes in my circuit like below :-

Update
I have re-flashed ESP8266 on 115200 baud rate, and uploaded empty program then it started to respond AT commands. I connected as like above only change is TX to TX and RX to RX respectively. Alright!
AT

OK
AT

OK
AT+GMR

AT version:0.50.0.0(Sep 18 2015 20:55:38)
SDK version:1.4.0
compile time:Sep 18 2015 21:46:52
OK

Well, I want to send AT commands from the Arduino serial monitor window to ESP8266 and print ESP8266 response to the command. When I upload above program then it stops to respond, same result as like empty screen this is weird. Isn't ?

Comments on the question are for clarifying the question - not answering it. If you have an answer please post it.

The ESP's AT firmware is probably configured for a higher baud rate, 115200 is typical. SoftwareSerial only works reliably up to 9600 baud. It can transmit "reliably enough" at 115200 for you to blindly send change-baud commands, though the ESP's response will probably be garbled. So you need to either: Reduce the ESP's baud rate or use the Uno's hardware serial port for the ESP, which means giving up the Uno's terminal output and makes it a pain to reconnect your PC each time you need to update the Uno's code. I've described the process of changing the ESP's baud-rate in more detail in
this answer.
Update: I'm not familiar with various AT comand-interpreter revs; my ESPs are all running with the firmware rev came on them; "AT+GMR" (show version info) replies:
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

There is no AT+CIOBAUD command listed in my ESP8266 AT Instruction Set document rev 1.5.3). The only one listed that affects baud rate - and the one I  use - is:
AT+UART_DEF=<baud>,<databits>,<stopbits>,<parity>,<flowcontrol>

, or:
AT+UART_DEF=9600,8,1,0,0

for 9600 baud, 8 bits, 1 stop-bit, no parity, no flow control. You probably know, but just in case, note that you will lose communication immediately after you change the ESP's baud rate, until you then change the local baud rate to match.
Update2:

This is program pastebin.com/dquCNYJj I am not sure what wrong I am
  doing

That code sets SoftwareSerial to 115200 baud; it can not run fast enough to receive data at that speed.
Update 3:
Since you've updated the ESP's firmware unsuccessfully, it's hard or impossible to know what's going on. The output in your screenshot looks rather like the result of a baud mismatch between the ESP and your terminal. You need to get a clean firmware update to the ESP before you can expect it to respond correctly and rely on its output to diagnose any other problems.
Update 4:
I'm not sure if we're talking about the same thing so please forgive me if you already know this; we might be talking about (at least) three different baud-rates:

The rate in use during flashing of new firmware to the ESP;
The default rate that new firmware will start listening at, whenever it is booted;
The actual rate used at any given time between the ESP with its new firmware and the Arduino or some other device external to the ESP.

My own experience is with using the factory-installed AT Interpreter firmware. I have never needed to update it so I don't have personal experience with (1).
(2) and (3) are programmable by the Arduino. When I first use a new ESP (or after you've just re-flashed its AT Interpreter), it will listen at a factory-default baud rate (mine have all defaulted to 115200). There are commands to change the current rate (not saved across a reboot) and/or the default baud (saved for all future sessions).
I almost always change its default rate to 9600 to use it with an Arduino software serial port. This is my initialization for a new device, using an Arduino to talk to the ESP. (Don't transmit my '#...' comments):
# Start talking at the ESP's default rate (115200 on my factory-fresh ones).
AT+RST                         # Reset
AT+UART_DEF=9600,8,1,0,0       # Default baud to 9600,N,8,1,no flow ctl
# Here, change the Arduino's port to match: 9600 in this case.
AT+CWMODE=1                    # Station mode (client)
ATE0                           # Command echo off

From now on, the ESP will wake up listening at 9600 baud, in Station Mode as a client, with no command echo.

I tried to change baud rate, first in my program then build then upload then same baud rate on serial monitor. For example esp8266.begin(115200);  then compile then upload it then 115200 on serial monitor then executed lot of commands AT+CIOBAUD=9600 then no response simply empty everytime. I repeated same process with 9600, 38400, 57600, 74880, 115200 and on sending any command on serial monitor, it does not give any response only empty everytime

can you suggest stable AT firmware for ESP8266 which runs on 9600 baud rate ? I think it is some issue with AT firmware, installed it like C:\Users\williams>esptool.py --port COM5 --baud 57600 write_flash 0 ai-thinker- 0.9.5.2.bin

I executed suggested command but in no response, empty response :( This is my ESP8266 flash settings http://imgur.com/a/scfty

This is program https://pastebin.com/dquCNYJj I am not sure what wrong I am doing

I have updated my question and added more detail. Please see

I have tried multiple times, by keeping same baud rate in ESP and terminal and tried different baud rate but no luck now I am trying to erase ESP8266 firmware using this command esptool.py --port COM4 -b 9600 erase_flash but getting an error `esptool.py v1.3
Connecting...................
A fatal error occurred: Failed to connect to ESP8266: Timed out waiting for pack
et header`

Even though If you see this https://imgur.com/a/J8Ueh I re-flashed ESP at 9600 baud rate

The rate during flashing isn't what's important here - the rates used by the Arduino and the ESP during communication is. They have to be made to match (if they don't already) when you run that firmware start a communication session with the Arduino.

Yes it is same. Some kinda when I made changes in my code like esp8266.begin(9600); then I kept same baud rate on serial monitor also, in this case 9600.

Thanks JRobert. It worked as @Rahul Rastogi suggested. It is working on 115200 baud rate, I simply uploaded empty program. When I am running my program which is in question then it is not working as it is not responding AT commands. I connected my circuit as like in the question. Do you have an idea why it is so ? Isn't this program is to send commands to ESP8266 and read a response of ESP8266 and print it on Serial Monito

Yes, that code is a "terminal program" for an ESP on pins 2 &3. Please update your question with this information: What started working? What doesn't work, i.e. what did you do; what did you expect would happen; what happened instead?

I have updated my question. Could you please see

On your last picture, you should connect the Rx of your Arduino to the Tx of your ESP8266 and vice versa.
If you did that and it doesn't work, try to upload an example sketch in order to determine if it's the code or the connexions that are problematic.
I recommend that you use the WiFiScan example, since that example doesn't require to change the code or to include other libraries othet than the ones from ESP8266Community.

SoftwareSerial esp8266(2, 3); // RX, TX - Doesn't this line manages own ? or Do I need to use RX/TX of Arduino ?

Is it possible that this is a hardware connection issue? According to the datasheet of the ESP8266, it states that the maximum voltage input is 3.6V, but by connecting directly to the Arduino, the signal output by Arduino would be more than 3.6V. (Around 5V output)

Instead of connecting directly, you might want to perform Level shifting first? (5V to 3.3V, vice versa)
(Here's the link to the ESP8266 datasheet: https://nurdspace.nl/images/e/e0/ESP8266_Specifications_English.pdf)

I have 3.6V on RX of ESP8266, I checked with multimeter. I made using some resistors as well I tried with 2xAA batteries but same kinda of issue and provided around 3.6 V to ESP8266 but no luck.

Have you tried sending the AT Commands via a USB-UART adapter instead?

I tried to connect with using putty + USB-UART, it didn't work

First of all, Please check if you are giving proper voltage and current both to ESP8266. I've seen it not working if it doesn't get proper voltage and current.
Secondly, Connect your Rx,Tx of ESP8266 to Rx,Tx of Arduino respectively. Then, try doing one thing, just upload empty sketch having empty setup() and loop() function only.
Then, open serial monitor select your baud rate (mostly either 9600 or 115200) and you are all done! Sending "AT" via serial monitor input field will show you "OK" in serial monitor response window.

It worked as you suggested. It is working on 115200 baud rate. When I am running my program which is in question then it is not working. I connected my circuit as like in the question. Do you have an idea why it is so ? Isn't this program is to send commands to ESP8266 and read a response of ESP8266 and print it on Serial Monitor

I have updated my question, please check it

Ok.. let me understand! You said, It worked as you suggested. So, it worked on 9600 baud rate but not on 115200 baud rate?

It worked on 115200 baud rate, when I run empty program. When I follow steps which is in my question and on same baud rate then it does not work

Try this:
/*
  Software serial multple serial test

 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 2 (connect to TX of other device)
 * TX is digital pin 3 (connect to RX of other device)

 Note:
 Not all pins on the Mega and Mega 2560 support change interrupts,
 so only the following can be used for RX:
 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69

 Not all pins on the Leonardo and Micro support change interrupts,
 so only the following can be used for RX:
 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).

 created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.

 */
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

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

  // Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  // mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

Explain why this code solves the problem.


text:
What if I have burnt my atmega328p?
Actually I am facing a big problem while programming my atmega328p using an arduino uno as ISP.
I followed a video on youtube  "Arduino as ISP" by Notes and Volts. Which look doing the same steps that the majority followed. For the blinking LED sketch the µC worked very well and it did not show any troubles.
So I  decided to carry on , and at this point I needed to upload a new program but this i wanted to upload my program using "avrdude" command line because my code was written with MikroC pro for avr, and here is the command line :
"avrdude -p atmega328p -b 19200 -C arduino -P COM7 -U lfuse:w:0xf7:m -U
 hfuse:w:0xc9:m -U efuse:w:0xff:m -U flash:w:LED.hex:i "
But unfortunately it did not work well and I have got the following error :
avrdude : invalid byte value <ff> specified for immediate mode
 avrdude : write to file 'ff' failed
 avrdude : safemode : Fuses OK
Seeing that error paniced me , that's why I decided to retry the programmation with an arduino sketch and then happened the big issue when the arduino generate an error message about finding a bad microcontroller [error about the device signature] []2.
My last try to find out if I ruined my µC is with switching the µCs; the arduino original and the one that I had to program and unfortunately It was not a good result :
"avrdude : stk500_recv() : programmer is not responding
 avrdude : stk500_getsync() attempt 1 of 10 : not in sync : resp=0x85"
Looking for more than day on the internet and I could not find a valid solution , except the possibility that I really BURNT my µC and I have to buy another one. And this is specifically why I am asking for your help; I need  to know if SO could figure this trouble out.Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .
Thank you
Regards

Without looking into the exact fuses that you set, there are a few that can cause the chip to not take new programming: If you set it to use an external clock crystal, you then need to have that external clock crystal connected to the chip in order to reprogram it. Or if you set the RESET pin as an output, you need a high voltage programmer to reprogram it. Oh, by the way, have you tried to "write bootloader" in the Arduino UI? If you have overwritten the bootloader it probably won't let you reprogram the chip until you've uploaded the bootloader again.

I did connect an external clock crystal of 16Mhz with its two 22pF capacitors. what do you mean by high voltage programmer
I have already burnt the bootloader but in all casses using the µC (that should be programmed) on the ardiono board does not allow me to upload any sketch even for burning the bootloader

Swapping the ICs would seem to mean you'd be trying to use the misprogrammed target chip as an ISP programmer; that of course won't work.

@ChrisStratton no I did not try to use the misprogrammed target as an ISP programmer, I tried only to upload a simple blink sketch to it to discover if it still working or not

You can't use a misprogrammed IC in an Arduino as it won't have a valid bootloader (on the ATmega series, ISP can only erase the whole chip, so any attempt to ISP that does not install a working one means there will be no bootloader)

@ChrisStratton ook I see what you mean now ; I did not know this information before thank you for this.
So I guess that I have to forget about this chip and buy a new one, Right??

With a working ISP setup and external clock you should be able to fix it, unless you set the reset disable fuse in which case you need a high voltage programmer.  But getting a new one may be simplest.

@ChrisStratton Would you please tell me how to fix it using a working ISP and external clock? it is not because I do not want to buy a new one but I am afraid to face the same errors even with a new one

Trying your fuse settings on an
AVR fuse calculator shows that you
have selected an “external full-swing crystal” as the clock source.
Now your ATmega won't work unless you connect it to an external crystal.
Or you could try just sending a square wave into the XTAL1 pin. Then
you can try to reprogram it.

it's already connected to an external crystal. And when I tried to reprogram it, the arduino software generate an error about selecting a bad µC

after two days of searching on internet, I decided to just reburn the bootloader again on my target µC to discover if it's really burned or not.
SO, I guess it was not damaged because I was able to burn the bootloader and upload the blink led  sketch successfully.

The first part of this could be an answer of the "the problem must have been elsewhere" sort; but the second part where you ask a question is not allowed in an answer, and must be removed.

What if I have burnt my atmega328p?

get a new one.

Otherwise, could somebode confirm to me that there is no hope with my µC and it's gone and I have to stop trying to make it works .

based on the information you have provided, no one can tell definitively. you could have changed the fuse settings, or your 2nd chip didn't have the bootloader, or bad connection, ....
a better approach is to get a separate programmer - usbasp for low prices, or dragon (older debugger with hv programming capability) and go from there.

Actually, I am using the arduino as an ISP  programmer because it was decreed by the company I am working for that's why the possibility of using a separate programmer is not allowed .


text:
Uno with LCD acting strangely - power issue?
I've got a Uno (Elegoo UNO R3) running with
- Ethernet shield (Kuman K15),
- 4 relay board (Elegoo 4 Channel DC 5V Relay Module with Optocoupler )
- Matrix Orbital 2041 LCD connected via I2C (11mA typical, 90mA with backlight)
- A series of buttons connected
The Uno is currently running plugged in via USB to my macbook pro.
All of these devices are powered by the 5V pin on the Arduino.
The LCD goes wonky from time to time, and other times will work fine, it starts flashing the backlight, and just behaves oddly, sometimes even rebooting, when buttons are pushed (which activate the relays).
I'm wondering if this a power issue, perhaps the Uno isn't able to supply enough current to run everything.
My reading indicates that the USB port should be able to provide ~400mA, and when on an external supply I should able to draw 900 mA when using an external power adapter.  However even with on an external supply (12v, 2A) I still have these issues.
Any thoughts would be much appreciated.
Thanks

I have found that my UNOs act MUCH better when given a proper power supply instead of trying to run them from USB power.  Have you tried that?

System resets can be caused by power droop and by noise at the Reset pin, among other reasons.  The problems mentioned could be due to power issues, or to electrical noise, or to wiring issues.
The total current draw apparently could approach or exceed the 400 mA mark mentioned in the question.  With all four relays on, and coils drawing 50 mA each, that's 200 mA.  LCD backlight and Arduino current make another 100, after which the ethernet shield could bring the total above 400 mA.
However, having the problems persist even with an external supply in use would suggest the root of the problems isn't power – if, of course, the external supply actually is supplying power directly to some of the peripherals, rather than via the regulator on the Uno.
When relays switch, they typically produce an electrical noise pulse.  If this is the problem, it could be mitigated using ferrite beads, chokes, noise filters, etc.  Using a separate power supply for +5 V to the board also should help.
Wiring issues include ground bounce and ground loops.  If you are using a breadboard, there may be poor ground or power connections.  Check that the grounds of peripheral devices and external supplies are solidly connected by decent wire and/or connected at a common point.

At this point I've tried providing the LCD with its own 5 volt power source, and that has helped satabalize the display.  However with a lot button pushing quickly (and correspondingly switching the relays on/off) I'm still able to get it to reset.
My relay board has a jumper which disconnects the relay power from the input power - pulling that jumper seems to help. thanks for your suggestion on powering the relay board separately, that seems to be the fix.


text:
PWM water pump flow control - in percent
I want to control flow level on 12V water pump with PWM pin, I'm using IRF520N MOSFET for that (and dedicated 12V power supply).
I'm assuming, that setting PWM to full byte should give me about 100% or 12V. But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%? Is it some logharitmic equation?

Unless the datasheet of the pump says something about it, you will have to experiment.

But is the voltage output on MOSFET linear? Like setting PWM to half gives me about 6V?

No. Setting the PWM to 50% is like having a switch ON half of the time (your motor gets nearly 12 V) and OFF (0 V) the other half. It is never at 6 V.

Expanding on dannyf's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).
Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.
Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

Source: ekwb

But how to set proper value on PWM pin so the flow equals to eg. 10%, 25% or 50%?

look at the pump's datasheet; and
experiment.

You'll need to tun the pump at some number of intermediate PWM values and measure its output at each one. The more intermediate values you measure, the more precise your control can be. Then you build a table of flow-rates vs. PWM level in flow-rate order, something like:
struct {
  float flow;  // measured flow rate
  float pwm;   // pwm value that gave that rate
} FlowTable[FLOWTESTS] = {
 // flow  PWM
  {   0.,    0. },
  { 218.,  256. },
  { 480.,  512. },
  { 732.,  768. },
  { 885., 1023. }
}

For a particular flow-rate, step through the table until you find a flow in the table that is >= to the flow you want (if it's ==, just use that PWM and you're done.)
We'll interpolate between the two table values that span the desired flow-rate. The idea is, if your desired flow is say, 17% (0.17) of the way between those two flows, you want a PWM value that's about 17% of the way between the two PWM values.
Let's say you want a flow of 600 (in whatever units your measurements are in - cc/minute, for example. Index 3 in the table (remember, our arrays are 0-based) has the first measured flow greater than 600, the desired flow, so we know the required PWM will be between 512 and 768. To find it, find the desired flow as a fraction of the interval [480, 732]:
frac = (600-480)/(732-480) = 120 / 252 = 0.476,
or letting 'i' be the index of the first table entry whose flow exceeds the desired flow:
frac = (flow_des-FlowTable[i-1].flow) / (FlowTable[i].flow-FlowTable[i-1].flow);
. We need the PWM that is 47.6% of the interval [512, 768]:
pwm_req = 512 + ((768-512) * 0.476)) = 634or
' pwm_req = FlowTable[i-1].pwm + ((FlowTable[i].pwm-FlowTable[i-1].pwm) * frac);`


text:
Current available SRAM?
I've reached the limit on available SRAM memory. I need to "cut down" some variables, but I actually don't know how far I need to go with it.
Is there a way on measuring current available memory on program execution?

Start with moving string literals into the flash memory only (AVR based boards) - Nick Gammon's article about it

If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.
Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:
int freeRAM () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}


text:
Hex String -> Byte Array -> Serial Write
I'm writing code that I discussed in a previous post. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending
This Code is working
void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

From what I understand something along the lines of char ISS = SubS.GetBytes(), but guidance would be appreciated

What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.
First, here are several criticisms of the code shown.
It's likely length(input) won't compile but that input.length() will.
The expression input.substring((2*i),(2*i)+1)) is a String of one character.  If you want two characters, use input.substring((2*i),(2*i)+2)).  And use i += 2 instead of i++ in the for loop.
I don't understand String CMD = CMD+ISS.  I won't say it's invalid, as I don't know without more research.  But it looks like it's declaring variable CMD and using CMD in the initialization of CMD.  [In the example code I give below, I assume CMD should begin as an empty string and be filled up with reconstituted bytes.]
RS485Serial.write(input); // Send byte to Remote Arduino looks mis-commented; presumably it will write out all of the input, not just a byte.
Using a timed delay for holding RS485 Transmit open, as in
delay(10);
 digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
may cause problems.  On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes.  Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.
The next paragraph describes some reasons that Strings may perform badly in this sketch.  For additional discussion of Arduino String objects, see arduino.cc's String page, and see Majenko's The Evils of Arduino Strings page.
Each of the String-object operations in the code creates a new String.  New String objects SubS and CMD are created and destroyed in each pass of the for loop.  The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time.  Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file WString.cpp.  Heap fragmentation can and will occur.  ... In brief:  In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string.  Note, as I don't know the specs for RS485Serial.write() or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.
// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c

void SendCTRL (String input) {
  const char *hin = input.c_str();  // Get character array
  int clen = input.length/2;
  // Next line invalid in C++, ok in C99.  Probably need to
  // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
  char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2) {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  RS485Serial.write(cmd);   // Send string someplace
  delay(clen/4);        // Wait for write to complete? What rate?
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte dehex(char c) { // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
  // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
  // It would make more sense to just use 16 consecutive characters,
  // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
  // could just say `return c & 0xF;`
}

Edit 2:

The first statement, byte dehex(char c); is a function declaration for the dehex() function.  It tells the C/C++ compiler the datatypes that the function accepts and returns.  Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows SendCTRL(), a dehex() caller that needs to know dehex()'s datatypes).  Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.
In this edit I added const before char *hin = input.c_str(); because ATE-ENGE reports  “char *hin =input.c_str() is giving me an invalid conversion error from const char* to char*”.  That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available.  Note, unfortunately the arduino.cc c_str() webpage doesn't specify the return type of c_str().

Edit 3:  Changed for (int i=0; i < clen; i+=2) to for (int i=0; i < 2*clen; i+=2) per notes in another question's answer.
Edit 4:  Changed cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1]) to  cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]) to avoid an operator precedence problem.  The precedence of +, addition, is higher than that of <<, bitwise shift, which in turn is higher than that of |, bitwise OR.  The unparenthesized expression with + adds 4 to dehex(hin[i+1]) and uses the total as a shift count; not at all as desired.  Note, one can of course use parentheses to control the problem, as in the expression (dehex(hin[i])<<4) + dehex(hin[i+1])

This looks like what I want, thanks a lot! I have two questions. One, What does calling byte dehex(char c); at the beginning do?  Two char *hin =input.c_str() is giving me an invalid conversion error from const char* to char* how should I fix that?

@ATE-ENGE, see edit 2

Ok! that all seems to be working now. I seem to not be getting the same input and output though. If you could give me your thoughts on what might be going wrong. As an Example, the input  010307E40001C549 should return me (as ASCII \code) \01\03\07\E4\00\01\C5I or (as U8) [1,3,7,228,0,1,197,73] Instead I'm getting (as ASCII) \100~@\EE or (as U8) [16,48,126,64,238] Updated code is posted above

How do you know the input the Arduino gets is 010307E40001C549, and the output the Arduino sends [1,3,7,228,0,1,197,73]? Or is that what you sent to the Arduino, and received from it somewhere?  Do you have a way for the Arduino to display debugging output?  (All of that is info I'd need as basis for what to do next)

Got it working, the counting was off in two different places. I have working code posted above now. If you see any improvements though, I'd like to know :D


text:
How can I add a LED to this build?
I recreated this project from Fritzing in my circuits.io project then on the arduino itself, it all works fine just how I wanted it.
The concept behind it is:

You plug it in and the time is set to 00:00
You can adjust the time to the time now let's say 22:46
You can put in an alarm to wake up let's say an hour later at 23:46
The piezo beeps in stops, so not continious.

So now my question is, how can I add a led that flickers on the same rhythm as the piezo (when the alarm goes off)? Can someone help me in my circuits.io project?
An update/edit would be great! I'm relatively new to all of this.
Thanks a lot!

That is impressive.  But when it comes to actually building the thing, my opinion is that you would be better off with an actual RTC module like the DS3231.  It not only holds the time even when the power is off, (once you set it with a separate program), but you can also program it to alarm and interrupt the Arduino to trigger the piezo and LED.

Also posted at https://www.reddit.com/r/arduino/comments/6atwt3/how_can_i_add_a_led_to_this_build/

You need to add an LED and series resistor between a currently unused Arduino pin and ground.
In your setup() function, set that pin's i/o mode to OUTPUT.
Where the code turns the tone on, it should also make the LED pin HIGH.
Where the code turns the tone off, it should also make the LED pin LOW.

Why not hang it off the same pin?  If the piezo is software-controlled, problem solved.  I do that for my low-voltage alarms on the solar plant battery monitoring system.  Of course, if the piezo is doing the sound timing internally, that would be a different problem.

That will work but the LED will run at 50% brightness - the tone() function being used in the OP's code generates a 50% duty-cycle square wave at the specified frequency. The sum of the currents drawn by the LED and the Piezo must also be within the pin-driver limits.


text:
my button won't work, why?
I have been trying to get the button to work properly for over a day, but it just won't, can you help me.
The lcd display is for another part of this project, not important at the moment, but I can't take it away.
Also, the piezo plays the sound within else{}.
const int buttonPin = A0;

int buttonState = 0;

void setup() {

  Serial.begin(9600);

  pinMode(buttonPin, INPUT);
}

void loop() {

  if (buttonState == HIGH) {
    tone(8, 400);
  }else{
    tone(8, 300);
    delay(375);
    tone(8, 200);
    delay(375);
    tone(8, 100);
    delay(750);
    tone(8, 400);
    delay(250);
    noTone(8);
    delay(5000);
  }

}

You seem to have forgotten to actually read the button state from the button...

@Majenko you mean this? buttonState = digitalRead(buttonPin);

buttonState = digitalRead(buttonPin);

Yes. Without that how can your program know what the button is doing?

i have that in the code i'm using, I forgot to copy it to this code. @Majenko

I didn't want to add all the code, because half of it are some custom characters i have made. @Majenko

So try your posted code for yourself and see if it does what it should do. Don't try and second guess yourself - the first step of debugging something is to write a program that tests that one thing and then see what the results are.

@Majenko Well, i have a program that sees if my code has any problems, I already tried my posted code for myself and it doesn't do what it should do.

Did you include the digitalRead in the program you tested?

@Majenko Yes i did.

@Majenko do you want me to post all the code i have, including the custom characters for the lcd?

No. With your test code did you hold in the button and wait the 7 or so seconds before it came time to test it again? Or did you just tap it hoping that all those delays would not matter?

@Majenko Okay, so with the 7 second delay it works, is there a way to make it work when i just tap it?

Define "work". At the moment it does exactly what you have programmed it to. If you want it to do something else you will have to program it to do something else. What do you want it to do?

@Majenko Well eventually I want to make a side-scrolling game, where you have to jump over obstacles, the sounds will be on a different place, except that one if you press the button

It sounds like you need to learn the art of writing non-blocking code. The use of delay() should be avoided at all costs.

@Majenko Got it, but can i use those delays for a death sound.

You can only use delay at a time when you are not wanting to do anything else at all. If all you are doing is playing the tune then sure, use delays. But never if you are doing anything else, like reading a button.

@Majenko Okay, thank you for taking the time to help me


text:
Correct use of interrupt vs monitoring switch
Background:
I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.
My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end.
e.g.
switchState = digitalRead(switch);
 if (switchState == HIGH){
 //do my routine which is a function defined outside of the loop
}

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

To not need the large delay at the end you could just store the previous state of the button and only run your code when the current state is HIGH, and the previous state was LOW. That was your code only runs once per button press. I think this is what you meant, right?

No, an interrupt here would be pointless.
You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.
If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.

Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

it depends critically on your definition of "go high", ie. if you are looking for a transition to high, or if you are looking for the switch to be high. edge triggererd vs. level triggered.
As is, your existing (level-triggered) logic can be easily implemented via an interrupt, as will an edge triggered logic.
interrupt-driven code is generally more efficient for slow / infrequent inputs: it doesn't waste the cpu's processing power. But it does add a level a complexity that can be difficult to handle for beginners.
As for me, I think it is (practically) impossible to code without the use of interrupts.


text:
analogRead over a certain time
I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.
thanks in advance

The simplest and crudest method:
int val1 = analogRead(A0);
delay(5);
int val2 = analogRead(A0);

if (val2 > val1) {
    // It went up (for example).
}

You just need to copy the value into another before you overwrite it with analogRead(A0) and then compare those two variables.
int prev_value = 0;
int value = 0;
unsigned long prev_read_time = 0;

void setup() {
    prev_read_time = millis();
    value = analogRead(A0);
}

void loop() {
    if (millis() - prev_read_time > 5) {
        prev_read_time = millis();
        prev_value = value;
        value = analogRead(A0);
        if (prev_value != value) {
            // value changed
        }
    }
}


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:
ATmega328P SPI Slave
I was scrolling through the ATmega328P datasheet when I came across a rather fascinating statement about the way in which the data part of the SPI interface is buffered. I can't seem to understand why the double input buffer is necessary. The following statement can be found on page 161 (Datasheet):

The system is single buffered in the transmit direction and double buffered in the receive direction. This
  means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle
  is completed. When receiving data, however, a received character must be read from the SPI Data
  Register before the next character has been completely shifted in. Otherwise, the first byte is lost.

Can someone please briefly explain to me why the double input buffer is necessary?

You have control over when you place a byte in the TX buffer and control over when you read a byte from the RX buffer. You don't have control over when the master sends data to you, though, so somewhere is needed to store that incoming data until you read it. Since the master can start sending another byte before you have read the last one it's critical that the receiving shift register is separate from the register you read the shifted in data from.  Only when the complete byte has been shifted in does it get copied to the receive buffer, so that another shifting in can begin.
When transmitting you don't need to worry about that since what you write into the TX buffer is what is about to be shifted out. You don't write anything else until it's time to send the next byte, at which point the TX register is empty anyway.

Aaah thanks! I guess this due to the fact that the SPIF flag is only set upon receival of a complete byte? Therefore (if enabled by the SPIE bit in SPCR) the corresponding ISR is only executed after the last bit in that byte.

That is correct.


text:
My button stays on high if I press it once, what did I do wrong?
If I press my button once, I get characters on all of the 32 character places and I get an infinite tone with my piezo. Can someone help me with this?

#include <LiquidCrystal.h>

const int buttonPin = A0;
int buttonState = 0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte run1c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B01110,
  B11100,
  B01110,
  B10010,
};

byte run2c[8] = {
  B00000,
  B01100,
  B01100,
  B00000,
  B11100,
  B01110,
  B11100,
  B10010,
};

byte jumpc[8] = {
  B01100,
  B01100,
  B00000,
  B11110,
  B01101,
  B11111,
  B10000,
  B00000,
};

byte jumpLowerc[8] = {
  B01110,
  B11100,
  B01110,
  B10000,
  B00000,
  B00000,
  B00000,
  B00000,
};

byte groundc[8] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
};

byte rightGroundc[8] = {
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
  B00011,
};

byte leftGroundc[8] = {
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
  B11100,
};

void setup() {
  lcd.createChar(0, run1c);
  lcd.createChar(1, run2c);
  lcd.createChar(2, jumpc);
  lcd.createChar(3, jumpLowerc);
  lcd.createChar(4, groundc);
  lcd.createChar(5, rightGroundc);
  lcd.createChar(6, leftGroundc);
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    tone(8, 400);
    lcd.setCursor(1,0);
    lcd.write(byte(2));
    digitalWrite(buttonState, LOW);
  } else {
    lcd.setCursor(1,1);
    lcd.write(byte(0));
  }
}

digitalWrite(buttonState, LOW);  That line is writing either pin 0 or pin 1 low.   Did you mean to just set buttonState = LOW;

@Delta_G yes, I thought that would fix the problem, so i just have to write: buttonState = LOW;

You shouldn't have to write that at all.  It should set buttonState from the digitalRead at the top of loop right before it compares it.  But either way, trying to digitalWrite with another pins state as the pin number is definitely not right.

@Delta_G And if I move that white wire, connected to A0, to pin number 13, and change that in the code. Will that make a difference?

Sure, it will make it so that the code you have is reading the wrong pin.  If you change the pin number in the code as well then you're in the same boat.  Why don't you try an active LOW arrangement for the button like I described in my answer below.

@Delta_G Okay, and the resistor? I wired that one based off the Genuino starter kit book

@Delta_G the resistor is direcly connected to ground, the blue wire is connected to another resistor, wich is connected to the lcd display

If you use the internal pull-up and wire for active low you don't need any resistor.

Also take note that you would normally use the two diagonal pins on the button.  Two sets are normally close and two sets are normally open.  Or try rotating the button 90 degrees.

@Delta_G unfortunately i cant rotate the button, it just would not fit into the breadboard at that moment. And with wire for active low, do i just have to replace the resistor with a normal wire, or am i not understanding you. (My English isn't that good sometimes)

I gave you good instructions in the answer below.  You tie one side of the button to ground and the other side to the pin.  There will be only two wires connected to the button.  One going to ground and the other to the pin.  So when the button is pressed, it connects the pin to ground.

@Delta_G It still gave me the same problem as before

Show the new wiring and the new code.

Where, in your program, do you ever tell it not to play the tone? You start a 400Hz tone on pin 8 but never stop it.

@Majenko I have added the noTone() in else{}

From what I can tell from your drawing, you have both sides of your button tied to 5V.  The green wire on one side and the blue wire through the resistor on the other.  So yes, the button will always read HIGH.
Instead, remove the resistor, tie one side of the button to the pin and the other side to ground.  Use INPUT_PULLUP in your pinMode cal instead of just INPUT.  Now a pressed button will read LOW and not pressed will read HIGH, so you'll have to reverse your logic in your code.  But the wiring will be much nicer.

the blue wire is connected to the lcd display with a 220 ohm resistor, the 10k ohm resistor is connected to ground

In your code you check the button state and if it is high you set the tone.
In the else section you do nothing with the tone.
Hence, once on, it will always stay on.


text:
Help understanding circuit for button example
I´m working on the button example
.Basically, i don't quite get the use of this connection.

Also, the breadboard i'm using is not quite the ones i see on most tutorials.

is there any 'mapping' i could make between them?
I really appreciate any help you can provide.

The connection in that picture is pointless.  They are just putting power and ground on the top set of rails, but they aren't using it.
Your breadboard has only one rail on either side.  So you'll have to designate one for power and one for ground and you'll need some slightly longer wires for some of the connections.

Thank you! i get it now, i'll see if i can make it work.