text:
How to power IR LEDs with arduino?
I need a circuit or something to power up IR leds as arduino only give 5v and IR leds needs 1.2V. Is there a way to make one arduino pin a power supply of 1.2 V code or something ?

You will get a better response if you provide a question. More specifically, if you show some of the code you need help with.

I am not asking here for any code , i need to control IR leds with arduino , am asking for the circuit

Typically, rational control of an LED sets the amount of current that goes through the LED, rather than setting its voltage.  You could add series resistors so that when the desired current is flowing through the LED, about 1.2 volts is across the LED and the rest (say 3.6–3.8V) is across the resistor.  (See Google images for typical circuits, and see various LED resistor calculator, eg the LED resistor calculator at hacktronics.com.)  It also is possible to use PWM to control LED brightness.
Note that if you have 3.6V across a resistor and 1.2V across an LED, you are wasting 3/4 of the power expended.  When LEDs are low voltage (ie, like 1.2V for your LEDs, vs. 1.6 for typical red or orange LEDs, vs 3+ V for white or blue) you can put several of them in series.  For example, put three of your IR LEDs in series, and calculate R so that 1.2 V drops across a resistor and 3.6 across the series of LEDs.  Also try four LEDs in series, and calculate R to drop 0.1 to 0.3 V.
Edit 1: Ignacio Vazquez-Abrams says, a little  obscurely, “Getting warmer. But this is a IR LED” and also “Pull up the datasheet for a IR LED. Read it carefully. The AVR can't handle one of the numbers”, perhaps in reference to IR LED current requirements.
Typical 5mm IR LEDs can handle several times more current than typical 5mm visible light LEDs.  For example, a typical green LED might be rated 30 mA max sustained current and 20 mA recommended, while a typical IR LED might be rated 100 mA max and 50 mA recommended.  Also note that 50 mA is 10 mA more than the 40 mA that most Arduino pins list as absolute max.  A sustained current of 40 mA or more in or out of an Arduino i/o pin may damage the processor.  If you want to drive a high-current IR LED, use an external driver (eg a transistor).  See eg the answer to How can I efficiently drive an LED? in Electronics SE, which shows dropping resistor calculations, constant current sources, etc. Also see links given in JYelton's answer to  Infra Red LEDs - Voltage Advice.
Treesrule14 points out “IR leds ... don't emit in the visible light range”, which is true; they emit infrared radiation, or heat.  Note, using an IR LED in a remote control usually is incompatible with controlling its average brightness with PWM; the pulses used in PWM would conflict with the pulse train in typical 36, 38, or 40 KHz IR control protocols.

Getting warmer. But this is a IR LED.

IR leds are  the same things as LEDs. They just don't emit in the visible light range. (look up electromagnetic spectrum and see that there is nothing special about visible light range if you still don't understand)

@Treesrule14: Pull up the datasheet for a IR LED. Read it carefully. The AVR can't handle one of the numbers.

That comment was so useful

@IgnacioVazquez-Abrams Can you please explain what you mean by both of your comments? I'm not quite sure what you mean (you're not giving enough context) and there seems to be some confusion. Thanks!

@AnnonomusPenguin: jwpat7 got it in their edit.

@IgnacioVazquez-Abrams, I moved up the paragraph about too much current


text:
Receiver xbee receiving data even if the Transmitter is not sending?

TX code:
#include <SoftwareSerial.h>

const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

SoftwareSerial   Xbee(10, 11);

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;
  while( i < length )
  {
    Serial.print(buffer[i]-48);
    Xbee.print(buffer[i]-48);
    i++;
  }
}

RX code:
const int MAX_LENGTH = 2;
char buffer[MAX_LENGTH];
char lineFeed = 2;

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

void loop() {
  int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
  int i = 0;

  while( i < length )
  {
    Serial.print(buffer[i]-48);
    i++;
  }
}

NOTE :
1- The Rx xbee is receiving data even if am not sending and even if the TX xbee is powered off
2- When i send data from the TX xbee id didn't get revived by the RX xbee
I need to solve both problems.
*** What i need exactly is to send serial data from my pc to arduino and send it wireless through xbee and then receive to the other arduino connected to my circuit

The reason that it is printing characters with no input is that the readBytesUntil function has a timeout. If no new characters are received for a certain amount of time, "Serail.setTimeout()" seconds, it will just continue with the code. the default timeout is 1 second.
The reason you are not receiving what you transmit (or at least a reason) is that the RX code does not read from an xbee, but reads from regular "serial".
I recommend you try something simple first to test the xbee's configuration, like having TX run this:
void loop(){
    xbee.println("Hello");
    delay(1000);
}

and RX run something to echo serial like this:
 void loop(){
     if(xbee.available()){
         Serial.print((char)xbee.read());
     }
}

And make sure you set up an xbee object an the receiving side first.

i already make a simple code for both TX and RX and it works fine i appreciate your answer but i need to know how to differentiate between regular Serial and Xbee because i am connecting the xbee to the hardware serial 0 and 1 of the arduino so in this case regular serial and xbee are the same ,

You can't differentiate between the PC and an Xbee if they are both using hardware serial. The standard serial can only go between two devices. If it worked with all three at all, its only because there was only one transmitter at a time. The random characters could actually be from hooking 3 serial devices together.

so why did they make a software-serial if its not gonna work for three devices at a time ?

can i add a diagram of what i need exactly so you can understand my problem ?

Using "Serial" for the receiver will work for a circuit as you have diagrammed because the second arduino does not connect to a PC; However, your diagram does not match the code you put up. The code (Both arduino's connect to PC) requires the use of multiple serial ports on each arduino, which means using software serial on Uno's.

source: Stack Exchange

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

sort: votes


text:
ULN2803 and common-anode RGB strip; how am I doing it wrong?
I'm not super-good with my electrical foo. But I've managed to get a ULN2803 wired up to give the +12v that my RGB LED strip needs. The strip has four connectors, RGB and common +12v.
My concern is that (I think) the Arduino is shorting out- while the Arduino processes my loop, the USB connection dies and the RX/TX LEDs light up.
Here's how I am wiring things. I'm currently powering the Arduino through USB, so when I say "power supply" I'm referring to the +12v supply I'm using.

power supply ground to Arduino ground, ULN2803 pin 9.
power supply +12v to 2803 pin 10, common +12v on LED strip.
arduino output pin 11 to 2803 pin 1
2803 pin 18 to green LED strip

So, that's my circuit. It works- the strip lights up. But again, I think it's wrong. How do I correct it?

"2803 pin 19 to green LED strip" ... What?

@IgnacioVazquez-Abrams it's actually pin 18 (corrected), note the goal is to light a RGB strip from the Arduino, so pin 18 is connected to the 'green' segment of the LED strip.

Is it a common ground LED strip (as per title) or common 12V LED strip (as per point 2 in question)?

@geometrikal it's common +12v (sorry, I got the title wrong), 'common anode'.

How is the arduino powered? From the same 12v?

@gerben arduino is (currently) powered via USB.

Just in case, try adding a resistor between arduino pin 11 and pin 1 on the ULN.

@gerben (finally) tried with and without a resistor. No difference. Accepting the main answer below with a comment- somehow I was drawing too much power on USB, but with a real power source it's okay.

The COM pin on the ULN2803 is for protection when driving inductive loads, which means motors, solenoid.  For an LED, nothing needs connect to COM.
The chip you are using is a low side driver.  That means it connects between the low side of the load (your LED) and ground.  When you drive +5 to the input pin, the transistors will conduct, connecting the output pin to ground.
So for your LED strip make the following connections:

Arduino output pin -> driver input, 1B = pin 1
driver output, 1C = pin 18 -> LED strip R G or B
+12 -> LED strip common power
ground -> GND = pin 9

Without the ground connection on the driver chip, no surprise that odd things happened.  There are diodes designed to protect the input and output pins (see chip data sheet).  Without the ground connection to the driver chip, the input protection diode might have been conducting back to the microcontroller output pin.

so, the only change you recommend is to not connect COM to +12v (or to anything). I did that, and initially it starts to work (say, with one color) but as I add more input/output pairs (R,G,B) it goes into "failure mode"- I don't know if it's shorting or going overvoltage on USB, but it's definitely dying. I can drive all three colors at a low PWM value (say, analogwrite 30) but anything further on all three colors causes the Arduino to fault out. That makes me think that I'm doing something very wrong.

The input pins on the driver can't draw enough current to exceed the ratings of the Arduino output pins.  More likely you are exceeding the rating of the 12 V supply or the LED's.  Start at DC without any microcontroller:  Just with wires turn each color on and off, one at a time.  Touch for a second the driver input to +5 and see that the LED lights.  Does the driver chip get hot?  If not, then plug it in and leave on a few seconds.  Still not hot?  Then try turning on 2 at a time, then all three.  Once you have shown that driver chip, power supply, and LED are okay, then go to code.

I spent an evening with my Fluke meter and a bunch of different debugging attempts. LEDs work fine on their own. I worked back up to arduino+driver and ensured the +5v and +12v lines were holding their voltage, then checked the amperage of the LED strip. (1.3A per color). That's actually more than the 12v+2A supply is rated for, but I was testing ONE color and it was failing. Ultimately it was the USB power source. I hooked it up to an actual +5V source and the Arduino quit "crashing". So it must have been drawing enough current to cause my OS to suspend power. Also, the USB hub died!

so basically, @jdr5ca, your hardware debugging process was perfect to figure this out.

Current measure mode -- highly overlooked feature of even the simplest DVM.  Better than setting things on fire.  1.3 A each? That is more than the rating of the driver chip, yes?

does some reading. 500ma for each pin, so 8 pins = 4 amps. Which means it'll barely work, and ideally I should underdrive one color (3 pins for two colors, 2 pins for remaining color).

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


text:
What's the difference between a clone and a counterfeit Arduino?
I've been hearing a lot about clones and counterfeits. What are the differences between the two?

Price is the main difference.

and quality is another issue

The difference is simple:
Clones don't say "Arduino," where counterfeits do
If I were to create 200 boards all labeled "Arduino UNO R3," it would be a counterfeit. If I were to call them "Happyduino," it would be a clone.

Note: You can still write Happyduino (Arduino Compatible) on your product. Here's a quote from the Arduino FAQ section

Not okay:

Arduino Xxxxxx
Xxxxxx Arduino
Arduino Compatible Xxxxxx - use "Xxxxxx (Arduino-Compatible)" instead

Okay:

Xxxxxx for Arduino - products that work with official Arduino boards    (e.g. shields or kits)
Xxxxxx (Arduino-Compatible) - variations and clones which are    software and hardware compatible

Note that while we don't attempt to restrict uses of the "duino"
  suffix, its use causes the Italians on the team to cringe (apparently
  it sounds terrible); you might want to avoid it. (It's also
  trademarked by a Hungarian company.)

I have a "Arduino" lying in front of me and it definitely a cheap clone. Nothing hints that it is not the original thing other than visual aspects as layout/color/silk screen font/... (and the brand name in a tiny print in a corner of the PCB)

I understand the "Happy" part, but I guess I miss the point you're trying to make.

@jippie what he's saying is, you can use the "duino" in your naming structure without trademark/copyright issues, so Happyduino is ok, but the word Arduino itself is not, except as detailed with "for Arduino" or "Arduino compatible"

I guess one key point is that if they say "Arduino" very directly in the name, they are giving the impression to the customer that it was actually made by Arduino, with the quality assurance that that would imply.  But if you stick the word "Arduino" off in a phrase AFTER the title, or if they only use the "duino" suffix,  then it is clear to the customer that this is made by a third company that is only promising that it will work compatibly with the original Arduinos.  Makes me glad- I am about to buy a few inexpensive chinese MEGAs and they are honest about it, so no guilt for me.

A clone is an exact or almost exact replica of an original Arduino board, with a different branding.
A derivative is a board based or inspired by Arduino boards, with some specific addition or modification (different layouts, built-in sensors...)
A counterfeit is a clone of an Arduino board, with the same branding of an Arduino board.
More info on an article on the Arduino blog.

So is there a difference in the functionality?

A counterfeit will strive to give the very same functionality. As for clones and derivatives, I think it depends on manufacturer's choice.

Quality of the passive components (such as reset buttons that stick), poor/cold soldering that fails, misaligned connectors, etc are the hallmarks of counterfeits.


text:
Value of the counter collide on my lcd while decreasing. How can I remove it?

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);
int visitor=0;  //variable for counting visitor number

unsigned long timer_1,timer_2;  //variables for recording time for ir_1 and ir_2

void setup() {
   lcd.begin(20,4);
   pinMode(A0,INPUT);
   pinMode(A1,INPUT);
}

void loop(){
 lcd.setCursor(0,4);
   lcd.print("visitor=");
   lcd.setCursor(8, 4);

   lcd.print(visitor);

   if(digitalRead(A0)==1 && digitalRead(A1)==0)
  {
    timer_1= millis();
  }
  if(digitalRead(A0)==0 && digitalRead(A1)==1)
  {
    timer_2= millis();
  }
  if(timer_1>timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor+1;
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;
  }
 else if(timer_1<timer_2)
  {
   lcd.setCursor(8,4);
   visitor=visitor-1;
    if (visitor<=0)
  {
    visitor=0;
  }
   lcd.print(visitor);
   delay(2000);
   timer_1=0;
   timer_2=0;

  }

}

Two IR sensors are placed in A0 and A1.
While the value of visitor is decreasing from 10 to 9 the LCD is showing 90 because  the '0' of previous 10 is here. How can I remove it?

A simple option would be to call lcd.clear() at the start of loop(). That will clear the entire LCD display. Everything else should work fine because it looks like you're outputting the entire display contents every time round.
Alternatively, you could remove the extra digit by printing a space over it, e.g.:
if (visitor < 10) print(" ");
lcd.print(visitor);

If visitor is a 1-digit number (i.e. less than 10), it will output a space at the start, getting rid of any underlying digits leftover from a previous iteration. If you want the number to be left-aligned then you could print the space after the number instead.

lcd.clear(); is a better option. thanks for helping @peter


text:
Stop servo when enter 0
I am trying to stop servo motor from rotating when I enter 0 in serial. The code is below. Can someone please help?
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int state;
int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin (9600);
}

void loop()
{
  if (Serial.available () > 0)
  {
    state = Serial.read ();
    if (state == '1')
    {
      for (pos = 0; pos <= 180; pos += 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);
      }
      for (pos = 180; pos >= 0; pos -= 1)
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);      // waits 15ms for the servo to reach the position
      }
      if (Serial.available () > 0)
      {
        state = Serial.read ();
        if (state == '0')
        {
          myservo.write ('90');
          delay (300);
        }
      }
    }
  }
}

Initialize state to 1, don't overwrite with value from Serial, but set to 0 when Serial reads 0.

From the code you posted it looks like you have the right idea but you've nested the 'IF' statements causing the check for '0' to only happen if you send two bytes and it will only go to 90deg when you send '10'.  The loop section should look more like:
if(Serial.available()){
    state = Serial.read();
    if(state == '1'){
           Make motor move;
    }else if(state == '0'){
           Make motor stop;
    }//end of elseif
}//end of if


text:
Unable to read the IC Card UID
I have a RFID module using NXP RC522 chipset.

I have no idea that is it correct the module using 27.120 mHz

And I have 4 IC card,

A) 0005302176, (Blue color tag, come with the RFID module)
B) 0008846830 134,65006 (White card, come with the RFID module)
C) 0004189112 063,60344 (White card)
D) White card, no number print on the card. Only this card UID can be read.

Here is the pinout

Which I connected to Arduino UNO R3

     RFID         UNO R3
(Pin Name, Pin)    (Pin)
SDA        1        10
SCK        2        13
MOSI       3        11
MISO       4        12
IRQ        5        -No Connect-
GND        6        Ground
RST        7        9
3.3V       8        3.3V

PS: I am using this library, and this example.
PS: The serial return this information MFRC522 Software Version: 0x91 = v1.0

Can you clarify what the problem is please?

Why I can read 1 card UID only, but others three cards UID unable to read. PS: the blue tag was come with the module, but still can't read UID, am I something go wrong?

It's probably the fault of the cards, they are very cheap and I have had a few with dead cards. You seem to have a whole pack of dead cards.
You could try with a contactless payment card, transport card, or staff access card from work.

@unknowndomain, I had tried my two staff access card. These card also printed numbers, and I have 6 white cards (both can read UID and both nothing printed numbers). Could anyone can answer me that the module should able to read the cards which printed number, or module never read the card UID except white card. Or someone answer me that, I should enter the SN (Maybe on chip/card) for reading Card UID.

I presume you are aware that different cards use different technology and only some are compatible with this reader, that said the ones that came with it should work.

@unknowndomain, I just mention in the post. The cards (blue tag & IC card with number) are not readable, but another card using same technology (base on e-shop description) can read the card UID. If there are never success read the UID, it means reader is not work. Normally, is it should read the UID and never necessary to provide any SN/Key/code printed on chipset or cards ??

Little unclear what you mean, but I would take it to mean that this unit is defective, because I am using the code from the Arduino.cc website which links to github and that works fine with the cards provided, so something is faulty because one reader can read them and the other not.

The question itself does not state a question. But it appears that the cards are "sometimes" working? It could be the cards or reader that are defective (depending on if one card will always work). And be sure to use an external power source (not using one often leads to "random" behaviour. The code is from a library and should be fine (given the fact that it read some cards).

Check your power source, if you are powering the module from arduino/USB=>part or something like that, there can be not much power for the module.
Also you can try powering it 5v (not 3,3 as they should be powered by reference).
In my case I have had problems reading some types of cards, and I have solved that problems by giving better power supply, also higher power supply than in reference for some of the cards.
"By magic" the cards that were not working started working as a charm.
Also you should check if the cards you are using are all  ISO14443 A
Only that kind of cards is compatible with that reader.
So if you got type B, or other type of ISO cards, that will not be working.
Some of them may use different frequency, there is a bunch of standards around.
Also as said before the cards can be damaged, or could be corrupted if you tried reading UID while writing to the card, the problem is known , and in that case you can damage the UID.
I hope it helps you.
cheers

The MFRC522 reader is for 13.56 Mhz tags; these tags normally dont have the UID printed on them, in my experience. 125khz cards, however, usually have their SNs printed on them; as you can see all the cards that didnt work, have a 10 digit SN that seems to follow the same pattern. These card SNs can't be read by the MFRC522, as they follow a different protocol. When you buy a tag/card, make sure that its a 13.56 Mhz tag (look for Mifare tags), if you want the MFRC522 to be able to read it.


text:
Use potentiometer to control motor's speed
Following the arduino starter kit, one of the projects uses a push button to on/off a motor.
In the end they suggest to try to use a potentiometer to control the speed of the motor.
I already did it, but I am not sure how I should use the capacitors(I placed one with the pot).
In one of the previous examples they used 2 100uF capacitors(one for the pot. and another for a servo motor) and I was wondering if this would be the same case.
This is my circuit:

The code:
const int POT_PIN = A0;
const int MOTOR_PIN = 9;
int motorSpeed = 0;
int potVal = 0;

void setup()
{
  pinMode(MOTOR_PIN, OUTPUT);
}

void loop()
{
  potVal = analogRead(POT_PIN);

  motorSpeed = map(potVal, 0, 1023, 0, 255);

  analogWrite(MOTOR_PIN, motorSpeed);
}

Previous example with capacitors:

Code:
#include <Servo.h>

Servo myServo;

int const POT_PIN = A0;
int potVal;
int angle;

int alpha = 0.8;
int rawReading;

void setup()
{
  myServo.attach(9);

  Serial.begin(9600);
}

void loop()
{
  rawReading = analogRead(POT_PIN);
  potVal = alpha*potVal + (1-alpha)*rawReading;
  Serial.print("potVal: ");
  Serial.print(potVal);

  angle = map(potVal, 0, 1023, 0, 179);
  Serial.print(", angle: ");
  Serial.println(angle);

  myServo.write(angle);
  delay(15);
}

You shouldn't need capacitors with either in this case. Perhaps if you showed the "previous example" we could explain why they were needed there.

I added the info about the other example.

I don't see any use for that capacitor at the potentiometer. I would probably add one in parallel to the 9V battery.

As far as the capacitor for the potentiometer, it is probably there to keep the analog value smooth to avoid small amounts of interference (chaining 0.0048828125 of a volt) that would cause the motor to seem a little jumpy @Gerben. A software solution would work fine for this purpose, too.

@AnnonomusPenguin in that case I'd expect an smaller cap between ground and the output of the potentiometer.

Ah, now I see. Your confusion in this case is perfectly understandable. They threw a couple of capacitors into the circuit without explaining why they were added in the first place. In order to understand why capacitors were added you need to go a little deeper into electronics theory, specifically capacitance and inductance, what they are and how they work.
Inductance is, to put it succinctly, resistance (not related to the resistance in resistors, measured in ohms) to change in current by sacrificing or absorbing voltage. If current is 0, then inductance will try to keep it at 0, if at 1A then it will try to keep it at 1A, and so on. Inductance is caused by the magnetic fields generated by electricity flowing through a conductor, and hence every conductor exhibits some measure of inductance. (Coils have much higher inductance though, since the magnetic fields of the loops reinforce each other. And a "core" material such as ferrite or iron intensifies the magnetic field.)
Now, this isn't a large problem if your conductors are short, but as they get longer their inductance can cause power issues. Sudden power demand increases are unable to be accommodated because the supply can't put the increased current through the inductance quickly enough. This is where capacitance comes in.
Capacitance is resistance to change in voltage by sacrificing or absorbing current. When something tries to reduce the voltage either through power consumption or because of high-speed switching, capacitance holds the voltage as close to constant as it can by pulling or dumping electricity out of or into the circuit. Capacitance is caused by charges between two conductors attracting each other through a non-conductive material.
So what happens is that a circuit needs bursts of power to work, and if the wires connecting the supply to the circuit have too much inductance then the circuit will be starved of power. We balance this by placing a capacitance close to the circuit so that it can supply power to the circuit for the short time while the supply is busy overcoming the inductance of the wires.
The servo, being a mechanical device, needs a decent amount of power. We put a bulk capacitor near it on the supply lines to help provide this power. The analog input connected to the potentiometer needs much, much less power, so the inductance there isn't a problem and we forgo the capacitor there.

@blacai A pity the long explanation, while it contains some truth, is irrelevant. A 100µF capacitor would have negligible impact in maintaining power (as a simple calculation of the energy stored would show). Maybe if it was 10,000µF. The capacitors serve to reduce interference on the supply, which could affect the microcontroller, but you would be hard pressed to find any difference if you omitted them.

In your opinion the previous example with 2x100µF, those are not needed?

Do you want to use a pushbutton to control the speed of the motor?
Then one way to go would be to increment a variable by say 10 every time the switch is pressed.
In pseudocode:
// In the setup section:
speed =0

// In the main loop:
Read pushbutton
if different from previous state then speed = speed + 5
if speed > 255 then speed = 0 // Go back to zero if over 255

analogWrite(pin x, speed)  // This sets the PWM value

If you want to have a more fancy control then you could increment speed every second by 5 while the pushbutton remains pressed, and also go back to zero speed in small decrement instead of in a single step.


text:
Breakout vs Shield
I would like to extend my arduino uno with WIFI and I am checking different options.
These are:
Adafruit-CC3000-Breakout-with-Onboard-Ceramic-Antenna
Arduino WiFi Shield (integrierte Antenne)
Viewing the price, obviously I understand that the shield will have more functions, I think also it is more "friendly" for programming and the breakout requires more low level code(I am not afraid of it...)
I already have an arduino yun but it is busy with a project, so I need something for the uno.
For what kind of projects could be better each of them? and what are the main differences between a shield and a breakout?
Also in the future I would do some projects with gsm, so this question could be similar ... gsm shield vs breakout.

Please note that stacking multiple shields sometimes results in conflict over their pin usage. When using regular breakout, can can connect the wires to any arduino pin you want, preventing these kinds of problems.

If you prototyping for a device intended for production then use breakout board with supposed WiFi module. Also if space is constraint then shield might be problem. For a hobby system use WiFi shield, which uses rather complicated circuit with AVR32 MCU, but you just plug-in and uses prooved libs. For production MCU would mean one more firmware flashing, upgrades, maintainance and higher price - from my point of view useless.

Thanks, I think it is better for me the shield, because I am novice and still learning. I will not develop a productive product.

Shields are in a form factor suited for direct attachment to the Arduino, but have fixed functionality for their connections. Breakout boards require more wiring work, but allow you to connect to any appropriate pins.

Could you please explain a little bit more about the communications protocols? Because I saw in this breakout " It uses SPI for communication (not UART!) " How does the shields communicates?

A breakout board usually has the sole purpose of making a single chip (gross generalization here...) available to the experimenter by "breaking out" its signal lines on to dedicated pins - header pins, for instance. It is only large enough for the chip and the printed circuit wiring to do this, and seldom adds any function beyond what the chip itself provides.
A "shield" is a larger board that usually plugs directly onto an Arduino board, matches its form factor, and is built for a dedicated more complex function, like a complete GPS system or cellular communication system (although some shields are left mostly blank to provide you the space to build your own device). They probably have several chips engineered and built into a complete plug-and-go sub-system.
One is to learn to use a chip or other device without having to solder up your own board, especially with surface mount devices. The other is a ready-to-go system building block.


text:
Basics with DHT11
I just bought the sensor DHT11 and trying to test it with the library code provided by the IDE, but I always get the same error on .read() . Code -2
/*####################################################################
FILE: dht11_functions.pde - DHT11 Usage Demo.
VERSION: 2S0A

PURPOSE: Measure and return temperature & Humidity. Additionally provides conversions.

LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
GET UPDATES: https://www.virtuabotix.com/

  --##--##--##--##--##--##--##--##--##--##--
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ## DHT11 SENSOR ##  ##  ##  ##
  ##  ##  ##  ##  ##FRONT ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  --##--##--##--##--##--##--##--##--##--##--
      ||       ||          || (Not    ||
      ||       ||          || Used)   ||
    VDD(5V)   Readout(I/O)          Ground

HISTORY:
Joseph Dattilo (Virtuabotix LLC) - Version 2S0A (27 May 12)
-Rewritten to with more powerful Versalino functionality
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.5 (11/11/11)
-Made Library Arduino 1.0 Compatible
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.0 (06/11/11)
-Fixed bugs (squish)
Mod by Rob Tillaart - Version 0.3 (28/03/2011)
Mod by SimKard - Version 0.2 (24/11/2010)
George Hadjikyriacou - Original version (??)
#######################################################################*/

#include <dht11.h>

dht11 DHT11;

void setup()
{
    DHT11.attach(2);
    Serial.begin(9600);
    Serial.println("DHT11 TEST PROGRAM ");
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHT11LIB_VERSION);
}

void loop()
{
    Serial.println("\n");

    int chk = DHT11.read();

    Serial.print("Read sensor: ");
    switch (chk)
    {
        case 0: Serial.println("OK"); break;
        case -1: Serial.println("Checksum error"); break;
        case -2: Serial.println("Time out error"); break;
        default: Serial.println("Unknown error"); break;
    }

    Serial.print("Humidity (%): ");
    Serial.println((float)DHT11.humidity, DEC);

    Serial.print("Temperature (°C): ");
    Serial.println((float)DHT11.temperature, DEC);

    Serial.print("Temperature (°F): ");
    Serial.println(DHT11.fahrenheit(), DEC);

    Serial.print("Temperature (°K): ");
    Serial.println(DHT11.kelvin(), DEC);

    Serial.print("Dew Point (°C): ");
    Serial.println(DHT11.dewPoint(), DEC);

    Serial.print("Dew PointFast (°C): ");
    Serial.println(DHT11.dewPointFast(), DEC);

    delay(2000);
}

And this is my ouput:
DHT11 TEST PROGRAM
LIBRARY VERSION: 2S0A

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

The wiring:
-left pin: 5v
-right pin: gnd
-middle pin: 5v - digital2 - through 10kO resistor

UPDATED:
I found a library that works. I also changed the wiring because I found out the sainsmart dht11 switches the pins:
-left: signal with 10kO and to 5v
-middle: 5v
-right: GND
Now just a question.
What is the difference between these two dht11 sensors.
Dht11 basic
dht11 with board
The one from sainsmart has a piece of circuit I don't know what it is.(I have a lack on electronics I try to fix step by step...)
It is a resitor, capacitor? it says 103.
How does this affect to the wiring?

In the code you linked, it says that you are reading pin 2 for input, but on your image, your wire is in pin 3.

Hi, thanks for the answer. You are right. It was a problem in the wiring. After fixing it I was still getting errors. The problem was the library version, that was giving some problems with read response for dht11 sensors

The DHT11 sensor is available as-is and integrated on a break-out board. The break-out board shows following differences:

the order of PINs is changed, e.g. in one version: 1 -> signal, 2 -> +, 3 -> GND (left-to-right, pins down, looking at the front)
the unused pin is not connected
the board already has a 10 KOhm pull-up resistor connected

Thus, when you have a DHT11 on a break-out board you have to adjust schematics that use it as-is - e.g. in this example you have to remove the external pull-up resistor and connect the pins in the correct order.
Be aware that there may be different versions of DHT11 breakout boards available - i.e. ones where the order of pins is different. You can look out for PIN markings like S (-> signal) and - (-> GND). Also, you can look at both sides of the breakout board to trace the connections.
The resistor usually comes as SMD on such a board - and if it has a marking it uses a special code. For example, 103 means 10 * 10^3 Ohm, i.e. 10 KOhm.
The adafruit DHT library comes with an example sketch that prints the sensor values over serial.

It seems you wiring is ok, although I think you already have pull-up resistor on breakout board (look for a small 103 resistor).
Maybe you can try another library for DHT?
I have used one made by adafruit (https://github.com/adafruit/DHT-sensor-library) and everything worked just fine.
Regards,
Ian

Thank you for the answer, but it didn't work. I tried with and without resistor(I saw the 103 in the dht11's board). Also tried with the adafruit library and then I get the "Failed to read from DHT sensor!" error. I debugged the example and readHumidity readTemperature get errors on reading. Maybe my sensor is broken. I ordered a new one to check...

The DHT11 board + sensor already has the resistor. I use those with arduino directly, no extra components required.


text:
Atmega168 interrupt error handling
I'm using an Atmega168 in a project that involve using the ISRs from multiple sources. I have an ISR hooked up to an external button and a timer, to use it as a reset button after a predetermined hold time.
I'm also using an ISR hooked upto UART. The UART is connected to an external Linux based SoC. Upon receiving specific commands from the linux machine, the atmel will perform certain functions.
In very rare occasions, the linux hangs up during tranmission and is always sending out the UART commands. This saturates the ISR and it also prevents the reset button ISR to function.
Although this happens rarely, I would like to take measures for this. As far as I know, there are no way to set priority in avr ISRs. So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?
EDIT:
I think the problem arises when the linux machine sends an empty string to the atmel.
the UART_receive() on the atmel gets stuck at: while ( !(UCSR0A & (1<<RXC0)) );
Any way I can avoid this?
unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

What interrupt are you using that has lower priority than the USART interrupt?

sorry if I wasn't clear. But there is no way I can set priorities. All the ISRs have equal priority.
I'm using : (INT0_vect + TIMER1_COMPA_vect) for the push button, and USART_RX_vect for UART.

No, they don't. The ISR priorities are given by their addresses. Both of the button ISRs have priority over all the USART ISRs.

It's hard to recreate the situation, but you are saying that even if the UART ISR is saturated with calls, the button isr and the corresponding timer should still work on it's own?

Provided interrupts aren't enabled during the ISR, yes.

that's my problem though. The UART ISR is always being called and never allows the button ISR to work. I need to find a way around this.

Interrupts are disabled when an ISR is called. Are you saying that the ISR explicitly enables interrupts?

If this only occurs occasionally you could try using the watchdog timer. If the watchdog timer times out, it will reset the entire MCU. You'd reset this timer somewhere in the main loop. So as long as the loop doesn't take more than the timeout amount, everything will continue to work as normal. But when the MCU is "hanging", the WDT will reset it.

I've updated my question. I think I know where the problem is.

Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.
Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".

while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received

The comment hits the nail on the head.
It'll wait forever, but it's so because it has been "designed" in such a way.
You've got 2 options:

Re-think your "design":

Do not make your UART wait for an n-amount of characters. You could buffer the received characters, and handle/clear the buffer. There should be a lot of info about this on the web.

Quick and dirty fix:

Add a timeout to the waiting.
for (unsigned int timeout = 16000; (!(UCSR0A & (1<<RXC0))) && timeout > 0; timeout-- );

This isn't very efficient, but should work.
Be sure to check for what reason the waiting stopped (if the timeout ran out, or if you actually received something), to avoid pushing in nonesense that's in the UDR0 at that moment (when you timeout).


text:
if/else statements without comparison operators and curly braces
I recently came across this code in a tutorial. The code works, but this form of syntax seems to differ quite a bit from https://www.arduino.cc/reference/en/language/structure/control-structure/if/, as it's lacking comparison operators and curly braces for statements. Can someone please run down why this works?
for (int i = 0; i < 15; i++)
{
lcd.setCursor(i, 1);
if (pressed[i])
  lcd.print("X");
else
  lcd.print(" ");

if (justpressed[i])
  digitalWrite(led, HIGH);
else
  digitalWrite(led, LOW);
 }

Arduino uses C++ programming language with specific libraries and .ino file conversion to C++ http://www.cplusplus.com/doc/tutorial/

About the missing conditions, e.g.:
if (pressed[i])

If is supposed to be a boolean, this is the prefered way, as long as the boolean has value zero (0) when false and nonzero when true. It is the same as writing:
if (pressed[i] != 0)

It is not usual to do this for integers, only for booleans.
About the brackets: If you have only one statement the brackets can be omitted. But it is quite a bad programming practice, since sooner or later you add a statement, without the brackets added and you have a bug introduced.
If you really want to shorten it than instead of
if (justpressed[i])
  digitalWrite(led, HIGH);
else
  digitalWrite(led, LOW);

use
digitalWrite(justpressed[i] ? HIGH : LOW);

This is called the Ternary operator.
update
Using the remark of wondra but with the ternary operation your code can be
for (int i = 0; i < 15; i++)
{
    lcd.setCursor(i, 1);
    lcd.print   (     pressed    [i] ? "X"  : " ");
    digitalWrite(led, justpressed[i] ? HIGH : LOW);
}

Just for fun of it, even the printing if/else can be much shortened: lcd.print(" X"[!!pressed[i]]);

@wondra right ... but most have to read a few times to see why it works.. I would it change to lcd.print(pressed[i] ? "X" : " "); probably.

Sadly, fun =/= smart in most cases. Fully agree - if the code is to be ever maintained one should stick to the most straight-forward solution (whatever that is it expected to be for the poor fellow doing the code maintenance).

True, in the organization I work for the ternary operation is allowed, but only in trivial cases like that, if bigger expressiosn are taken into account the if/else should be used. Btw; to make it shorter you can probably even put everything in the for statement (not loop).

It's actually called the "Conditional Operator". It just so happens to be the only ternary operator.

@wondra I don't know arduino, but if this is really C++ like another comment said then you'd be passing a char instead of a string to lcd.print(). It's not a problem if lcd.print is a polymorphic method that is also made to work with chars, but that's not necessarily the case, so that could be a bug. Strive not to write simple ideas in a complex manner, but to write complex ideas in a simple manner.

Small nit-pick: shouldn't it be equal to saying if (pressed[i] == 1), not if (pressed[i] != 0)?

@McMastery Actually it's not the same ... there is a convention (not always true, especially in C), that a boolean FALSE value is 0, and a TRUE value is non zero. In your case, if TRUE would be 255 it would go wrong.

@MichelKeijzers Ah, sorry. I thought the convention was the other way around for some reason

if (something) is the same as if(something!=0), if condition is a non-zero value, it is considered as fulfilled condition, read about the Conditionals - The true or false story
For single line statements you don't need to use curly braces. But using the braces makes the code more readable and the code is less prone to errors

It's worth noting that curly braces on single-line statements can definitely help prevent some insidious bugs: remember Apple's famous SSL bug? Curly braces almost certainly would have avoided that, or at least made it more clear where the error was.

@ke4ukz I think the fear of repeating that SSL bug is over stated. If you're going to use an inline if statement, do it ... in... line. Don't put it on a new line. if (someEarlyExitCondition()) return; never hurt anyone, if it was all in one line. The new line+indent that people put whenever they use inline if statements always confused me. It's just so unnecessary!

@Alexander I agree: inline for inline, curly braces for indenting/multiple lines

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


text:
Windows stops recognizing Arduinos
I've just got my first Arduino Pro Mini and a USB to TTL chip. When I try to upload the program I get the message The uploader process failed followed by
avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.
and a bunch of lines like

avrdude: ser_drain(): read error: The device does not recognize the command.
avrdude: ser_send(): write error: sorry no info avail
avrdude: ser_recv(): read error: The device does not recognize the command.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48
avrdude: ser_send(): write error: sorry no info avail

with 10 attempts after which nothing comes from avrdude and I can't upload nor get Arduino's visible in port choice menu all the time until the Windows 7 boots again. I can upload to my Arduino Uno with no problems before I try the ttl chip. TTL chip also shows up in the port menu before trying to upload, with correct name next to the port number. I installed drivers I found on a official site that sells the chip that looks just the same as mine, before I did that it wouldn't show up in the port choice menu at all. Is there any way to reset whatever it is that is preventing me from uploading to Arduinos so I don't have to restart my computer every time it happens? I managed to upload one program to the Arduino Pro and it's working fine but after a couple of hours, when I tried again, it didn't work. Maybe it would be of some use to say that I left my pc on sleep with the TTL chip plugged in and powered by the usb. My guess is that this chip is defective and was near it's life end when I uploaded so now it's just confusing the driver to the point where Windows decides to block the driver for the session.

Did you try to close arduino IDE and then reopen it? Did you try to unplug the USB-to-TTL converter and plug it again? Did you try close Arduino - unplug - plug again - open Arduino IDE?

@frarugi87 Yes, of course. I've figured out how to fix this and much more, answer coming soon ;)

i see this question a lot, so it would be helpful if you could post an answer...

@dandavis I posted it that day but for some reason it didn't appear. It should be ok now.

After a couple of hours I figured out what was happening so I will write all my analysis here for anyone having some of my problems.
First, a list of my components:
-USB TTL ship, used to upload programs to Arduino Pro. The one on the picture on instructables dot com /id/Usb-to-SerialTTL-adapter/, and used that driver.
-Arduino Pro. Chinese copy, red board just like Sparkfun's. 328p chip @ 5V = 16mhz.
-A board very similar to this one. It has a chip with FT232 written on it, also FTDI in bold letters.

The big USB TTL pcb I was using has 5 output pins: 3v3, 5v, TX, RX, GND. Turns out this is not enough to program Arduino Pro as you need one more pin. If you don't connect this pin, avrdude just gets stuck after opening the COM port and waits indefinitely/until you kill the process. To even be able to see this USB TTL chip in Windows, you need to download a driver from the website(first link) and my guess is that the driver is buggy since it won't exit the process when it encounters this type of error, further leading to suspicious/dangerous behaviour which results in Windows completely shutting down all COM ports until next restart.
To get this pin(it's called DTR/GRN), I borrowed the other chip(3rd) and I connected it regarding to this scheme:
I also had to download a different driver for it, I don't remember where I downloaded it from but it's called CDM21226 driver, when you install it it says FTDI driver installed.
Now my uploading was getting stuck no more, however after the first successful upload to my Arduino Pro the upload process would get stuck in the part where it is burning the program, if you turn verbose option in Arduino IDE on, you can see something like Writing: [#######              ].
It turns out this driver was faulty too, as I uninstalled it and when I installed it with the very same setup as before it worked seamlessly ever since. It also took me some time how to uninstall a Windows driver without using Device Manager because it wouldn't show up there - no device attached to it.
To do that open Command Prompt as admin and type pnputil.exe -e to get a list of all drivers. Among them will be one called FTDI and that's the guy, in my case he was called oem51.inf. To delete him, type pnputil.exe -d oem51.inf, or add -f before -d to force deletion - in my case it kept saying device is busy so it required this drastic measure. Change 51 to the number you have above your ftdi driver. After this just install the driver again and everything should be fine, even without reboot.
Phew...
So much work to get a simple program burned to Arduino Pro. Hope you have less trouble with it than I did.

If someone can edit the first link that would be great since I am not allowed to put more than two links in my post :/


text:
Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();
I am trying to connect my Arduino Pro Mini 3.3V to an nRF24L01 transceiver and cannot see what I am doing wrong. I've checked my wiring a million times because the problem hints there is an invalid or no connection between the Arduino and the transceiver. I have the following pin connections:

Arduino --------------- nRF24L01
--GND ------------------- GND
--VCC ------------------- VCC
---D9 --------------------- CE
--D10 -------------------- CSN
--D13 -------------------- SCK
--D11 -------------------- MOSI
--D12 -------------------- MISO

I am using the following sketch
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9, 10);

const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0C2LL };     //Addresses to send/receive

void setup()
{
  printf_begin();
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, pipes[0]);
  radio.printDetails();
  radio.stopListening();
}

void loop()
{
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);
}

I have no clue where I am going wrong. This setup works well on my Uno, however I cannot replicate it on the Arduino Pro Mini. Can anyone tell me if I am doing something super wrong that would prevent this from working? I'm all out of ideas. Appreciate any help in advanced!
Update:
I forgot to copy and paste the output from printDetails():
STATUS  = 0x00
RX_DR=0
TX_DS=0
MAX_RT=0
RX_P_NO=0
TX_FULL=0
RX_ADDR_P0-1    = 0x0000000000 0x0000000000
RX_ADDR_P2-5    = 0x00 0x00 0x00 0x00
TX_ADDR = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR   = 0x00
RF_CH   = 0x00
RF_SETUP    = 0x00
CONFIG  = 0x00
DYNPD/FEATURE   = 0x00 0x00
Data Rate   = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power = PA_MIN

Sorry guys quick update: forgot to copy and paste the output from printDetails(): STATUS   = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1  = 0x0000000000 0x0000000000
RX_ADDR_P2-5  = 0x00 0x00 0x00 0x00
TX_ADDR   = 0x0000000000
RX_PW_P0-6  = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA   = 0x00
EN_RXADDR  = 0x00
RF_CH   = 0x00
RF_SETUP  = 0x00
CONFIG   = 0x00
DYNPD/FEATURE  = 0x00 0x00
Data Rate  = 1MBPS
Model   = nRF24L01
CRC Length  = Disabled
PA Power  = PA_MIN

The printdetails output indicate bad connection or faulty module. Check your wiring and try again.

Aside from the fact your program does not look like this one, I would venture to guess that you are trying to use the address of the pointer to the first letter in your character string.  Try it again w/o the  '&'.  I think that way you will just use the pointer to the first letter in your character string.

Whenever you get an all zeros output from the printDetails() function you can bet you are having a communication issue between the Arduino and the nRF24 module.
Start by checking your connections.
Check your connections again, using a multimeter to ensure continuity.
Check your connections again (no, I'm not joking).
Finally add a capacitor (anything between 1uF and 100uF will do) between the VCC and GND pins of your nRF24 module: those modules are pretty sensitive to voltage fluctuations and they are subject to current consumption spikes at startup.
Pair that with a possibly not state of the art voltage regulator (especially on cheap Arduino clones) and you end up with a non responding nRF24 module: the capacitor will provide the extra juice whenever it's required by the radio module.
This is such a common problem that I started soldering the capacitors directly onto the modules to save breadboard space!


text:
NeoPixel setPixelColor works only in for loop
I am working with a NeoPixel RGB led and have gone through various tutorials but I have a question regarding the setPixelColor().
If I do not have my setPixelColor() and show() inside of a for loop it will not work.
This works:
void holoLight(uint32_t c){
  for(uint16_t i = 0; i<2; i++){
    holo_pxl.setPixelColor(i, c);
    holo_pxl.show();
    delay(2500);
  }
}

This does not:
void holoLight(uint32_t c){
    holo_pxl.setPixelColor(1, c);
    holo_pxl.show();
    delay(2500);
}

I am sure it is something specific to the language or execution but would love some clarifications, thanks =)

Please edit question and say what happens -- ie what colors appear, which lights turn on or off -- rather than ambiguous "works" and "not work" descriptions.  Also, to do the same thing in the second version as the first (except for delays) add holo_pxl.setPixelColor(0, c); and report results.

Please show the part of the code that initializes holo_pxl and describes your neopixel device better (is it a matrix? how many LEDs does it have?)

Out of curiosity, have you tried holo_pxl.setPixelColor(0, c);instead of holo_pxl.setPixelColor(1, c); in the second example?

@jfpoilpret you were spot on, I can't believe I skipped something so simple.  Thanks for the help =)


text:
Is a variable declaration inside a loop static declaration or dynamic?
while(condition){
    Object object = new Object();
}

So my question is, will each iteration would create a different object in different memory location or it will overwrite the once created object every iteration.

You are strongly encouraged not to use dynamic memory allocations. Due to the low ammount of memory you will get into trouble if you are not careful. Try to avoid calls like new and malloc. instead you should use Object object(args); to initialize your object in the loop. It will be disposed at the end of the loop automatically.

This code is not proper C/C++, it should be Object* object = new Object(); otherwise this would not even compile.

It will be created every iteration.
Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:
Object object;

Also, if you do not delete/remove the object at the end of each while condition (with the delete keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).
What I also miss in your code is the pointer (*, because the new keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:
Object* object = new Object();

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable
Object object;

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).

maybe also mention cleaning up the object when using new

@ratchetfreak I already put a notice for that, but I extended the comment slightly.

Did you perhaps mean memory leak instead of memory breach? First time I hear "memory breach", google does not seem to know what a memory breach is neither.

@wondrea memory leak is indeed a better word, I change it

Dynamic object creation is using operator new. Operator new creates object on heap and the object exits until you delete it with operator delete.
Object object creates object on stack. It will be removed from stack when the variable goes out of scope on the end of the block.
Some classes have copy constructors. If your Object object = new Object() compiles, then the class Object has copy constructor. The code creates an object on stack, then creates an object on heap and then copies it's content into object on stack. The object on heap stays and you have no pointer to it to delete it. The program soon crashes on low memory.
Static variables have keyword static. If you would have static Object* object = new Object(), then the pointer is created on global level and the object on heap is created and assigned only ones.
EDIT:
I tested this. Class String has a copy constructor, but the Arduino compiler doesn't allow String s = new String(a). It can be misleaded with String s = *(new String(a)) (a is some variable).

reason for the down-vote?


text:
Cannot access "tools>Serial port" on Kali Linux
I just got my Arduino UNO delivered and I wanted to see if it's working properly or not.
I tried following this page to create a simple program and the program compiled successfully.
But when I tried to select the serial port on IDE, the port option was grayed out. I searched for the problem and I landed on this page. It says

Linux includes the drivers necessary to use Arduino, and no additional
  install is needed. However, permissions might need to be configured.
  For current instructions on how to set up these permissions, visit
  this page.
An alternative method is to run Arduino as root in the terminal.

But I still see the port option grayed out even as a root user. Any idea?

Have you tried following the instructions in any of the myriad of troubleshooting pages for Linux and Arduino?

@Majenko: Nope. Not yet. Any suggestion?

How about doing that thing I just asked if you had done?

Did you check if Linux created a new device in the /dev directory?  Did you perform a "tail -f" on the log file of your Linux distribution and watched the output as you plugged in your Arduino?  You didn't say which Linux you were using so we can only guess where it keeps it's log file.  BTW, you will probably have to have root permissions to look at the log file.  BTW, you can check on the permissions of new devices at the same time you are checking on what if anything gets created in the /dev directory.

@st2000 : I'm using Kali Linux and no, plugging in the Arduino doesn't create a new directory in /dev directory. I have the root permission and I tried running Arduino as a root user but the same happens. I do not see any new device/file in /dev.

Running the application with different permissions will do no good if there is not a device in /dev for the application to connect to.  Plugging in the USB device and creating a serial device in the /dev directory needs to be solved first. Kali is sort of an "attack" version of Debian (older versions were based on Ubuntu, but I'm just going to assume you have a new version of Kali).  So, if they didn't change anything the log file should be at /var/log/syslog.  You can "tail -f /var/log/syslog" and watch while you plug in your USB device and see what is happening.


text:
LCD displays wrong temperature
Hi I have a program that does not work right as I aspect:
v = tempC;
h = tempC * 10;
h = h % 10;
memset(stempCA, 0, sizeof(stempCA));
sprintf(stempCA, "%+.2d.%d", v, h);

it works fine on positive temperature "+11.22"
but not for negative values : "-02.-1"
where is my mistake?
 thanx

where is my mistake? test the temperature first to see if it is negative or positive. your code works for positive temperatures only.

I think, that -1%10=-1, not 9 as you would like. I use
if (tempC<0) {print'-';tempC=-tempC;};
print tempC as usual for positive numbers

no , I put it in a Buffer for LCD display, I don't use print :                                                                 sprintf(Buffer2, "U:%s A:%s",  stempCU, stempCA);

Got i myself:                                                                                sprintf(stempCA, "%+.2d.%d", v, abs(h));


text:
Reading and interpreting Serial information
I am trying to use a Raspberry Pi to control a ESC and for that I am sending the instructions for the ESC using serial. My problem is that when i send the instructions i can not interoperate them, and by interoperate I mean check what the first letter is and then remove it and make the Arduino output a PWM signal. My problem is when I use the serial monitor to send an instruction it firstly comes up on several lines, and when I try and look at the first letter of the string the if statement thinks it is true for all inputs of "FirstLetter" my function to get the serial input it
String readSerial()
{
  char SerialInput;
  String Data = "";
  if (Serial.available())
  {
    SerialInput = Serial.read();
    Data.concat(SerialInput);
    //Serial.println(Data);
  }
  return Data;
}

the function that should interoperate  the information from readSerial() is
void DecodeInput()
{
  String input = readSerial();
  if (input != "")
  {
    char FirstLetter = input.charAt(1);
    if (FirstLetter = 'U')
    {
      Serial.println("Hello World");
      //input.setCharAt[0, '');
      //SetPower('U', Power);
    }

Two things immediately jump out at me:
char FirstLetter = input.charAt(1);

charAt(1) is the second letter, not the first - the first is charAt(0).
if (FirstLetter = 'U')

That is saying "If I have been successful in assigning the value 'U' to FirstLetter then..." - "=" is assignment, you need "==" for comparison.
Also your readSerial() function is complete junk.  It's not doing anything at all like you think it is.  You should read this to better understand Arduino serial reading: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


text:
How to remove SD card safely
I’m constructing an arduino based sytem that uses a SD card and I’m looking for a way to safely remove the card from the system during operation. One way would probably be to turn of the arduino before removal of the SD card, but that is not acceptable in this context.
The library I’m using:
https://www.arduino.cc/en/Reference/SD
Is it possible to safely remove the SD card during operation? If no, how can I minimize the risk of damage to the SD card while inserting and removing it?

The physical construction of the card and socket are designed such that power to the card is cycled properly when the card is inserted and removed. The only thing the firmware has to do is to stop writing to the card before it is removed.
Unexpected removal can cause a problem in "larger" systems (e.g. cellphones or PCs) because they may have structures open on the card that are not yet complete, but small embedded systems typically do not have the capability to do so and so once all writes are completed the card can be removed.
Detection of non-presence of a card is another issue though, and the firmware will have to be designed to not fail in such a situation.

In my early days of computing, the computer used to turn on a led when writing to cassette tape or floppy disk. If you wanted to remove the tape or disk, you had to wait for the led to turn off.
I think that could be your easiest solution.

An SDCard is very much like a hard disk drive.  Both in how it is made and how it is treated by the host.  As such there are critical times where interrupting the communication to the SDCard can cause corruption.
To avoid problems it is advisable to finish all transaction before removing the SDCard.  In a perfect situation all data will be flushed from the host's buffers (cache) and the files being accessed closed.  So research the flush() and the close() function calls in the library you are using.
In order to accomplish the above, it is obvious the host device needs to be told the SDCard is about to be removed.  In most cases this is accomplished using a switch (human interface) and some code to flush and close any open files.
All this said, often people pull SDCards with out any obvious problems.  This is likely because SDCard transactions are fast and completed in fractions of a second.  Also pulling an SDCard when periodically reading a file is far safer then when writing to a file or altering any information on the SDCard (for example the name of a file).  If you can suffer the possibility of corruption, it may be that the added effort is not worth it.  However if you stand lose a great deal, I would advise you to do some research into the best ways to avoid SDCard corruption.

authors: Дмитрий Журавкин


text:
How to correctly serve a webpage from an SD card
It's been days that I'm trying to figure it out how to edit this perfectly working code in order to load load a webpage from the sd card.
#include <SPI.h>
#include <Ethernet2.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;
boolean L1chk;
boolean L2chk;
boolean L3chk;
boolean L4chk;
boolean L5chk;
boolean L6chk;
boolean L7chk;
boolean L8chk;
int led;

void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);

pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
  // start the Ethernet connection and the server:
  Ethernet.begin(mac);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // Create a client connection
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
         }

         //if HTTP request has ended
         if (c == '\n') {
           Serial.println(readString); //print to serial monitor for debuging

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println();
           client.println("");
           client.println("");
           client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
           client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
           client.println("<TITLE>CONTROLLO LEDS</TITLE>");
           client.println("");
           client.println("");
           client.println("
FLASHATI
");
           client.println("
");
           client.println("LED1");
           client.println("LED2");
           client.println("LED3");
           client.println("LED4");
           client.println("LED5");
           client.println("LED6");
           client.println("LED7");
           client.println("LED8");
           client.println("
");
           client.println("
");
           client.println("
Created by Rui Santos. Visit http://randomnerdtutorials.com for more projects!
");
           client.println("
");
           client.println("");
           client.println("");

           delay(1);
           //stopping client
           client.stop();
           //controls the Arduino if you press the buttons
           if (readString.indexOf("?1") >0){
               ledUno();
            }
           if (readString.indexOf("?2") >0){
               ledDue();
            }
            if (readString.indexOf("?3") >0){
               ledTre();
            }
            if (readString.indexOf("?4") >0){
               ledQuattro();
            }
            if (readString.indexOf("?5") >0){
               ledCinque();
            }
            if (readString.indexOf("?6") >0){
               ledSei();
            }
            if (readString.indexOf("?7") >0){
               ledSette();
            }
            if (readString.indexOf("?8") >0){
               ledOtto();
            }
           readString="";
        }

        }
    }
}
}

So I came out with this after a lot of research:
/*
    Created by Rui Santos
    Visit: http://randomnerdtutorials.com for more arduino projects

    Arduino with Ethernet Shield
*/

#include <SPI.h>
#include <Ethernet2.h>
#include <SD.h>
File webFile;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
byte ip[] = { 192, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
byte gateway[] = { 192, 168, 1, 1 };                   // internet access via router
byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
EthernetServer server(80);                             //server port
String readString;
boolean L1chk;
boolean L2chk;
boolean L3chk;
boolean L4chk;
boolean L5chk;
boolean L6chk;
boolean L7chk;
boolean L8chk;
int led;

void setup() {
    // Open serial communications and wait for port to open:
    Serial.begin(9600);

    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    // start the Ethernet connection and the server:
    Ethernet.begin(mac);
    server.begin();
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;    // init failed
    }
    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
}

void loop() {
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println();
                    // send web page
                    webFile = SD.open("index.htm");        // open web page file
                    if (webFile) {
                        while(webFile.available()) {
                            client.write(webFile.read()); // send web page to client
                        }

                        webFile.close();
                    }
                    break;

                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                    if (readString.indexOf("?1") >0){
                        ledUno();
                    }
                    if (readString.indexOf("?2") >0){
                        ledDue();
                    }
                    if (readString.indexOf("?3") >0){
                        ledTre();
                    }
                    if (readString.indexOf("?4") >0){
                        ledQuattro();
                    }
                    if (readString.indexOf("?5") >0){
                        ledCinque();
                    }
                    if (readString.indexOf("?6") >0){
                        ledSei();
                    }
                    if (readString.indexOf("?7") >0){
                        ledSette();
                    }
                    if (readString.indexOf("?8") >0){
                        ledOtto();
                    }
                    readString="";
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
                //controls the Arduino if you press the buttons

            }

        }
        delay(1);      // give the web browser time to receive the data
        client.stop();
        if (readString.indexOf("?1") >0){
            ledUno();
        }
        if (readString.indexOf("?2") >0){
            ledDue();
        }
        if (readString.indexOf("?3") >0){
            ledTre();
        }
        if (readString.indexOf("?4") >0){
            ledQuattro();
        }
        if (readString.indexOf("?5") >0){
            ledCinque();
        }
        if (readString.indexOf("?6") >0){
            ledSei();
        }
        if (readString.indexOf("?7") >0){
            ledSette();
        }
        if (readString.indexOf("?8") >0){
            ledOtto();
        }
        readString="";
    }
}

void ledUno(){
    led = 2;
    if (L1chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L1chk = 1;
        return;                   //Led 1 acceso
    }

    if (L1chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L1chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledDue(){
    led = 3;
    if (L2chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L2chk = 1;
        return;                   //Led 1 acceso
    }

    if (L2chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L2chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledTre(){
    led = 4;
    if (L3chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L3chk = 1;
        return;                   //Led 1 acceso
    }

    if (L3chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L3chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledQuattro(){
    led = 5;
    if (L4chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L4chk = 1;
        return;                   //Led 1 acceso
    }

    if (L4chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L4chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledCinque(){
    led = 6;
    if (L5chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L5chk = 1;
        return;                   //Led 1 acceso
    }

    if (L5chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L5chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledSei(){
    led = 7;
    if (L6chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L6chk = 1;
        return;                   //Led 1 acceso
    }

    if (L6chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L6chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledSette(){
    led = 8;
    if (L7chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L7chk = 1;
        return;                   //Led 1 acceso
    }

    if (L7chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L7chk = 0;
        return;                   //Led 1 acceso
    }
}

void ledOtto(){
    led = 9;
    if (L8chk == 0){                                             //Il Ledled 1 è Spento
        digitalWrite(led, HIGH);
        L8chk = 1;
        return;                   //Led 1 acceso
    }

    if (L8chk == 1){                                             //Il Ledled 1 è Spento
        digitalWrite(led, LOW);
        L8chk = 0;
        return;                   //Led 1 acceso
    }
}

So far the web page is correctly loaded, but the sketch of the LED light logic seems to not work anymore like it was working correctly before. I thought that maybe someone of you guys could help point me in the right direction.

What happened to the "readString" after your edit?

@MikaelPatel What do you mean?

You removed the section after the comment  //read char by char HTTP request.

@MikaelPatel it was just for debuggin purpose

It looks that I found the solution to my problem, the first skecth was working correctly because  the SD card is using the pin 4  for his purpose, so the sketch was working good becuse the SD card was not used here, in the second code where I used th SD card to serve a webpage was not working anymore not because of the code, but becuse the PIN 4 where I connected a led was used by SDcard and so it messed up by blinking the LED
DON'T USE PIN4 WITH AN ETHERNET SHIELD IF YOU PLAN TO USE THE SD CARD

A pin plan can help. Download http://fritzing.org/download/ and save a plan. You don't need to create a full schema to still document how you are going to use your pins. Very handy when you pick up this project in half a year or so.

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


text:
I need to power some coils sequentially, can someone help me with the code?
int coilSetOne = 0;
int coilSetTwo = 1;
int coilSetThree = 2;
int coilSetFour = 3;
int switchInput = 4;

void setup()
{
  pinMode(coilSetOne, OUTPUT);
  pinMode(coilSetTwo, OUTPUT);
  pinMode(coilSetThree, OUTPUT);
  pinMode(coilSetFour, OUTPUT);
  pinMode(switchInput, INPUT);
}

void loop()
{
var switchMode = digitalRead(switchInput)
    if ( switchMode == HIGH ) {
        digitalWrite(coilSetOne, HIGH);
        delay(20);
        digitalWrite(coilSetOne, LOW);
        delay(10);
        digitalWrite(coilSetTwo, HIGH);
        delay(20);
        digitalWrite(coilSetTwo, LOW);
        delay(10);
        digitalWrite(coilSetThree, HIGH);
        delay(20);
        digitalWrite(coilSetThree, LOW);
        delay(10);
        digitalWrite(coilSetFour, HIGH);
        delay(20);
        digitalWrite(coilSetFour, LOW);
}}

If the arduino detects that the switch is powered, it should power the coils. They  should stay on for 20m and the delay between coils turning on should be 10ms.

Include your code in the post, not out on a link.  After you paste the code into your post, select it and click the code icon (or press ctrl-K) to get code-formatting.  In your post, tell us what is going wrong, not just that something is wrong.

Are you saying there should be a 10ms delay between switching each coil on, or a 10ms after the previous coil is switched off before the next is turned on?  You haven't said what the problem you are seeing is so I'm going to vote to close until you can explain the problem.

I ran your code, and the problem seems to be the "var" you declare, which is not an Arduino type. Use int instead. Also if you have PINs 0 and 1 as output, Using the Serial might prove difficult.
    int coilSetOne = 0;
    int coilSetTwo = 1;
    int coilSetThree = 2;
    int coilSetFour = 3;
    int switchInput = 4;

    void setup()
    {
     // Serial.begin(9600);
      pinMode(coilSetOne, OUTPUT);
      pinMode(coilSetTwo, OUTPUT);
      pinMode(coilSetThree, OUTPUT);
      pinMode(coilSetFour, OUTPUT);
      pinMode(switchInput, INPUT);
    }

    void loop()
    {
      int switchMode = digitalRead(switchInput); //Use int
     /* Serial.print(digitalRead(switchInput));
      Serial.print(" ");
      Serial.print(digitalRead(switchInput) == HIGH);
      Serial.print(" ");*/

      if ( switchMode == HIGH ) {
        Serial.print("#Triggered");

        digitalWrite(coilSetOne, HIGH);
        delay(20);
        digitalWrite(coilSetOne, LOW);
        delay(10);
        digitalWrite(coilSetTwo, HIGH);
        delay(20);
        digitalWrite(coilSetTwo, LOW);
        delay(10);
        digitalWrite(coilSetThree, HIGH);
        delay(20);
        digitalWrite(coilSetThree, LOW);
        delay(10);
        digitalWrite(coilSetFour, HIGH);
        delay(20);
        digitalWrite(coilSetFour, LOW);
      }
     // Serial.println();
    }

You didn't explain us the problem so I'm sorry if I missed the point.

So I should just switch PINS 1 and 0 to 5 and 6?

yes, if you need to use the serial port; Also the program now compiles, but I can't know if it does just what you need.


text:
Iterate an Object Array
I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.
Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {
    //code intentionally removed
}

void Train::move() {
    //code intentionally removed
}

const int trainCount = 2;
Train train1;
Train train2;
Train trains[trainCount] {train1, train2};

void setup() {
    Serial.begin(9600);
    train1.numOfCars = 5;
    train1.init();

    train2.numOfCars = 5;
    train2.init();
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train tr = trains[n];
        Serial.println(tr.numOfCars); //always prints 0
        tr.move();
    }
}

You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)
Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with new[] and use them. Like this:
#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {}
void Train::move() {}

const int trainCount = 2;
Train* trains = new Train[trainCount];

void setup() {
    // initialize trains
    for (int i = 0; i < trainCount; ++i) {
        trains[i].numOfCars = 5;
        trains[i].init();
    }
    Serial.begin(9600);
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Serial.println(trains[n].numOfCars); //always prints 0
        trains[n].move();
    }
}

Unless the Train constructor depends on other things being initialized first (in which case you would new in setup()), there is no point in using dynamic memory allocation: just declare Train trains[trainCount];.

As uint128_t has already put it, your problem is that you are creating
an array of copies. You should really avoid copying trains around,
especially if you are going to put a significant amount of data in them.
Instead, just create them once in the array, and then you can either
invoke them as array members directly (e.g. trains[0].init();) or use
references.
For example, if you initialize your trains like this:
const int trainCount = 2;
Train trains[trainCount];
Train &train1 = trains[0];
Train &train2 = trains[1];

Then the "real" trains live in the array, and train1 and train2 are
references to them. The rest of your code should work fine unchanged. I
would however suggest to avoid copying the trains in loop:
void loop() {
    for(int n = 0; n < trainCount; n++) {
        Train &tr = trains[n];        // notice the '&'!
        Serial.println(tr.numOfCars);
        tr.move();
    }
}


text:
Atmega168 breaking out of ISR
I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART_receive() on the atmel gets stuck at: while ( !(UCSR0A & (1<<RXC0)) );
Is there any way I can break out of this? The code is posted below:
unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.
ISR(USART_RX_vect)
{
    len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0"
    UART_flag = 1;
}

The the buffer is set up in main()
unsigned char uart_string[20];

I don't see an ISR here. Your code is for UART Rx polling. Do you have a Uart RX ISR in parallel, which reads from UDR0? This may cause problems. Or is this function called inside the ISR? And hopefully your *x points to a reserved array big enough to hold your string. Otherwise you will overwrite other data in memory.

Edited my question. Included the actual ISR now.

Just implement some timeout functionality, so the the while loop will break if no new data is transmitted withing the specified time.

Do you know how can I do that? like put one of the timers into an ISR? Will it work if it's already stuck in this ISR?

Receiving multiple characters within an ISR is a big waste of time. Keep your ISR short. Interrupt when a char is received, get the single character and put it in a buffer, then exit the ISR. Let main() do the rest.

... Then, each time through the main() loop you could check to see if the string terminator has been received. When you detect that, you process the string and clear the buffer. No blocking code anywhere.

You really shouldn't try to receive a string of multiple characters in an ISR - rather, receive only one, or at most however many are then available.  If you want to wait for a full string, do that in your main loop, not your ISR.

Just to second @Tut and Chris Stratton: Look at the USART_RX_vect ISR in HardwareSerial.cpp, which is a good example: read one char, store it, done.

I agree, make the ISR store a single character in a "ring buffer". Or a regular buffer where you reset the index after each message. This is more a design fault as a code fault. What OP is trying to do is not encouraged or a really bad code-model/design.

First of all, you shouldn't share a simple variable between ISRs and the main loop: unsigned char uart_string[20]; should be volatile unsigned char uart_string[20];. Moreover, you must define it out of any scope.
Also, using possibly blocking loop in an ISR is strongly not recommended. In fact, whenever your microcontroller enter an ISR, everything else is stopped: thus, an ISR should last as short as possible. Plus, the USART_RX_vect triggers whenever a single character is received: this means that you'll have to wait for the next one. Thus, you mustn't use ISR like that: I would just use a global volatile variable to monitor the amount of received characters. Then, in the main loop, I would analyze the input characters whenever this counter is greater or equal than 2
.
Finally, in your ISR, you try to read four input characters: '/0' is only one character, in the ASCII table it's called NULL, so you should only read up to three characters.

As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.
The interrupt fires when a character has been received, so that is all your program should count on finding.  You can if you really want to poll the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened and you definitely should not be waiting for it in the ISR.  Rather, if the ultimate consuming code needs multiple characters, then that should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.
Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.

I would suggest using code like this:
//Above your program, global variable.
char uartRXbuffer[100];//Adjust size!
int  uartRXbufferIndex = 0;
//bool uartRXmessage = false;

ISR(USART_RXC_vect){
   uartRXbuffer[uartRXbufferIndex++] = UDR;//read UART register into buffer. And increase index by 1.
   if(uartRXbufferIndex > sizeof(uartRXbuffer){
      //uartRXmessage = true;
      uartRXbufferIndex = 0;
   }//else if(uartRXbuffer[uartRXbufferIndex-1] == "\n"){
   //   uartRXmessage = true;
   //}
}

void loop(){
   HandleBuffer();
}

void HandleBuffer(){
   //Do something with your buffer values.
   //if(uartRXmessage){
      if(strstr(uartRXbuffer,"Command1")){
        //Code for when "Command1" is found in your buffer.
      }
   //}
//uartRXmessage = false;
}

I havent tested this code, but the idea is correct I believe.
You can un-comment the uartRXmessage stuff if you only want to handle the buffer when there is an end-of-line character or when the buffer is full.
Alternatively you can implement a ring buffer.

I think I may have a very simple solution. Completely overlooked this while I was messing with the timers. I took the hint from a I2C routine in some threads in the the forum here.
This works with empty strings as well as large strings with garbage values. It doesn't seem to hold the system anymore, so it works for my purpose.
Anything I should add here?
int count_for_break = 0;
while ( !(UCSR0A & (1<<RXC0)) )     // wait for another char - Waits for 200 cycles.
        {
            count_for_break++;
            if(count_for_break > 200)
                break;
        }
//then reset the counter upon break or char receive.

If you do this, make sure you stay in the loop for at least a full character time at the lowest baud-rate you expect to use. This can work if the entire string is sent at once, but may fail if there are gaps between characters such as can occur with typing using terminal programs or when using VCP adapters such as USB to serial. Failure may be avoided if you save your received characters if the string is incomplete. A better solution is to receive one character per interrupt and not waste time waiting for another (see my comments above).


text:
Atmega168 Watchdog timer
I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.
Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps > System Reset every 8 sec > goes back to sleep.
While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources.
I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.
Here a basic rundown of what I was thinking about.
ISR(wdt_timer)
{
    how to stop the full system reboot?
    how to make the interrupt start again?
}
ISR(button_press)
{
      gotoSleep=0;
}

void watchdog_init()
{
    /* Reset the wdt. */
  wdt_reset(); //from wdt.h

  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   */
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  /* set new watchdog timeout prescaler value */
  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

  /* Enable the WD interrupt (note both interrupt and reset). */
  WDTCSR |= (1<<WDIE) | (1<<WDE);
}

void main ()
{
    watchdog_init();
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        reset_watchdog();

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        gotoSleep();

        //wake up here

    }

}

I think the way it goes is: at 8 sec-- interrupt triggered, at 16 second --system reset. Correct me if I'm wrong.

Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.
Also, consider using <avr/wdt.h> and <avr/sleep.h> to handle (most of) the watchdog and sleep functionality.
EMPTY_INTERRUPT(WDT_vect);

void main ()
{
    watchdog_init();
    set_sleep_mode(SLEEP_MODE_STANDBY);
    //and initialize all the other hardware and power supply

    while (true) //no need to step out of this loop
    {
        wdt_reset()

        //
        //main program
        //

        if(go_to_sleep=1)  //command received through serial
        {
            sleep_enable();
            sleep_cpu();
            sleep_disable();
            WDTCSR |= _BV(WDIE);
        }
    }
}

the "wdt_reset()" from wdt.h only resets the time, not the WDE or WDIE, right?

It becomes a wdr opcode in the binary.

if(go_to_sleep=1) ? Surely: if(go_to_sleep==1)  (I realise it is pseudo-code, but still).

@NickGammon: I'm sure it will be fixed once the pseudocode is translated to C.