text:
How to improve date-time control from RTC?
I want to run cameras at a remote site from external batteries as long as possible. I need power-miser Arduino to switch battery power on/off at set intervals (e.g. 5 min) during daytime only. I am a beginner with Arduino and electronics.
Have set up 'breadboard' arduino with mosfet module for switching the power supply and RTC module, both from Freetronics (http://www.freetronics.com.au/collections/modules/products/real-time-clock-rtc-module#.V-i-S8knuPs). Following their recommendation I'm using RTC library here: http://rweather.github.io/arduinolibs/index.html
I need to refine the crude hour-based script below. Weatherley library returns separate objects e.g date.day, time.hour etc. Is there a simple way to convert to date-time object? Then calculate sunrise and sunset times based on latitude?
  #include <JeeLib.h> //  power saving library
  ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Setup jeelip watchdog
  #include <SoftI2C.h> // rweather lib for RTC module
  #include <DS3232RTC.h> //rweather lib for RTC module
  SoftI2C i2c(A4, A5); // assign pins to SDA and SCL
  DS3232RTC rtc(i2c);
  RTCTime time;
  int gatePin = 12;   //  mosfet Gate connected to digital pin
  int startHour = 6; // want to replace with sunrise time
  int endHour = 19; // want to replace with sunset time

void setup()
{
 pinMode(gatePin, OUTPUT);   //  output pin for mosfet module
}

void loop()
{ // main loop starts here
  rtc.readTime(&time);  //get current time
  if (time.hour >= startHour && time.hour < endHour) // check daytime
  {   // if condition begins here
      while(time.hour < endHour ) // daytime operating period

      {   //  while loop (day) begins here
      digitalWrite(gatePin, HIGH);   // turn on gate for power supply
      Serial.flush(); //needed before sleepy
      Sleepy::loseSomeTime(30000); // low power wait
      digitalWrite(gatePin, LOW);    // turn off gate for power supply
      Serial.flush(); // needed before sleepy
      for (int i=0; i <= 3; i++){
        Sleepy::loseSomeTime(65000); // low power wait
        } // end for loop
      rtc.readTime(&time);
      } // end while loop (day)
      } //  if condition (daytime) ends here
else
  { // else condition (night time) starts here
    while (time.hour >= endHour || time.hour < startHour )
    { // while loop (night) begins here
    for (int i=0; i <= 59; i++){
    Serial.flush(); // needed before sleepy
    Sleepy::loseSomeTime(65000); // low power wait
    } // end for loop
    rtc.readTime(&time);
    } // while loop (night) ends here
// need to refine timing else hour-long wait periods can run past the end of night period
  } // else condition (night) ends here
} //  main loop ends here

I will be very grateful for advice, many thanks in advance!
EDIT: Part of my original question could be answered - see below about time-date format without using RTC. Issues with RTC appear harder than I expected. I think they will need a new question later.

I'd suggest using a light sensor. That way you can safe power if it is e.g.heavily clouded in the evening and therefor dark earlier.

Light sensor not suitable in this situation. The cameras will be used for scientific project (monitor bird activity at their nests). Therefore need to record images atset time intervals for each day from sunrise to sunset. Also I need to learn about date-time programming in Arduino for further development from this basic script.

There is a potential solution in a helpful answer to my question about understanding compiler error text.

Clarification - my comment above does not refer to complete solution to this question. Answer to q about understanding compiler error has a good explanation and solution for TestRTC compiler error - see below in this question.

I didn't mean to suggest removing the RTC. merely to suggest using a light sensor to detect sinrise and sunset. That way you don't have to enter latitude and longitude. Also data will still be collected if the time is wrong somehow (accidental reset of the RTC e.g.). So

Is there a simple way to convert to date-time object?

Not with this library. But you can find other
libraries supporting the DS3232 which work with the Arduino
Time library[]. This time library provides both the date and time in a
single object, either:

a time_t, which is just the number of seconds elapsed since a
standard “epoch”
a tmElements_t struct, which has the date and time broken into
separate elements (year, month, day, hour...).

Then calculate sunrise and sunset times based on latitude?

There are quite a few algorithms describes on the Web for that. The more
accurate ones are also the more complex.

#include <SoftI2C.h>

Doesn't your Arduino have a hardware I2C port? That would be more
efficient than software emulation.

Serial.flush(); //needed before sleepy

It's only needed if you are actually using the serial port.
Edit: I saw on your other question that you have been bitten by
an incompatibility between the Arduino Time library and the file
time.h from avr-libc. Now I just noticed that avr-libc includes the
functions sun_rise() and sun_set() that you may find
handy. Not sure they will play well with the Arduino time libraries
though. One possible incompatibility is the fact that they use different
epochs for defining time_t (year 1970 v.s. 2000).

Many thanks and sorry I don't fully understand. Using SoftI2C.h because I followed example doing it that way. Unsure whether my RTC module and atmega chip will communicate without it. Started with Uno board connected to laptop via USB, using serial window to see what was happening. At that point had to add Serial.flush(). Left it in, being unsure if needed later. Have moved the atmega chip from Uno to a breadboard with no 'peripherals' in order to minimise power usage. How do I determine whether "hardware I2C port" is available or not? Many thanks for patience with total beginner!

@jules: All the peripherals of the Arduino Uno are part of the ATmega328P chip. Thus you still have them on a “barebones” Uno (i.e. the bare ATmega). The I2C port (called TWI by Atmel) is available on pins PC4 = A4 = SDA and PC5 = A5 = SCL. You would use this port through the standard Wire library.

Great to know I have required hardware, thanks. I installed DS3232 and Time libraries you linked above. TestRTC, the example sketch for tecsmith DS3232 library gave compile errors that I cannot understand. Error text too long to add here.  Any advice on how to resolve this?

Checked both two new libraries are present, Wire was already installed. Compile TestRTC has exit status 1 'tmElements_t' does not name a type

@jules: TestRTC has #include <Time.h> on line 46. Did it find that header? Don't you have typedef struct {...} tmElements_t, TimeElements, *tmElementsPtr_t; in it?

Looked at files on my laptop, see installed Stoffregen Time library (link in your answer above) has time.h in the Time-master folder. Where do I look for  typedef struct {...} etc please?

There was an underlying issue with same-name components in different libraries. Very helpful explanation and advice in another question resolved the compile errors. Now I can now try to use the two recommended libraries for date-time.

I hope I am allowed to summarise progress. Edgar Bonet's answer above pointed me in the right direction regarding date-time format and I want to 'accept' that answer, although it did not resolve my difficulties with RTC. I need to ask a new question about RTC later.
Using the Time library Edgar Bonet recommended, I managed to set and change date-time format, and calculate duration between date-time instances. I hope my example below could perhaps be useful for other beginners. If anyone has suggestions to improve this example, please add them.
    #include <TimeLib.h> // https://github.com/PaulStoffregen/Time
    time_t tstart;

    void setup()  {
    Serial.begin(9600);
    // assume no RTC available therefore set date-time in this sketch
    // when serial monitor opens, date-time will be set as follows
    setTime(8,30,0,17,10,2016); // (hr,min,sec,day,mnth,yr);
    tstart = now();
    Serial.print("Started at: ");
    digitalClockDisplay();
    Serial.println();
    }

    void loop(){
    Serial.println("Waiting...");
    delay(20000 + random(500, 5000) );
    Serial.println();
    time_t tnow = now();
    Serial.print("Now it is: ");
    digitalClockDisplay();
    time_t duration = tnow - tstart;
    Serial.print("Duration since start: ");
    showDuration(duration);
    Serial.println();
    Serial.println();
    }

    // function to print current date-time
    // modified from example in TimeLib
    void digitalClockDisplay(){
      Serial.print("Date: ");
      Serial.print(day());
      Serial.print("-");
      Serial.print(month());
      Serial.print("-");
      Serial.print(year());
      Serial.print("  Time: ");
      Serial.print(hour());
      printDigits(minute());
      printDigits(second());
      Serial.println();
    }
    // utility function from TimeLib
    // to print leading zeros
    void printDigits(int digits){
      Serial.print(":");
      if(digits < 10)
        Serial.print('0');
      Serial.print(digits);
    }

    // function from example TimeRTCLog
    void showDuration(time_t duration){
    // prints the duration in days, hours, minutes and seconds
      if(duration >= SECS_PER_DAY){
         Serial.print(duration / SECS_PER_DAY);
         Serial.print(" day(s) ");
         duration = duration % SECS_PER_DAY;
      }
      if(duration >= SECS_PER_HOUR){
         Serial.print(duration / SECS_PER_HOUR);
         Serial.print(" hour(s) ");
         duration = duration % SECS_PER_HOUR;
      }
      if(duration >= SECS_PER_MIN){
         Serial.print(duration / SECS_PER_MIN);
         Serial.print(" minute(s) ");
         duration = duration % SECS_PER_MIN;
      }
      Serial.print(duration);
      Serial.print(" second(s) ");
    }


text:
How do I turn off a 12V 3A RGB LED strip?
I'm trying to understand how to control an RGB LED strip, I set up all the TIP120 (because I could get my hands on an n-channel mosfet), if I power everything in this way I can change colours and everything:

but now I'm facing a dilemma now, whats the correct way to manage to switch my power strip ON/OFF based on an input from a pir sensor? I mean, how can I handle 12V 3A (requested by my led strip), how do I correctly wire my Arduino up in order to make it switch the LED strip ON/OFF?

That's pretty simple: when you turn off all the colours you are actually turning off the entire strip with very minimum leakage current in each of the three FETs.

Oh...really? Is that so simple? Do I need to use some king of Voltage regulator? Is it safe for my Arduino to receive a 12V in(yes) at 3A(I don't know)? The schema provided so will be ok? I don't even need to put 12V into my Arduino..right?

@FabioEnne With the schematic you have provided the 12V doesn't go anywhere near the Arduino.

@Majenko I know...I was just wondering if with this schematic will I be able to switch the LED strip off

@FabioEnne The FETs (or TIP-120s if you must) are just switches. Just like a light switch. Only for dimming you switch the light switch on and off really really fast.

@Majenko so you mean that I just need to give to the Red, Blue and Green pin a zero value or just set them to LOW?

That is correct. 0 is off. All three channels at 0 the entire strip is off.

@Majenko so in this way I should need any sort of voltage regulator right?

@FabioEnne You only need a voltage regulator when you want to change a voltage from a higher one to a lower one for the purposes of powering a device.

source: Stack Exchange

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

sort: votes


text:
Difference between Wire.setClock() method and TWBR method for changing I2C Frequency
I want to change the I2C frequency of my Arduino Mega 2560. I did find two methods. One method is to change the TWBR variable after Wire.begin(). The other one is to use Wire.setClock() after Wire.begin().
Whats the difference between the 2 methods? which one is better? Can I set any I2C frequency I want?

Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.
There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.
Cheers!

They are both one and the same. One is easier to remember though (I'll let you work out which).
Wire.setClock(frequency) just (ultimately) does:
TWBR = ((F_CPU / frequency) - 16) / 2;

You can set any frequency that ends up with that formula generating an integer between 0 and 255.

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


text:
How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan
I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums.  I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects.  I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc.  However, I'd like to see the underlying code.  For example, I use the code "digitalWrite" to turn off/on LEDs.  I'd like to see the code for this.  I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it.  I was hoping there was a right-click->"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app.   I don't see a folder with .c and .h files as suggested in this post:  Arduino IDE, Underlying Code and Libraries  Maybe I'm missing them?
Also, is it possible to set a breakpoint?
Again, sorry if these are "obvious" questions.  And I did look at the Arduino site without any success.
Thanks,
Dave

The simplest way is to look at the source on Github:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.

Thanks Majenko.  Can you suggest (1) a way to pull all relevant files, and (2) how to search for a specific method.  For example, how would one know which file to find "digitalWrite" in?  The link you gives seems to list files in date order in which they have been last modified. Presumably, it would be better to just pull an entire directory structure with all files that went into making Arduino Studio version 1.7.10  Thanks

use git. 2) use grep. Both from the command line. And no, they are listed alphabetically (case sensitive).

Or alternative to 1), click the root of the repo, then download the zip.

Yes, they need a right-click->"Go To Definition"
Assuming the first appearance of a variable is the definition (variable declaration), use the following easily learnt "hack"..
Double click variable, then ^F, Esc, ^Home, ^G
..(where ^ = Ctrl).

what? In Arduino IDE?

Yes Juraj. It is in reply to his I was hoping there was a right-click->"Go To Definition", but I don't see it. (where OP states which IDE). On re-reading the question, he wants to see the library code, not really the definition at all, but for others googling here simply wanting to see variable definitions (which is how I found this), I think my advice is as good as it gets (without getting a better IDE). IMHO, the other answer, "The simplest way is to look at the source on Github" is not a great answer for beginners.

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


text:
My computer dose not recognise my Arduino Uno
I had never used Arduino before. When I tried to interface my new Arduino Uno board to my computer, the computer failed to recognize the board.
Why isn't the board interfaced successfully? How should I troubleshoot that problem?

Did you install the drivers? Is it a genuine Arduino? Are you using a fully wired USB cable?

Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.

Also if you are on a Windows PC be careful because FTDI drivers have been known to kill these boards.  I've also encountered something with Windows 10 when the updated driver causes the CH340 to quit responding.  If you have access to a machine running Ubuntu these drivers come preloaded and work out of the box.


text:
Ramping a stepper motor
I at the moment trying smoothly move a stepper motor. The problem with the stepper motor, is that it makes a high pitch noise while it moves, or sometime a crackling noise from the motor.
So i tried ramping up the frequency of the step signal, which seemed to help a bit but not perfect. Then I tried micro stepping rather than  full stepping, which also helped a bit but still, the noise is very clear.
The motor I am using is a PK244-01A
And the driver it is connected to is this one
I am not at all sure if the ramping I do is either too steep, or completely  incorrect, but here is the code that controls the motor.
void stepper_motor::step_pwm()
{

    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(dir_pin,HIGH);
    //LOW  - Move towards the sensor
    //HIGH -  Move away from the sensor

    delay(0.005);
    int increment = 0;
    int step_count = 0;
    while(step_count <= max_step)
    {
      digitalWrite(step_pin,LOW);
      delayMicroseconds(2000);
      digitalWrite(step_pin,HIGH);
      delayMicroseconds(2000-increment);
      step_count++;

      if(step_count >= 1)
      {
        increment++;
        step_count = 0;
      }
    }

}

Anything I could do to make the noise of the motor less significant?

If you want to figure out if the issue is with your ramping or your operation, decide if the problems are evident only during speedup or slowdown, or if they are also evident while the motor is running at the target speed.

Well... The issue occurs during the ramping up, from the start and up... as you can see in my code, i don't end at a certain point, i just start at a frequency and increases it for each step it moves.   It makes the sound at all time.. I am not sure what i should change? The rate? the start frequency? or something completly different?

Your ramp isn't linear. Your step period is determined by the increment variable, yet how often you increment the increment variable depends on the step period. Shorter steps lead to more frequent increments. I'd use a hardware timer of the ATmega to generate the step signal, an interrupt of said timer to increment the step count on each step, and have the speed control logic running in parallel as the main task, at a fixed frequency. An easier option would be to have a library do all that for you, e.g. accelStepper.

When it comes to noise, that's what steppers excel at producing. You won't be able to eliminate it, but you can take measures to reduce it: Drive the coils with a sinusoidal current waveform (which is exactly what microstepping does), reduce the motor current, reduce the acceleration of the motors and mount the motors with a vibration damping material. The "crackling" is what happens with uneven timing due to bugs in your code.

I had a similar issue once before. It actually matters a lot to properly ramp up your stepper motor. Especially under load if you ramp up too steep you can loose steps.
Since you are already using the arduino environment I suggest you could use the AccelStepper library.
I lets you set the acceleration and max. speed parameters nicely and uses a properly calculated ramp.

How would i know the proper acceleration?.. is it stated in the datasheet? is there a general rule or something like that?

Look for maximum 'slewing rate'

You need to be using the adjusted delay for both the high and the low part of the signal.  Also, what happens when the variable "increment" is larger than 2000?  Nothing good, for certain.  I'd personally like to be able to delay by a negative number and undo some things that are already done, but I don't think yoz can turn back time using an Arduino.

you are right about the above 2000. I don't run the code for that long, usually just check it for 3 seconds an turn it off. so i guess i would have reached a negative delay.   How do i figure out these adjusted delays?

The "adjusted delay" is just the value you've already calculated:  2000-increment

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


text:
Make a stepper motor move
I am at the moment trying to make a bipolar stepper motor move.
I am interfacing it through a control board, which takes the input Step, Dir, En, and 5V.
I am providing those input signal via an Arduino, but can't get the damn thing to move. all it does it move a step forward and backwards, like it being stuck or and tries to wiggle out of something.. What could the reason be..
Here is the Code:
#include "stepper_motor.h"
int max_step = 200;
stepper_motor::stepper_motor()
{
  pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin,OUTPUT);
  pinMode(dir_pin,OUTPUT);
  pinMode(en_pin,OUTPUT);

  alive_bool = true;
  position_bool = false;
  step_count = 0;
}

void stepper_motor::step_pwm()
{

  if(position_bool==true)
  {
    //Dir pin low
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = false;
  }
  else
  {
    //Dir pin high
    delay(1000);
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = true;
  }

}

Updated step_pwm():
void stepper_motor::step_pwm()
{
    //Start -  En Low , DIR HIGH, STEP high
    //init configuration!
    digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,LOW); // Previous LOW

    delay(0.005);

    //T1-  En HIGH , DIR HIGH, STEP HIGH
    //Enable high
    //digitalWrite(step_pin, HIGH);
    //digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    //T2-  En HIGH , DIR low, STEP HIGH
    //Direction choosen
    //digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,LOW);
    //digitalWrite(en_pin,HIGH);

    delay(0.005);
    //T2-  En HIGH , DIR low, STEP HIGH
    //STEP  step between low and high with 2.5µs between

    while(1)
    {
      digitalWrite(step_pin,LOW);
      delay(2.5);
      digitalWrite(step_pin,HIGH);
      delay(2.5);
    }

}

The control board i am using is a ST330-v3
The motor i am using is this one
here is a little block diagram of how things are connected.

Your voltage is too low.

Its getting 12 volt, as required by the motor? and plenty of amp.. it is rated 1.2 A but the control board is capable of giving it 3 amp

You have the stepper connected wrong? Post the schematic.

I've posted an image of how things are connected..
I suspect it could have something to do with common ground?

It cannot be the common ground. I am only providing one ground signal... So it should not cause a problem.

"I am only providing one ground signal... So it should not cause a problem." No, that is your problem. You need to tie the Arduino ground to the driver board as well. As it stands, the driver has no way of knowing whether your inputs are high or low. The 5 volt connection does not suffice. In fact, the failure to provide a ground means that all the driver logic is unpowered. Consider this - would you expect your Arduino to work if you only connected its 5V, and not the ground?

So... you suggesting connect the negative terminal of the power with ground terminal of the arduino? Sorry for asking such a stupid question.. I am very much a noob when it comes to electronics.. Not at all my strong suit..

Doing above didn't not help..

Verify continuity in the two motor coils (multimeter). Reconnect and replace the Arduino with a debounced pushbutton driving the step input and tie EN and DIR to active and an arbitrary level respectively. Verify the voltages change across the coils sequentially.

Ok.. I will post an update code.. I made the motor move, but  only by removing the enable signal.  I accidentally pulled it out of the arduino and the system began to move. Then tried to remove the enable pin, and it changed direction.  But i can't codewise change the direction.. I guess this concludes that there isn't any wiring problem but the problem relies in the code..

Maybe your impression of which pin is enable and which is direction is swapped.  Best recheck everything with the most authoritative source documentation.  If the board documentation isn't great, get the IC data sheet and trace the connections to it.

I am using a wemos d1 mini.
The pin_mapping comes from this .h file
https://github.com/esp8266/Arduino/blob/master/variants/d1_mini/pins_arduino.h#L49-L61
If the mapping made above is incorrect, then would it explain alot of things

"am providing those input signal via a arduino" - "I am using a wemos d1 mini" ???

Well... It should not matter since i am using the arduino library.. So there implementation should still be there.

But the d1 mini uses an ESP8266 which has 3.3V GPIO. You are powering the opto-couplers with +5V and the ESP8266 is pulling down from +3.3V to its ground, so the optocouplers are getting 1.7V (5V-3.3V) when the GPIO outputs are high. Since the infrared LED in the optocoupler only needs 1.1V to turn on, there is a chance it will stay turned on enough to prevent the high signal from being transferred. This might explain why you had to disconnect the EN signal (yes, disconnected is same as high on the ST330 - bad design!)

wauw... That sound like something that could make sense..
Anyway can I still could use the board someway, or would I have to use an arduino uno or something like that?

an uno does the same thing..

I am NOT sure  at all what what the solution is.. The ST330 seem like a bad design..?

You must set EN BEFORE you set DIR.  The datasheet says EN must be high for at least 5 microseconds before you set DIR.  You should probably just set EN high when your program starts, then not fool with it until your program ends.
The next thing is that I don't see you incrementing the variable "step" anywhere.  So, if you did get the stepper to turn, it wouldn't stop.

The updated code looks like it ought to work.
You should use DelayMicroseconds instead of Delay(0.005) though.  Delay takes an integer instead of a decimal value, so you won't get what you expect.  Curse the Arduino IDE for not throwing a fit when pass a float for an int.

It looks like anything working properly is purely luck.  The board you are using(NOT an Arduino) uses 3.3V logic levels.  The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.
The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it.  The 8266 might put up with, and might just die on you.
You might be able to drive the ST330 by switching the mode of the pins.
Low would be "set pin to mode output and set low."
A high would be "set mode input."
Input mode leaves the pin floating, which the ST330 will interpret as a high.
Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.
The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

You can use NPN transistors like this to drive the ST330:

simulate this circuit – Schematic created using CircuitLab
Setting the  GPIO from the ESP8266 to high would cause a low on the ST330 input.
Setting the GPIO pin to low would cause a high on the ST330 input.
This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

If you'd like to try a purely software solution, then do this:

To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step_pin,INPUT) then DigitalWrite(step_pin,LOW))
To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step_pin,INPUT)

When the GPIO pin is in input mode, it floats.  It doesn't have a voltage level of its own - it acts like it is disconnected.
If that works, I'd still prefer to use the transistors.

You can avoid all of this using the UNO.  It has 5V logic levels on the outputs.

It this based on the updated code or the prior?

The step variable is missing that is right, and it turned yes it didn't stop.  but the direction cannot be coded. what the mean by EN set before DIR is set.. isn't the case?

The ST330 has opto-couplers that require connection to +5V and signal inputs only ('yin and yang' interface!). To maintain the isolation barrier the Arduino ground and ST330 ground should not be connected together.

@BruceAbbott: I missed that while looking at the timing diagrams.  I'll change that part.

@CarltonBanks:  Based on the original code.  I'll take a look at what you've changed.

I understand the changes.. But is it what you had i mind..
I still have an issue with the thing only running when I use delay() and not delayMicroseconds(). The motor outputs a high pitch noise.

The high partand the low part of the pulse must each be at least 2.5 microseconds long.  The force the motor can generate is proportional to the pulse length.  Shorter is weaker.  If the pulses are too short, the motor can't move.  A quick look around the internet shows typical pulse rates in milliseconds range rather than in microseconds.

The change you made is pretty much what I meant.

Its just stated in the datasheet. But as mentioned the function only works with delay and not delayMicroseconds.

If you use DelayMicroseconds, then you would need a value of 2500 to get 2.5 milliseconds.

Regarding to your update..what do mean by switching of the pins? Could i use a uno instead? or what is the solution here?

And what is the solution you refer to.. I mean is an arduino uno able to provide this output

Are you sure about the input current... VM input current = 16 mA as max..

typical being 10 mA

Thanks for the last one..
I have an uno lying around, and if everything would work fine with the uno.. I would just transfer the code from the ESP to the uno..

Uno  made it work..
Thanks for the help

This is problematic:
 delay(0.005);

The Arduino delay() function takes an unsigned long as an input, which is an integer rather than floating point type.  As a result, the argument you pass to it will be treated as zero.  Depending on how delay() is implemented this will result in either no delay (beyond overhead), or a minimum that may be longer than you intended.
Of course you now seem to only be running this code once, and then going into an unending loop which uses a 2.5 ms delay that will, for the same reason, be more of a 2ms delay.

I am not sure i understand the answer.. I myself have wonderes why it works with the delay() and not delayMicroseconds() it seems a bit of.

You need to take time to understand the difference between integer and floating point types, otherwise any success will be little more than luck.

Ohh.. i understand the difference.. The only reason why i know it works is as you mention yourself. The code overhead. running delay(0) or delay(0.005) takes aprox. 12 µs which would have fulfilled the minimum required timeslot.


text:
Use Arduino Yun Shield as ISP for bootloaded ATMega328-PU
My question is how do I replace the Aarduino Uuno board in this circuit:

...With an Arduino Yun shield? I can setup the hardware - ICSP configuration is easy enough - but how do I go about using the IDE to do this? Cheers

It's highly unlikely you will be able to do it from the IDE. Instead you will have to do it from the Yun's command line (SSH) using avrdude and the linuxgpio driver, or the handy run-avrdude script.
$ sudo run-avrdude bootloader.hex

where bootloader.hex is the bootloader file found somewhere in the IDE that you need to copy over to the Yun with scp.
You may find you need to tweak the fuse settings in the script to get the bootloader to work. I am not familiar with AVR fuses, but IIRC there is one that tells it to run the bootloader instead of the sketch. Just copy the values out of the boards.txt in the IDE and place them into a copy of /usr/bin/run-avrdude in your home directory.

The ATMega came with a bootloader intalled, so is the procedure the same for any other sketch? I've tried migrating the hex file onto a usb host and launching run-avrdude command - I was thrown an error message... Is that the correct-ish procedure though?


text:
How do I use ATTiny pin 5 (RESET) as a digital output?
I am using an Arduino Uno as ISP (Using the standard ArduinoISP sketch) to program an ATTiny13A through the Arduino IDE. (I also have a USBtinyISP 2.0 and a USBASP 2.0, but can't reliably get either to program this chip with any sketch.)
I want to use all six I/O pins on the ATTiny to each control 1 LED. Pins 0 through 4 work fine, but since pin 5 is the RESET pin, it doesn't want to work as an output normally.
I have read from many sources that I can disable the reset pin by changing the fuse bits, and that once I do so I will not be able to program the chip any more. Every source I've seen has given this warning, but has then proceeded to NOT say how to accomplish the 1-time-write.
Assume I've got my sketch exactly 100% as I want it, don't have a high-voltage programmer, and am fine with only being able to program the ATTiny once. How can I program the chip and set the appropriate fuse bits with what I have access to?

Please edit question and list programming-related items in your  “what I have access to” class.  For example, do you have an AVRISP or USBASP or similar ISP programmer?  I assume you don't have an AVR Dragon or STK500 or a high-voltage programmer since you say you don't have a high-voltage programmer. Note, I think  high-voltage programmers can reprogram chips with any fuse settings.

@jwpat7 Done, but I did say I was using an Arduino Uno running the ArduinoISP sketch.

I'm having trouble getting the fuse bits to write; It reads as 0xFF, then writes 0x7F, then reads as 0xFF when it verifies. The output says safemode in several places. Is that preventing the fuse bits from changing?

Found my problem. I needed to set the bit on the other end, that is, change it from 0xFF to 0xFE, rather than to 0x7F. Using http://www.engbedded.com/fusecalc/ helped me figure it out.

RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (-U hfuse:r:-:h), clear bit 0, and then write the value back out (-U hfuse:w:0xXX:m).

Do I program the sketch in Arduino IDE first, then do this? I've never used avrdude directly before, so assume I don't know how to do this.

Yes, since once nRESET is disabled you won't be able to program it without HVSP. Enabling verbose compilation in the IDE should give you the other avrdude options you need to use.


text:
How do I use two PulseIn() functions simultaneously in Arduino?
I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

PulseIn() is an Arduino-specific thing.  Like much of the Arduino software, it's a user-friendly thing, but it's far from optimal.  If you want Arduino-specific help, you might be better asking on the Arduino stack exchange.  On the other hand, if you want help to do this directly with the timers on the Atmel chip, this site is the right place.  In that case, you'll need to edit your question to say which microprocessor your Arduino uses.

As it stands, the question could be migrated to the Arduino stackexchange.

You can't use pulseIn() if you want to use both ultrasonic sensors at the same time.
So either:

don't use pulseIn, and instead do that part yourself using
eg. digitalRead,
use the ultrasonic sensors sequentially, one then the other, or
use pin-change interrupts to sense the signal pulse return.

The easiest approach is to use the ultrasonic sensors sequentially. In that case use the form pulseIn(PIN, value, timeout);, where timeout, in microseconds sets the maximum time to wait for a pulse.
This is practical if you know the realistic range is within a couple of metres. The speed of sound is 343.2 metres per second, or 0.3432 metres per millisecond. So if timeout is set to 3000 microseconds (3 milliseconds), then it will wait for an echo up to (roughly) 0.5 metres away.
Edit:  The distance to the object, measured by timing the delay, is half the total distance travelled because the sound travels to the object, then bounces back to the sensor.
Ie. distance to object = total distance travelled by sound / 2
An alternative is to do what pulseIn does, but for more than one pin.
This is simpler than the real pulseIn code, but illustrates the idea:
int inPin1 = ...;
int inPin2 = ...;

void setup() {
  // ... other stuff, then set up the pins
  pinMode(inPin1, INPUT);
  pinMode(inPin2, INPUT);
}

void loop() {
  // start ultrasound 1
  // start ultrasound 2
  // wait for ultrasound 1 to send pulse
  // wait for ultrasound 1 to send pulse
  long startTime = micros();
  while (digitalRead(inPin1)==LOW && digitalRead(inPin1)==LOW) {
    ; // do nothing
  }

  long stop1st = micros();
  int firstBack = -1;
  while (digitalRead(inPin2)==LOW) { // wait for the other if it was 1 first
    firstBack = inPin1; // remember pin 1 returned first
  }
  while (digitalRead(inPin1)==LOW) { // wait for the other if it was 2 first
    firstBack = inPin2; // remember pin 2 returned first
  }
  long stop2nd = micros();

  // now have the two return times, and the pin which returned first
}

You could read the source of pulseIn() and write better code than this.
The third option, to use external or pin-change interrupts, depends on which Arduino you are using. A normal ATmega328 has a couple of pins, 2 and 3, which have their own 'external' interrupt service routines (ie. each pin has a 'function' which is called when the hardware detects a signal change on a pin). To see how to attach them, see attachInterrupt.
Other pins can also be used with a 'pin change' interrupt, but each interrupt has to figure out which of a port (up to 8 pins) has triggered it, so it isn't as quick and simple.
The idea here is to start the ultrasonic sensors exactly as before, save the time they are started, exactly as before, but let a short interrupt routine capture the time that the returning echo pulse triggers the pin.
There is a little bit of care in making sure the times are captured and the main loop signalled.
You might choose to dedicate a timer to measuring the ultrasounds round trip, if you want higher resolution and lower jitter than the normal 4 microsecond timer. A microsecond is about 0.34mm, so 4 microsecond is about 1.3mm error.

"So if timeout is set to 3000 microseconds (3 milliseconds), then it will wait for an echo up to (roughly) 0.5 metres away."  It should be close to ~1.02 meters away. Am I right?

@Mat_python - sound travels 0.3432m/millisecond, so in 3 milliseconds it will travel about 1 metre. An ultrasound sensor works by bouncing sound, so sound has to travel to the object, and then return. So you are measuring round-trip time, hence the distance to the object is total distance/2.

Thank you. I thought so. I am trying to detect a moving object. i.e, a soccer ball. I am working on building a goal counter. The problem with an ultrasonic sensor is it misses the ball sometimes. I used two ultrasonic sensors to detect a soccer ball, which could be moving really fast, but it detected 8 times out of 10. what could be the problem? Is there any other sensors I can use to detect the soccer ball passing between 0-1.5 meters of distance from the sensor. I also tried PIR sensor, but it does not work well for non-living objects.

@Mat_python - if all you want to make is a soccer ball counter, would detecting something crossing a line do? That could be easy to make. Or do you mean drive around a field counting balls? You'll need to be clear about the problem, and it may be worth writing a new question.

Yes. I want to make a soccer ball counter, and detecting something crossing a line will work. I tried using ultrasonic sensor. But, it misses if the ball is too fast. what are other alternatives? I also wrote new question thread on this here : http://arduino.stackexchange.com/questions/29748

here is how i fixed the problem for my self -5 years later im doing this on my own, running the pulsein code twice within the same loop function WILL NOT WORK, i got around it by adding a second separate part, idk the name if its a function or library...but here is my example code simply creating a distance measuring from 2 different sensors. i hope this help
const int trigPin =6;
const int echoPin =5;
const int trigPin2 = 11;
const int echoPin2 = 10;

long duration2;
long distance2;
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
digitalWrite(trigPin, LOW);// Clears the trigPin
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
Serial.println(distance2);
test();
}

void test()
{
digitalWrite(trigPin2, LOW);// Clears the trigPin
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration2 = pulseIn(echoPin2, HIGH);
distance2= duration2*0.034/2;
}

my code only prints the second sensor distance not both as you can see...not perfect this was a quick sketch i did


text:
Arduino uno - Ethernet Shield enc28j60 hangs after some time
I am using Ethernet Shield enc28j60 for retrieve data from web server, but Ethernet Shield enc28j60 hangs after some time and it only works after restarting power supply (router usb port).
My sketch : https://github.com/shyamjos/Arduino_ServerMon

I have fixed it myself by increasing Ethernet::buffersize, I have also heard that sometimes it is caused due to power issues so providing external 3.3V for enc28j60 may help.

Increasing a buffer size doesn't normally fix a hang that occurs after some time, it just delays it.  It might be worth checking your code sending data to see how long this buffer is going to last.

In my case it is working fine for last 48 hours after adjusting buffer size , before it was getting stuck within few minutes.

Are you sure your ethernet connection works? Try to debug with Serial.println(F("message")) to find out where it hangs.
I used the same Ethernet Shield and EtherCard library, and I had to change
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) {

on line 152 to
if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {

because the ENC28j60 uses a different default CS pin (10 instead of 8).

I am already using CS pin as 10 and it is working fine


text:
Measuring .7 volts on pin 2 and 0.0 on the rest when setting all pins low
Having my Arduino Nano 328P disconnected from any circuitry and setting all pins to pinMode(OUTPUT) and writing LOW to (almost) all the pins, when I connect my multimeter to every output pin and the Arduino ground, I measure 0.7 volts on pin 2 and 0.0 volts on 3 to 19. Here I mean the pin numbers on the edge of the Nano, not the processor pins.
For my project it worked out fine because I needed those 0.0 and not the 0.7, but I'm afraid it suddenly might not be pin 2 that's 0.7 in the future and my circuit would fail.

Why is there this one pin giving 0.7 instead of 0.0 and how can I make sure or argue that it will only be pin 2 that gives 0.7?

EDIT as per request, the full test code is below.
void setup() {
  for (int i=1;i<20;i++){
  pinMode(i, OUTPUT);
  }
}

void loop() {
  for (int i=1;i<20;i++){
    digitalWrite(i, HIGH);
  }
    delay(3000);
    for (int i=1;i<20;i++){
    digitalWrite(i, LOW);
    }
    delay(3000);
}

What voltage is your 328P running at? At 5V, 0.7V is still perfectly within specification (0.9V max V[OL]).

@Majenko I'm not sure exactly, I'm running it via a phone wall adapter which outputs 5V/1A which I think should be enough, how could I check if it really is? If you think it's the voltage provided, I'll check when powering it via my laptop.

No, you misunderstand. There are two options for running the boards like the Micro / Nano, etc - 5V or 3.3V. The V[OL] specification changes depending on supply voltage, and that is fixed by the board, not the PSU. It sounds like you have a 5V version anyway, so the output is within specification.

@Majenko Ah yeah I knew about the 5V-3.3V difference, but I have the 5V one. I confirmed that V[OH] is 4.7V for every pin. But where did you find the maximum V[OL] is 0.9? I had googled before asking the question to find that value but didn't find results. Do I understand correctly that that means you just know the voltage output is between 0 and 0.9 and you cannot guess the exact value?

The value is in the datasheet, page 313, table 30-1.

@Majenko I'm a bit confused which datasheet, I mean there is no Nano datasheet right? I looked into the ATMega 328P sheet but can't find it there.

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

@Majenko Oh that's curious, I was looking at a 328P datasheet but a different one. Anyway, I see what you mean, the 0.0 or 0.7 is just some kind of stable noise. Thanks for pointing that out, I'll think of a way to adapt my circuit to that.

You were probably looking at the summary sheet.

@Majenko To summarize 660 pages into 444 seems weird to me, haha. http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf

@Majenko I think you should post your comments as one answer.

Can you post your code please? I personally like to see code, not a description of it.

@NickGammon Of course, I'll do that immediately next time. I included it now.

writing LOW to all the pins - all pins except pin D0, eh? Your question is a bit non-specific. Do you mean pin D2 on the edge of an Arduino Uno? Or pin 2 on the actual Atmega328P chip? Pin 2 on the chip itself is D0 in the IDE, which you have not written LOW to.

@NickGammon Ah I didn't know those number differed, I meant pin 2 on the edge of the Nano (not Uno) all the time, that I didnt include pin 0 shouldnt matter as I skipped pin 0 and 1 alltogether. I'll edit the question.

For future reference, thanks to Majenko: these values fall within the expected voltage output range of 0-0.9V, and you cannot be certain it will stay this way. See the datasheet page 313.


text:
What sensor would work for soccer ball detection efficiently using Arduino?
I want to make a soccer goal counter using Arduino and some sensors. I built using an ultrasonic sensor, but it does not detect if the ball is moving too fast. Are there any other sensors I can use to detect soccer ball?

That may not be easy.  You need to detect the ball not the goaltender, so may need to be somewhat back from the line (though this would miss technical but unlikely goals like one that slowly rolls barely over the line and stops).  You need to detect a ball potentially in flight so need a grid or area not a single line.  And you can't false trigger on wind so an instrumented net may be tricky.

I also felt it could be a challenging problem. I tried using ultrasonic sensors, but it does not detect if the ball is too fast. I am not sure modulated IR would work or not considering sunny and windy condition.

This is potentially well beyond the capabilities of a simple MCU like an Arduino UNO. So I think it is very important to clearly define the problem you're trying to solve.
Currently, at top national and international level, video cameras are used to detect a ball crossing the goal line. AFAICT, a lot of the complexity comes from having the goal keeper and several players on the line too. It is important that a player kicking across the goal line is not mistaken for the ball crossing the line. Also, it is important that players bodies can't block the view; a simplistic approach might not be able to see the ball if its kicked between a players legs.
This amounts to (probably) millions of sensors (one per pixel) being monitored at 100+ Hz.
So, I'll assume you are not trying to solve such a complex problem. Instead I'll assume you only want to detect a ball crossing the back edge of the goal line, without considering interference by players.
First, let's gather some numbers to describe the core problem.
A soccer ball/football is at least 68cm in circumference, so it is
68/pi = 21.6cm in diameter, or 0.216m, which is 0.108cm radius.
Then there is the goal. FIFA rules say "The distance between the posts is 7.32 m (8 yds) and the distance from the lower edge of the crossbar to the ground is 2.44 m (8 ft)"
So a question is, must the system detect the ball crossing the goal line at any place?
A goal is about 34 times wider than the diameter of the ball, and
just over 11 times taller. So, if the sensors were some form of 'light beam' being broken, the 'simplest' system would need more than 11 sensors looking horizontally from one goal post to the other.
How fast might the ball travel through the posts? This says Cristiano Ronaldo was measured kicking a ball at 130km/hr. That's 36.1m/s.
So the ball is going to take 0.216/36.1 = 0.006 seconds, 6 milliseconds to pass the back edge of the goal line, ie. front edge to back edge will pass a point in 6 milliseconds. This means the sensors must all be scanned, at worst, every 6 milliseconds.
For a sound based system there are more issues.
How much of the ball is 'seen', ie. if only a small fraction of the ball is 'in view' might the returned sound be too small to register with an off-the-shelf ultrasound sensor? For example, if the angle of the reflected sound is too big, ie. from the front or back of the ball, will enough reflected sound return to the sensor to be detected?
Does the ball reflect sound well? It is a membrane at quite a low excess pressure, very different from a solid wall, so I would guess it isn't a perfect sound reflector. I haven't found anything quantifying this, but it seems reasonable to assume off-the-shelf ultrasound sensors might miss the ball under some circumstances.
So it would seem reasonable to assume that two or more sensor readings of the ball would give a significantly more reliable reading than a single sensor reading.
This equates to sampling at least every 3milliseconds. That is a maximum distance of 0.34m * 3/2millisecons (round trip) = 0.5m (approximately).
This might seem to be too much of a restriction. However, the ultrasound sensor only sends a pulse of a few cycles, so it isn't able to detect the ball for the whole of that 3 milliseconds. I haven't found a spec for the off the shelf sensors, but a plausible assumption might be each pulse lasts for about 10 cycles of 40kHz, so the pulse lasts for 0.25 milliseconds. That is the time the ball might travel, about, 1cm. So the angle of reflection would not change much. Hence trying to detect the ball more frequently will increase the quality of at least one signal.
This may explain why the ball is not always detected using ultrasound sensors in your existing approach.
Using any type of sensors to detect the ball, there is a bit of a trade-off. The ball is round, and so if the sensors are almost at the balls diameter apart, then the sensors are going to need to be scanned more quickly to detect a small part of the ball (think of this as a much smaller ball). On the other hand, if the sensors are much closer so at least one gets a longer 'view' of the ball, then one is going to see something closer to the diameter of the ball, hence see it for longer, and so they could be scanned more slowly.
This adds up to a similar outcome. Increase the number of sensors so one sees the ball for a reasonable length of time, or scan the sensors much faster to have a reasonable chance of a measurement.
A 'classic' way to detect something crossing a plane (a door way or in this case the goal mouth) is with a set of laser beams (think Mission Impossible, Entrapment, etc.).
So, consider eye-safe visible-light laser pointers? They must be eye safe, which AFAIK largely implies visible light lasers as eye-safe partly depends on the eyes 'blink response'.
At the width of a goal, the laser will have spread to several cm, but should still be straightforward to detect. With some care, it might be feasible to use mirrors to reflect a beam back towards the goal post carrying the laser, halving the number of lasers, and keeping all of the wiring on one side. I don't know how many reflections might work, but it is worth experimenting as every reflection reduces the number of lasers and sensors.
One advantage of an optical approach vs sound is the goal mouth could easily be monitored at a much higher rate than the ball could possibly pass.
To discriminate between sunlight, stadium or street lights, or other sources of light, the lasers would be modulated. 5kHz is a common figure, this is well away from mains frequency. The signal should be 'low' when the laser is off, and 'high' when the laser is on. If that isn't the case, then their is signal interference, and it isn't going to work.
With a little bit of electronics at the sensors, the signals may be purely digital, so there would be no reliance on the Arduino's slow ADC; the sensors could be scanned with digital GPIO pins, with, say, all 11 sensors being scanned at 10kHz.
You may be able to achieve a similar effect using narrow angle, high-power LEDs, lenses and tubes. A reasonable lens system should be able to focus LEDs over 7.32m of the goal mouth. However, I think eye-safe laser pointers would work with simpler optics, and the mechanics and optical systems are often harder to make robust than the electronics.
Summary:
A 'raster' of eye-safe, visible-light lasers, at approximately 10cm apart, maybe with mirrors to significantly reduce the number of lasers and sensors, directed horizontally across the goal mouth, could detect a ball passing.
However, it would be confused by players across the goal line.

You should be able to detect an object as large as a soccer ball with an array of modulated IR transmitters and receivers.  However you might want to avoid using IR receivers like the ones found in entertainment equipment.  These have an AGC stage which will, when blocked, turn up the gain until the receiver finds a weak indirect signal.  Instead, try searching using "Long-Range Presence and Proximity Sensors".

Great. Thanks. But, will it work in sunlight too? IR modulated Tx-Rx should be co-planar in windy condition too, which is difficult. Proximity sensors work fine for slow balls. If the ball is moving very fast, they miss sometimes. I like the idea of using modulated IR, but I am only worried about the distance. It should work fine if I place them 3 meters apart! Will it? How many modulated IR will work to create the grid?

Most of the sensors I have see are modulated at 38KHz.  That should take care of some of the sunlight interference.   But most of the applications, admittedly, are indoors.  You might need to take care and place the receiver in a black tube to shield it from sunlight.  Also, you probably need to mount the transmitters and detectors on the ridged part of the soccer goal frame.  The municipal goals I have seen are super sturdy welded metal frames.  Lenses might help but will be a bother to assemble.  You might investigate COTS parts such as Garage Door Beam Interrupters.


text:
Code for activating a led after 2 minutes and will blink after 30 seconds interval
Can anyone help me to build a code which will activate a LED after 2 minutes when the power supply is cut off and blink that LED after a time interval of 30 seconds.
I want to import the code on Arduino-Uno.
I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the Arduino will blink the LED after 2 minutes and will keep blinking at 30 seconds interval

How do you expect to do anything if the power has been removed?!

I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the  Arduino will blink the led after 2 minutes and will keep blinking at 30 seconds interval.

Can any one help me with a code that can switch ON a pump for 5secs and then switch on a blower for 3secs and the operation continues like that.

Use a commonly available USB power pack re-charging from mains and powering the Arduino.  Use a light source directly powered by main and optically couple that to an Arduino.  There are plenty of examples on the web where an Arduino is used to detect light.  Once triggered, write some additional code to blink the led.  Since you are not doing anything other than timing, you can use the delay Arduino library to time events.

I have edited it now can you please help me

I think it would be easier to use a rechargeable USB power pack.  They are very common.  I added a let-me-google-that-for-you link so you can see what I am talking about.  I still think optically isolating mains power from the Arduino is a good idea.  So I am sticking with what the answer says.  Read the pages the links take you to.  Then ask your questions.  It is always best if you make an attempt at programming then ask your questions posting your code with your question.

The Blink example will tell you how to blink an LED, you just need to change the times in the delay statements.
You want to detect the failure of a power supply.  You Arduino has a backup battery (cell) to power it when the power fails.  Correct?
There are voltage sensor kits available that can monitor mains voltage, just search for "Arduino Voltage sensor".  However there is a risk to you working with main voltages.  So using optical isolation (as ST2000 says) is probably safer for you.  There may be some optical isolator IC that can manage mains and 5V, they are usually white in colour.

I have a code edited by me
int pinButton = 8; //the pin where we connect the button
int LED = 2; //the pin we connect the LED

void setup() {
 pinMode(pinButton, INPUT); //set the button pin as INPUT
 pinMode(LED, OUTPUT); //set the LED pin as OUTPUT
}

void loop() {
 start:delay(120000);
 check:int stateButton = digitalRead(pinButton); //read the state of the button
 if(stateButton == 0) { //if not pressed

   digitalWrite(LED, HIGH);
   delay(250);
   digitalWrite(LED, LOW);
   delay(30000);
   goto check;
 }
 else { //if  pressed
  digitalWrite(LED, LOW);
  goto start;
 }
}

The goto start is completely redundant, because at the end of loop it goes back to the start of it anyway. Please avoid using goto - your other one can be replaced by a while loop

DISCLAIMER: This is just a suggestion. No hate for this anwser please.
You could use a capacitor. A super capacitor (high capacity) with a proper joule theft circuit for your project could power the arduino for propably another 5min even if main power is cut off, plus you do not need any extra power source once the main source is cut off. It can be useful if you need to change the battery or move it to an other location but you do not want the module to be turned off.
const int led = 13;    //led pin
const int sensor = A0; //connect this your power supply, use a voltage divider if necessary
                       //this will act like a volt meter

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(sensor, INPUT);
}

void loop()
{
  int V = analogRead(sensor);
  V = map(V,0,1023,0,5); // the 5 is replaced with the ammount of voltage that you supply the arduino

  if(V < 1) // when the power is below a point or simply disconnected, the capacitor
            //will kick in by itself because the Arduino will draw its power
    {
    delay(120000)
    while(V < 1)
    {
      V = analogRead(sensor);
      V = map(V,0,1023,0,5);

      digitalWrite(led, HIGH);
      delay(500);
      digitalWrite(led, LOW);
      delay(29500);
    }
  }
}


text:
What to do after prototyping?
I want to make a USB gamepad, and I've heard that an Arduino would be great for this kind of project. But before I start to work on it, I want to make sure I understand some things. Here are my basic diagrams of what the project will look like during prototyping and after prototyping:

Do the diagrams look right? Am I understanding the process correctly? For me to properly build a final circuit, I would have to emulate all the necessary (the most important one being the USB) circuitry that an Arduino has around it's microprocessor.
And my final question is, how would I load my program on to the microprocessor (with and without the "Arduino-like" USB circuitry)?

Like this? https://www.conrad.nl/nl/kaart-esplora-atmega32u4-arduinodvar-a000095-95443.html?WT.mc_id=gshop&insert=8J&gclid=Cj0KEQjw4MK_BRC1n6KTtezikbIBEiQA872hYUi_UaiOFnbFnOmFQU15ifGYq0lB8XuAMTdqGbIiQFAaAjXb8P8HAQ&tid=211354628_36784275548_pla-219283182788_pla-095443&WT.srch=1

Yes, something like that. But I want to learn the process of making one, so I would like to build my own circuit. I want to know how to go from prototyping, to a full-blown circuit/PCB.

Please embed your images into your question, rather than posting links. Links can go down.

I think I found a possible answer to my second question here. So for loading my program, I would first have to "install" a boot-loader on the microprocessor. And then I would be able to load the program via [?]. Is this correct?

So you've got no experience and want to do one project that involves designing a PCB and programming a joystick? You should break it up in smaller projects or iterations.

You'll have to make your own board, with the required buttons, but you should really check out blogs/tutorials on creating such a thing.

Yes, your thinking is pretty much correct.
You can place an ATMega32U4 chip and the associated required circuitry within your own circuit design. The required circuitry is actually quite simple - a crystal for the CPU clock, a few capacitors (load capacitors for the crystal, and decoupling), two 22Ω termination resistors for the USB bus, and a 10KΩ pullup on the reset pin. That's about it (besides power of course).
As far as programming goes, you can either install a bootloader (butterfly - like the Leonardo etc) that works through the USB, or you can directly program the chip using ICSP. It's best to provide an ICSP header anyway (it's the SPI pins plus RESET basically), and if you have done that (which you'd need really to be able to get a bootloader on there) then you may as will skip the bootloader entirely and just program direct through the ICSP header. Of course, you'll need some kind of programmer (an Arduino can do the job at a pinch, but it's worth spending the $10 to get a cheap AVR programmer from eBay).

The ATmega32U4 (not 'RC) comes with DFU and crystal fuses preprogrammed, so all you need to make it USB-programmable is the external crystal and load capacitors.

@IgnacioVazquez-Abrams What do you mean by "'RC"?

An ordering code that starts with ATmega32U4RC, which indicates blank flash and fuses programmed for internal RC oscillator operation.


text:
Which sensor to detect light?
I have a kit of 37 sensors as described here:

http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

if the light is detected - flash LED
if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...
Can you please advise me which sensor to get?

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

Number 23 in the list says photoresistor, corresponding to module KY-018 in your kit, which is what you called photocell (a photocell is another type of sensor to my knowledge).
As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.
A photoresistor usually looks like:

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a voltage divider: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.
The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: 5V, ANALOG and GND.

simulate this circuit – Schematic created using CircuitLab

Your last paragraph is complete nonsense.

Why do you say so @Majenko? If he connects the LDR directly to 5V and GND and he moves the rig under a 50W lamp he will create a short, with the LDR resistance quickly becoming negligible under strong light.

If he connects the LDR directly to 5V and GND how on earth is he going to get any readings at all from it?

@Majenko where on earth did I mention getting a reading? And anyway, does my last paragraph make sense now? Also, will he be able to get a reading out of its rig by using a voltage divider? Not to mention how many times I've seen beginners getting surprised they were constantly getting a 1023 or 0 out of their analog readings just because they had connected their pin to the 5V or GND lines. Anyway, I'm going to update that paragraph, but relax!

No, that is not much better at all. It has absolutely nothing whatsoever to do with sinking or sourcing too much current and everything to do with the fact that the Arduino ADC reads a voltage and a voltage divider is the easiest way to get a variable voltage from a variable resistance.

I edited my answer once again to remove the absolutely nothing whatsoever infringing part you seem to care so much, but I believe it is still a valid general advice. Nonetheless you have no reason to be that aggressive to me, I am trying to help people here and my advice was not like stick your fatty fingers in the mains socket, so cool down and be more kind to your fellow contributors! I appreciate the comments and corrections, that doesn't justify an aggressive wording though.

Let us continue this discussion in chat.

You are after the "KY-018 Photo resistor module". It is number #23 "Photoresistor" on the instructables.com webpage.

The module contains a Light Dependant Resistor (LDR).
More information on the module can be found at https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module.

Use a photoresistor aka photocell. They are variable resistors that change there values depending on the intensity of the light source.
It is sensor KY-018 : KY-018 Photo resistor module.
Here is a helpful code:
const int sensor = A0; //declare photocell pin
const int led = 13;

void setup()
{
  pinMode(sensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
  int val = analogRead(sensor);
  if(val > 512)
  {
    digitalWrite(led, HIGH);
    delay(500);
    digitalWrite(led, LOW);
    delay(500);
  }
}

No,  I would suggest you not bother with photocell, phototransisters nor light-dependent resistors.
Better answer is the 1750 light-detection and measurement module.

It connects by I2C and reads out a numeric value corresponding to the amount of light (Lux) it senses.
Very easy to set up.
I use one to measure the light of the sky so I can compare it to the output of my solar cells.
Here is a cool light meter project (complete with hookup instructions and code) that uses one to sense light and displays the results on a 7-segment display:
BUILDING A SIMPLE DIGITAL LIGHT METER USING ARDUINO AND BH1750FVI SENSOR

The OP already owns a light-detecting sensor. Unless you are selling those, it makes very little sense to advice the OP to buy yet another module.


text:
How to read differential TTL signal from encoder using Arduino?
I am using Arduino UNO/ MEGA to read the incremental encoder pulses (Baumer encoder EIL580). Currently, I am using it in single-ended mode (reading A,B and Z outputs) as I am not sure how to read the differential signal in Arduino (A, Ainv, B, Binv, Z, Zinv) as it would improve the reliability of the data. Is there any addon shield or circuitry to interface this signal with Arduino?

Differential signals are used to reduce or cancel common noise from long cables.  Usually Arduino projects are small and everything is in close proximity.  Is the encoder far away from the Arduino.  That is, are the cables long?

It looks to me like something similar to RS485 (I have a page about that here).
You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.
I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.

I've had succes with the MAX485 chips, I believe they are pin compatible with the (one of the most common) LTC chips. The max485 may be cheaper (especially from ebay, but they may be counterfeit and not work as well).


text:
Arduino nano & pro micro SPI simple communication
I'm working with Arduino boards with AVR C coding to perform simple SPI communication from master for simple blink application on slave side.
They don't work, the TX function on the master side doesn't seem to work, after serial monitor debugging is discovered the function never get over the while loop! Why is that?
Here are the codes I worked on last night:
Master:
/* nano board is the Master and transmit
  data to slave to blink LEDs */

void SPI_Init(void);
void SPI_TX(uint8_t data);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  void SPI_Init();
  delay(100);
  Serial.println("SPI intialization is complete");
}

void loop() {
  uint8_t d = 0x20;
  SPI_TX(d);
  Serial.println("just sent the 1st byte");
  _delay_ms(400);
  d = 01;
  SPI_TX(d);
  Serial.println("just sent the 2nd byte");
  _delay_ms(400);
}

void SPI_Init(void)
{
  DDRB = (1 << DDB3) | (1 << DDB1); // DDB2 MOSI, DDB1 SCK
  SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
}

void SPI_TX(uint8_t data)
{
  SPDR = data;
  while (!(SPSR & (1 << SPIF)));
}

-------------------------------------------------------------- -

Slave:
-------------------------------------------------------------- -

/* pro micro as slave and receives data then push them on
  PORTD and PORTB to blink LEDs */

void SPI_Init_S(void);
void SPI_RX(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);//start Serial
  Serial.println("Setting Up");
  SPI_Init_S();
  delay(100);
  Serial.println("SPI intialization is complete");
  DDRD = (1 << DDD5); // TX LED as output
  DDRB = (1 << DDB0); // RX LED as output
}

void loop() {
  // put your main code here, to run repeatedly:
  SPI_RX();
  PORTD = SPDR;   // blink the TX LED on pro micro board
  _delay_ms(500);
  SPI_RX();
  PORTB = SPDR;   // blink the RX LED on pro micro board
  _delay_ms(500);
}

void SPI_Init_S(void)
{
  SPCR = (1 << SPE) | (1 << SPR0);
}

void SPI_RX(void)
{
  return SPDR;
}

 void setup() {
// put your setup code here, to run once:
 Serial.begin(9600);//start Serial
 Serial.println("Setting Up");
 void SPI_Init(void);   // <---------------- this is wrong!
 delay(100);
 Serial.println("SPI intialization is complete");
 }

That isn't how you call a function.
It should read:
SPI_Init ();

You should use SS (Select Slave) pin for synchronization on both devices. If you have master with default settings for SS pin (= INPUT), any interferences will switch your master into the slave mode and SPI_TX will wait forever for clock pulses from outside.
Without using SS on both sides it can be also shifted (unsynchronized).
Edit: And yes, also not calling SPI_Init causes pretty similar deadlock.

Where is the SS pin on the pro micro board? I couldn't find it! So I switched the configuration to Uno master and Nano slave and it's still not working! Why? the master TX function is not passing and not executing the next commands!


text:
An audio jack modem
I'm looking at controlling Arduino by reading audio commands sent from a raspberry pi (through javascript). I've found the SoftModem code and wonder how it works. It claims that "It uses the phone's audio jack and Bell 202 modem-like FSK encoding", but I wonder how it's done. Doesn't it need to sample the ADC and apply some filtering like FFT? I can't seem to find where all this is done.
Any thought appreciated.

Which Arduino do you have?

@NickGammon It's a Nano. I could a Uno though.

Judging by the blog from the post you linked, he is calculating the frequency received by using the analog comparator built into the processor. That lets you detect a signal rising, falling or both, compared to a reference voltage.
With some interrupts and some timing, you could work out what frequency signal you were receiving, and thus deduce if you got a 0 or 1 bit incoming.
I have a page about the analog comparator if that helps.

Do you think there should be an opamp in that circuit? Shouldn't there be some kind of "signal conditioning" going on there?

Possibly. It depends on the voltage levels. The analog comparator is a high impedance input. Maybe a capacitor and/or diode should clamp the input to 0 to 5V.


text:
combination of arduino uno and mega?
I am new to Arduino. Can I combine Arduino UNO and MEGA in 1 project? Arduino UNO is for audio output and MEGA for LCD display. If I am wrong, is there any ideas how do combine both LCD display and audio output in one microcontroller?

When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.
It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.
Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.

I think you can manage to find a display that uses only a few pins, like Adafruit 2.2 TFT which has a 3-pins SPI communication.
Then you have a lot of pins left to connect for example an audio shield.
I think this could be done on a single Arduino, you'll just have to find an Arduino board compatible with both audio and video systems you choose.
I only wonder if the audio playing would be suffering from screen refresh if both communications are in SPI.


text:
What is LCD bias voltage and where do I have to connect it?
I noticed that I have VB0+, VB0-, VB1+ and VB1- pins on my LCD. In the datasheet it says they are for the "LCD Bias Voltage". I have never heard about that. So what is it? Where do I have to connect it?
Here is the datasheet of the LCD: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

You need to look at the interfacing document kindly provided on the same page as that datasheet:

http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf

It shows plainly that you need to connect 2.2µF capacitors between the + and - of each pair of pins.


text:
Fading RGB LED between 10 and 60 cm
What I want to achieve is that between 10 and 60 cm of my HCSR04 sensor the color fades from red to blue on my RGB LED in steps of 1 cm between 10 and 60 cm.
I have tried creating some own functions which calculate how much the analogWrite has to change every cm. Yet have had no succes..
I want to implement this function in the following code:

I hope my question is understandable...

Try using the Arduino map() function...

You should include the code as text rather than an image.
Also, I assume that the ranging works (and prints the distance), is that true?

@paul Indeed, the code above works as it should, I just have to implement the function I described.

analogWrite(Kleur1,distance);
analogWrite(Kleur2,1024-distance);

Theoretically, this is all you need.
You'll color the LED "kleur1" with the analog value of the distance, so it will become brighter when the distance is higher.
And you'll color the LED "kleur2" with the "inverted" analog value of the distance, so it will become less brighter when the distance is higher.
But this kind of depends on what the value is on your maximal distance etc.

Thanks for the answer! I am going to try this out somewhere this week!


text:
Update variable using buttons
I made a part of code to change the temperature limit for alarm system. On warm days user have to change the temperature limit with buttons and OLED display.
The question is: How can the variable templimit keep its last setup value after many restarts(for many reasons)?
This is the code:
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit; // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.print("Update temperature limit if not wait 10 sec time out");
  updatevalue();
  Serial.print("Done");

}

void loop() {
// do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  timenow = millis();
  // this loop is just for 10 sec time out
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) {
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    if (timepassed >= 10000)
    return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }
  templimit = buttonPushCounter; // update templimit value

}

You can save to EEPROM on pressing the 'Enter' button.

I tried to modify the program. this project I use to limit the value of ADC. can this program be used? because I've tried but it does not work. thank you `#include <EEPROM.h> float read_from_eeprom(unsigned int address) {// read float config; for (byte i = 0; i < sizeof(config); i++) { reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i); } return config; } // this constant won't change: const int buttonPin = 8; // up const int buttonPin1 = 7; // down const int buttonPin2 = 6; // enter int tro=A0; int value=0; int out=9; int Switpin=10; int Switch; int buttonPushCounter; // counter f

The microcontroller on the Arduino MEGA boards have 1024 bytes of EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive).
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
I wrote two read/write functions if the value you want to write on EEPROM is negative because temperature has negative values too. Arduino EERROM write word with values between 0-255, also, has a lifetime 100,000 write cycle/ cell.
You can use EEPROM.update(address, value) instead of EEPROM.write(address, value) so the value is written only if differs from the one already saved at the same address.
Save to EEPROM:
void save_to_eeprom(unsigned int address, float config) { // (address, value)

  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }

Read from EEPROM:
float read_from_eeprom(unsigned int address) { //(address)
  float config;
  for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
    reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
  }
  return config;
}

This is how templimit will keep its last value after restart, the full code is:
#include <EEPROM.h>

  float read_from_eeprom(unsigned int address) {// read
    float config;
    for (byte i = 0; i < sizeof(config); i++) {
      reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
    }
    return config;
  }

// this constant won't change:
const int  buttonPin = 8;    // up
const int  buttonPin1 = 3;    // down
const int  buttonPin2 = 2;    // enter

// Variables will change:
int buttonPushCounter;   // counter for the number of button presses
int buttonState;;  // up
int buttonState1;;  // down
int buttonState2;;  // enter
int templimit = read_from_eeprom(20); // temperature limit for alarm

void setup() {
  Serial.begin(9600);
  Serial.println("Update temperature limit if not wait 10 sec for time out");
  updatevalue();
  Serial.println("Done");
  Serial.println(templimit); // temperature limit for alarm

}

void loop() {
  // do nothing
}

int updatevalue(void) {
  int timenow;
  int timepassed;
  int counter = 10;

  timenow = millis();
  while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) { // this loop is just for 10 sec time out
    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down
    timepassed = (millis() - timenow);
    delay(1000);
    Serial.println(counter--);
    if (timepassed >= 10000)
      return 0;
  }
  while (buttonState2 != HIGH) { // do this until enter is pressed

    buttonState2 = digitalRead(buttonPin2); // enter
    buttonState = digitalRead(buttonPin); //up
    buttonState1 = digitalRead(buttonPin1); // down

    if (buttonState == HIGH) { // up
      buttonPushCounter++;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    if (buttonState1 == HIGH) { // down
      buttonPushCounter-- ;
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    delay(700);
  }

  save_to_eeprom(20, buttonPushCounter); // save to address 20 tha value it can be negative

}

void save_to_eeprom(unsigned int address, float config) {// write value it can be negative

  for (byte i = 0; i < sizeof(config); i++) {
    EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
  }
}

An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex.  Fortunately there is an Arduino EEPROM library already written for you.  Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library.  The read is self explanatory.  But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write.  In this way we save the EEPROM a little bit of ware and tare.  As EEPROMs usually have a finite number of write cycles until they start failing.  Which usually is in the tens of thousands.

Atmega328p has 1024 bytes of EEPROM.


text:
Using two pins to sum maximum available current
I have a theoretical question about using digital pins of arduino. The specification of Arduino Uno (or any other I guess) says, that maximum current from digital pin is 40mA. If I would need more than 40mA and less than 80mA, can I use two pins to supply enough power to the sensor or would it burn the pins in the end?
Thanks

You could also hook the sensor up to the 5V rail of the Arduino?

I know, as I have written, it is only a theoretical question. I was more interested in arduino internals than real usage of this...

40mA is the absolute maximum current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.
Theoretically, yes, that should be possible. However in practice doing such things is problematic.  You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.
It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.

You also have to make sure that the maximum current draw for the port in use is not violated, as those have their own separate limits.

@IgnacioVazquez-Abrams Yep. And don't forget the maximum current on a power or ground pin...


text:
Self made microphone burns Arduino
I'm very new to electrical engineering and I'm trying to read microphone input with Arduino Nano. I've made a separate microphone module (based on this example) and plugged it into Arduino like this:

Unfortunately it was the last time my Arduino was working. It's no longer displayed as a connection, and acts "randomly", so I think my microphone toasts controller for some reason. Here are some more pictures and a scheme of my mic module, could someone explain what am I doing wrong?

simulate this circuit – Schematic created using CircuitLab
R1 - CR1/4W 10 (brown,black,black,gold)
R2 - CR1/4W 2KO (red,black,red,gold)
I have no education in electrical engineering, so I'm not sure about the correctness of this schema of units, just pasted what's written on the pack

Your schematic shows R1 as 10k ohms.
Your color codes and description lists it as 10 ohms. 10K would be Brown, Black, Orange.
http://www.allaboutcircuits.com/textbook/reference/chpt-2/resistor-color-codes/
So R1 is the wrong value by a factor of 1000, you may want to fix that ;-)
As for damage to the main board, depending on the microphone used that may have put an excessive strain on the 5V supply pin. Does the power LED still come on at the same brightness as before? If not then the power supply regulator is probably toast. If it does then I'm not sure what the problem is, you shouldn't have broken anything else.


text:
Will 5V 2A current input to the power port kill my Arduino?
I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

No, and whatever the device requires at any one moment in time.

"I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?"
No! It won't. Even tough the reason has been already explained in this other post, I want to add something.
First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly ok, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....
You're missing a key point, here: the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!
In other words:

if you have a device that requires a very little amount of current to properly operate (as an example, this DHT22 sensor, requires as little as 2.5mA, or 0.0025 A) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;
if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);
if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (Which kind of problems you'll encounter is a matter for a different question!)

To be more specific:

a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to not require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" are strongly related.
In your OP you mentioned "mobile charger ... 5V" so I bet that you've an USB power-supply, rated at 2A/5V.
People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed exactly to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;
as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).
As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a barrel-jack, providing a voltage inline with what specified by official documentation:

[...]
  The board can operate on an external supply of 6 to 20 volts. If
  supplied with less than 7V, however, [...] the board may become unstable. If using more than 12V,
  the voltage regulator may overheat and damage the board. The
  recommended range is 7 to 12 volts.
  [...]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;
apply some "magic" to such a current and bring it down _to_a_very_precise_ 5V flow;
provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.
You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a fundamental concept to be kept in mind is that such a reduction will produce "heat"! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!
Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)