text:
Minimum current or power for Arduino Mega
I wanted to use the cigarette lighter receptacle of a car as the power supply for the Arduino Mega. From 12 V, I will convert it to a 7 V supply, but my problem is, what must be the minimum current or electrical power to be fed into the Arduino Mega?
And are there any things I have to do to the Arduino Mega 2560 for it to function well in supplying it a 7 volts supply from a car?

Also see  Powering Arduino with car batteries, and Arduino Forum's Arduino Idle Current draw? and Power Consumption Arduino and Gammon's page about power-saving techniques for the Atmega328P

The Arduino's voltage regulator is rated for a suggested input range of 7 to 12 volts. Automobile power will range from slightly below 12 volts to over 13 volts, so stepping it down to 7 volts is a good idea.
Looking at the data sheet it doesn't say how much current it draws. Since it uses a linear power supply it will likely draw the same amount of current regardless of the input voltage, and simply waste the power from a higher input voltage as heat.
The power from a car cigarette lighter should have plenty of current, so your proposed setup should work just fine. Is your 7 volt supply regulated?
Note that you could also use a "buck" style switching power supply to feed 5 volts directly into the 5V line. There are several buck style power supplies on the market for less than $10 US that will provide up to 3A of regulated 5 volts.

Recommended voltage is 7-12V, maximum is 6-20V. So 13V would still be fine (though wasteful).

Is stepping down the 12V to 7V and limiting it to 2Amperese already sufficient for the Arduino Mega 2560? Can it run 4 different UARTS, where these 4 different shield also get its power sources from the 5 V of the Arduino?

@Gerben - automotive power is not limited to 13v.  In fact it's notoriously variable (lower and much higher) and electrically grungy, for example when the engine is running (or worse, starting).

The input filter caps are rated for 16V, so putting an Arduino on the automotive supply directly is a very bad idea.


text:
How to reset Arduino from software
As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.
I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?
I use C# to communicate with serial.

OK, I have solved this by sending DSR pulse as seen on code below:
mySerial.DtrEnable = true;
mySerial.Open();
Thread.Sleep(1000);
mySerial.DtrEnable = false;

FYI: The Leonardo's reset is triggered when the Leonardo's virtual (CDC) serial / COM port is opened at 1200 baud and then closed

source: Stack Exchange

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

sort: votes


text:
ESP8266 shows garbage in serial monitor
I have my ESP8266 connected via serial to USB like the image shows:
It worked just fine, however, when I tried flashing Blynk code
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "YourAuthToken";

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, "ssid", "pass");
}

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

It started outputting loads of garbage in the serial monitor, while Blynk app said ESP is not connected to network. I've tried since then flashing empty sketches or some other stuff, whatever I do, serial monitor shows loads of junk. I've tried changing modes, I've tried changing baud rates (57600 was default, and AT worked just fine).
Junk example:
  …ÕZªP‚,JHVYº—¡VÕ]J*ÉW¥¡Õ¥Õ-”ªUŠQd®”¡âJ%H
!HiZÊIIRPÖuUPÒ‚BñZT¥ *EUeZB\)*EVjU!\©Š_¥¢”ÅVªqYiUµP”¬ÕPQT°*uH)HZKB*ÕXªuH!HBHBH…µEIâHBH!H©ªqY+hZVB\BH!HÊ*Òµe�qHBHBHŠ*i±…Z¦-hUµPÔ¬ÔPQT°*uH)H-KB*ÕXªuH!HBHBH…µEB\!H!HBVªqY+iZVB\BH!HeVÒZ¢qHBHBHŠ*iQ…Z¦-hUµPÔ¬ÔPQTaYRB\    jHiBHªaYRB\BH!HBVªaYRB\BH!HBVªqY+iZVB\BH!HÊVÒZ¢qHBHBHŠ*i±Õ\V
iUµPÔ¬ÕPQT°*uH)H-JBVªaYRB\BH!H!VªaYR!\BHBH!Vªq©+hZW!\BHBHJ*iµE�âHBH!HŠ*i±…Z¦-hUµPÕ¬ÔPQTaYR!\    %Hi!HÕXªuH!HBHBH…µEIqHBHBH

In this case, it looks like your Serial Monitor just isn't set to the right baud rate with Both NL & CR. Even if your monitor is set to the default 115200 baud rate, you'll still see some garbage characters which leads into the next issue.
Using 115200 has too many instructions for the Arduino Uno to reliably decode characters and that's where the garbage is coming from.
The ESP8266 default baud is 115200, so you need to connect at the default rate and issue an AT command to reduce the baud rate to 9600.
Each time you reset, the ESP8266 goes back to the default baud rate.
Here's an example script that connects at the default baud rate and then reduces it to 9600. You'll connect the Serial Monitor at 9600. At the lower baud rate, I'm not getting any garbage characters.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

void setup()
{
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);
  ESPserial.end();
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");
}

void loop()
{
    // listen for communication from the ESP8266 and then write it to the serial monitor
    if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

    // listen for user input and send it to the ESP8266
    if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
}

An odd thing that happened to me is that I tried to use a baud rate of 4800 and I bricked one ESP8266 module. I don't know if that was a glitch or just a coincidence.

Try stabilizing the power source.
I parallel connected two AA batteries with the Arduino's 3.3V output and the garbage disappeared and my ESP8266-01 got much more stable.

I had errors in printing sensor values to serial, normal output starts with "D:" and ends with "all".
D: 23 24 25 23 22 22 21 22 22 22 23 24 23 24 24 24 24 25 25 25 26 26 25 25 21 21 21 21 21 21 all
 36 36 37 45 44 43 41 41 41 40 39 39 38 38 37 38 38 38 37 40 all
&&B⸮⸮R⸮B &⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
⸮⸮5
D: 29 45 29 28 27 26 25 27 29 26 22 23 24 22 21 21 20 20 22 22 149 26 25 24 27 26 23 21 21 22 all

I grounded, stabilized power source, change code not to use interrupts notthing had changed
How i solved:
I had spare mcu, changed it,  now serial works flawlessly.

This might be related to old ESP-01 firmware. I mean 2018-ish firmware in 01s I bought 3 years ago or so.
I had the same problem –- write_flash works but after the reset garbage is coming in. Try this [installs micropython; change serial device to fit your setup]:
esptool.py -p /dev/tty.usbserial-02022FD3 erase_flash
esptool.py -p /dev/tty.usbserial-02022FD3 write_flash 0xfc000 esp_init_data_default.bin
esptool.py -p /dev/tty.usbserial-02022FD3 write_flash -fs 1MB 0x00000 ../upython-esp8266-1m-20220117-v1.18.bin

Note: the location is flash size dependant – my ESP-01s have 1 MB of flash and you can check it using the esptool.py flash_id command. Use this reference:

0x7c000 for 512 KB, modules like most ESP-01, -03, -07 etc.
0xfc000 for 1 MB, modules like ESP8285, PSF-A85, some ESP-01, -03 etc.
0x1fc000 for 2 MB
0x3fc000 for 4 MB, modules like ESP-12E, NodeMCU devkit 1.0, WeMos D1 mini

The esp_init_data_default.bin file is taken from Espressif SDK, here's my SHA256 of it:
shasum -a 256 esp_init_data_default.bin
81e04e5ec0afef0aad3b52cca2a9bbccc205f4c57334c438e1d81e38ce94b932  esp_init_data_default.bin

But I guess the init file from Github should work OK as well [didn't try though].
https://github.com/espressif/ESP8266_RTOS_SDK

I had a similar problem with a NodeMCU ESP-12E (Amica v2) board... after pressing and releasing the RST button with Serial Monitor open & set to 115200 baud, it would display the boot message (starting with " ets Jan 8 2013, rst cause:2, boot mode(3,6)", and ending with "~ld"), then display gibberish when the program itself attempted to use Serial.print() or Serial.println().
It appears to be a strange bug related to NodeMCU itself, but the following work-around got Serial.print working for me:

Before using Serial.print() or Serial.println() for the first time in the program (setup() is probably a good place), do Serial.begin(74880);
Step 1 notwithstanding, set the baud rate in Serial Monitor to 115200.

My guess is that somewhere between the Arduino library and CP2102, a register value is being miscalculated (or mangled), and calling Serial.begin(74880) results in setting a register to the value that calling Serial.begin(115200) should have set it to.
Here's the page where I read about the bug: https://github.com/esp8266/Arduino/issues/4005

it is not a bug. the esp ROM bootloader expects a 40 MHz crystal, but most esp8266 modules use 26 MHz crystal. then the resulting baud rate is 74880 instead of 115200 used by the bootloader. but it has nothing to do with the baud rate used by the application/sketch which uses the right frequency setting

Have you also pulled up the ESP8266's reset pin? I don't know what effect not doing so might have, but the recommended connections I have read and followed include that. The RST and CH_PD pins are adjacent; they're easy to jumper together.

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

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


text:
How to make servo rotate for angle bigger than 180°
Connected servo motor (180°) to Arduino Uno R3.
Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.
So do I need to go for a continuous rotation servo motor (360°), so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?
I am referring to Servo - Generic High Torque Continuous Rotation (Standard Size)
Current code, which I am using 180° servo motor.
Servo myservo;
int pos = 0;
void setup() {
  myservo.attach(9);
}

void loop() {
   {
    myservo.write(180);
    delay(15);
  }
}

Indeed, you need a continuous servo or to hack away the blockade.  These servos are limited to angles < 360 degree. Also keep your 8 bit limit in mind - 360 degree / 256 steps is your maximum resolution.

continuos rotation servo motors aren't 360 degrees. They are "infinite degrees". They are more like a motor, than a servo. See this video

The drawback of a continuous rotation servo is you don't know where it is; you code only tells it how fast to move, not where to move to.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

No. The continuous rotation servo rotates continuously and you can not control where to stop. You can control the rotation direction and the speed at a little.
What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.
Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


text:
Why is my pushbutton always reading LOW?
I know this is ridiculously simple task but I spent the last two hours trying to get this to work and it is not working.  I don't have an Arduino but I have an ESP8266 Huzzah Feather which is programmable via the Arduino IDE.  So, I don't think I can provide a Fritz diagram but in any case, I'm just trying to hook up a pushbutton and be able to read a HIGH or LOW (via my Serial monitor).  Currently, everything is 0.
As best I can describe it is:
5V from Feather into resistor into one terminal of the pushbutton.  Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.  Feather is also grounded.
My code is:
void setup()
{
  Serial.begin(9600);
  pinMode(12, INPUT);
}

void loop()
{
  int button_val = digitalRead(12);
  Serial.println(button_val);
}

It shouldn't be this hard for me.  Whenever I open and run the serial monitor, it reads 0s.  What am I missing?
Oh, an issue that I faced is determining which 2 out of the 4 terminals of the pushbutton to use.  Some resources I find say that it is the same side as the terminal the voltage is flowing into; other resources say it is the terminal opposite to the side the voltage is flowing into.  I currently have it opposite.

If you have a multimeter you can measure how to connect your switch up, measure the resistance between the pins. Two sets of pins will measure 0 Ohms, you want to use a pair which doesn't measure 0 Ohms

If you don't have a multimeter, you can connect an LED (with current limiting resistor) between your Arduino and button. It should go on when the button is pressed.

And before doing everything else read @Majenko's answer, because reading what you wrote you wired the button in the wrong way (this is the correct way)

Out the other terminal of the pushbutton is a wire connecting to pin 12 of the Feather, and also a wire leading to ground.

That sounds to me like you have connected the IO pin direct to ground.
The IO pin should connect to the same pin as the resistor that connects to +5v. The other side of the button should connect to ground only.
For instance using @HansNeve's button picture you could connect pin A to the IO pin and via a resistor to +5V, and pin B to ground.

Oh, my.  This worked wonderfully for me.  Thank you!  Both answers were helpful but I had to pick this one because it told me that my IO pin was connected incorrectly as well as which terminals of the button to use.  Now, a follow-up question: my button reads 1 without a press and 0 with a press.  Is that right or should it be the other way around?  I tried swapping terminals but that didn't seem to correct the issue.

That is completely correct. It is known as "active low" because it gives a "low" signal when you activate it.  To make it "active high" you reverse the entire circuit by connecting the wire that is connected to ground to 5V instead, and the resistor that is connected to 5V to ground instead.

@noblerare be aware, though, that the active low configuration is the most common, because you can exploit the internal pull-up (no need for resistor, just enable the pullup)

@frarugi87 thanks, I kept it as active low and modified my code accordingly.

The pins on each side of the button are shorted, the "button" is between the sides of the button. Else your code looks alright.
Edit: Here's an image which shows how a push button is connected internally, make sure you're using the correct pins.


text:
Is there a thermal sensor with a distance of 10 meters for Arduino
I am looking for a thermal sensor with a distance of 10 meters . In my plan , I would like to recognize objects based on the heat. for example car.

Check this one i just found. http://www.farnell.com/datasheets/1675620.pdf . Price is friendly ~36 pounds. This is other datasheet http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf

@Martynas I can't find  maximum distance in datasheet.

Because there is no distance. You get a matrix. Here look at this https://www.youtube.com/watch?v=_ix0Rd4pIeA

How about this one at £20?
The range depends on what lens you put in front of it - this has to be plastic as IR doesn't penetrate glass, but you can set your own range, like a focus adjustment. Commercial IR remote thermometers generally have aiming dots (laser) so you can see the optimum range - there's a fixed lens.
The actual sensor won't have a defined range, because of this.


text:
Feasibility of a Wi-Fi Positioning System
In the project of guiding a sight disabled person in a known environment, we need to have a precise way of figuring out where the user is. Our current solution is to use WPS.
This is however our first project with Arduino, and we're not quite sure if we're going the right way about this. We're thinking of getting a compass component and such, but is there something we should know before advancing further in the project?
EDIT: Additional information.
The system is placed on the user, most probably strapped to the arm. The communication to the Wi-Fi beacons will be done from there, as well as the calculations.
The environment is supposed to be as complex as an exposition hall, but we can aim higher.
Budget range is around $100, Arduino itself excluded. A UNO is already provided to us.

You need to know where the person is and also in which direction the person is facing (so instructions like "move left", "move right" or whatever are correct). To do this most simply, you would need some kind of sensor or detectable marker on the person. Is this something like you're planning? Perhaps expand a bit more on your thinking.

@RogerRowland My bad; I went a bit too fast and forgot to include that part. I've edited the question with extra information.

This is probably a more general problem than Arduino, have a look on EE.SE where there have been numerous similar questions. It may help refine your ideas.

I don't think that arduino is the right hardware for such a project. Better use a cheap android phone, there you have a stronger processor with more memory as well as a lot of sensors like compass, accelerometer, gyroscope and maybe in newer ones barometer, which you will need - also you have wifi. An arduino uno just comes without wifi and all the sensors. Also I guess a lot of persons already have a phone, so this will lower your project costs, because hardware is already available at most users. Last but not least I think you could use mobile phone vibrations to give feedback to the sight disabled users, oder sound commands like "go left" etc.


text:
If I have a group of Arduinos connected via I2C, can one Arduino cause the rest to freeze?
I have a group of four Arduino boards connected via I2C.  One is the master, which sends and receives values from all of the others.  I noticed that the Master will stop executing its loop if power is removed from one of the other Arduino boards.
Can one Arduino in a I2C group cause the rest to freeze?
Is there a way to prevent this?
I am using one of the Arduino boards to connect to a server via network shield and I don't want the other Arduino boards to be effected if the networked Arduino freezes.

It really depends on the code that you are using.  Can you pair down your code and post the master and slave i2c portions so we can have a look?

I wish I still had it, but that code got re written and I have not seen the problem again.  If I se it happen again , I'll update the question.

More specifically, the question should really be if the I2C code (library?) and any surrounding code can handle failures of the remote end, or it if will sit and wait forever, and if it can possibly get into a state that is not recoverable even if the remote end does start operating normally again (such as after the remote, but not local, end is reset).

Sounds like the unpowered node pulled down the I2C +5V. I've also had I2C devices not work when the arduino is powered by 5V plug (but does with USB power).

There are a number of places in the standard Wire library where the code goes into a tight loop waiting for an interrupt to occur. If that is missed for some reason, it will loop indefinitely.
By removing power from one of your devices you may be introducing electrical conditions that prevent the I2C messages from being transmitted properly (possibly just noise). Alternatively the device may parasitically power up from the SDA/SCL data and then behave in unpredictable ways. It is probably unwise to do this.
There is an alternative I2C master library at http://dsscircuits.com/articles/arduino-i2c-master-library which does not hang (I believe it times out instead).


text:
How to compile and upload the specific (.cpp + .h) code?
I have a specific arduino code (no .ino files) https://github.com/justintconroy/MdbBillValidator , which can't be opened by arduino IDE. How can I make & upload this code? I have an arduino 2560 mega.
I've created an empty MdbBillValidator.ino file and added these lines:
#include "MdbBillValidator.h"

void setup() {

}

void loop() {

}

Here is the error message
MdbSerial.cpp: In function ‘void __vector_37()’:
MdbSerial.cpp:289:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:291:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_52()’:
MdbSerial.cpp:314:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:316:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: In function ‘void __vector_55()’:
MdbSerial.cpp:339:23: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp:341:24: error: ‘TXB8’ was not declared in this scope
MdbSerial.cpp: At global scope:
MdbSerial.cpp:554:135: error: expected ‘)’ before numeric constant
MdbSerial.cpp:554:189: error: no matching function for call to ‘MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, int, int, int, int, int, int, int, int, int, int, int)’
MdbSerial.cpp:554:189: note: candidates are:
MdbSerial.cpp:352:1: note: MdbSerial::MdbSerial(ring_buffer*, ring_buffer*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, volatile uint8_t*, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t, uint8_t)
MdbSerial.cpp:352:1: note:   candidate expects 20 arguments, 19 provided
In file included from MdbSerial.cpp:38:0:
MdbSerial.h:52:7: note: MdbSerial::MdbSerial(const MdbSerial&)
MdbSerial.h:52:7: note:   candidate expects 1 argument, 19 provided

That's a library. You can't just run that code. You can create a new sketch, and place these files in this new sketch's folder. Then #include it inside the ino file.

Hm!
Okay, I'll try to do that!

@Gerben which files should I include?

I think #include "MdbBillValidator.h"

don't work. compilation error

Let me get my crystal ball, to see the error message.

Oh, I've added it. Pls review the question again. Any ideas?

What folder are the library files living in? How many files from that repository did you download, and what folder do they live in? All the error report is telling me is that the library can't find the files it depends on.

I've cloned a file to the directory, and create an MdbBillValidator.ino (as the name of the directory)

The problem is that I need to import this code just a simple usual library.


text:
Does Arduino Uno R3 require cooling in a closure?
I was looking at getting an enclosure to house my Arduino Uno R3, but I'm not sure if I should also attach a fan.  Does anyone have experience with this?  It doesn't look like much heat is being generated, but with no ventilation except some slits in the enclosure, there won't be much air circulation without a fan.  My concern with adding a fan was the fact that I'd need to power it.

If you aren't running any other current-hungry peripherals e.g. motors within the enclosure, you won't need a fan or other cooling, for a typical (not hyper-insulated) enclosure.

The biggest heat culprit on the Uno would be its internal voltage regulator(s). If you can power 5V from an external regulated source it will keep things cooler in the box. Especially if you have a horde of sensors drinking power from the Uno board.

The only times I had an AVR run hot was when I applied reverse power to it. You'll be fine without a fan for the Arduino board itself, as long as you don't run power hungry peripherals from it.
Probably the only thing you really need to check (apart from absolute maximum ratings: 40mA max per IO pin and 200mA max for the whole microcontroller) is the on board voltage regulator (usually three pin device with a heat sink soldered down to the PCB) if you power it from a voltage > 7V or so.

No, You shouldn't need any type of cooling device such as a fan as long as the case has a few holes in order to allow the heat to rise out of the case. I do not recommend using cases that are completely sealed, unless you are using it in an environment that has things that could hard the Arduino such as  ROVs or Nuclear waste facility (although I don't know why you would be at one in the first place).

Outdoors, marine, and underwater applications also require sealed cases.

One of my friends actually has a job working at a nuclear power plant.

@Cybergibbons excellent point regarding the outdoors... hmm.


text:
Arduino Uno R2 and Ethernet Shield R3 compatibility
I bought an Ethernet Shield R3 for my Arduino Uno R2, but since R3 has extra pins it does not fit. Can I use the shield? Should I cut off the extra pins. What do I need to do to make it work?

@AsheeshR These extra pins get in the way when putting the shield on the Arduino. If I cut them off it would fit. Should I cut them off?

Which pins are interfering? I dont have the shield, but from what I can make out, the extra pins on the shield do not seem to be areas where there would be any conflict.

The only issue that may create an incompatibility seems to be the IOREF pin next the 5V output pin which is extra on Revision 3 but not in Revision 2.
However, I just had a look at the board schematics and the shield does not use IOREF.

Pin 2 is extending IOREF
So, the shield should work correctly with the Uno Revision 2. As far as the extra pins are concerned, I would recommend not damaging them in any way. If you absolutely need to, then just try to bend them outwards very carefully.

The extra pins do not matter. Just leave them. If you really want, cut them off, but this will remove some compatibility with other products.
They should hang off the ends of the headers closest to the power/USB end of the board.


text:
What happens when I call exit() from my program?
In either of setup or loop, if I were to add an exit(0) call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?
I am using a revision 2 Arduino Uno.

My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...
An extract of Blink.ino's listing, with exit(0) added:
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
  exit(0);
}

The disassembly of the above:
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 100:   80 91 00 01     lds r24, 0x0100
 104:   61 e0           ldi r22, 0x01   ; 1
 106:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 10a:   68 ee           ldi r22, 0xE8   ; 232
 10c:   73 e0           ldi r23, 0x03   ; 3
 10e:   80 e0           ldi r24, 0x00   ; 0
 110:   90 e0           ldi r25, 0x00   ; 0
 112:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 116:   80 91 00 01     lds r24, 0x0100
 11a:   60 e0           ldi r22, 0x00   ; 0
 11c:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 120:   68 ee           ldi r22, 0xE8   ; 232
 122:   73 e0           ldi r23, 0x03   ; 3
 124:   80 e0           ldi r24, 0x00   ; 0
 126:   90 e0           ldi r25, 0x00   ; 0
 128:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  exit(0);
 12c:   80 e0           ldi r24, 0x00   ; 0
 12e:   90 e0           ldi r25, 0x00   ; 0
 130:   0e 94 1e 02     call    0x43c   ; 0x43c <_exit>

...

0000043c <_exit>:
 43c:   f8 94           cli

0000043e <__stop_program>:
 43e:   ff cf           rjmp    .-2         ; 0x43e <__stop_program>

Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.

avr-objdump -S {compiled *.elf file} produces a file that includes the C code that lead to each section of assembly code. It's much easier to follow.

aaaand I just tried it, and it's not correctly emitting inline C code for the loop function. What the hell?

Whoa, extremely strange. I compiled the project with Stino instead of the arduino editor, decompiled the *.elf from that, and then I get the proper debugging symbols. I think the Arduino text-editor/button-macro (I refuse to call it an IDE since it's not) thing is stripping the debug info from just the compiled main C++ file, for some bizarre and stupid reason.

There is an explanation, and it is to do with the way the IDE copies your files to a temporary location. You can "fix" that by telling avr-objdump where the source is: avr-objdump -S -I/path/to/the/sketch/folder  xxx.elf  . That is the sketch folder path, not the .ino file itself. Then you should get the C source in the dump.

Well I just tested it with my Arduino Uno and it just completely stopped the code and left all the outputs as they were when the code stopped running (so it left an LED I had on on). There seems to not be a IO cleanup when you call exit. This was what I expected because the Arduino IDE provides the setup and loop functions, if you program the ATMEGA*28 with with any other AVR IDE you start with the main function like all C/C++ programs. The setup and loop functions are not standard on AVR MCU's.
Note: The press of the reset button restarts the code, if you were wondering.

Good to know. I was looking for something more detailed and at a lower level. On calling exit(0) the disassembled instructions are (IIRC) __stop_program, cli and a spinlock. I wanted to verify if that is correct with an explanation of how the control is passed i.e. call stack pop?, ISR call?

Ah, well I haven't looked into arduino on such a low level, for that information you might want to check the atmel website.


text:
What are the main differences between the Arduino Tre and the Intel Galileo?
I'm looking to find a suitable board for a robot I'm developing (it'll involve computer vision, else I'd be using my Arduino Micro) and I've come across two possibilities: The Intel Galileo and the Arduino Tre.
Now as I understand it, the Intel Galileo has a 400MHz Quark processor, whilst the Arduino Tre has 2 processors, an onboard 16MHz standard ATmega32u4 with the Arduino bootloader and then another 1GHz TI processor with Linux installed on it.
However, I'm not sure of the differences between both products, as price estimates appear to place them at approximately the same price (around $70) and the Intel Galileo doesn't appear to have any real advantage over the Arduino Tre (except for a full x86 instruction set).
Does anyone have any information on comparison of the two boards so I can make a better informed decision?

Biggest difference IMHO: Tre hasn't been released yet!
Besides that, there are a few different things that you should compare. Not much is available about the Tre as of now, but I'll update this post when it's released.

Basic Specs: [First sub-bullet is TRE, second Galileo; better spec in bold]

Microcontroller:

Texas Instrument Sitara AM3359AZCZ100 (ARM Cortex-A8) (1 GHz, 32 bit), Atmel ATmega32u4 (16 MHz, Secondary, found on Leonardo)
Intel® Quark SoC X1000 (400 MHz, 32 bit)

RAM:

512 MB SRAM (2.5 KB ATmega32u4)
512 MB SRAM

Pins

14 Digital 5V, 7 of which are PWM, 6 analog 5V (additional 6 multiplexed) (32u4); 12 Digital 3.3V, 4 of those are PWM (Sitara)
14 5V digital, 6 of those are PWM, 6 analog 5V

Networking:

Ethernet 10/100
Ethernet 10/100

USB port:

1 USB as slave, 4 USB host ports
Up to 128 devices as host, 1 USB slave

Video

HDMI (1920x1080), LCD header
None that I can find

Audio

HDMI, stereo analog audio input and output
None that I can find

MicroSD card

Yes
Yes

PCIe Slot

No
Yes

Sources (I combined a bunch of data for this): Galileo & Tre

Conclusion: If you need a board before the Tre comes out, which seems to be soon (Spring 2014), Galileo is your only option. Other than that, the Tre seems to be better all around in most aspects, minus the PCIe slot. I can't comment on power, but it seems like the Tre will be able to supply 4x the power per pin than the Galileo. The Galileo is getting older, and it doesn't seem like the Galileo can provide full Linux support like the Tre will.
Personally, I'd wait for the Tre. The only thing I can think that the Galileo would be better for would be either a.) lower power usage or b.) the PCIe slot for a WiFi adapter that works decently. The second one could be solved by doing a common WiFi router hack.
If you need a lot of processing power without the need of low latency, you should conciser sending data to a computer to process.

Source

Source

+1. galileo has no video, and is supported on the INTEL form, not the arduino's official. Alsto tre as A LOT more pin :)


text:
Sending Large Amounts of Serial Data
So in the fields of robotics sometimes you need multiple boards and or computers linked together to share information or save statistical data. Currently I need to send a few different variables over a serial connection and was wondering what was the best way to go about doing such?
So far I've determined that sending structures would probably be the easier way to send data. Does anyone know of any other way that might be more efficient?
Please keep in mind that I will essentially be having to send the data for 4 motors, compressor, different temperatures, random things, and the 3 sections of the arm.

With my personal thoughts on Structs being the most efficient way to send many different variables I've constructed a library to help make it easier to send structs and variables over serial.  Source Code
In this library it makes sending through serial easily. I've used with with hardware and software serial. Usually this is used in conjunct with xbee's so I can wirelessly send the data to and from the robot.
When sending data it make it simple as it allows you to either send a variable or a struct (it doesn't care).
Here is an example of sending a simple char over the serial:
// Send the variable charVariable over the serial.
// To send the variable you need to pass an instance of the Serial to use,
// a reference to the variable to send, and the size of the variable being sent.
// If you would like you can specify 2 extra arguments at the end which change the
// default prefix and suffix character used when attempting to reconstruct the variable
// on the receiving end. If prefix and suffix character are specified they'll need to
// match on the receiving end otherwise data won't properly be sent across

char charVariable = 'c'; // Define the variable to be sent over the serial
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Example of sending a simple int over the serial:
int intVariable = 13496; // Define the int to be sent over the serial
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Example of sending a struct over serial:
// Define the struct to be sent over the serial
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct;
simpleStruct.charVariable = 'z'; // Set the charVariable in the struct to z

// Fill the intVariable array in the struct with numbers 0 through 6
for(int i=0; i<7; i++) {
  simpleStruct.intVariable[i] = i;
}

// Send the struct to the object xbeeSerial which is a software serial that was
// defined. Instead of using xbeeSerial you can use Serial which will imply the
// hardware serial, and on a Mega you can specify Serial, Serial1, Serial2, Serial3.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Send the same as above with a different prefix and suffix from the default values
// defined in StreamSend. When specifying when prefix and suffix character to send
// you need to make sure that on the receiving end they match otherwise the data
// won't be able to be read on the other end.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'u');

Receiving Examples:
Receiving a char that was send via Streamsend:
char charVariable; // Define the variable on where the data will be put

// Read the data from the Serial object an save it into charVariable once
// the data has been received
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable));

// Reconstruct the char coming from the Serial into charVariable that has a custom
// suffix of a and a prefix of z
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Receiving an int that was sent via StreamSend:
int intVariable; // Define the variable on where the data will be put

// Reconstruct the int from xbeeSerial into the variable intVariable
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Reconstruct the data into intVariable that was send with a custom prefix
// of j and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Receiving a Struct that was sent via StreamSend:
// Define the struct that the data will be put
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct; // Create a struct to store the data in

// Reconstruct the data from xbeeSerial into the object simpleStruct
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Reconstruct the data from xbeeSerial into the object simplestruct that has
// a prefix of 3 and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'p');

Once you read the data using StreamSend::receiveObject() you need to know if the data was GOOD, Not Found, or BAD.
Good = Successful
Not Found = No prefix character was found in the specified ostream
Bad = Somehow there was a prefix character found, but the data isn't intact. Usually it means there was no suffix character found or the data wasn't the correct size.
Testing Validity of Data:
// Once you call StreamSend::receiveObject() it returns a byte of the status of
// how things went. If you run that though some of the testing functions it'll
// let you know how the transaction went
if(StreamSend::isPacketGood(packetResults)) {
  //The Packet was Good
} else {
  //The Packet was Bad
}

if(StreamSend::isPacketCorrupt(packetResults)) {
  //The Packet was Corrupt
} else {
  //The Packet wasn't found or it was Good
}

if(StreamSend::isPacketNotFound(packetResults)) {
  //The Packet was not found after Max # of Tries
} else {
  //The Packet was Found, but can be corrupt
}

SteamSend Class:
#include "Arduino.h"

#ifndef STREAMSEND_H
#define STREAMSEND_H

#define PACKET_NOT_FOUND 0
#define BAD_PACKET 1
#define GOOD_PACKET 2

// Set the Max size of the Serial Buffer or the amount of data you want to send+2
// You need to add 2 to allow the prefix and suffix character space to send.
#define MAX_SIZE 64

class StreamSend {
  private:
    static int getWrapperSize() { return sizeof(char)*2; }
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar);
    static char _prefixChar; // Default value is s
    static char _suffixChar; // Default value is e
    static int _maxLoopsToWait;

  public:
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize);
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static boolean isPacketNotFound(const byte packetStatus);
    static boolean isPacketCorrupt(const byte packetStatus);
    static boolean isPacketGood(const byte packetStatus);

    static void setPrefixChar(const char value) { _prefixChar = value; }
    static void setSuffixChar(const char value) { _suffixChar = value; }
    static void setMaxLoopsToWait(const int value) { _maxLoopsToWait = value; }
    static const char getPrefixChar() { return _prefixChar; }
    static const char getSuffixChar() { return _suffixChar; }
    static const int getMaxLoopsToWait() { return _maxLoopsToWait; }

};

//Preset Some Default Variables
//Can be modified when seen fit
char StreamSend::_prefixChar = 's';   // Starting Character before sending any data across the Serial
char StreamSend::_suffixChar = 'e';   // Ending character after all the data is sent
int StreamSend::_maxLoopsToWait = -1; //Set to -1 for size of current Object and wrapper

/**
  * sendObject
  *
  * Converts the Object to bytes and sends it to the stream
  *
  * @param Stream to send data to
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize) {
  sendObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}

void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  if(MAX_SIZE >= objSize+getWrapperSize()) { //make sure the object isn't too large
    byte * b = (byte *) ptr; // Create a ptr array of the bytes to send
    ostream.write((byte)prefixChar); // Write the suffix character to signify the start of a stream

    // Loop through all the bytes being send and write them to the stream
    for(unsigned int i = 0; i<objSize; i++) {
      ostream.write(b[i]); // Write each byte to the stream
    }
    ostream.write((byte)suffixChar); // Write the prefix character to signify the end of a stream
  }
}

/**
  * receiveObject
  *
  * Gets the data from the stream and stores to supplied object
  *
  * @param Stream to read data from
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize) {
    return receiveObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  return receiveObject(ostream, ptr, objSize, 0, prefixChar, suffixChar);
}

byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar) {
  int maxLoops = (_maxLoopsToWait == -1) ? (objSize+getWrapperSize()) : _maxLoopsToWait;
  if(loopSize >= maxLoops) {
      return PACKET_NOT_FOUND;
  }
  if(ostream.available() >= (objSize+getWrapperSize())) { // Packet meets minimum size requirement
    if(ostream.read() != (byte)prefixChar) {
      // Prefix character is not found
      // Loop through the code again reading the next char
      return receiveObject(ostream, ptr, objSize, loopSize+1, prefixChar, suffixChar);
    }

    char data[objSize]; //Create a tmp char array of the data from Stream
    ostream.readBytes(data, objSize); //Read the # of bytes
    memcpy(ptr, data, objSize); //Copy the bytes into the struct

    if(ostream.read() != (byte)suffixChar) {
      //Suffix character is not found
      return BAD_PACKET;
    }
      return GOOD_PACKET;
  }
  return PACKET_NOT_FOUND; //Prefix character wasn't found so no packet detected
}

boolean StreamSend::isPacketNotFound(const byte packetStatus) {
    return (packetStatus == PACKET_NOT_FOUND);
}

boolean StreamSend::isPacketCorrupt(const byte packetStatus) {
    return (packetStatus == BAD_PACKET);
}

boolean StreamSend::isPacketGood(const byte packetStatus) {
    return (packetStatus == GOOD_PACKET);
}

#endif

All-code answers, like all-link answers are discouraged. unless your code has tons of comments, i would recommend putting some explanation of what is going on

@TheDoctor, I've updated the code. There should be more comments now

If you really wanted to send it fast, i recommend Full Duplex Serial (FDX). It's the same protocol that USB and ethernet use, and it's a lot faster than UART. The downside is that it usually requires external hardware to facilitate the high data rates. I've heard that the new softwareSreial supports FDX, but this may be slower even than hardware UART. For more on communication protocols, see How to connect two Arduino without shields?

This sound interesting. I'll have to look further into it.

How can "full duplex serial" be "a lot faster than UART" when it is, in fact, standard UART communication?

UART is a fixed rate communication. FDX sends data as fast as possible and resends the data that didn't make it.

I would love to find out more about this protocol.
Could you add a link to your answer that describes a protocol that is faster than UART?
Are you talking about the general idea of automatic repeat request using ACK-NAK, or is there some specific protocol you have in mind?
None of my Google searches for "FDX" or "full duplex serial" seem to match your description.

Sending a structure is fairly simple.
You can declare the structure as you normally would, and then use memcpy(@myStruct,@myArray) to copy the data to a new location, and then use something similar to the below code to write the data as a datastream.
unsigned char myArraySender[##];   //make ## large enough to fit struct
memcpy(&myStruct,&myArraySender);  //copy raw data from struct to the temp array
digitalWrite(frameStartPin,High);  //indicate to receiver that data is coming
serial.write(sizeof myStruct);     //tell receiver how many bytes to rx
Serial.write(&myArraySender,sizeof myStruct);   //write bytes
digitalWrite)frameStartPin,Low);   //done indicating transmission

Then you can attach an interrupt routine to the pin on the other device that does the following:
volatile unsigned char len, tempBuff[##];
//volatile because the interrupt will not happen at predictable intervals.

attachInterrupt(0,readSerial,Rising);

//tell the mcu to call fxn when pinhigh. This will happen during virtually any moment. if that is not desired, remove the interrupt and simply watch for new characters in your main executive loop (aka, UART polling).
void readSerial(unsigned char *myArrayReceiver){
    unsigned char tempbuff[sizeof myArrayReceiver];
    while (i<(sizeof myArrayReceiver)) tempBuff[i]=Serial.read();
    memcpy(&tempbuff,&myArrayReceiver);
    Serial.flush();
}

Syntax and use of pointers will need some review. I pulled an all-nighter so I'm sure the above code won't even compile, but the idea is there. Fill your structure, copy it, use out-of-band signalling to avoid framing errors, write the data. On the other end, receive the data, copy it to a struct, and then the data becomes accessible via normal member access methods.
The use of bitfields will also work, just be aware that the nibbles will appear to be backwards. For instance, attempting to write 0011 1101, may result in 1101 0011 appearing at the other end if the machines differ in byte order.
If data integrity is important, you can also add a checksum to make sure you aren't copying misaligned garbage data. This is quick and effective check that I recommend.

If you can tolerate the data volume, debugging communicatons is so much easier when sending strings than when sending binary; sprintf()/sscanf() and their variants are your friends here. Enclose the communication in dedicated functions in their own module (.cpp file); if you need to optimize the channel later - after you have a working system - you can replace the string-based module with one coded for smaller messages.
You'll make your life lots easier if you hold tight to protocol specs on transmission and interpret them more loosely on reception, regard to field widths, delimiters, line endings, insignificant zeros, presence of + signs, etc.

Originally the code was written to send back data in a stabilizing loop of a Quadcopter so it had to be fairly fast.

Send struct data across serial
Nothing fancy. Sends a struct. It uses an escape character '^' to delimit the data.
Arduino code
typedef struct {
 float ax1;
 float ay1;
 float az1;
 float gx1;
 float gy1;
 float gz1;
 float ax2;
 float ay2;
 float az2;
 float gx2;
 float gy2;
 float gz2;

} __attribute__((__packed__))data_packet_t;

data_packet_t dp;

template <typename T> void sendData(T data)
{
 unsigned long uBufSize = sizeof(data);
 char pBuffer[uBufSize];

 memcpy(pBuffer, &dp, uBufSize);
 Serial.write('^');
 for(int i = 0; i<uBufSize;i++) {
   if(pBuffer[i] == '^')
   {
    Serial.write('^');
    }
   Serial.write(pBuffer[i]);
 }
}
void setup() {
  Serial.begin(57600);
}
void loop(){
dp.ax1 = 0.03; // Note that I didn't fill in the others. Too much work. ;p
sendData<data_packet_t>(dp);
}

Python Code:
import serial
from  copy import copy
from struct import *

ser = serial.Serial(
#   port='/dev/cu.usbmodem1412',
  port='/dev/ttyUSB0',
#     port='/dev/cu.usbserial-AL034MCJ',
    baudrate=57600
)

def get_next_data_block(next_f):
    if not hasattr(get_next_data_block, "data_block"):
        get_next_data_block.data_block = []
    while (1):
        try:
            current_item = next_f()
            if current_item == '^':
                next_item = next_f()
                if next_item == '^':
                    get_next_data_block.data_block.append(next_item)
                else:
                    out = copy(get_next_data_block.data_block)
                    get_next_data_block.data_block = []
                    get_next_data_block.data_block.append(next_item)
                    return out
            else:
                get_next_data_block.data_block.append(current_item)
        except :
            break

for i in range(1000): # just so that the program ends - could be in a while loop
    data_ =  get_next_data_block(ser.read)
    try:
        print unpack('=ffffffffffff', ''.join(data_))
    except:
        continue

I have no official credentials here, but in my experience things have gone pretty efficiently when I pick a certain character position(s) to contain the state of a variable, so that you might designate the first three characters as the temperature, and the next three as the angle of a servo, and so on. On the sending end I would save the variables individually and then combine them in a string to send serially. On the receiving end I would have the string picked apart, getting the first three characters and turning them into whatever variable type i need, then doing so again to get the next variable value.
This system works best when you know for certain the amount of characters each variable will take up, and you always look for the same variables (which I hope is a given) each time the serial data loops through.
You can pick one variable to put last of indeterminate length and then get that variable from it's first character to the end of the string. Granted, the serial data string could get really long depending on the variable types and the sheer amount of them, but this is the system I use and so far the only setback I've hit is the serial length, so that's the only disadvantage I know of.

What kind of functions do you use to save x amount of characters into an int/float/char?

You may not realise this, but what you describe is exactly how a struct is organised in memory (disregarding padding) and I imagine the data transfer functions that you use will be similar to the ones discussed in Steven's answer.

@AsheeshR I actually had a feeling structs might be that way, but I personally tend to hit a wall when trying to reformat structs and then read them again on the other side. That is why I figured I'd just do this string thing, so that I could easily debug if things get misread, and so that I could even read the serial data myself if I designate it like "MOTORa023 MOTORb563" and so on, without the spaces.

@Steven10172 well I admit I don't keep track of the specific functions, rather I google the particular function each time. String to int, String to float, and String to char. Bear in mind that I use these methods in regular c++ and have not tried them in the Arduino IDE myself.


text:
How to prevent breaking my Arduino by mistake?
What is the best practice to make my Arduino circuit more robust against prototyping mistakes (like shorting pins)? I don't want the controller to release its blue magic smoke while experimenting with it, what precautions can I make while designing a circuit?

Not best practices, but an alternative approach:
Consider the Ruggeduino instead of a standard Arduino. At a price ($39.95) comparable with the equivalent Arduino, the Ruggeduino offers:

Resettable fuse on each GPIO pin, i.e. all GPIO pins are protected from short-circuit to ground or other pins
All GPIO pins withstand 24 Volts
Reverse voltage protection (-30 V) on Vin
Microcontroller overcurrent protection
3.3V and 5V outputs on the board are over-current and short-circuit protected

Besides the above points specific to the question, the boards are designed to survive harsh environments and various mistakes. Also, the clock is more precise than on the Arduino.

I don't know if there's one best practice, but the following might be helpful:

Limit the voltage on input pins to 5.5 V maximum.
Do not short IO pins.
Use pullup or pulldown resistors when conecting switches or pushbuttons.
Respect the current limits (for each pin and in total). Use resistors.
The Arduino is just the brain, not the power station. If you have to drive higher loads, use simple transistors, Darlington arrays, etc.

Something that could be attached to bullet point 4: Yes, LEDs need resistors. :)  This has to be the most common Arduino mess-up ever.

I believe LEDs do not need an resistor if you have other means of limiting current or voltage.

Don't move any wires with the power on. Way too many boards are damaged that way.

Just because you have to be careful doesn't mean you can't do it; I have moved, connected, and disconnected wires all while powered up without any ill effects (other than an occasional required reboot). I have even soldered to a powered board. Sometimes troubleshooting wins over the 'correct' way to do things; a blanket prohibition smells like cargo-cultism.


text:
Dead reckoning with an accelerometer
Is it possible to use an Arduino, connected to a 3 axis accelerometer, to estimate a platform's continuous change in position and orientation? I have a small mobile robot, and given an initial position and velocity vector and sequence of acceleration changes, I'd like to calculate the current position and velocity vector.
From this question, it sounds possible, but I can't find any reference to projects or code to accomplish it with an Arduino. I understand the main problem will be the build-up of errors over time, but that's ok, as a rough estimate is acceptable. I'm also using wheel encoders to calculate the same values, and I want to use the accelerometer to account for errors in the encoders, like slippage. e.g. If the encoders say we're accelerating at 1cm/sec but the accelerometer says we're at a constant speed, then I know to ignore the encoders because the wheels are probably slipping.
I understand the math behind this, so the problem is how to write it in C to run on an Arduino. Is anyone aware of existing open source code for something like this? I'd like to avoid reinventing the wheel in-case anyone's implemented a similar system.

for each accelerometer:
   sample the accelerometer;
   low-pass filter its values (current and recent history) to remove noise;
   multiply by the sample interval to get the velocity increment;
   add the increment to a running sum to get velocity;

   sample the velocity (the running sum you just updated);
   maybe low-pass filter, as above;
   multiply by the sample interval, as above, to get the position increment;
   add the increment to a running sum to get position;
end;

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?

using the midpoint rule when multiplying by the sample interval will help a little bit

I considered the optical approach. It's still tricky. A hacked optical mouse sensor has a simple interface, but will only work when very close to very flat surfaces. A cheap USB webcam could be used instead, but then you need a beefy processor to calculate optical flow, which an Arduino isn't really suited for. And extra wheel would be cheap and simple, but would be mechanically cumbersome and awkward. An accelerometer is small, relatively cheap, and can be easily accessed by an Arduino.


text:
Conflict between OneWire and I2C?
I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.
So, I tried to merge some code from the standard examples (Wire/master_reader, Wire/slave_sender and dallas/simple).
When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)
sensors.requestTemperatures();
sensors.getTempCByIndex(0);

the serial monitor shows nothing.
I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.
Any suggestions would be appreciated.
Master
#include <Wire.h>

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

void loop(){
    Wire.requestFrom(2, 6);
    while(Wire.available()){
        char c = Wire.read();
        Serial.print(c);
        }
    delay(500);
   }

Slave
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(){
    sensors.begin();
    Wire.begin(2);
    Wire.onRequest(requestEvent);
 }

void loop(){
}

void requestEvent(){

    //sensors.requestTemperatures();
    //sensors.getTempCByIndex(0);

    Wire.write("hello "); // respond with message of 6 bytes
}

The only thing I see in OneWire.cpp that could maybe cause a conflict, is the use of noInterrupts() -- OneWire has these timing-critical sections where the interrupts have to be disabled, and maybe that's conflicting with the I2C slave. What if you swap the master and slave roles, so the Master manages the OneWire interface (thus avoiding possible conflict with I2C slave listener), and let the Slave device echo to serial monitor?

Indeed, when the master manages the OneWire, it seems to work OK . Nevertheless, I need to collect temperature data from two or more stations (slaves) and send them to central (master), so if slave cannot manage OneWire, that would be a problem. Thank you anyway.

The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.
1-Wire Peripheral Interface - for Arduino
What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.
volatile float lastTemp;

void loop(){
  sensors.requestTemperatures();
  float t = sensors.getTempCByIndex(0);
  // protect move of 4 bytes
  noInterrupts ();
  lastTemp = t;
  interrupts ();
}

void requestEvent(){
  Wire.write ((char *) lastTemp, sizeof lastTemp);
}

Untested, but that is the general idea.
Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: http://www.gammon.com.au/interrupts

If there is a conflict, could the slave switch between i2c and one wire?
I don't know how often your device needs to poll, but if you can get away with, say, once per minute, you could poll at regular intervals, and spend the rest of the time (99%) listening for the master. If it is not polled, the number read could be queued. When the master does manage to connect, it could collect the entire queue quickly.
The master, from it's side, could poll more frequently - say once every 53 seconds. About once or twice an hour, it would fail - it would need to handle that gracefully. No matter, it would get the data next time round. Even failing several times in a row wouldn't be a problem; the data would be queued at the slave for later transfer.


text:
Remove certain characters from char*
I've got an array of char* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char*, find and remove any colons but it just comes out as garbage.
  char* espData[15];

  // pull data from serial and tokenize with strtok > feed to espData

  for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]);
    espData[x][nullTerm - 1] = '\0';
    char* output
    for(size_t i = 0; i < strlen(espData[x]); ++i){
      if(espData[x][i] != ':') output += espData[x][i];
    }
    espData[x] = output;
    Serial.println(espData[x]);
  }

Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.

Arithmetic on a char* does nothing to its contents.

the comment tokenize with strtok suggests your code uses strtok, which would be one (probably bloated) solution - yet your code doesn't use strtok!!?

espData[x][nullTerm - 1] = '\0'; is redundant code

@Jaromanda Actually, it overwrites the last character in the string - or underflows the buffer if nullTerm is 0!

@JohnBurger - of course you're right

@JaromandaX the comment is just placeholder for code that I already had working correctly with strtok so I left it out for brevity.

@JohnBurger I hadn't thought of underflow on the buffer, I will put it a check for that. Do you know what kind of problems that could cause if it did underflow?

@Tri42 Shudder! I don't want to think about it! It depends on where you got espData[x] from: the heap? You're going to trash the previous object on the heap. The stack? You've going to corrupt another variable - or worse, the return address from a function. The data section? You're simply going to alter an unintended variable.

You've assumed that a char * is some kind of string object, since you've got the following line of code: output += espData[x][i];, and then later espData[x] = output;
It quite simply doesn't work like that. At best you can point output inside espData[x] and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.
Please consider the following code instead:
char* espData[15];

for(int x = 0; x < index-1; x++){
    size_t nullTerm = strlen(espData[x]); // Get current length
    char* output = espData[x];            // Start of string
    for (size_t i = 0; i < nullTerm; ++i){
        if(espData[x][i] != ':') {        // If it's NOT a colon
            *output++ = espData[x][i];    // Copy character 'up'
        } // if
                                          // If it WAS a colon, then
                                          // output does NOT get incremented
    } // for
    *output = '\0'; // End string off with NUL
    Serial.println(espData[x]);
} // for

That works perfectly, thank you! I have never been great with pointers

@Tri42 I just finished a pointer-post on another question. Take a look: http://arduino.stackexchange.com/a/25317/22924


text:
Arduino Due SD Card
I have an Arduino Due and want to save data to an SD card. For this I use a 3.2 'display of ITead with integrated SD slot (http://imall.iteadstudio.com/im120419006.html). This I connected to the Arduino.
However, the Arduino doesn’t detect the SD card (I've tried two different cards and also reformatted both). I wired the three SD ports correctly to the SPI. I wired the CS output on to pin 4, 10 or 52 (each one once tested), without success. I have also tried using ICSP instead of SPI, which the Arduino website suggests. Again, without success.
The test program I used is a  test program on the Arduino website for SD cards (the program in the end of the post, changes marked in bold). Is the problem in the program code or is it a hardware problem? If it is a software problem, could you send me a test program that is designed for Arduino Due?
I have invested several hours and read tens of forums but found nothing comparable. Also, the proposed solutions never worked.
/*
  SD card test

 This example shows how use the utility libraries on which the'
SD library is based in order to get info about your SD card.
Very useful for testing a card when you're not sure whether its working or not.

 The circuit:
  * SD card attached to SPI bus as follows:
** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
** CS - depends on your SD card shield or module.
        Pin 4 used here for consistency with other Arduino examples

 created  28 Mar 2011
by Limor Fried
 modified 9 Apr 2012
by Tom Igoe
*/
// include the SD library:
#include <SD.h>
**#include <SPI.h>**

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = **10**;

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

  Serial.print("\nInitializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
  pinMode(**chipSelect**, OUTPUT);     // change this to 53 on a mega
  **SPI.begin(chipSelect); //habe ich eingeführt, da es in einigen Foren erwähnt wird, funktioniert jedoch mit und ohne nicht. //I made this, becaus it’s mentioned in severals forums, but it didn’t workt wiht it and whitout it**     // change this to 53 on a mega

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card is inserted?");
    Serial.println("* Is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
   Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch(card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }
  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster(); // clusters are collections of blocks
  volumesize *= volume.clusterCount(); // we'll have a lot of clusters
  volumesize *= 512; // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);
  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
}

void loop(void) {
}

That board should have 2 CS pins. One for the display and one for the SD. I can't find any pinouts for that module. Try using a multimeter and test where all the pins of the SD-holder go to (especially the middle one).

Thanks very much,
I just controlled the connections from the SD-Card to the pins on the lcd-display, and they work. Also the wiring from the display to the arduino is okay.Do you know, if there are special needs to initialise SPI on the due?

Thank you very much. I solved part of the problem. I tried it whit a new SD Card. When I use pin 52, I am able to read the card information with the program above. But only if I use SPI.
Pin 10 doesn't work at all and Pin 4 a bit. If I work with Pin 4, it accepts the card, but it can't find out what format the SD card has. This is kind of weird, I think, because Arduino say alls three pins should work (http://arduino.cc/en/Reference/SPI). Does anybody knows something about this?

I use SD card with Arduino UNO. I connected SD card to the Arduino and I saw the Arduino don’t detect the SD card. Then  I see this tutorial and Arduino detect the SD card now.
Don't connect the SD card breakout board to Arduino and use non-inverting hex buffer(4050).


text:
HTTP POST request to IFTTT
I'm trying to send a POST request to IFTTT from a Node MCU. Instead of writing the code from the scratch, I've tweaked an already existing code (for GET request). It does not seem to work, what am I doing wrong? Needless to say, I replaced the WIFI ssid, the password and the IFTTT token. When testing the POST request with CURL, it works perfectly. Here's how the request should look like:
https://maker.ifttt.com/trigger/{event_name}/with/key/my_super_secret_token
...and the code:
#include <ESP8266WiFi.h>

const char* ssid     = "mywifi";
const char* password = "mywifipassword";

const char* host = "maker.ifttt.com";

void setup() {
  Serial.begin(115200);
  delay(100);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "trigger/{trigga}/with/key/IFTTT_token";
  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

    // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

Don't you need to send any actual data in the body of the POST request? Do you get any output on the serial console?

I get nothing on the serial console, not even error code. I don't think my request goes through at all.

@Gerben, Not sure about sending data. IFTTT recipes do not expect data. That's what they say: Make a POST or GET web request to:
https://maker.ifttt.com/trigger/{event}/with/key/my_super_secret_token
With an optional JSON body of:
{ "value1" : "", "value2" : "", "value3" : "" }
The data is completely optional, and you can also pass value1, value2, and value3 as query parameters or form variables. This content will be passed on to the Action in your Recipe.

I'm still not sure how to make this work but this one (with GET method) works nicely: http://bigjungle.net/blog/2015/6/26/connect-maker-to-anything-ifttt

When you say you get nothing in the serial monitor, does that include the Serial.print()s in setup()? Nothing at all shows when you run the sketch? Perhaps its a baud rate issue? How is the ESP connected to the Node MCU?

Problem I see is that the request is incomplete - the server will be waiting for your payload.
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");

You haven't specified a Content-Length header so the payload should start after the headers finish - but you don't send anything.
You need to (at least):

add a payload or
add a Content-Length: 0 header or
add a payload with a matching Content-Length: header.

You can use curl to see a full set of valid POST headers like this:
curl -v -d "" http://localhost

You can use Chrome and Firefox's Web Inspector's Network tab to look at the raw headers of requests too.


text:
Controlling an LED using a transistor (TL188)
I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.

(The resistor I used was 150 ohms, and I forgot to change the resistor value in the diagram.)
The program on the Arduino Uno was the basic Blink sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000 ms and turn off for 1000 ms. But when I connected the LED like the diagram below
For the first 1000 ms delay:

LED on pin 13 stayed on
LED connected using the transistor stayed off

For the next 1000 ms delay:

LED on pin 13 stayed partially on (it was dim)
LED with the transistor was on

I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?

Your transistor is a PNP transistor. They are slightly harder to work with than NPN transistors. I would suggest starting with an NPN transistor as a low side switch first before stepping up to PNP transistors.

Okay,. But the reason i used a PNP was, I have a bunch of 7segment LED(common anode type). so before connecting a segment i wanted to just try connecting an LED.

@Rob It's not too bad if all your voltages are the same - it's when you start trying to switch higher voltages with a lower voltage signal that you get difficulty - you can't get the base voltage up to the level of the emitter to get it to turn off. You then need extra drive circuitry or other trickery.

Did you connect ground correctly? Looks like an external power source (battery) but not ground is not common.

If you provide complete details of your setup So, giving specifics as I think it would help understand the maths, if you have say a 10 3.4v\25ma LEDs in 5 sets of 2 LEDs with a 100ohm resistor on each pair connected to a 9v supply along with an Arduino Nano (5v\40ma PWM output pins) with say a 2N3904 transistor (NPN, 200ma max, ~0.7v drop, 100-300hfe I think) how do you calculate "a resistor in the range 1K to 2K should do"?

You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.
A PNP transistor is somewhat harder to get to grips with than an NPN transistor.  Much of it does things backwards.
The operation you see seems to be completely correct when you understand how a PNP works.
With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.
When you have a voltage close to or above the voltage at the emitter the transistor will be off.  That means, providing a HIGH to the base will turn it off.  A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on.  That means providing a LOW to the base will turn it on.
So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off.  When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.
"But", you say, "the on-board LED doesn't turn off".  That is correct. It just gets dimmer.  That is, again, because of how the PNP transistor works.  Current (seen from the conventional sense - i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly*.

*That is a little crudely put, but kind of illustrates what is going on.

In what way are PNP transistors "harder to work with"? They do things "backwards" compared to a NPN but NPN works "backwards" compared to PNP.

@Rob Everything is the opposite of its opposite. Of course an NPN does the opposite to a PNP if a PNP does the opposite of an NPN.

Thanks for the explanation. So if some amount of current is flowing back through the pin and into the microcontroller, then the controller will get damaged right.? By adding a resistor as you suggested will also allow some amount of current to pass through. Am i correct ? so can a PNP be never connected to a controller's pin(even using a resistor on the base) directly ?

My point is, PNP works differently than an NPN but it is not more difficult. Just different.

Some current is safe. Up to the limit of what the IO pin can handle (40mA absolute maximum, 25mA sustained recommended maximum). The resistor is there to limit that current to a safe level so it doesn't exceed those limits.

@Rob It's not too bad if all your voltages are the same - it's when you start trying to switch higher voltages with a lower voltage signal that you get difficulty - you can't get the base voltage up to the level of the emitter to get it to turn off. You then need extra drive circuitry or other trickery

In no way is that statement true. You can make a PNP switch exactly the same way with no more difficulty, ignoring that the voltages won't be the same. Again, my point is, PNP transistors are different than NPN but no more difficult to work with.

@Rob They are when you don't understand them, is MY point. When you DO understand them, and understand their differences, they are no harder. But since the concepts are backwards compared with the easier to understand NPN it IS HARDER to work with them - UNTIL you DO understand them.  REMEMBER - THIS IS A BEGINNER STRUGGLING TO UNDERSTAND IT.

Which is exactly why you shouldn't confuse him by saying PNP transistors are more difficult to work with. That statement is false.

@Rob Ok, let's argue semantics then. Would you feel more comfortable if I used the phrase "More difficult for the novice to get to grips with" which means exactly the same in the context above.

No cause that's not always true. You should have just said "differently" and that would have worked.

@Rob Well, maybe if you don't like my answer, instead of getting all sarky and pedantic about the most minuscule of things, why not WRITE A BETTER ONE (which incidentally you could have done in the time you wasted here). I like my answer, the OP likes my answer. It's only you around here that seems not to.

I said nothing about your answer. I said your statement about PNP transistors is false and I mention it so others won't be confused by that. Such statements may dissuade new users from using PNP transistors. And that's a bad thing.

@Rob I see you are pretty new to this site. You have to realise that this site isn't like many of the other SE sites. This site is frequented by people who have pretty much no knowledge at all on the subject of electronics. You have to spoon feed them a little bit at a time. In the context of those people the phrase "PNP transistors are harder to work with" is completely correct. If I were on Electronics.SE then it would be incorrect. You have to understand this concept of context and learn a little about the site before you decide what is right and what is wrong.

The fundamentals of electronics do not change based on which forum you are on.

@rob I never said they did. It's the UNDERSTANDING of electronics that changes depending on which forum you are on. There is a concept called Wittgenstein's Ladder - I suggest you read up on it.

guys,.. thanks a lot. for the explanation..  and also for making the fell nothing is difficult

It really doesn't matter if you use a PNP or NPN transistor, they are just mirrors of one another. If you have some common anode displays then just start directly with the PNP's.
The flaw I see in your circuit is that you should always use 2 resistors to drive a LED (See schematic). R2 (as you already have) will limit the current to the LED; 220 Ohm you as illustrated is fine.
R1 is needed between the I/O pin and your transistor. This will limit the current through the I/O pin. For what you are attempting a resistor in the range 1K to 2K should do, even if you're switching a few LED's in parallel.
If you provide complete details of your setup we can always refine the calculations. One can then take into account the total currents from your displays, the amplification factor of the transistor (hfe) etc.


text:
Arduino Uno and Leonardo SPI clock can't be measured
I want to measure the SPI clock (pin 13) using the Arduino example code for the SPI library (very simple example). Basically independent from the loop function, the clock should be fired continuously.
I deployed the Arduino SPI example code on the board and measured pin 13 on an oscilloscope, but nothing was found, always zero volt.

Note: In contrast to Arduino Uno, on the Arduino Leonardo the SPI clock (SCK) is not connected to pin 13 (see SPI library, sub section "Connections")

On Arduino Leonardo the SPI signals are only available on the six-pin ICSP header.

Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop
#include <SPI.h>

void setup() {
  SPI.begin();
  while (1) {
    SPI.transfer(0x00);
  }
}

Thnaks alot mpflaga for your help. i will test it today and i hope it will work..thanks alot really !!


text:
Arduino Uno rev 3 toggling a 230 V submersible pump on intervals
I am software programmer and hobby farmer. While I was working on a hydroponic farming stuff, I had to use submersible pumps with timers. I don't want to buy timers that are actually a tedious scheduling process. so I am making one myself.
I want to toggle 230 V for turning a submersible pump(150-230 V and 18 W) ON/OFF. I read that Arduino may not able to supply enough input current that the relay requires. I am not sure about what transistor to use to amplify the input current. I came across a circuit diagram and a relay board. Do I still need to use a transistor and diode if I use this relay with an Arduino?
This is the two-channel relay I am about to use and the circuit is below.

Should I follow the circuit if I am using this relay? The relay has a tolerance of 250 V. What if the voltage fluctuates above 250 V? I am going to use a 9 V battery to power the Arduino. Feel free to explain anything that I may have to know.
UPDATE
Thanks marla for making it clear that I don't need diodes and transistors. Andy, as you said, I can't keep changing batteries often, and it will limit the system. Shall I use an adapter which reads output 5 V and 1 amperes? Will that drive the Arduino and be sufficient for both the relays?

@Andyaka could you please take a look at the update ?

The Arduino will easily drive this relay board, and it needs only a very small input current.
The board you linked to has a built-in optical isolation circuit, so there is no direct electrical connection between the Arduino-side of the circuit and the relay side. This should protect your Arduino if something goes wrong. For what it's worth, the product description specifies this board is suitable for "AC [...] appliances such as [...] motors". A pump is primarily a motor.
The voltage may fluctuate when the pump is started and stopped (Back-EMF). It's hard to say what this might do to the relay board if it goes way over specification. Perhaps you might be happier with a much more robust solid-state relay (SSR) that has a higher rating than the target load. Something
like SSR-25DA 25A Solid State Relay - White. Since solid-state relays are non-mechanical, they will not wear-out from repeated switching either.
You may also want to build some fail-safe sensors into your project. For example, water level float switches for both high-water and low-water marks.

I am not using solar power now. but thinking about failsafe. i power arduino from wall wart dc supply. so incase of mains failure i want to supply from battery so my arduino wont restart and mess things.


text:
Home-Made EL Tape chaser
I am working on a project involving 14 sections of EL tape. This is a circular array that incorporates a chaser effect with two lights lit on either side. originally I had found a small diy LED sequencer board that controlled both speed and brightness from 2 POTs.
Now I am attempting to adapt this to activate 7 relays (in place of the LEDs) which will in turn divert the power of the EL inverter to the tape sections.
Each relay is the connection of 2 EL panels to the (+) of the sole EL inverter while its (-) is hardwired in parallel among all the panels.
These are all small panels cut from a 3m length and have worked using this inverter independently both full length and cut. through some trial/error as well as some brightness and speed tweaking I have made this system work for a panel or 2, sometimes more, but other times the inverter and relays are working by the sound of it but the lights are not lighting or when they do they are skipping. It's intermittent too sometimes swapping panels works but at times it looks like the socket may be bad and the light is good other times it's the opposite even with the same pieces.
I have considered the sparkfun sequencer and it would most certainly save the day except that along with space being an issue my device also incorporates a few other Arduino devices including 2 servos, a sound module and a push button to start the sequence. however the sequencer doesn't seem capable to run 7 el connections as well as 4-6 other operations. is there a simpler way?
Am I missing components between my relays and lights?
Could I use my Uno in place of the sequencer? or can I expand the number of pins on the sequencer?
I would like to avoid daisy-chaining arduinos/boards as much as possible and even break down the number of separate boards I already have. I am trying to run this off of a single 9v and maybe a pair of button batteries.
Unfortunately I can no longer find the exact sequencer I am using but there are many 8 channel led chasers (w/o Brightness control) similar to mine on ebay.
Any help, insight, coding, recommendations anyone can offer would be greatly appreciated.
Thanks in advance.

Can you please edit your question to include what you've tried? Have you chosen any parts? What exactly do you need help with?

I can't bring myself to read the question. Have you heard of paragraphs? Or starting sentences with a capital letter? People here are volunteers who are keen to help you, but you have to make some effort to make the question readable. Please read How do I ask a good question?

My first guess is that you're using a power supply that can't supply all the power that the ELs, LEDs, relays, etc. are pulling. So the voltage drops (brownout) so low it makes the Uno act weird. Can you temporarily set up a test with a mains-powered power supply rated to supply at least 10 times the watts you think you might need? Can you help us help you by linking to which specific sequencer, specific relay, and specific EL you are using?

You raise a good point David. Though now that I have learned a lot more I am starting to think that perhaps the timing of the AC and relay switching is continuously falling out of sync and finds a different pattern each time I hook it up. I haven't been using anything for voltage controlled switches like triacs.

Is there a reason you've chosen relays? Every time the sequence changes you'll hear audible clicks. If this is not a problem then there's no real reason to change, but MOSFETs or (possible gate-drive) optocouplers would be both smaller and quieter.

just what was available combined with the, then, limited extent of my knowledge. I have since learned a lot more through research. I am currently experimenting with MOSFETs and triacs based on a design I found. Thanks for your input though CharlieHanson I will keep gate drives and optocouplers in mind as well. It all needs to fit in a narrow space but I may soon change that design as well.


text:
Direct port manipulation to write 40 bits
I have 5 shift register changed in series and want to shift the data quickly. I have learned that the internal shiftOut function is slow and direct port manipulation can speed up the things.
However, I am not sure to write code in the specific way.
The current working code block is:
#define SensDataPin 4
#define SensClockPin 9
#define SensLatchPin 8
updateAllShifters()
{
digitalWrite(SensLatchPin, LOW);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_1);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_2);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_3);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_4);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_5);
digitalWrite(SensLatchPin, HIGH);
}

As the code shows, I have 5 bytes which are written by independent functions and just before the return statement, these functions call "updateAllShifters()" to mark the changes.
I have followed few tutorials over the internet and have re-written the logic like:
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(int i=0;i<40;i++)
{
HOW TO CODE HERE USING THE DEFINED MACROS!
}
MSLATCHHIGH;

Edit: Coding example of this (but want a more optimized way):
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(byte i=0;i<8;i++)
{
 if(!!(byte_1 & (1 << i)));// LSBFIRST
   {
   MSDATAHIGH;
   }else
   {
   MSDATALOW;
   }
}
 MSCLOCKHIGH;
 MSCLOCKLOW;
//DO ABOVE FOR ALL REMAINING 4 BYTES
MSLATCHHIGH;
}

Is there a reason why you aren't using SPI?

I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow. I just want to optimize it to maximum possible level.

I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow.

You can change the SPI speed at any time. Once the device is selected (Slave Select asserted) then reconfigure the SPI bus for high speed operation.
eg.
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI is definitely the fastest way you can communicate with a shift register.


text:
Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array
I' m trying to change 1 to 0 in two-dimensional (5x5 matrix) for specific servo positions.First, i tried to program forward movement of my robot.  My code is like this:
#include <Servo.h>
#define x 5
#define y 5

Servo myServo;
Servo myServo2;

int pos = 0;

int counter1;
int counter2;
int integer;

void setup() {
  Serial.begin(9600);
  myServo.attach(9);
  myServo2.attach(10);
}

void loop() {

  int my2dArray[x][y]= {
  {1,1,1,1,1},
  {1,1,1,1,1},
  {1,1,0,1,1},
  {1,1,1,1,1},
  {1,1,1,1,1},
  };

  int robot = my2dArray[2][2];

   if (counter1 > 0){
     for (integer = 0;  integer <2; integer +=1){
      int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

     }
 }
}

  int moveForward(){
  for (pos = 0; pos <= 360; pos += 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter1 += 1;
    }
    return counter1;
}
}

int moveBackward(){
  for (pos = 360; pos <=0; pos -= 1) {
    myServo.write(pos);
    myServo2.write(pos);
    delay(15);
    if (pos == 360){
    counter2 += 1;
    }
    return counter2;
}
}

But i can' t change the [3][2] and [4][2] elements from 1 to 0. I get an error:
 error: variable-sized object 'my2dArray' may not be initialized

Can you help me?
Thanks.

Apart from the error mentioned below, you're using counter1 and counter2 before they are initialised.

The error is in this line:
  int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

The presence of the word int there tells it to try and make a new variable. You don't want to do that, since it's an error.  Lose the int and it might work.

Yes @Majenko is correct - You're re-declaring another array of the same name.  The loop counter "integer" is confusing too, since it sounds a little like "int".  It's common practice to use i, j and k as simple for() loop variable names.