text:
NodeMCU - Vin pin as 5V output?
I know that Vin can be used to power the board but have also been reading that it can be used as a 5V output. Is it possible to assign Vin as an output as I would any other GPIO?
If I want to power an LED from GPIO 12, I would assign GPIO:
const int LEDpin_0 = 12; // D6, LED power pin

...and in the setup:
pinMode(LEDpin_0, OUTPUT);

I can then turn on and off the LED based on whether or not GPIO 12 goes HIGH or LOW.
Can I do the same with Vin without resorting to relays or other hardware?

The board will still need power (probably over USB?). You cannot change the power pin in code or switch it on/off. But if the 5V usb is going straight to the vin pin, then you can use it to power external components.

Im wondering if i can have 3Amps power supply source for this. Im not sure what regulator does the board have. cause 3amps is quite high for dev boards

There is confusion about what is and what isn't possible with this board. This is because there are different versions with different power arrangements.
NodeMCU 0.9
In this board the USB's 5V and the 5V pin are directly connected together. The combined result is then fed through a diode before entering the 3.3V voltage regulator.
With this arrangement the 5V pin will provide the exact same voltage that the USB port feeds the board. However it is dangerous to connect that pin to any power source - it may kill (or at the very least disable) the USB port in your computer - when the board is also connected to a computer through the USB port.
NodeMCU 1.0 and 1.1
On this version the USB's power is first fed through the diode and then to the 5V pin and the 3.3V regulator together.  This means that the 5V pin will show about 0.5V below whatever voltage is fed in through USB. This isolates the USB from the 5V pin so it becomes safe to provide power through the 5V pin whilst at the same time having the board plugged in to the computer - at the cost of having a slightly lower output from the 5V pin.

Original answer:
The VIN pin not directly connected to the USB's 5V supply (at least on the LoLin v3 board). this means the pin cannot be used as a 5V supply output.

You cannot control that voltage. It is always on, and always 5V (or whatever your USB port happens to provide - 4.75v - 5.25v).
You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on that board.
Drawing more than 500mA from the VIN pin could cause the USB port of your computer to be shut down.

It is not directly connected. There’s a schottky diode between the USB 5V pin and the 5V pin.

This answer is not completely accurate. At best, it's no longer accurate. I can confirm that the 5V on my V3 board is NOT connected to the supply. When I meter it, I get 1.3V.

The edit made this answer gibberish. That is, either the first paragraph is correct, or the rest is, but they are directly contradicting one another, so they can't both be true.

my 2 cents:
A LoLin NodeMCU V3 when powered via USB in the Vin pin reads 2.2 V (don't know why) but... in the VV pin you can get the 5V coming from the USB; so if you need 5V use that pin.
The board if powered via Vin with 5V, the VV pin reads 2 V (don't know why either)
in any case you can always get 3V in the 3V pin.
Cheeers!

IMPORTANT WARNING: According to other sites around NEVER feed a NodeMCU via Vin (5V) and also connect it to a USB. You can blown your USB port or board.

the question was if you can use 5 V pin as gpio. (I know, it is hard to understand how can someone ask it)

Your comment is the only one I've found so far searching that states the LoLin NodeMCU has power on VV instead of Vin. I'm seeing that as well. Doesn't follow the NodeMCU spec. Although I agree with other comments that this doesn't necessarily relate to this question.

No you cannot use a Vin or VU pin as a GPIO pin which can be controlled by a program. Vin can be used as an input for 5V battery or as a 5V output when NodeMCU is powered by USB (except on NodeMCU v3 by LoLin).
On the V0.1 LoLin board, there are 2 diodes between the VIN and VU pins.  So you cannot get power from one to the other.  These diodes isolate the two possible sources of 5V power from each other while allowing the board to obtain the 5V needed by its its 3.3V power supply from either 5V source.
Other board versions might be different.
To control 5V sensor with help of GPIOs on NodeMCU you will need a logic shifter connected between your sensor and GPIO pin thats boost the 3v3 to 5V.


text:
Arduino ethernet need help with game logic!
I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.
Example image: https://i.sstatic.net/gtnUm.png
I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.
Code that switches LED:
led = random(1, 4);
switch(led) {
  case 1:
    ledLeftState = HIGH;
    break;
  case 2:
    ledMiddleState = HIGH;
    break;
  case 3:
    ledRightState = HIGH;
    break;
}

Code that checks if the wrong button is pressed:
 if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
    static unsigned long lastTime = 0;
    if(millis() - lastTime > 400) {
      Serial.println("Ouch, minus ten miliseconds!");
      hurt += 10;
      lastTime = millis();
    }
  }

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.
Thanks for your time!

I'm not too good at making up code in my head and then solving any problems with it. ;) Please post a Minimal, Complete, and Verifiable example of what you are talking about.

First: Your buttons are not wired up properly according to the diagram.  They seem to be only connected to 5V.
On Arduino buttons can be wired both active-high and active-low.  Active-high means then when the button is pressed you get a HIGH signal, and LOW otherwise.  Obviously active-low is the opposite.  The code below assumes active-high.
You might want to go do some reading on "button de-bouncing".  I've included some rudimentary code to help, but it's not perfect.  A 0.1 micro-farad capacitor across the button terminals will help with this too.
So ... onto the code.
It's really the game-loop that needs some work.
I'll assume your random LED-lighting code is in a function called newRandomLED(), and variables ledLeftState, hurt, etc. are globals.
The new_pattern_time variable should probably also be set in newRandomLED() since they always are called together.  But I'm trying to help, not re-write ;)
const int debounce_time  =  30; // milliseconds
const int max_push_time  = 400; // milliseconds - How long is a turn

// Draw the first LED pattern
newRandomLED();

// the time the latest LED pattern was re-drawn
unsigned long new_pattern_time = millis();

// Reset the score
hurt = 0;

while (true) // TODO: insert some game-length decision
{
    // Has the time to press a button expired?
    if (millis() - new_pattern_time > max_push_time)
    {
        // TODO: sound the buzzer for *fail*

        // Time is up, penalise the user
        hurt += 10;

        // Time for a new pattern
        newRandomLED();
        new_pattern_time = millis();
    }

    // Perform the initial-read of the buttons
    int butt_left  = digitalRead(BUTTON_LEFT);
    int butt_mid   = digitalRead(BUTTON_MIDDLE);
    int butt_right = digitalRead(BUTTON_RIGHT);

    // de-bounce the button presses
    delay(debounce_time);
    if (butt_left == HIGH)
        butt_left = digitalRead(BUTTON_LEFT);
    if (butt_mid  == HIGH)
        butt_mid = digitalRead(BUTTON_MIDDLE);
    if (butt_right == HIGH)
        butt_right = digitalRead(BUTTON_RIGHT);

    // So now we have the state of the three buttons, de-bounced too.
    // Was there any input from the user?
    if (butt_left == HIGH || butt_mid == HIGH || butt_right == HIGH)
    {
        // So one (or more) buttons have been pressed
        // Check that for each LED that is on, that the button is pressed too
        boolean success = true;
        if (ledLeftState != butt_left)
            success = false;
        if (ledMiddleState != butt_middle)
            success = false;
        if (ledRightState != butt_right)
            success = false;

        // Was the user correct?
        if (success == true)
        {
            // TODO: sound the buzzer for *WIN*
            hurt -= 10;

            // And we need to show the next pattern
            newRandomLED();
            new_pattern_time = millis();
        }
    }
}

So essentially you're looping around checking to see if the player pressed anything.  Most of the time, there will be no input from the user, and this loop will spin thousands of times without any input.
On each loop the code checks to see if the time is up, or some buttons were pushed.  In both cases, it's time for a new pattern.  A side effect of this code is that it allows for simultaneous button pushes, so at higher difficulty levels you could illuminate more than 1 LED.
Note: this code is a quick response to the question.  It may not be 100% correct, nor have flawless C-textbook syntax.

The line
if(millis() - lastTime > 400)

is supposed to test that the button press does not come right after the
LED switches. This means the line
lastTime = millis();

should be right when you change the displayed LED.

Off the top of my head and without a compiler would something like this work?
int BasePin = 3;
int BaseButton = 7;

int led = random (1, 4); // Are you sure its 4??
digitalWrite(BasePin+led, HIGH);

if (digitalRead(BaseButton+led))
{
  // Success
}
else if (millis() - lastTime > 400))
{
  // Out of time
}
else if (  digitalRead(BaseButton+1)
        || digitalRead(BaseButton+2)
        || digitalRead(BaseButton+3)
{
  // Wrong button
  // (The right one will have been handled by the earlier clause)
}

OK the last clause is a bit of a hack, but it should give you a starting point to tidy up.
You are probably going to get issues unless you debounce the switches.

source: Stack Exchange

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

sort: votes


text:
Arduino with HC-05 Bluetooth Module | No data will be transmitted
I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.
My Arduino code:
#include <SoftwareSerial.h>

int state = 0;

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

  pinMode(13, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    state = Serial.read();

    if (state == '1') {
      Serial.println("Turned on LED");

      digitalWrite(13, HIGH);
    }

    if (state == '0') {
      Serial.println("Turned off LED");

      digitalWrite(13, LOW);
    }
  }
}

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".
I also tried different apps from the PlayStore but all of them didn't work.
Does someone has an idea how I could fix this? Thank you for your answers.
EDIT: A drawing how my Arduino is connected to my HC-05 https://i.sstatic.net/N2YsJ.jpg

It may be helpful to show how the RX and TX signals are connected between the bluetooth module and Arduino.

@timemage A drawing: https://imgur.com/a/FtUz5So

I appreciate the effort, but what I was most interested in what what signals you connected to what on the HC-05, and this doesn't show the HC-05's pins labeled.  So, rather than have a back and forth, I'll tell you what my wild guess is, and if I turns out to be correct I'd like you to post it an answer to you own question.  The TX signal coming from either the Arduino or HC-05 should be connected to the RX of the other as I understand it, because both are labeled from the perspective of their respective chips.

The TX signal coming from either the Arduino or HC-05 should be
connected to the RX of the other as I understand it, because both are
labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).
Thank you for your help. :)

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


text:
ESP8266 ESP-01s Not Responding, No LED Blinking, Overheating
I have an ESP-01s that I want to use as a shield so my Arduino Uno project could communicate with my Blynk app through wi-fi. I used this video as reference.
This is the sketch. It is just the ESP8266_Shield example from the Blynk library.
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

char auth[] = "-------";

char ssid[] = "-------";
char pass[] = "-------";

#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2,3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);

void setup()
{
  // Debug console
  Serial.begin(9600);

  delay(10);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
}

void loop()
{
  Blynk.run();
}

This is the schematic:

What happens:

The moment the Arduino is connected, the Blue LED flashes for a split second then all LEDs will remain off. No red led, no blue led, really just off.
The ESP-01s becomes very hot to the touch
Tried speaking to the ESP-01s through the Serial Monitor with BareMinimum example @115200 baud rate (Many Sources say that this is the default baud rate of the recent boards) however no response whatsoever.
Running the code above will get this error:

What I've done:

Tried using the HW-131 Breadboard Power Supply to supply the 3.3V (Common GND with Arduin) of the ESP-01s because I read that the ESP-01 could need more current than the Arduino Uno could provide. Still the same effect, no LEDs blinking, (even more) hot to touch, not responding to AT commands.
Attempted to follow a video on how to flash the ESP-01s but when I tried to run the flasher, it could not communicate with the ESP-01s.
Switching Rx Tx ESP-01s but no luck.
Added a 10k ohm resistor from 3.3V to the Vcc and EN pins of the ESP-01s. Not heating up anymore but still no response.

I really thought this is a power problem but could it be the ESP-01s itself is defective?
This is what the ESP-01s look like

Overheating = bad. Sounds like it's dead.

I don't see a pullup on the ESP's reset line. I doubt that is causing your your heating issue but you may get spontaneous reset issues later.

The ESP8266 is (highly likely) dead. The overheating is the giveaway.
Because you haven't mentioned it, please measure the 3.3V coming out of the Arduino with a multimeter. Unlikely to be the issue but it is easy to check.
You will need to buy a new ESP8266 and connect it up and give it a try with a fresh board. If all is good with the new board then the first thing you will notice is that there is no overheating. (If there is overheating, then you need to check your wiring.)
I notice that quite a lot of people add a 10K pull up resistor between the 3.3V line and the Enable pin. It certainly won't hurt to add a 100 ohm resistor between the Tx pin and D2 of the Arduino as a current limiting resistor, just in case.

I forgot all about this thread and yes that was the case :( I got a replacement ESP-01s and it worked.

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


text:
Rfid checking continuously for cards
Well I am making a automatic car parking system where a any one parking their car will get a card as a token and have to return it before leaving with their cars one card for a slot
And if they don't do so the buzzer will go high
There is also a ultrasonic for each slot to check if the car is present or not.
So far I have managed to do all the part except to check or store a value when the card is removed for that I have been searching for a way to make my rfid reader to check for a tag continuously but all I get so far is my reader only respond when there is a card is present.
I am doing my project any way excluding this part but I would love to add it as it will help to increase the security level.

Can you please share your code? Also which RFID module are you using

this is a Q&A site ... not a chat forum ... please ask a specific, answerable question about Arduino

Do you mean that the RFID reader only reports a tag once when it comes near it and not continously while its near the reader?


text:
Softwareserial send wrong values
I'm trying to use softwareserial to exchange datas with a sensor.
After some tries without any answer from the sensor, I checked the arduino TX with my scope and what I've seen is not what I've sended.
My original byte array (before the setup function):
static byte simple_write[] = {0xfe, 0x41, 0x00, 0x80, 0x01, 0x10, 0x28, 0x7e};

What I got on my scope:
0X77 , 0x61 , 0x69 , 0x74 , ...
Every single sent byte is wrong. I don't understand why.
The only thing on the way is a bridge divider to reduce 5V TTL from the arduino to 3,3V CMOS.
If someone have an idea, thanks in advance.
EDIT2: I use IS.MDuino.21+ (ATmega2560)
EDIT: Here are the parts of my code who involve the softwareserial
    #include "SoftwareSerial.h"

    SoftwareSerial LP8_Serial(1, 0);

    static byte simple_write[] = {0xfe, 0x41, 0x00, 0x80, 0x01, 0x10, 0x28, 0x7e}; //Write 0x010 to address 0x0080

void setup(){
LP8_Serial.begin(9600); //Opens the virtual serial port with baud of 9600
}

void loop(){

LP8_val1 = GetDatas_uart();

}

int GetDatas_uart() {
  if (first_loop == 0) {
    //reset_device();  // includes a 500 msec delay
    sendRequest(simple_write, 8, 4); // send to address 0x0080 a 0x10
    first_loop = 1;
  }
  else
    sendRequest(write_to_0x20, 8, 4); // send to address 0x0080 a 0x10
  delay(2000);
  unsigned long valCO2 = getValue(response);
  delay(3000);
  Serial.println("Now reading 32 bytes");   //sendRequest(read_16_bytes,7,21);
  sendRequest(read_32_bytes, 7, 37);
  Serial.print("CO2 from 0x9a-0x9b = ");
  Serial.print(response[29], HEX);
  Serial.print(response[30], HEX);
  Serial.print(" = ");
  int decimal = 256 * response[29] + response[30];
  Serial.print(decimal);
  Serial.println("d");

  return decimal;
}

void sendRequest(byte packet[], int m, int n)
{
  while (!LP8_Serial.available()) //keep sending request until we start to get a response
  {
    Serial.println("waiting for Software.serial port availability");
    LP8_Serial.write(packet, m);
    //LP8_Serial.write(simple_write, m);
    delay(1000); // Necessary to get consistent loading of response[i]
  }
  int timeout = 0; //set a timeout counter
  while (LP8_Serial.available() < n ) //Wait to get a n byte response
  {
    timeout++;
    if (timeout > 10) //if it takes too long there was probably an error
    {
      while (LP8_Serial.available()) //flush whatever we have
        LP8_Serial.read();
      break; //exit and try again
    }
    delay(50);
  }
  for (int i = 0; i < n; i++)
  {
    response[i] = LP8_Serial.read();
    //    Serial.print("response[i] = ");
    Serial.print("response[");
    Serial.print(i);
    Serial.print("] = ");
    Serial.println(response[i], HEX);
  }
  Serial.print("\n\n");
  Serial.flush();
}

Please show us your code. How did you analyse the scope data? Through a function of the scope? Are you sure that is configured correctly?

The code is pretty big. It's the only function who don't work. I will add the concerned parts in the original message. But yes, it's through a function of my scope.

Then please create a smaller working example code, that shows your problem, by cutting away code, that does not have something to do with the SoftwareSerial code

@chrisl, it is ATmega2560 and OP uses SoftwareSerial on hardware Serial pins (on Mega!)

So than this answer might be fitting here

Sooo, I feel a little ashamed...
After re-reading the documentation of the Arduino from Industrial Shields I use (model 21+), I discovered that using Serial0 on this board is unadvised because these pins are shared with USB.
I connected my serial wires to the Serial1 connection and now, my scope show me exactly what I wanted to see on my TX line.
Sorry for that. Like often, the problem whas between the screen and the chair.
Thanks,

so you used SoftwareSerial on hardware serial pins? Arduino Mega has 4 hardware Serials. don't use SoftwareSerial library with Arduibo Mega

Yes. I did. When I use Arduino, I rarely bother to use hardware serial except for debugging. I needed a "ready to use" electronic system for a project.

I don't meant an external USB-to-TLL-Serial, but the on chip UART peripheral

This module (Industrial Shields M21+) provide only TTL and RS232 level serials.
Moreover, I wanted to go fast with a new sensor and someone wrote an arduino library for it. The example use a softwareserial, so basicaly "Copy / Paste / Check".

and then quick to Stack Exchange


text:
Digital Reading from a array without using the exact element
Is it possible to read a digital input from an array without using the exact element? Such as
   while(digitalRead(myButtonArray[i]))
     digitalWrite(myLEDArray[i], HIGH);

Reading the myButtonArray one by one and turning on the led one by one doesnt make for clean written code. The following is just an example code. When button on pin 2 which is element 0 is pressed turn on led on pin 7 and turn off when released. When button on pin 3 is pressede turn on led on pin 8 and turn off when released and continue on in the same fashion with the rest of the buttons and leds as well.
 int myButtonArray[] = {2,3,4,5,6};
 int myLEDArray[] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<5;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
 while(digitalRead(myButtonArray[0]))
      digitalWrite(myLEDArray[0], HIGH);

 while(digitalRead(myButtonArray[1]))
      digitalWrite(myLEDArray[1], HIGH);

 while(digitalRead(myButtonArray[2]))
      digitalWrite(myLEDArray[2], HIGH);

 while(digitalRead(myButtonArray[3]))
      digitalWrite(myLEDArray[3], HIGH);

 while(digitalRead(myButtonArray[4]))
      digitalWrite(myLEDArray[4], HIGH);
 }

You want a for loop.

The AVR chip has operations that affect multiple pins at once, however this is guided/limited by their organization into ports at hardware level; the Arduino framework slaps numbers on these that bridge the divisions between the several distinct ports, and then gives you "one pin at a time" functions that hide all that detail.  I don't believe there are any Arduino-type bulk methods short of using the individual methods in a loop, and targeting the actual AVR port registers is usually only recommended where speed, rather than cleanliness, is the goal.

Is this what you want?
 #define NUM_ITEMS 5
 int myButtonArray[NUM_ITEMS] = {2,3,4,5,6};
 int myLEDArray[NUM_ITEMS] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<NUM_ITEMS;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
     for (int i=0 ; i<NUM_ITEMS ; ++i) {
         while(digitalRead(myButtonArray[i]))
              digitalWrite(myLEDArray[i], HIGH);
         digitalWrite(myLEDArray[i], LOW);
     }
 }

This code does the job I was looking for exactly. Thanks for your help.

You're welcome. Worth spending some time understanding the other answers as well because there are some interesting points made.

I think, you did not realized, that digitalWrite(i,value) sets the pin i to value AND the pin have the value until set otherwise. So you probabelly want something like this:
void loop() {
  for (int i=0;i<5;i++)
    digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
}

where each LED follows each respective Button both HIGH and LOW.

In your question you wrote

and turn [the LED] off when [the corresponding button is] released

and yet you never turn the LEDs off in your code. Then, I assume the
code in your question is irrelevant, and you just want the LEDs to show
the states of the buttons at all times. This can be done by writing to
the LEDs the values you read from the buttons. Do this for each
button/LED pair, and loop over the pairs:
void loop() {
    for (int i = 0; i < 5; i++)
        digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
}

Yes the code here is irrelevant, I wrote it just for a quick example to see if it was possible to digitalRead from a array and then to  digitalWrite to an LED in another array of the same element. Thanks for your help

It isn't clear from the question or the code what you actually want to do.  Perhaps back up a step: edit the question and write a clear-cut problem specification.
For example, a specification for what the code you have actually does, is:

For each of five buttons,

If button k is on, turn on LED k, and stall in a loop until button k is released.  Leave LED k on when the button is released.

I made an edit so hopefully it is easier to understand now.

@1fastk: It is still unclear whether the “stall in a loop” behavior is a desired feature or a bug in your code.

@EdgarBonet: Im not exactly sure what you mean by "stall in a loop" but what I am trying to achieve is to not have to have multiple digitalRead and digitalWrite statement for every element inside of the arrays. I want to just have only one digitalRead statement to read which button is HIGH inside of the array and then to have one digitalWrite statement to write the led HIGH of the same element. If the element 3 goes high on myButtonArray[] to write element 3 in the myLEDArray HIGH as well. I hope this make better since.

I mean that while the first button is HIGH, your program does not check the other buttons, as it is stuck inside a while loop.

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


text:
EEPROM PUT and GET audio playback
I am new to Arduino.
My project is an electronic piano that has 8 tactile switch keys that can play 8 octaves. I want to record a song that a user plays on the keys into EEPROM. I have implemented it. However, the playback is bad. You can't hear different note frequencies but you can hear soft buzzing when a note is supposed to be played.
Here is my code. Could you please help me find the problem? Thank you in advance.
#include <EEPROM.h>
#include "pitches.h"
#define speaker A5
#define record_button 3
#define play_button 5
#define record_led 2
#define play_led 4

int eeAddress = 0;
int eeAddressplay = 0;
const int inPot = A1; // potentiometer to change octaves (8 octaves total)
byte octave;
byte tone_out;
int tone_key; // frequency of key
boolean silence;
int maxNumber = 500;
byte time = 20;
byte check = 0;
byte buttons[] = {6,7,8,9,10,11,12,13};
int saveSounds[500];
int saveNumber = 0;

byte melody1[8] = {
  NOTE_C1 , NOTE_D1, NOTE_E1, NOTE_F1, NOTE_G1, NOTE_A1, NOTE_B1, NOTE_C2};
byte melody2[8] = {
  NOTE_C2 , NOTE_D2, NOTE_E2, NOTE_F2, NOTE_G2, NOTE_A2, NOTE_B2, NOTE_C3};
int melody3[8] = {
  NOTE_C3 , NOTE_D3, NOTE_E3, NOTE_F3, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4};
int melody4[8] = {
  NOTE_C4 , NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5};
int melody5[8] = {
  NOTE_C5 , NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
int melody6[8] = {
  NOTE_C6 , NOTE_D6, NOTE_E6, NOTE_F6, NOTE_G6, NOTE_A6, NOTE_B6, NOTE_C7};
int melody7[8] = {
  NOTE_C7 , NOTE_D7, NOTE_E7, NOTE_F7, NOTE_G7, NOTE_A7, NOTE_B7, NOTE_C8};

//PIANO FUNCTION
void freePlay()
{
  octave = map(analogRead(inPot),0,1023,1,7);
  if (digitalRead(buttons[0]) == HIGH) {
    tone_out = 0;
    silence = false;
  }
  else if (digitalRead(buttons[1]) == HIGH) {
    tone_out = 1;
    silence = false;
  }
  else if (digitalRead(buttons[2]) == HIGH) {
    tone_out = 2;
    silence = false;
  }
  else if (digitalRead(buttons[3]) == HIGH) {
    tone_out = 3;
    silence = false;
  }
  else if (digitalRead(buttons[4]) == HIGH) {
    tone_out = 4;
    silence = false;
  }
  else if (digitalRead(buttons[5]) == HIGH) {
    tone_out = 5;
    silence = false;
  }
  else if (digitalRead(buttons[6]) == HIGH) {
    tone_out = 6;
    silence = false;
  }
  else if (digitalRead(buttons[7]) == HIGH) {
    tone_out = 7;
    silence = false;
  }
  else {
    silence = true;
  }

  if (silence == false)
  {
    switch(octave)
    {
    case 1:
      tone_key = melody1[tone_out]; break;
    case 2:
      tone_key = melody2[tone_out]; break;
    case 3:
      tone_key = melody3[tone_out]; break;
    case 4:
      tone_key = melody4[tone_out]; break;
    case 5:
      tone_key = melody5[tone_out]; break;
    case 6:
      tone_key = melody6[tone_out]; break;
    case 7:
      tone_key = melody7[tone_out]; break;
    }
    tone(speaker,tone_key);
  }
  else {
   noTone(speaker);
   delay (5); }
}

//SETUP FUNCTION
void setup()
{
 for(int i = 0; i < 8; i++)
 {
  pinMode(buttons[i], INPUT);
 }
 pinMode(speaker, OUTPUT);
 pinMode(melody_button, INPUT);
 pinMode(record_led, OUTPUT);
 pinMode(play_led, OUTPUT);
 pinMode(inPot, INPUT);
}

//MAIN CODE
void loop() {
freePlay();
if (digitalRead(record_button) == HIGH) {
  digitalWrite(record_led, HIGH);
    for(int i = 0; i < maxNumber ; i++) {
      octave = map(analogRead(inPot),0,1023,1,7);
        if (digitalRead(buttons[0]) == HIGH) {
        tone_out = 0;
        silence = false;
        }
        else if (digitalRead(buttons[1]) == HIGH) {
        one_out = 1;
        silence = false;
        }
        else if (digitalRead(buttons[2]) == HIGH) {
        tone_out = 2;
        silence = false;
        }
        else if (digitalRead(buttons[3]) == HIGH) {
        tone_out = 3;
        silence = false;
        }
        else if (digitalRead(buttons[4]) == HIGH) {
        tone_out = 4;
        silence = false;
        }
        else if (digitalRead(buttons[5]) == HIGH) {
        tone_out = 5;
        silence = false;
        }
        else if (digitalRead(buttons[6]) == HIGH) {
        tone_out = 6;
        silence = false;
        }
        else if (digitalRead(buttons[7]) == HIGH) {
        tone_out = 7;
        silence = false;
        }
        else {
        silence = true;
        tone_key = 0;
        }

        if (silence == false) {
        switch(octave) {
        case 1: tone_key = melody1[tone_out]; break;
        case 2: tone_key = melody2[tone_out]; break;
        case 3: tone_key = melody3[tone_out]; break;
        case 4: tone_key = melody4[tone_out]; break;
        case 5: tone_key = melody5[tone_out]; break;
        case 6: tone_key = melody6[tone_out]; break;
        case 7: tone_key = melody7[tone_out]; break;
        }
        tone(speaker,tone_key);
        delay(time);
        }
        else {
        noTone(speaker);
        tone_key = 0;
        delay (time);
        }

    saveSounds[saveNumber] = tone_key;
    saveNumber++;
    if (digitalRead(play_button) == HIGH){
    break;}
    }

digitalWrite(record_led, LOW);
tone(speaker, 700);
delay(200);
noTone(speaker);
check++;
}

for (int i = 0; i<500; i++) {
  EEPROM.put(eeAddress,saveSounds[i]);
  eeAddress = eeAddress + 2;
}

if(check >= 1) {
  while (0 == 0){
    freePlay();
    if(digitalRead(play_button) == HIGH) {
      digitalWrite(play_led, HIGH);
        for(int i = 0; i < maxNumber; i++) {
        if(saveSounds[i] != 0) {
          tone(speaker,EEPROM.get(eeAddressplay,saveSounds[i]));
          eeAddressplay = eeAddressplay + 2;
          delay(25);
        }
        else {
          noTone(speaker);
          delay(time);
        }
        }
      noTone(speaker);
      digitalWrite(play_led,LOW);
    }
    freePlay();
  }
}
}

I don't have an answer on your question, sorry for that. However, some general comments: in freePlay you can make a loop instead of the first 8 if statements, even for the second 8, if you make from melody an array (so melody[melody_nr][...]
In loop, you can also make a for loop of the 8 if statements, and second again using the same melody[melody_nr][...] variable. This will greatly reduce your code size (and maintainable etc).

Thank you for your message. I'm new to Arduino and C programming. I don't really understand what you mean. Could you please give an example?

I am not being sarcastic, but have you checked the volume control?  It could be you need more power to the speaker.  Another possibility is you are outputting to the 'LINE' rather than the 'SPEAKER'.  It could be something to do with the resistance of your speaker not matching your circuit.

The whole thing was working prior to me saving the data into EEPROM.

NOTE: this is not an answer, but a response not able to put in a comment as request from the submittor mirandamg.
For the first example
Instead of
if (digitalRead(buttons[0]) == HIGH) {
  tone_out = 0;
  silence = false;
}
else if (digitalRead(buttons[1]) == HIGH) {
  tone_out = 1;
  silence = false;
}
...

Use
for (int buttonIndex = 0; buttonIndex < 8; buttonIndex++)
{
    if (digitalRead(buttons[butonIndex] == HIGH)
    {
       tone_out = buttonIndex;
       silence = false;
    }
}

This method does not work directly for variables melody1, 2, 3...
Therefore, make an array, instead of:
byte melody1[8] = {
...

use
byte melodies[8][8] = {
...

The first 8 is for the number of melodies, the second is for the number of notes.
You can improve it even further by making 2 constants:
const byte NR_OF_MELODIES = 8; // Number of melodies
const byte NR_OF_NOTES = 8;    // Number of notes per melody

And the array can be created s
byte melodies[NR_OF_MELODIES][NR_OF_NOTES] = {

If you make a const for the number of buttons:
const byte NR_OF_BUTTONS = 8; // Number of physical buttons

Then also the first line in the loop in my example can be changed as:
for (int buttonIndex = 0; buttonIndex < NR_OF_BUTTONS; buttonIndex++)

If you later need to change the number of notes, melodies or buttons, you don't need to iterate over your application to find all values. Especially since they are all 8.


text:
WS2812 - First are white and then they turn red/yellow/orange near the end
I'm trying to power about 150 WS2812 LEDs from my ESP8266 NodeMCU board (running NeoPixel Arduino code). The first few LEDs are white, but about half way down, the LEDs turn yellow, then they turn orange, and at the end they're basically red.
Could this be caused because of the power draw? The strip itself is currently drawing about 900 mAh, and I am powering the ESP8266 with a 1.5A 5v supply. The LEDs are running off 3.3v directly from the ESP8266.
Also, after like 2 minutes, the LEDs turn off completely. The board never disconnects from my WiFi. They just turn off. I can turn them on again right after.

See Powering NeoPixels.

Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).
...
To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even 9 amps for absolute safety.

The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.
However one (fairly powerful) supply directly connected to the NeoPixels might do the trick. That is, not through the ESP8266.
Also see NeoPixels Revealed: How to (not need to) generate precisely timed signals.
On that page:

Q: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?
A: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!

Thanks for the reply! I don't have NeoPixels LEDs. I just use their library (well, Hakuna's library to be specific). Adding power to a 5m strip seems a bit... weird. Is that the only way? They do support 5v if that helps.

WS2812 - same thing. :) Adding power to the strip is perfectly OK. You just take data and ground from your ESP8266 to give them commands, and +5V and ground from your power supply to the pixel string.

Read the page I linked with tips from Adafruit. They have lots of suggestions there.

Oh yeah, powering the strip isn't a problem.. per se. The issue is, I don't want to run additional wires across the entire room, just to power the strip. Surely there is a better way? I have over 15M of LED strip I can power with a single 12v source (just regular RGB 5050 LEDs). Can't this be achieved?

I can see the last LEDs are about 2.2v... That's not good haha.

So I up hooking up the same 1.5A 5V supply directly to the VIN and GND on the ESP8266, then connect 5V and GND from the strip to that same source. Much, much better result. Now the first 3 meters are all the same white, but yellow after that. So from 1 meter to 3 meter just by hooking it up like this. Great success so far.
If I found a suitable 5V supply with high amperage output (like 10A) would that be fine?

A larger supply will almost certainly help. For my Xmas lights I had a strip of 300 NeoPixels, running from a 5V 3A wall-wart. I think there was a slight colour drop towards the end, but not too much.

That's very interesting. I'll look into grabbing a 5V supply with a lot of amperage. I still have to power them both seperately, as the ESP8266 NodeMCU won't output that much amperage :( If I power the strip off the ESP while powering the ESP through it's VIN and GND (5v), I get the exact same result. But if I just move the power from the strip to the power source (same lane as powering the ESP), I get a "good" result.

I bet there is an internal resistance in the Vin traces, because they will be thin copper strips not intended to carry 5 amps.

Yeah I bet. So basically splitting up the connector would be efficient enough I guess.

One thing not to neglect is your power wires gauge. Smaller the wire it is the more resistive it is, causing voltage drop and current pinchoff. Use "big" wires for power.

From the Adafruit Uberguide.
https://learn.adafruit.com/adafruit-neopixel-uberguide/power
I am experiencing the same issue.  This is the solution I found.

Distributing Power The longer a wire is, the more resistance it has.
The more resistance, the more voltage drops along its length. If
voltage drops too far, the color of NeoPixels can be affected.
Consider a full 4 meter reel of NeoPixels. With 5V applied at one end
of the strip, for those pixels closest to this end, power traverses
only a few inches of copper. But at the far end of the strip, power
traverses 8 meters of copper — 4 meters out on the +5V line, 4 meters
back on the ground line. Those furthest pixels will be tinted brown
due to the voltage drop (blue and green LEDs require higher voltage
than red).
leds_brownout.jpg
Pro Tip: NeoPixels don’t care what end they receive power from. Though
data moves in only one direction, electricity can go either way. You
can connect power at the head, the tail, in the middle, or ideally
distribute it to several points. For best color consistency, aim for 1
meter or less distance from any pixel to a power connection. With
larger NeoPixel setups, think of power distribution as branches of a
tree rather than one continuous line.
leds_nobrown.jpg

Just incase anyone else has the problem,
You need to connect the strip as a ring by returning the tail end to the psu,
Electricity basics !!!!


text:
Can the Arduino be hurt by connecting too many LEDs in serial?
Today I learned about Vf for leds, after founding out that 3 leds in series driven by 5 V did not make them light up while 2 did.
However, I also read that it is quite bad for a power source to use more volts (like 3 times 2V) this way than the power source (5V for the Uno).
Can the Arduino be hurt this way?

The Arduino can only supply a few tens of ma for each output pin, so as a practical matter you present it with an open circuit when you string along too many.  Essentially the same as having nothing connected to the pin at all.  That won't hurt the Arduino, no.

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

The forward voltage of an LED or diode is the applied voltage of the "knee" in the exponential characteristic at which it starts to substantially conduct, and in the case of an LED, produce light.
It is not, under ordinary circumstances of indicator-type LEDs, a voltage that would be produced internally to the LEDs, at least not with any substantial current capability.
As long as you are supplying the LEDs from a voltage within the Arduino's I/O range, it should not be hurt by a series strings of too many LEDs.  However, in theory (if rarely in practice) a series string of too few LEDs that did not include a current limiting resistor would stress the Arduino beyond its ratings - and possibly (and more commonly) also the LED(s) beyond their current limits.

Thank you very much  ... about your last paragraph ... I already found that out ... luckily by only destroying one LED and not my Arduino.

Placing 3 "typical" LEDs in series and then driving them with the Arduino will not produce any light because the Arduino can only output 5V on any pin.  It would require approx 6 volts to drive current through the LEDs when connected in series.  This is for typical green, yellow, red type LEDs that have a 2 volt or so forward voltage drop. Note: some other colors require more forward voltage.
When you place two of these LEDs in series the forward voltage drop required to light them is only about 4 volts, that's why they light up when 3 in series didn't.  However, since the Arduino outputs 5 volts on its pin and the LEDs only require 4 volts the extra 1 volt can cause more current to flow which, if excessive, can damage the output pin.  Thats why when driving LEDs in this way its usually a good practice to place a current limiting resistor in series with the LED(s).  This resistor limits the current induced by any driving voltage which is over the voltage needed to drive the LEDs to conduction.


text:
How to code Arduino to follow schedule
I'm working on my system and I have to make arduino repeat such action or block of code if its the set time .. I'm using DS3231 module to track date and time .Example If I set the time in 6:00 AM and when the arduino reads the module and it turns out that its already 6:00 AM the arduino will now execute some action or the block of code .. sorry for my english ..

Could you use the TimeAlarms Library ? https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

Check out how the DS3231 Alarm functions work.  They will interrupt even a delay() statement.  At the appointed time the specified function is called.
This same question was answered here:
How to set Alarms on the DS3231 easily?
For another way to see how to set this up, let me refer you to this article:
Build Programmable Time-based Switches Using a Real Time Clock
The code can be downloaded Here

This example shows a simple way of conditionally processing an event at a given time of day, once per day. The example allows 59 seconds of accuracy but in reality if the Arduino is free to read the time this will happen almost exactly at 6.00am.
You need to declare and populate currentTime and currentDate by reading the DS3231. This example assumes the currentTime is in millis.
unsigned long action1_LastDoneDate;
unsigned long TIME_600AM = 21600000; // millis 6.00 am = 6*60*60*1000
unsigned long TIME_601AM = 21660000; // millis 6.01 am

void setup()
{
 action1_LastDoneDate=0L;
}

void loop()
{
 //make sure we have not processed today
 if (action1_LastDoneDate != currentDate)
 {
   //make sure the time is within range
   if (currentTime>=TIME_600AM && currentTime<TIME_601AM)
   {
     //save off the current date so we don't try do process this alarm again
     action1LastDoneDate = currentDate;
     //now do the 6am stuff
   }
 }
}

Thanks for the quick reply .. I will try this and give you update , Thank you :D

authors: Айгуль Балгалиева


text:
Is it possible to save different values on address 0 and 1 in EEPROM?
I want to save different values on address 0 and 1 on eeprom I tried to change it but when I put data on address 0 and also put data on address 1 the address 0 change its value stored into random number and vice versa .. Is it possible to change the value of respective address without affecting others ..
CODE
in the setup
     int eepromSize=EEPROM.length();
      Serial.print("EEPROM found, size=");
      Serial.println(eepromSize);
        // Get the last fade value (as an integer)
      EEPROM.get(0, WATEREQFORN1);
      Serial.print("Last Value N1: ");
      Serial.println(WATEREQFORN1);

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

The user will input the value that will be save in eeprom i use switch because the user will input like this example .. 100A or 23B
case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        WATEREQFORN1 = val;

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

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

        break;

The problem is, when I change/write value into address 0 and after that change/write also into address 1 the value on address 0 also change into different random numbers.

Yes. Post your code so we can see where you went wrong.

@Majenko I edit my question and add my code ,

What are WATEREQFORN1 and WATEREQFORN2? You only show a bit of your code, and have omitted what may be the most important parts - your variable definitions.

unsigned int WATEREQFORN1; unsigned int WATEREQFORN2; That is the value the user enter sir .. example 200A it will be get by case a and be assign in WATEREQFORN1as show in my code WATEREQFORN1 = val the val initially hold the serial value 200 and pass to WATERECFORN1

The variable names in all upper case is a style problem you should address.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of WATEREQFORN1 consider waterEq1, etc.
The problem of your second value overwriting part of the first in EEPROM is an allocation problem.  Presumably the WATEREQ... variables are multiple bytes in length.  EEPROM.get() and put() read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if WATEREQFORN1 is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.
The following code snippet shows a way to automatically and systematically allocate EEPROM space.  The sizeof operator returns the size in bytes of its argument.  Thus, an expression like WaterAddr2=WaterAddr1+sizeof waterEq1 correctly sets WaterAddr2 to be the next available cell after waterEq1, no matter what type waterEq1 is.
enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...

Thanks I think thats  the problem , I follow your advice and It Works like a charm .. :D

the allocation is the problem ..

EEPROM.put() and EEPROM.get() write or read the object you pass them. An int is 2 bytes so that is what they write or read. It sounds like you intended for the functions to only handle 1 byte. In that case, make the your variable's data type something that is 1 byte, such as int8_t; otherwise allocate 2 bytes of EEPROM to each.
Update:
It works because you had only allocated 1 byte in EEPROM for each variable but you store 2-byte variables. Now you're storing 1-byte variables, which matches your EEPROM allocation.

So instead of unsigned int i will use byte ? because i only want to save numbers.

It works now that i change the unsigned int WATEREQFORN1; into byte WATEREQFORN1 i dont know why but it works , when i write new data to  WATEREQFORN2 the WATEREQFORN1 dont change into random numbers

Is it possible to change the value of respective address without affecting others ..

Yes, if the two values are 8-bit types.
Otherwise, No.

Probably WATEREQFORN1 is an int or word, at least more than one byte.
If you write a 2 byte value on address 0, it will occupy address 0 and 1.
When you overwrite address 1 (again with a 2 byte value), it will occupy addres 2 and 3, destroying the LSB part of the value written to byte 0.
Try writing on address 0 and 2 (or 0 and 4 when using 4 bytes).


text:
Controlling a LED array from Arduino NANO
I have a project Im currently busy with that I need a lot of help with.
What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).
I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?
How would I manage the current for all the LEDs
Thank for taking the time to listen to a n00b like me :D

i think you can drive them all from one GPIO, depending on the RGBs used; which?

Are you planning on buying a pre-made LED matrix, or making your own? That might affect the advice somewhat. Individually addressable LEDs are available but not (AFAIK) in matrices.

Probably going to buy individual LED and assemble them in a grid myself

In that case, I would suggest looking into addressable LEDs. Get it working once (Arduino libraries exist), no messing with external shift registers.

You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).
For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.
If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.
And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.

There are a lot of ways to do what you want to do. Wiring them up individually would be one possibility those find a chip with that many pins can be a challenge
You can use shift registers, either statically or dynamically.
You can also use display drivers, like 7219 or the ht variants.
...
End of the day it will depend on your application and constraints it has to live under.


text:
Keypad number input and store
i'm stuck with a little problem. I need to create a program that can store a number via keypad (this number will be chosen by the user) and then do something with it. To be more specific i will create a temperature control in which the user will be able to input a value of temperature they need and then with this value control a heater, but that's another story, the main point here is that the program needs to be able to store a value via keypad.
i use the keypad library and some of its commands like getKey() and waitForKey() and so on.
thanks for your answers!

It doesn't sound like you've asked a question. Can you show us what you have tried?

“Store a number via keypad” is too vague to be an adequate problem description or program specification.  Please edit your post and add question details, keypad model and which pins you attach it to, and some code that shows keypad library #include and calls.  (To mark code as code, highlight it and press ctrl-k)

There are many issue when interfacing a processor to a physical switch.  So many that this one question can and has been broken down into several separate questions here on this web site:

How to de-bounce a switch has been asked many times including here.
How to use pull up resistors with a switch has been asked many times including here.
How to scan a switch matrix has been asked many times including here.

Add to that, you need to decide how to parse your data.

Will you always expect 2 digits?
If so, What will you do if the user enters 3 digits?
Will you support a back-space feature?
Hows about a clear-entry feature?
What about a enter-key feature?

Fortunately many of these questions are addressed in this tutorial.

http://playground.arduino.cc/Code/Keypad#Example here is the setup for you, you should see, what you are pressing.
then try something like this:
int temp=0;
bool in_press=false;
void loop() {
  char key = keypad.getKey();
  if (in_press &&  key == NO_KEY){ in_press=false; return;} // key released
  if ( ! in_press ){
    if (key != NO_KEY){ // if key is just pressed - proceed it
      in_press=true;
      if (key == '*') {temp=0; return;} //cancel input
      if (key == "#') { do_something_with(temp); temp=0;return;} //accept input
      // key is '0'..'9' - add it to result
      temp= temp*10 + (key-'0'); // maybe check it temp is not too high ...
      return;
    }
  }
  // this pass of loop no new key was pressed, do anything else to do
  // if we want, we can test in_press to see, if key is holded or not
  // or ignore it at all
  do_other_stuff_like_blinking_leds_or_what();
} // end of loop()

The return at third line of loop() is unnecessary and is problematic -- it locks out do_other_stuff_like_blinking_leds_or_what() during the whole time a button is  held down.

@jwpat7 No, just one, as it sets in_press to false and so the next time the in_press && ... is false, thereturn is skipped and so no more locking occures. On the other hand those returns may be avoided, but the structure would be more complicated. And if the process is reading human input (really slow) and manages room temperature (slow as hell), then one or two more cycles thru loop() does not mean real problem. I did choose more simple and straithforward approche (and slightly less efficient), as it looked to me, that the autor is not much skilled, so clarity is better than speed.

Ok, you are correct that do_other_stuff...() gets skipped only once.

well there are other returns too, so theoretically you can press/release keys so fast, that the other_stuff is avoided at all - but you cannot do it by hand, you would need some other comp to emulate it. But it is not important here I think.


text:
Moving motion sensor?
Long story short, I'm trying to build some form of device that you can wear and it will detect when something moves behind you. I wanted to use PIR sensors for the motion detection, but I have no idea if they can detect objects if you're moving. Any ideas?

OP didn't really specify the actual requirements other than detecting movement and wanting to use PIR while in motion.
PIR (Passive Infrared) implies looking for warm bodies.  In general, PIR motion sensors look for the presence of thermal radiation that moves between the individual parts of the sensor.  On TV it is shown that you can fool PIR detectors by carrying a large cold panel between you and the detector. ;-)
They also detect reflected thermal radiation that is moving.   It does not need to be a direct view.  So moving the sensor around outside would pick up a lot of reflected IR sunlight changes.  And certainly incandescent lights would do the same since about 80% of their emitted energy is IR.
The way they are designed, (with lenses like a bee's eye) they are more likely to detect your own arms swinging back as you walk and generate false alarms that way.  So you would need some kind of mounting arrangement that only allowed it to "see" directly behind.  And even then only in a dark room.
PIR sounds like a lot of trouble for an application like this.  (As in, probably not suitable)
Here is a decent instructable that explains how they work:  http://www.instructables.com/id/PIR-Motion-Sensor-Tutorial/
If PIR is not a be-all requirement, here is an alternative to be considered, even though it would require some work to get it right:
Radar
Here is a nice, inexpensive radar unit that will arrive eventually on the slow boat, and the price is right.  It could work well in motion if you program it to detect changes that occur at speeds faster than your own motion.  And you would want to program a pulse gate it so it only senses objects at more than a certain distance behind you.
Anyway, in the spirit of hacking, I offer this idea:
LFS-DC04 2.7GHz Microwave Radar Module DC 5V
http://www.ebay.com/itm/262662221979
It is small enough to wear.  But it is slow, so I wouldn't recommend using it to detect intruders with violent intent.  I believe it would be good mounted on a bicycle-pulled trailer or something like that, to make sure you know if something is coming up on you too fast.
Product Introduction:
1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree

It is low enough power that it shouldn't fry your kidneys.  Probably very similar to sitting next to a high-power WiFi router all the time, or like having a cellphone in your pocket with WiFi and 4G turned on all the time.

New information:  I hooked up a PIR sensor and tried moving with it hanging over my shoulder.  It would not stop triggering constantly.  I couldn't hold still enough to make it stop.  So I believe that isn't going to work for you.

PIR sensors detect the movement of a warm body relative to the location of the PIR sensor.  Therefore if the PIR sensor moves then the location of a static object relative to that PIR sensor will change and motion will be detected.
So no, PIR is not really suitable for this.
TBH I can't, off the top of my head, think of a simple way of achieving what you want short of image processing with OpenCV on something considerably more powerful than an Arduino.

A PIR is entirely passive. The sensor has an enclosed vertical and horizontal IR receptor which reacts to the change of IR coming through a faceted lens, to accentuate the effects of movement, striking the surfaces through a small window on top.
Having a passive system attached to a moving body would result in mostly false positives.
It could be worth looking at active systems such as video, microwave, or even ultrasound


text:
Accessing Values From Array Within a Library
There are many great examples of how to access information from an array on the net. I ran into a specific case that has me confused. I am using a library for attiny 85 TinyPpmReader.h. This is a simple library that will take PPM signals in from a RC receiver running in pulse position mode and allows you to attach to a pin to process input. Easy enough.
In the code below, I ran into some confusion when trying to access the data in the array. I am trying to filter out a single channel in the ppm stream and print the contents of only 1 channel (Original example prints 8 channels) and eventually map that value to a servo. (I pasted the serial monitor ouput at the end of the code)
I tried accessing the variable stored in the array like this:
void loop()
{
for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */

if(TinyPpmReader.detectedChannelNb == [5]) //Is this channel 6 in index 0-7?
{
Serial.println(TinyPpmReader.width_us[5); // if so, print only index 5 containing channel 6 values
}
delay(500);
}

Example unedited sketch from library
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

#define PPM_INPUT_PIN  2

void setup()
{
  Serial.begin(38400)
  TinyPpmReader.attach(PPM_INPUT_PIN);
}

void loop()
{

  Serial.print(F("* Period="));Serial.print((int)TinyPpmReader.ppmPeriod_us());Serial.println(F(" us *"));
  Serial.print(F("ChNb="));Serial.println((int)TinyPpmReader.detectedChannelNb());
  for(uint8_t Idx = 1; Idx <= TinyPpmReader.detectedChannelNb(); Idx++) /* From Channel 1 to Max detected */
  {
    Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us"));
  }
  delay(500);
}

The serial monitor prints this:
* Period=17928 us *
ChNb=8
Ch=1496 us
Ch=1744 us
Ch=896 us
Ch=1560 us
Ch=1640 us
Ch=1496 us
Ch=1536 us
Ch=1688 us

Any suggestions? It is probably something simple but I dont think I am googling the correct question to get the correct answer.
EDIT: That worked Mark!
New Code Mapping attempt (Compiles,does not work)
#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

//int potpin0 = 3;    <---------          // This worked
int val0;                     // integer to store value

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

void setup()
{
  setupServos();
}

void loop()
{
  val0 = analogRead(PPM_INPUT_PIN);  <---------          // reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
  val0= map(val0, 1000, 2000, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)
       // scale it to use it with the servo (value between 0 and 180)

moveServo(PANSERVO, val0);

  delay(5);                           // waits for the servo to get there
}

We'll need to know how the library stores data in the array, if you know that. Or a link to the library would help. I can tell you that your loop() function has syntax errors and won't compile as shown here. There is no need to scan the array with the for() loop and only read one element; you can just read that element like: ArrayName[5] (I can't be more specific than that without seeing the library). I have no idea how TinyPpmReader.detectedChannelNb == [5] evaluates but [5] by itself is unusual, if it even has any meaning, in C++. Did it even compile?

This is the link to the library. What Mark suggested below worked to only print the channel 3 values to the serial monitor.
https://github.com/RC-Navy/DigisparkArduinoIntegration/tree/master/libraries/DigisparkTinyPpmGen

This code (from the example) is what prints a single index - index Idx:
Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

To print, say, index 3 you'd use
Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

To simply get the value from index 3, without printing it:
int a = TinyPpmReader.width_us(3);

(assuming it's an int)

That worked! Thanks!
I was able to only print channel 3 info to the serial monitor.
The ultimate goal was to map channel 3 using:
int a = TinyPpmReader.width_us(3);
But if you check the new code I just added above (below original post) I am not able to map this as an integer for some reason. I added arrows where I changed the code to try to map channel 3. Why does it not compile or map like this?

Glad to hear it.  This is a new question really - we should stick to one question per, erm, question. If you post a new question I (or others) will try to help.

That said, perhaps you're not clear what PPM_INPUT_PIN is.  It's just the number of the pin - not the reading taken from that pin or anything - simply a way to identify the pin. With that in mind, int PPM_INPUT_PIN = TinyPpmReader.width_us(3); looks nonsensical.

OK, I will post another question and try to clarify. This question plus the new one hopefully will help people see how to access the array and map it .Thanks again Mark. Very appreciated!

posted new question about mapping the input here:
http://arduino.stackexchange.com/questions/33224/mapping-ppm-signals-to-servo-values


text:
Is it possible to create an interface between Teensy 3.2 and a DSP?
I realize that this is a forum for Arduino but since the Teensy 3.2 is compatible with the Arduino IDE I thought it would be appropriate to ask the question here.
Anyway, can I create an interface between the Teensy 3.2 and a DSP, more specifically the TMS320C5534-Fixed-Point Digital Signal Processor and how could I go about it?
What I am trying to do do is capture an EEG and EoG (electrooculogram) signal, amplify it, filter the signal, use the DSP for ADC and signal processing and finally get this information from the DSP to the Teensy 3.2, which will then make a decision based on the signal obtained from the DSP.
Maybe this is a simple question but I couldn't find any answers online. I am pretty new to the world of microcontrollers.
Thank you guys!

Why can't the DSP make the decision?

Because this involves obtaining and analyzing large amounts of data in real time. I though it would be faster If I used the DSP strictly for signal processing, which is intensive in this case, and then send the processed signal to the microcontroller to compare this information with the signal that I am looking for (i.e a certain brain wave and a pattern of eye movement). If a match was found then the microcontroller has to send a notification wireless to a mobile device saying that a match has been found.

the microcontroller would also monitor that there is good contact with the electrodes. So, I guess in short it would be to make the whole system faster, but I am not sure it that would be the result.

Yes, you can do it - for example if the data rates are moderate with an asynchronous serial interface.  But don't even bother trying to implement pattern recognition and decisioning on a microcontroller, until you have fully validated your algorithm on a PC, possibly against a large set of recorded data, and ultimately against data transmitted from the DSP sampler.  Until you have done that it is premature to select a micro as you can't reliably know what your computational and memory needs are.

I would use one of the serial interfaces and connect them together that way.  If Asyinc run as fast as reliable.


text:
How to use web data from GSM Sim900 to be used as input for Arduino?
I have a GSM Sim900 connected to an Arduino Uno. I'm successfully able to use HTTP READ commands to show data from the web on the Arduino's serial monitor. It is showing complete HTML from that URL on the serial monitor.
Now, how should I filter data from the web? I mean I just want to display selected numbers in the serial monitor and not the complete HTML.
And secondly, how should I store these numbers into a variable so I could use them as input data for Arduino?
Thank you.

You need to learn how to parse strings with the C string library, specifically strstr(), strtok() and strchr(), as well as how to manipulate strings with pointer arithmetic.

You should read the manual.
More specifically the "Sim900 AT reference".
I've found it on a russian server (https://www.google.nl/url?sa=t&source=web&rct=j&url=http://wiki.amperka.ru/_media/%25D0%25BF%25D1%2580%25D0%25BE%25D0%25B4%25D1%2583%25D0%25BA%25D1%2582%25D1%258B:gprs_shield:gprs-shield_sim900_at_commands.pdf&ved=0ahUKEwinze2Tp7fQAhWBMSYKHQFkBh0QFghEMA0&usg=AFQjCNGKd5Uohe7CmcJcIc1Am-SKdRsWXg&sig2=XIsvvkLWHs60sTo7FZ7tWw) but you may want to try and get it directly from the manufacturer.
In the datasheet, it will explained what values are allowed with the "at+httpread" command. You can actually specify which part you want to read. This is usefull when your Arduino can't parse the complete page.
If you have control over the page, you may also generate a device-friendly page consisting of key-value pairs, instead of it being a whole HTML page.

Mind that my answer only applies when the page is too big to put in a buffer at once.

What about RapidXml? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments so might work here. Boost software license means source is freely available. http://rapidxml.sourceforge.net.
The other way to go is just parsing out the numbers with string manipulation.

authors: Геннадий Горбенко


text:
cu port always busy on Mac
I'm going bonkers here. I'm using a Macbook Pro with Yosemite. Connected to the MKS Gen-2Z V1.1 reprap board (ATmega 2560).
The Arduino IDE only shows the cu port being available and not the tty.
Any attempts at opening the CU port show it as being busy. This is also true when I open the port using PronterFace (3d printer software). Yet, the PronterFace shows the tty port and gladly opens it and communicates. I downloaded Arduino 1.0.6 and the tty is available in the dropdown menu and it will open the port. But my 3D printer firmware will fail building on any Arduino IDEs prior to 1.6.0.
I found a few suggestions on creating a file "lock" in /var/ and then changing the r/w permissions. Also doing the same for /var/spool/uucp. Changing both of those permissions did nothing for me.
I may just have to build it and use AVRdude directly so I can use the tty port, but I have no idea why the cu would be busy all the time. Any suggestions?
Here's the Arduino output when I try to upload:

avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL00YS9R": Resource busy
      ioctl("TIOCMGET"): Inappropriate ioctl for device
      ioctl("TIOCMGET"): Inappropriate ioctl for device
      avrdude: ser_send(): write error: Bad file descriptor
      Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Is there something useful in http://arduino.stackexchange.com/questions/13299/inappropriate-ioctl-for-device?

Don't you also have a /dev/tty.usbserial-AL00YS9R?

Can't you see what's hooking the serial port with sudo lsof -n | grep cuaU0 ? If so, sudo kill -9 12345, where 12345 is the offending PID. Your FTDI chip may need a driver, try sudo dmesg after pluggibg it in, or use systemprofiler.

JRobert - I'll have to try the csrutil suggestion. The problem I see with that is the board I am trying to interface with has a genuine FTDI chip, the 232RL. The answer posted was to install a driver for a chinese USB chip.
Gerben - I do have a /dev/tty.usbserial-AL00YS9R. The Arduino IDE is only showing the cu ports.


text:
Is it possible to use AWS and Arduino Uno to upload data from Arduino to a website running on my localhost?
I was wondering if it's possible to send data from my Arduino Uno (e.g. from the temperature sensor) to the Amazon Web Service RDS or anything there, which will then upload the data to a website on my localhost?
If yes, could someone give me guidance please?
I've been messing with this for a few weeks now, but I am just getting lost with linking it all up together.
Thanks.

First of all you must post your code how you are progressing, like @Majenko said it is not easily possible but it can work.  I will guide you along the way

You'll probably only need one server, and let the Arduino's upload to that directly?

No... by definition the only thing that can upload anything to "localhost" is that host itself, because "localhost" always refers to oneself.  It may well be possible to contact this from some other device, but never by referring to it as "localhost"!

If the goal is to get the data from the arduino to your local machine? Is the arduino on the same local network as the your local machine? if so, skip AWS altogether and just have the arduino talk directly to your local machine...

No, it is not (easily) possible.
AWS has no access to your localhost - you are (most likely) behind a NAT router.
You could possibly open up port forwarding on your router and then ensure that AWS knows always what the IP address of your router is so it can connect (using some dynamic DNS service maybe).
However, that is not secure, and dynamic IP address assignments makes it a real pain. It opens up your computer to hacking from the internet.  A more secure method is to use AWS as the "central point" and have your computer go and fetch data from there rather than having it send data to your computer.

What would you suggest would be a good idea doing what I want to achieve? Thanks

@deeveeABC The last sentence of the last paragraph.

You can always setup a dynamic dns (as I do), with no-ip or dyndns clients (most routers allow you to configure that), and use the port forwarding thing. You can even configure a afraid.org dns redirection (pretty easy), but you have to note that you won't be capable of fetching / posting via https, so it's very likely it's not gonna work or be very prone to attacks.

I realize that this probably two years too late for the OP; however, I'd like to provide insight to anyone else who might be interested.
It is possible to do what you're asking. What you are looking for my friend is AWS IoT Core and the related IoT Services (e.g. IoT Device Management).
There are several steps that you're going to need to perform prior to being able to send telemetry to AWS:

Ensure that your device has the necessary components to connect to the Internet (e.g. a network shield).
Once you are Internet-capable, locate here the AWS IoT SDK that will work well with your device.
Read the documentation (I'll let you look that part up ;-)...probably within the sub-links on the page from #2) on how to connect your device to an MQTT-based Web Sockets connection to AWS IoT Core.
Once you've figured out how (using the SDK from your device) to connect to AWS using MQTT, read about AWS Lambda and how you can setup various triggers off of IoT Core, which can then propagate data down to your RDS DB or the like.
Once you have your data in AWS, you can then connect your "localhost" website to RDS, using the appropriate connection string, and pull the data from there.

Good luck and happy IoTing.


text:
How can I make a garage door laser sensor?
I would like to make a sensor that detects when my car is clear of a certain point. So, when backing in my car to my garage, I would have a beam and sensor. When the beam is broken, an LED light would turn on and then when the beam gets through, the light turns off and I know that the car will clear the garage door.
I am pretty sure I have to use either an Arduino or Raspberry Pi, but I'm completely new to home automation. There are a few other things I'd like to do but this is a good starter.
I don't know where to start.

I'd suggest adding a mirror, so you don't need wires at both sides of the garage. You don't even need an arduino. Laser, LDR or Phototrasistor, Transistor or Opamp, Potentiometer for fine-tuning triggerlevels, and an led. You could even just shine the laser on the photosensor of a cheap night-light.

@Gerben I love the night light idea.

I agree with @Gerben but would recommend a reflector so the mounting angle is not critical.  Having said all that I think you could do this more simply by using an ultrasonic range sensor.

You could also use a mirror so all the wiring is as the same side or the door.

I would recommend using laser and LDR. This will be very efficient and will not cause any problem due to light or ultrasonic deflecting. It will be precise by mm if you do thing right way. I made a simple porject back in 2005 using laser, LDR and relay.
Here what you need to do.
Get a laser, any laser will work. www.ebay.com/itm/6mm-650nm-DC-5V-5mW-Mini-Laser-Dot-shaped-Diode-Module-WL-Red-Copper-Head-Tube-/291089398593?pt=LH_DefaultDomain_2&hash=item43c647bb41
Get a PhotoResgister www.ebay.com/itm/Reliable-Hot-New-20-PCS-Photoresistor-GL5528-LDR-Photo-Resistors-Light-Dependent-/161434780484?pt=LH_DefaultDomain_2&hash=item2596434344
Put ldr in the dark box and drill a hole in it so that no other light can enter 2mm diameter hole will work.
Connect the LRD to your board. Fire laser and change status of indicator led by the value of ldr.
Check this link for refrence www.instructables.com/id/Arduino-Laser-Tripwire/?ALLSTEPS

I am pretty sure that Arduino would be enough for this project since the proper computation should not be that complex. Arduino Uno seems to be the simplest to start, at the same time not being too big for your application domain. However, you could also consider some smaller Arduino model, there would not be any "computational power" problem probably.
You could use an Infrared Proximity Sensor to check whether a car is present or not, here is a link that could be useful for this: http://arduinomega.blogspot.it/2011/05/infrared-long-range-sensor-gift-of.html
In this way, the system would light ON one or more LED(s) whenever the measured distance turns out to be less than some threshold value that you decide (maybe using a test-driven approach), and then light it/them OFF once the distance returns over the fixed threshold.
Hope this will be helpful.

Yeah, but I'm just not sure that IR will give me the accuracy. Essentially, as soon as I'm clear of a certain point, I want to trigger an action.

Looking at its characteristics, the sensor I linked to you above should be able to detect movement up to 150 cm far. So, it depends on how far from the car you plan your sensor to be in your project. However, consider that, even if IR sensors are not that accurate with respect to Ultrasonic sensors, for example, an object like a car would be easily detectable. As far as the responsiveness of the system is concerned, it depends on the frequency with which you perform your sensing. On the other hand, IR sensor are much more cheaper, and work well in closed/quite-dark places like a garage.

I'll look into it. I'd be curious to see how wide the detection area is. When the car is parked, there's only 2-3 inches between the car and door, ideally. Thanks!

You're welcome! Have a nice time working on your project!

I cant make out from the picture if you have consider this thought.
Install sensor at height so car tail breaks the beam.
Also It might not be ideal solution if you have multiple car lets say one Range rover SUV and another hatchback.
You might want to consider having multiple sensor from ground to around 4-5 feet.

Yep, that's exactly what I want to do. I back into a single-car garage, so essentially, as the car enters, the beam would be broken near the garage door. When the front of the car clears the door, the beam would pass and trigger the sensor.

I know some projects are just for the sake of the project alone but have you considered this no-tech solution?
http://www.instructables.com/id/Automatic-garage-parking-aid/

Hah. I loved the idea of the ball being tied to the garage door. Great stuff. However, because I back in to a single car garage with very tight tolerances, I wanted something more accurate and unchanging. If one of the kids was playing with the tennis ball, then suddenly I'm out a few inches and the garage door may come down on the front of the car.

You want a light sensor like at http://rookieelectronics.com/light-sensor-using-arduino/ - the usual way is infrared (same as remote controls), so you can't see it. You might want to blink the light, to get a more accurate signal (i.e. turn the led on; test the brightness; turn it off; test the brightness; find the difference) in different light conditions.
Personally, I would probably use a http://www.dx.com/p/hc-sr04-ultrasonic-sensor-distance-measuring-module-133696#.VRH9k3WjlIc Ultrasonic distance sensor - but there are lots of ways to accomplish this.
Not an Arduino answer, but.... a friend of mine put his car in the exact place it should be, then hung a tennis ball from the roof, at the right place so it just touches the windscreen. Now, when he pulls into the car, he moves forward until the tennis ball touches his windscreen, and he knows he's in exactly the right place.

Ultrasonic could work, but the smooth curved surface of a car might deflect the waves at shallow angles without reflecting them back to the sensor, causing a false negative.

True. You'd have to think about where you put the ultrasonic. I would go for pointed at the license plate. Alternatively, if you place it pointing OUT from BELOW the license place, you could take it with you - LOL

Yeah, I've tried the tennis ball trick already. Problem is kids play with the ball. Also, because I'm backing in and the garage is dark and I have tinted windows, It's not clear when I hit the tennis ball.


text:
How can Arduino know Wire.available() is true or false?
In this part of code
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

How can Arduino know that Wire.availble() is true or false?
I thought that when the microcontroller "reads" the value from the sensor, in pieces of 8 bits, he reads from 0 (n) to 5 (n+5) at the I2C address of the MPU-6050, and when he increments 6 it finds nothing, but this is my conclusion, i am not sure about it.

I am studying how Serial.available works and how the circular buffer works for the data comunication, because available() inherits from the Stream utility class.
The entire code is the following taken from  this question
  #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

Minor Question
I am trying to undestand the difference between the register and the device address, but i did find anything on my book.

You've used lots of words, but I don't actually understand what it is you think you are asking.

Sorry, i think my bad english is  a problem to explain my question. The while statement end when Wire.available() is false. This happen when there is nothig to read (?). How can arduino know that there is nothing nothing more to be read? Thank you :)

Because the Wire library software coupled with the I2C hardware interface has determined that is the case? You should read the datasheet and the Wire library source code.

If you request 5 bytes you have 5 bytes in the buffer, and when you have read all 5 there will be nothing available.

Ok, i think, now is little bit clearer, i will read the Wire library source code . I have read the mpu6050 datasheet yet, your blog post on buffer, but it was still not clear and hard for a self-taught like me :)

I2C is one of the harder protocols to understand. It has nothing in common (other than the fact that one bit follows another) with Serial, so reading Serial in the hope of understanding I2C is not going to help.

Ok so is very normal to have this difficulties :)

When the Wire.requestFrom is used, the receive buffer inside the Wire library is cleared and the received data is stored in that buffer. The Wire.available tells how many bytes are in that buffer. That means you start with a fresh cleared buffer every time before reading data from a sensor. The I2C only defines that the first byte is the address of the sensor. How the sensor selects its internal register or how it handles commands is up to the sensor. Often a byte is written to set the register-address inside the sensor and after that a number of data bytes is read from the sensor.

The simple answer is that the Arduino Wire library has an internal buffer, and it can bring in characters and have them sitting there ready for you to pick them up.
It can also sense a total disconnect because of the way it uses both data pins to establish communications.  It is more like a current loop than a simple one-is-transmit-and-the-other-is-receive.  If it disconnects the Arduino knows it is not available.
Kudos on going to the documentation, by the way.


text:
Write to serial only if the state of a light sensor changes
I need to know the times when an LED strip turns on and turns off.  The LED switch is driven by light dependent resistor.  When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven.  I need to know the times (in local time) that the LED turns on and off.  I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second.
I can listen to the serial port via Python and record the seconds via Python.  No worries
What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes.  For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once.  I am having trouble figuring out the code to do that.  The LDR is not like a button since it is always reporting back analog data.    Any help is appreciated.

You need to keep track of the previous value and compare the current value to that. (It may work better to keep track of the last few dozen previous values and compare the averages of, e.g., the last dozen to the dozen before that.) Does this help you try to write some code that you could put into your question for us to help you further with?

Ditto.  Especially the idea of taking multiple readings before deciding it is a for-real change and not just a glitch.

You wrote: “I am using the Arduino Uno to print to the serial monitor
its state every second.” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.
Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.
Then you can write something like this:
const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}

+1 for the hysteresis -- it quickly handles the debouncing since it will trigger once on the first observation above the threshold, and won't reset until it is definitely lower.

An LDR doesn't have a "state", being a resistor that varies continuously, and inversely with the light intensity. The LED strip has distinct states: lit and not lit. It sounds like you want your code to deduce the LED state from the sensor value. You'll need to define lighting states based on the the LDR readings, and those readings won't be consistent; they'll vary from measurement to measurement of the same lighting conditions and they'll be affected by changes in the ambient lighting. If you can exclude ambient light falling on the LDR, the job will be easier. @Edgar_Bonet described a way to ranges of LDR readings corresponding to 'lit' and 'not lit'
When a moving average of LDR readings, or some number of consecutive LDR readings falls within the range contrary to the state your code been keeping for the LED lighting, it should change the state and print.
If ambient lighting changes are unavoidably affecting the LDR, you'll definitely need to keep some sort of moving average and watch for a large difference between a small number of averaged readings and the longer-term moving average used to correct for ambient. This is a kind of auto-zeroing and it can lead to its own errors: sensing the room lights being turned on or off, cloud shadows, or a person or animal passage throwing a shadow, can all cause false change-of-state detection.
Update:
I'd add that you might compare the LDR output to 3 ranges: [0 - MAXDARK], [MINLIGHT - 1023], and "neither" - the gray zone in between. This is analogous to how the digital input-pin receivers in the MUC decide whether a digital signal (which is inherently analog) is HIGH or LOW. You'll have to experiment with the values of MAXDARK and MINLIGHT to find the right values for your environment.
Then you you'd print, once, whenever the LDR signal solidly enters either the MAXDARK or MINLIGHT zones, and not again until after the signal has solidly exited that zone, or equivalently, solidly entered the gray zone.
"Solidly" is probably something like NCONSECUTIVE averaged samples. Again, you'll have to find a value for NCONSECUTIVE that is both reliable and responsive. Too low a value may give you several time-stamps for the same event; too high a value will delay how quickly you detect the event (which might be totally irrelevant for a twice-a-day event).

I need to know the times (in local time) that the LED turns on and off. .. I am having trouble figuring out the code to do that.

simple.

attach a pin to the circuit's output that turn on / off the led.
set up your arduino to read the state or state changes of that pin. this can be done via interrupts or polling.
based on the state of the pin, determine if the led is on or off, and record the current time.

step #1 can be done with light sensors (on the led's light output). but that can be slightly trickier.

The LDR is not like a button since it is always reporting back analog data.

you can set up the ldr to read it like a button.

If you have already set the resistor to print to Serial every second, then it is simple to modify. Your code is probably like this:
void loop() {
// something something
Serial.println(analogRead(resistorPin));
// other other
}

and you want something like this:
int lastValue,newValue;
int treshold=200; // or some other empirical value,
// analogRead() returns 0..1024, so it should be safely inside
void loop() {
// something something
newValue=analogRead(resistorPin);
if (newValue-lastValue > treshold) {
    Serial.print("Value increased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
if (lastValue-newValue > treshold) {
    Serial.print("Value decreased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
// other other
}

the treshold value should be set so the event is triggered if substantial change in value happend (so probably those LEDs went on/of) but not trigger when there is a smal change (like cloud going on sky).
Eventually you can also print the time, at which the event happened, using something like http://playground.arduino.cc/Code/DateTime or http://playground.arduino.cc/Code/Time or any other library suiting your needs. You may also consider to use some real time module like https://www.pololu.com/product/2770 or https://www.adafruit.com/product/264 or https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview or any other RTC module you like/have.

Python datetime module can also be used to timestamp the events, this will eliminate the need for syncing or using external RTCs.


text:
Turning on led every half hour
How can I make my program so that every half hour LED lights on and work for 5 minutes and than go off and the process should repeat
I made code but it does not works. Can someone help me?
void setup() {
  pinMode(8,OUTPUT);

}
void loop() {
  digitalWrite(8,HIGH);
  delay(300000);
  digitalWrite(8,LOW);
  delay(1800000);

}

Whats the problem? what's happening? btw. this does shift 5min every 30min... you can try this: http://playground.arduino.cc/Code/SimpleTimer

When i run my code nothing happens.

First start with a smaller delay (a second or so) until you know it is working.

Test the LED: Connect it between +5v and ground with its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.
Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.
Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.

You need to make sure that the LED is connected with the right polarity, you need to connect the negative to Ground and the positive to the digital pin 8.
Try the led by connecting 3.3v and GND so you are sure that the led is not broken.

I see that the code is OK,
are you sure that the led pis is 8 ?
what is your input voltage ? (is it between 7 to 12 ?)
did you tried lower time values ? (like 1:2 minuts ?)
if you answer to all of these questions is "yes" then probably the arduino board is broken.