text:
Problem with NFC on Arduino MEGA
My Objective :
I am trying to send my Mifare's unique number with some other parameters to my server database. As soon as the tag come closer to NFC, it detects, and some additional details are passed to the server Database.
Steps done :

I have Arduino UNO, Arduino GSM shield and Adafruit NFC shield . I had tried my test with UNO and works well. But to add some more features, due to memory salvation it could not be achieved through UNO. Then we moved to MEGA.
There are some changes need to be done with MEGA to make [url]http://arduino.cc/en/Guide/GSMShieldLeonardoMega[/url] GSM shield coordinate with the microcontroller[Take the Pin 2 out from GSM shield and with jumper connect Pin 2 with Pin 10]. Then we did and we tested it with GSM web client example and worked fine.
Now to accomplish our goal, when we placed NFC shield above the GSM shield and executed same GSM web client example, it is not working. And Suddenly once in a blue moon it connects to the GSM network and works . But often, it fails.

[code]
/*
  Web client

 This sketch connects to a website through a GSM shield. Specifically,
 this example downloads the URL "http://arduino.cc/asciilogo.txt" and
 prints it to the Serial monitor.

 Circuit:
 * GSM shield attached to an Arduino
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe

 http://arduino.cc/en/Tutorial/GSMExamplesWebClient

 */

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

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

  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while(notConnected)
  {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

What is the problem? and where is the problem ?

It is likely that placing the GSM shield between the Arduino Mega and the NFC shield is interfering with the GSM antenna.  Antennas react in strange and usually less useful ways when large conductors are placed nearby.
You could try reversing the order of attaching the shields, or you could try spacing the shields further apart using "stackable Arduino headers" (you can do a web search for suppliers).  If there is an option for an external antenna, that would be even better.
If you get GSM working, you might still have some trouble with the NFC shield, as it's possible that the GSM transmitter being so close could interfere with the NFD's circuitry - not because they use the same frequences, but just because any conductor so close might pick up electrical noise, and there will be various sensitive circuitry in the NFC electronics.

Power usage might be another aspect. It won't hurt trying to decouple the power supply.

if your design allows , the NFC is available on a module rather than a shield allowing you to separate the GSM and NFC. like this on ebay


text:
Over voltage on Arduino and Ardumoto
I am using Arduino Leonardo and Ardumoto to drive 2 12v motors running at 1.3 amps each.
I purchased a rechargeable battery of 12V with 5AH
I first started by plugging in the battery to the Arduino via the barrel jack. Arduino then sparks and is fried.
I read somewhere that I wasn't supposed to hook it up to the Arduino and to hook it up to the VIN ports in the Ardumoto. I purchased a new Arduino and plugged in the Positive and negative from the battery to the ports and now the Ardumoto board fried (copper lining on board burnt off).
I'm reading online and from what I've gathered, the Ardumoto can handle a max of 18 volts and a maximum of 2 amps per each output. I'm obviously missing something and would not like to fry my boards next time.
Please assist?

Are you sure you got the polarity right?

Would you post a diagram (a photo of something hand drawn will be fine) and, maybe photos of your wiring?

Alright, I went ahead and edited the picture

@IgnacioVazquez-Abrams I'm sure I had the correct polarity. If I didn't the first time you sure as heck know that I triple checked the second time.

@teknicalissue  You could add another image.  There are good photos of the Ardumoto on the web.  You could take one of them and point out exactly which copper trace have burned.

@NickAlexeev Done! It should be up now

Were the motors connected up at the time? Any chance of a short there?

That connector on the ardumoto is directly connected to VIN. And so is the barrel jack on the leonardo. The only reason it is preferred to use the vin on the ardumoto, is that the vin trace on the arduino board is not made for 4 amps. But in both cases nothing should have blown up like it did. You can maybe still fix the board by soldering a wire between the vin header just next to the screw terminal, and the vin-pin that goes down into the arduino. That way you bypass the blown trace.

From your description, everything should be wired correctly. It should not have failed.
Unfortunately, testing this sort of thing with a 5 amp-hour lead-acid battery is not a great way to get started, since a battery that large can source a lot of current, and doing anything wrong will likely produce immediate and spectacular failure.
Really, the only think I can think of is that you have the polarity of the output lugs/pins on the battery backwards. Buy a $5 multimeter, and check them.

source: Stack Exchange

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

sort: votes


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

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

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

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

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

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

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

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

@gerben arduino is (currently) powered via USB.

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

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

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

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

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

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

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

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

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

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

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

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


text:
Sensing busy-ness of a restaurant?
I'm planning on an Arduino project for a restaurant I work at that would require determining how busy it is at any point in time, but I'm not sure how I would go about procuring this information.
I don't have access to any of their IT systems or I would have simply pulled the data from their till systems.
I was thinking perhaps measuring the ambient sound of the restaurant as it gets quite loud during peak time but that could be thrown off when the music volume is adjusted.

There are a few ways to  go about it but my initial thoughts would be to detect people entering (and exciting) the front door and simply keep a running total.
Motion detector
http://www.adafruit.com/products/189
IR beam detectors
http://arduino-info.wikispaces.com/InfraredBeamPair

I don't think this is possible as the project must be small and placed in a dedicated corner of the restaurant, which is away from the door. If I were able to move it near the door, how would you distinguish between people entering and exciting?

You could use a variety of sensors but easiest would be a pair of $10 proximity sensors and depending on when they trigger you could work out if which direction the person was travelling. Alternatively use IT beam detectors http://arduino-info.wikispaces.com/InfraredBeamPair

I expect that a direction-of-travel based people counter might often loose track in many restaurants I'm familiar with - too many people waiting in the entryway, holding doors for others in their party, walking in side by side, etc.


text:
Use Arduino's PWM to control motor direction?
I'm looking for a way to allow Arduino to control a motor using PWM.
So far what I have gathered is that using Arduino's PWM sets the digital value of 255 to 5v and 0 to 0v.
However what I am looking to do is to set the motors to stop at 2.5v, move forward as it approaches 5v and move backwards as it approaches 0v.
Any suggestion on how I would go about accomplishing this will be highly appreciated.

Just use two pins. One for ground and the other for 5v (with PWM). To reverse, have the first do the 5v (pwm) and the second be ground. Just note that the arduino pins can only provide enough current to power a small motor. Alternatively use an H-bridge

You seem to have misunderstood PWM here. It's actually a digital signal which is constantly pulsing on and off very quickly (several hundred times per second). You don't actually change the output voltage at all -- it's only ever HIGH or LOW (+5v or +0v). The thing you change is how long the signal is HIGH for on each pulse.
This page gives a deeper explanation: http://arduino.cc/en/Tutorial/PWM
When you're controlling a DC motor, this approach is actually better than varying the voltage. The constant pulses still make the motor turn at an adjustable speed, but without losing torque. PWM is also useful for controlling the brightness of LEDs, which don't respond so well to changes in current/voltage.
To address your original motor control question, there's no sensible way to change the motor's direction using the PWM value. You will need some additional circuitry which is able to reverse the polarity of the connections to the motor (meaning your PWM value just controls speed, and doesn't care about direction).
An H-bridge is the usual approach for this. Here's a fairly good tutorial which covers the basic principles: http://www.instructables.com/id/H-Bridge-on-a-Breadboard
Obviously you'd need to modify it for use with your Arduino project. The push switches could easily be replaced by digital signals from a couple of Arduino pins. The motor's power supply would be controlled by the PWM signal. You'll need an extra transistor for that, because you can't safely power the motor directly from an Arduino pin.

You can use a MOSFET to control a DC motor directly from an Arduino. Using a H-Bridge is another way to control DC motors. Probably the L298N is the most used one but I prefer TB6612FNG. It's a bit expensive, but uses much less current and is something with a better response.
You will find tons of tutorial with both modules.
Good luck!

continuous rotation servo demonstrates a different approach of using PWM.
A continuous rotation servo is a standard servo modified in 2 ways. First the "position feedback" in the servo is disconnected and set to always read as if the servo was in the center position. Second the "stop" which physically prevents the motor from turning 360 degrees is removed.
Then if you set the servo to 0 degrees it rotates fast in one direction if you set it 180 degrees it move in the opposite direction.
More information:

http://www.instructables.com/id/How-to-modify-a-servo-motor-for-continuous-rotatio/
https://learn.adafruit.com/modifying-servos-for-continuous-rotation


text:
Eclipse AVR for arduino not uploading
I recently read this post about setting up Eclipse for Arduino.  I Build the test project with no erros, but when I go to upload my test project it just hangs at 5%, with no error messages.
If I unplug the arduino-uno it cancels the upload, so I know it can see the arduino board. It is just not uploading. Does anyone have any ideas as to what is wrong?
I don't know whats changed, but now it doesn't hang i just get a message after trying to upload:

avrdude: stk500_recv(): programmer is not responding

Does the Arduino IDE upload successfully with the identical physical setup?


text:
Two 300RPM 12V DC motors connected to arduino motor shield r3 power supply
I have two 300RPM 12V DC motors connected to arduino motor shield r3 that is mounted on arduino uno board.
Problem is my motors  runs very slow some times not even running.
After googling I found I need to use external power supply. I did  supplied 9 volt dc power to arduino motor shield r3.
But still motor is running very slow what could be the issue.
My other questions.
When supplying power to arduino motor shield r3  via external power supply pins do I need still need to provide separate power to arduino uno board via power jack.
Can I use 9 volt dc for arduino uno board and another 9 volt batter to arduino motor shield r3.
Is single 9 volt batter enough for running two 300RPM 12 dc motor.
My circuit.

My program
          void setup() {

          //Setup Channel A
          pinMode(12, OUTPUT); //Initiates Motor Channel A pin
          pinMode(9, OUTPUT); //Initiates Brake Channel A pin

          //Setup Channel B
          pinMode(13, OUTPUT); //Initiates Motor Channel A pin
          pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

        }

        void loop(){

          //Motor A forward @ full speed
          digitalWrite(12, HIGH); //Establishes forward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 255);   //Spins the motor on Channel A at full speed

          //Motor B backward @ half speed
          digitalWrite(13, LOW);  //Establishes backward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 123);    //Spins the motor on Channel B at half speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

          //Motor A forward @ full speed
          digitalWrite(12, LOW);  //Establishes backward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 123);    //Spins the motor on Channel A at half speed

          //Motor B forward @ full speed
          digitalWrite(13, HIGH); //Establishes forward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 255);   //Spins the motor on Channel B at full speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

        }

9V batteries have very low current source capabilities. Your motors will work, but they will be "weak" once you apply loads to them. They will seem fine without loads.

how are you running the motors anyway? digital HIGH or using PWM?

How to overcome this problem.. any solutions

@KyranF I updated the question with program. Please let know if any things is wrong.

well in your code in both parts when you 'engage brake' for the motors, you are not correctly applying break to motor B. You double set pin 9 high. lol.

sorry what is AAs i cant understand.

anyway, i am not quite sure what is wrong. I think it's you are not applying enough voltage to begin with, try with 9V batteries and get back to us. using separate supply for motors and Uno is probably a good idea if you can.

@KyranF you mean you want me to try separate 9v batter for motors and another 9v for Uno board.. Did i understand you correctly.

well yes, but you do not have to.

@KyranF I dont have to ?... why

9v "transistor" batteries are rarely suited for motors, and generally a poor choice for the arduino itself. Even with a lower impedance 9v supply, your 12v motors would probably perform poorly with only 9v in and the motor shield itself loosing at least another volt.

@ChrisStratton What is the solution. What battery or should I have do to make run at decent speed. Any suggestions..

Disconnect the motors and battery from the motor shield. Then do these tests: 1. When you connect your 9V battery to one motor, does it run much more quickly, and well enough? 2. When you connect both motors to the battery do they run okay? If either answer is no, then the current approach is not going to work. Even if it is okay, the Arduino motor board will reduce the battery voltage, making things worse.

The external power of the shield is connected to the VIN pin, so it will power the Arduino via that. (vin goes to the voltage regulator that will provide the 5v the arduino needs).
You can connect two batteries in parallel to provide mode current.
But since they are 12v motors, they would need 12v to run at maximum power. 9v is a lot less than that.

would you please give a word here : http://arduino.stackexchange.com/questions/9145/which-battery-should-i-use-to-power-arduinomotor-shield-two-motors


text:
RF Remote Clone using NRF905
I have come across the various blogs which talks about cloning RF remote using cheap 434 MHz Tx/Rx and RCSwitch library.
I tried using RF 434 MHz ASK (https://www.sparkfun.com/products/10532) module with arduino, but the range I get it very less , just around 5-6 centimeters. Seems these RF 434 MHz modules are not stable. So I am planning to use now another RF Module which uses NRF905.
Link -
http://www.ebay.com/itm/2pcs-NRF905-wireless-module-PTR8000-wireless-transmission-433-486-915MHz-/270963407796
My query is can I use NFR905 based RF modules which is also 434 Mhz to clone any existing remote working on 434 MHz. Please help

You can connect an external antenna to pin 8 on that module. Just use a piece of wire that is 17.3cm long. But since the range is that bad to start with, probably means it isn't tuned very well. I'd return it, or try fiddling with the pot at the back. Not sure why Sparkfun has these crap transceivers for sale. Transceivers without a crystal are very inaccurate in their frequency.
If you only need to transmit, I'd suggest this products: https://www.sparkfun.com/products/10534
 . Those worked great for me, and are currently switching on the power sockets for my lights when it gets dark enough.

Thanks Gerben for your inputs and response. I will try out with a pot added at the back. Also, trying out with nRF905. This uses FSK instead of ASK. Is this module (nRF905) good for using in home automation or should I use ASK based RF modules only.

I really don't know the nRF905. It will probably work for home automation, but I'm not sure if it's the easiest to work with. E.g. the nRF24L01 I'm using for my home automation takes care of a lot of stuff, like addressing, data integrity, auto-ACK etc.. Using a raw data module like the module in the link I posted above, you'd have to implement all of that yourself. Glancing through the datasheet it look like the nRF905 does some of that too. The lower frequency may also help in getting a better range that the 2.4Ghz products out there.

Thanks Gerban for your inputs and views, really appreciate. I am getting my nRF905 in couple of days. Will post the feedback once I use this.

+1 for the external antenna suggestion and the comment about the crystal (nowadays I always use 434Mhz with crystal). NRF24L01 is 2.4Ghz and will probably not suite for cloning an existing 434 RF remote. Also, the Sparkfun's product is a receiver, not a transceiver.

can I use NFR905 based RF modules which is also 434 Mhz to clone any
  existing remote working on 434 MHz.

The answer is, inevitably, no, you cannot. Each such remote controlled device might have a different digital modulation scheme. Best if you could focus on one specific product and adjust your design to fit it.
Note that the two products you are referring to are both 433Mhz but differ by many other parameters, such as:

Supply voltage (5v vs 1.9v-3.6v)
Interface (single digital output vs SPI)
Capabilities (receiver vs  transceiver),
Presence of a crystal
Power consumption
Price

This might affect your final design as well, and should be taken into consideration.
For example, from my experience, if you will shrink your project into a ATtiny85 at some stage, you might not have enough I/O pins to satisfy the NRF905, but enough for the Sparkfun's product (or a similar one).

but the range I get it very less , just around 5-6 centimeters.

The maximum range I got with the Sparkfun's module using a half-wave antenna (34cm) was ~40 meters inside a building and about 80 meters in open air. My testings with quarter-wave length was about ~30 meters inside a building.


text:
Driving power MOSFET from 3.3v or lower Arduino Pro Mini
I want to control a low voltage (hobby class) motor with a 8Mhz/3.3v Arduino Pro Micro.  I'd like to power both from 2 alkaline cells.  The motor draws approximately 1 A @ 3V with new batteries.  I would be doing PWM of a couple of channels at the normal Arduino rates.
My thought is to connect the batteries to the Vcc pin (not Vraw) and run the Arduino unregulated at about 3V, but somewhat less when the motor is running.  I'm willing to reprogram the fuses for a lower brownout voltage (or none) if needed.
I'm feeling my way on the rest of this - I'll lay out my (perhaps naive) approach and get some feedback about whether I'm understanding it, and how to proceed.
With such a low battery voltage, a TIP120 darlington seems to drop too much voltage and substantially reduce the motor speed/power.  So I'm thinking that I need to use a power N channel MOSFET, and it appears that I need to be fairly selective to get one which can sufficiently turn on with a <3V gate to source voltage.
I'm considering something like the

FQP30N06L http://www.mouser.com/ds/2/149/FQP30N06L-244344.pdf

If I read the datasheet correctly, Vgs of 3V and a load Ids of 1A would result in less than 100mV drop Vds.  But this transistor may be overkill, and the TO220 package is larger than I'd prefer.
If I'm willing to deal with SOT-23-3 surface mount packaging, there are some options like:

Toshiba SSM3K324RLF http://www.semicon.toshiba.co.jp/info/docget.jsp?type=datasheet&lang=en&pid=SSM3K324R
Infineon BSS806NE  http://www.mouser.com/ds/2/196/BSS806NE_Rev2%2001-359816.pdf

If I'm reading it right, with 2x1.5v (nominal) batteries directly powering an Arduino Pro Micro, I can sufficiently drive Vgs to handle 1A Ids at a small Vds and a low enough power dissipation, with any of these three.
I would put a reverse diode and a cap across the motor.  I've seen devices with a small electrolytic across the motor terminals, and I've seen a smaller value ceramic cap - what's the best practices?
Is this a feasible and reasonable approach?  What are the gotcha's that I need to take into consideration?  Any advice about choosing among these (or other) transistors?
My concerns are: not understanding MOSFETs enough, and the unregulated power supply being too noisy for the ATMega328p when it's also powering the motor.  Can I handle the latter by adding another cap or two across the Arduino Pro Micro's Vcc/Ground?
Backup option: run 3x1.5v alkalines and power the Arduino Pro Micro through its regulated Vraw input.

The FET seems to work, tho using PWM creates a lot of audio noise unless I use the highest PWM frequency.
My current concern is motor noise on the power supply.  As it turns out, I also want to operate a radio transceiver like the nRF24L01+, which is somewhat finicky about its power supply.  This issue of a noisy battery power supply and how to mitigate it is part of the original question (other than adding the nRF) - should I pursue that aspect here or start another Q?

I don't think the mosfets will be an issue. Looking at the last one (BSS806NE); in figure 5 in the datasheet you see that for 1A and 1.4v (Vgs) you'd get a Vds of only .1v.
I think a bigger problem might be the voltage of the batteries dropping under load. You'd have to measure that with a multimeter while the motor is running. A simple cap might help with a little noise, but not with the voltage dropping while the motor is running. Not sure how much the AVR would mind having its supply voltage dropping all of a sudden.
Of the top of my head the minimal voltage of the Atmega328 @8mhz is 1.8v, while default fuse settings use 2.7v, so I'd probably change to fuses to make BOD at 1.8v. Other fuses don't need to change.
Backup option sound good, though you might have to go with 4 x 1.5v depending on the voltage drop under load. Another alternative might be to have two sets of 1.5v batteries in parallel, halving the current load on each battery.


text:
MMA7361 readings deviate a lot
This is what I get using a MMA7361 breakout board (just the IC, no resistors or capacitors). The IC is powered using arduino nano's 3v3 pin.
The x, y, z values are read from analog pins A0, A1, A2. The readings are subtracted with 338.
x   y   z
-4 -26 44
44 -27 -5
-57 -11 27
-29 -23 22
28 -21 9
-44 3 20
-26 -14 39
26 -32 -8
-17 -12 19
-30 -15 35
4 -26 14
24 -43 49
-58 -19 0
16 -29 24
9 -48 13
-58 -42 12
12 -47 14
-24 -31 9
-46 -31 10
16 -52 1
-43 -21 8
-31 -25 16
37 -18 11
-45 -10 20
-22 -36 16
27 -19 20
-5 -9 1
-59 -10 10
37 -18 30
-53 -18 16
-30 -8 10
54 -19 17
-27 -29 15
-40 -23 -14
-1 -18 19
34 -22 2
-35 -24 41
13 -17 7
-14 -17 21
-39 -14 35
-19 -31 6
62 -9 34
-63 -16 16
-12 -6 23
60 -33 36
-45 -2 34
-18 -15 9

As you can see the x value, when the whole thing is not moving, can range from -59 to +44. This looks very unusual as other people's reading seems to have just +-3 deviations. What might be wrong with my setup?

(just the IC, no resistors or capacitors)
What might be wrong with my setup?

That's easy: You miss the capacitors ;-)
Check figure 5 of the datasheet and try again.

I'm still getting +-20 of deviation with capacitors on.
Could it be wire length? Or I'm worried that I might have damaged the IC when soldering it with a torch (literally).

Wire length can be an issue. You mentioned "other people"... ask them for their schematics. Maybe they have higher capacitance for their capacitors. This will make the signals smoother, but also slower.


text:
From transfer function to arduino
This question might seem stupid, but I have been curious about it for a long time.
So I am a new engineering student, and we learned a lot about "designing a controller". For example, design controller for a car steering system and so on. All the "controllers" we designed are in the Laplace domain aka s-domain. And most of the times it will be just a transfer function. So how do real control system engineers use these transfer functions in arduino and other microcontrollers? I mean you cannot just put the function in there right?
Do you have to convert the transfer function to some other form and write the code for the microcontroller or is there a simpler way to do it?
Thanks for your time!

Let's assume you have an Arduino that you have arranged to sample a signal with a sample rate of 1/T that is then processed by your controller. Let's also assume that the processing time for your controller is small compared to T e.g. 0.1/T
Firstly, you need to convert the controller transfer function to discrete time. There are lots of ways to do this. Matlab has a convenient c2d() function. One way you can do it on paper (not the best way), is to use Euler's Method.
s=(z-1)/T   where T is the sampling period.
Converting a transfer function then: (s+a)/(s+b) => (z-(1-aT))/(z-(1-bT))
So now you have a TF in z such as : Y(z)/X(z)=(z-c)/(z-d)  where Y is the output and X is the input.
To implement this in a controller you need this as a difference equation in terms of delays. So convert the equation to a function of (z^-1) which is a delay:
Y(z)/X(z) = (1-cz^-1)/(1-dz^-1)
and re-write as:
Y(Z)(1-dz^-1) = X(z)(1-cz^-1)
Y(Z)-d.Y(z).z^-1 = X(z)-c.X(z).z^-1
and change to sample time treating z^-1 as a delay:
y(n) - d.y(n-1) = x(n) - c.x(n-1)
rearranging:
y(n) = d.y(n-1) + x(n) - c.x(n-1)
You can implement this easily in the Arduino by realising that y(n-1) is the previous value of y(n) and similarly for x(n), and x(n) is the value input to the controller; i.e. the reference minus the output from the ADC.

Would you mind giving us some code example in order to implement these kind of exercises? I would be really thankful to you. In my case a have a transfer function a/s+a, "a" is a value a have to enter through a keyboard connected to the arduino mega, i have calculated the operations like this, using tustin method: a1Z+a2/b1Z+b2 where each value is: a1=a2=(aT/aT+2); b1:is always 1; and b2:aT-2/aT+2. T is the sample time.
As you can see I have calculated everything but I have difficulties in the programming code in arduino mega, if you can help me I would be really thankful.


text:
analogRead function not working in MATLAB
I am new to Arduino and I am trying to control it through MATLAB.  I have downloaded the arduino IO package and installed it.I am using MATLAB 2014a.I have a LED and I change its brightness by changing the PWM voltage as follows :
a=arduino('COM3');
brightness_step = (5-0)/20;
   for i = 1:20
      writePWMVoltage(a, 11, i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end

   for i = 1:20
      writePWMVoltage(a, 11, 5-i*brightness_step);
      val=a.analogRead(0);
      display(val)
      pause(0.1);
   end
clear a

Everything works great except for the analogRead part which throws the following error :
No appropriate method, property, or field analogRead for class arduino.
What am I doing wrong?

That function is part of legacy code.

NOTE: This solution (formerly known as "Arduino IO Package") is no
  longer supported. It is recommended that you use Arduino support
  packages that are developed and supported by MathWorks:

MATLAB Support Package for Arduino Hardware: Read, write, and analyze data from Arduino sensors
  http://www.mathworks.com/hardware-support/arduino-matlab.html
Simulink Support Package for Arduino Hardware: Develop algorithms that run standalone on your Arduino
  http://www.mathworks.com/hardware-support/arduino-simulink.html

Use this legacy support only if one of the following is true:
- You are using MATLAB R2013b or earlier (but not earlier than R2011a).

You are using 2014a, so its probably the reason analogRead isn't working. Get the more recent package and use this function instead:

Sorry, I don't have MatLab to verify this but try this in the two places you call a.analogRead(0);
val=analogRead(a,0);

This is based on what appears to be the classdef for the arduino object.

Both val=analogRead(a,0) and val=a.analogRead(0) appear as valid examples in the function's description. I don't understand why one would work but not the other, but that's no reason not to try...


text:
Webservice C# JSON to Arduino
I have a project in Microsoft Visual Studio C# and I have to pass JSON data to my Arduino via Ehternet Shield.
This is how it works:

Is it possible? How to do it?

Yes.
If you're using an Ethernet Shield, you should be able to run a webserver on the Arduino and simple do an HTTP request from your C# webservice to the Arduino.
Check this tutorial on how to write a webserver for arduino using the ethernet shield: http://arduino.cc/en/Tutorial/WebServer
Doing an HTTP request of any kind from C# should be easy enough and is not in the scope of this site.


text:
Why does the battery eliminator connected to the wall provide a better spin to my dc motors than my battery of the same voltage?
Using a H-bridge, I've connected my DC Motors to an Arduino. When I accept the external power source from a wall, using a 9V battery eliminator, the motors spin well and consistently. However, when I connect it to a 9V battery, the motors spin slower, and the speed deteriorates till the motors stop. This happens in approximately 5 minutes. I checked with multiple 9V batteries of the same type. I have tested the batteries to check if they're dead after the motors stop. They are not, and if I reconnect the motors to them, the same process occurs all over again. I have checked for short circuits, and there are none. Any possible ideas as to why this is happening?

Does the battery heat up? If you immediately disconnect then reconnect after running down do the motors go again?

No, the 9V battery does not heat up. Once i reconnect, the motors spin, but still very slow compared to the wall power.

First off, never use 9V batteries to power motors or any device that consumes more than a few hundreds mA. Those batteries are just too weak.
Now a battery eliminator is not a pure equivalent as it can typically supply 800 mA or more, depending on the model you get.
The only commonalities between the battery and the eliminator are the 9V voltage and the socket.
If you want to power DC motors with batteries then rather use several 1.5V batteries in series.

Yes - those 9v batteries are series strings of tiny (smaller than AAA) 1.5v cells, simply use the same idea with larger AA, C, or D cells.

The question is not about volts, but current.
A 9V battery is notoriously bad at powering anything that requires high current, like running a motor. Due to to chemical nature of the battery, the 9V will struggle to keep supplying enough current and will fairly quickly drain.
A regular alkaline 9V block can supply you with 565 mAh, which is not much if you power motors. You'll have more luck with LiPo (lithium polymer) batteries, which are capable of supplying 2200 mAh or more!
To learn more about different types of batteries check out https://learn.sparkfun.com/tutorials/battery-technologies
Wall power can quite easily provide the required current your motors need.

Batteries use a chemical process to produce power. If you draw to much current (motors use quite lot) the chemical process can't keep up and the voltage will drop, resulting in a slower running motor. Try connecting two batteries in parallel. That way each battery only has to produce half the current.

That's not really a good solution.  What's missing from the analysis is that the process you describe - in effect the internal impedance - is very limiting for the 9v "transistor" battery, and it simply should not be used for most motor loads.


text:
Communicating between a computer and multiple Arduinos
I am designing a experiment of controlling 6 small wind turbines wirelessly. For each wind turbine, I need to measure power time series (or voltage or current time series) from the generator, and control blade pitch angle, yaw angle, and generator load (using variable resistance). The control input will be all PWM signal.
I am planning to put an Arduino UNO with a ZigBee wireless module to each wind turbine, making it measure the power time series and transmit to the central node, as well as receive the control input from the central node and command the control input to servo motors. The central node will be additional Arduino UNO.
Here are my questions:

Is it possible for each Arduino to send time series signal to central node wirelessly without interference with other Arduino? (6 wind turbines transmitting time series to a central server). If it is possible, How can I implement such network ? recommending a source for learning would be also greatly helpful.
Interface between the central node and the computer software: The algorithm in the computer need to process the received power time series and determine the optimum control input for 6 wind turbines. Then these control input should be transmitted to wirelessly to 6 wind turbines. In such case, what is the good option to interface the algorithm and the Arduino connected to the computer? Currently the algorithm is written in Matlab. I heard there is the sketch interfacing Arduino and Matlab, is it efficient enough for such project?

It is very interesting project. In my opinion, i would not do like you want to control generators from one point.

Look at ZigBee and Wireless sensor network. It is possible. Do more search, also there are several books about networking.
I think that would be more efficient to control the wind turbine with an Arduino and send only data to the main computer. Main computer should do some calculations or send some main configuration data or control on/off wind turbine basis of:
2.1  Metrological data (wind speed or else);
2.2 Storage SOC(if you will store it in batteries or somewhere);
2.3 Required power of grid and etc. etc.

Arduino UNO like you said, connected to computer could do just data collection and making it compatible with computer(MatLab or whatever) and spread control data from PC to targeted Arduino.
Added links
Could not add more than 2 links due to low reputation :)
http://www.digi.com/pdf/wp_zigbeevsdigimesh.pdf , http://forum.arduino.cc/index.php?topic=105273.0

In such a case I would use HTTP requests from a web server using PHP to arduino.
In a simple explanation the PHP sends a string in its url and then the arduino checks for that string and do something.
I have used such method and it served me well and actually fast too.

I have done a similar project in the past;
for simplicity's sake, lets call the 6 arduino's + turbines "Endnode" and the central receiving and sending arduino the "Controller"
The general idea is that each endnode periodically sends a zigbee package(it's important that it is an actual zigbee package, do some research on this subject) to the controller.
The controller can receive these packages in the form of a serial interrupt. that way, whenever a package is send, the controller instantly starts to handle it.
The controller can send the data to the computer, I recommend using http transfer, as it's easy and probably fast enough.
This proces can be reversed in order to send a command to the endnodes to control the turbine.
If you're interested in my previous work on this subject, I reccomend you check out:
Libraries of my previous work
And
The sketch used for the project
I appologize for any weirdness, as it was a student project. But it worked flawless ;)
Good Luck!

From experience my recommendation would be to use Arduino nanos and NRF24L01 modules, using this library: http://tmrh20.github.io/RF24/
Use nanos for monitoring and one for acting as host. I presume you are comfortable writing a vb.net app or similar for reading the host serial data via usb?
Quite simply, your six monitors will await signals addressed to them. Depending on that signal, they can either transmit their current data, or change turbine settings, etc.
With clever coding you can avoid multiple arduinos attempting to transmit simultaneously, and avoid any interference issues.
Good luck, drop me a line for more info if needed. Using nano clones and pack of NRF24L01 modules for < $10 you'll be able to set this experiment up very cheaply - aside from the turbines!


text:
Micro not detected, can't reset
I just picked up a new Arduino Micro for a project, but the first time I tried to upload to it, things went terribly wrong. The USB cable was loose, so the power light kept blinking on and off. When I did get it stable, I accidentally had 'Uno' selected under 'Tools->Board'. I think this was the source of the problem.
I'm aware that the solution for these kinds of problems is to try to upload some simple code while in bootloader mode, but pressing reset shortly after pressing the Upload button. But this board doesn't even respond when I press reset. I have tried it with both the on-board button and with an externally button linking RS to ground.
Furthermore, the board doesn't show up in my Device Manager, not even as an "Unknown Device". The device managed doesn't even refresh when I plug it in.
I know the connection is okay because the power light is on. And I know it's not a driver issue or an issue with the port, because I have no trouble getting a different Micro recognized.
The only thing I haven't tried is burning the bootloader through ICSP, since I don't have the right cable. Is there anything else I can try, or is this just bricked?
Thanks, everyone

That appears to be based on a 32u4, so if it isn't physically damaged you may be able to recover it using DFU mode - at least it's worth doing some research on the subject.

This certainly seems plausible, but it looks liek getting into DFU mode requires resetting the board via the ICSP headers. I have tried that, and just like when I reset with the pushbutton or by connecting the RS pin to ground, the board doesn't respond in any way. Or do you think I'll regain the ability to reset later on in the process?

You can use another arduino as ICSP programmer.

This is probably way to late, but with newer editions of the Micro you have to "double-press" the reset (input).
I have had some experiences today where playing with low-power modes that shuts down the usb interface, and the only way I got it back was activating the reset input twice fast, and then uploading a new scetch (this time with a 10sec delay before any usb-chaning stuff takes place!)
Richard


text:
Do ultrasonic sensors sense through transparent materials?
Do ultrasonic sensors sense through transparent materials?
In my case, I have to read if there's something inside a transparent acrylic bottle.

No, ultrasonic sensors will work only in gas environments (typically, in air atmosphere).

Only through materials which are transparent to ultrasound. I think rubber or polyurethane work. See for example the material that covers the reverse sensors in cars. @jfpoilpret I don't think they will work in e.g. helium gas.

The issue is not transparency to ultrasound (sound will travel within hard plastic for some distance quite well), but rather presenting the same impedance at the ultrasonic frequency as the intervening air does.  Since most solids do not, the majority of incident energy reflects off the discontinuity, and only a small amount transfers through.

I'm assuming you mean a "normal" sensor, like this:

Ultrasonic sensors work by sending out sound waves. Obviously, sound waves don't care whether a material is transparent or opaque, so they are blocked just as easily by acrylic as by a brick wall.
Side note: If you look on the front of an ultrasonic sensor, you will notice that it is covered by a screen, not glass or plastic. This is why.

Which means that it would sense through grids, meshes, nets or veils, and may even sense through thin but opaque fabrics. Fabrics can cause strange readings because they do not provide a solid enough block. Visible light opacity has nothing  to do with it.

Ultrasonic sensors detect echoes of high frequency sounds bouncing off of a boundary between  air and some other substance.
As others have pointed out, the light transmission properties of an object (transparency to light) has nothing to do with its transparency to ultrasonic sound waves.
It's possible to project ultrasonic sounds through solids or liquids, but that's not what these sensors are designed to do.
Trying to send ultrasonic pulses through an acrylic bottle will no doubt mess up the signals. Try pointing one of these sensors at an acrylic bottle in a controlled environment (fixed distance, mounted firmly and the same way each time, a solid back-stop at a fairly large, fixed distance behind the bottle to avoid varying echoes from behind the bottle) and check the distance measurement with the bottle full and empty. If you detect a difference in readings, then use those 2 different distance values for full and empty. (But make sure your production environment is the same as your test environment, including the area around and behind the bottle you're measuring)

Wanting to use HC-SR04 to measure water level, but protect the SR04 from moisture I tried covering with cling film, the most minimal film I could find. No - the sensor sees it and reports 1cm distance.  So these sensors have to be left exposed - probably won't last long at top of my water tank.

I'm unsure how useful answering a question (that has received multiple answers) from 2014 with something that's much more of a comment is. I think there are much more applicable sensors for this

Well, you can visualize babies in a womb using ultrasonic sensors. So why should it be a problem to "hear" inside a bottle? Maybe not with the sensors you can afford, and maybe not with an arduino, but basically it is possible, even if the bottle is not transparent.
if the bottle is open, and the content is liquid, a simple approach could be implementing a kind of ultrasonic range finder. This can be done with comparatively cheap hardware.

Ultrasonic sensors sense the reflection off an impedance discontinuity.  For the "in-air" type of sensor most likely being discussed, that would be the transition between air and a solid or liquid surface, and their receivers typically only report the first major reflection.  For a medical sensor, the sensor is coupled to the body with gel to improve the impedance match, and a much more sophisticated receiving system picks up partial reflections (at multiple depths, from multiple directions) off of density variation of tissues and fluid within the body.

@Chris Stratton: Sure! But the question was generally about "ultrasonic sensors", and not what's "most likely" used. Nevertheless my answer includes a solution for the "most likely" sensor, thus a downvote is not justified in my opinion. But... feel free!

I did not downvote your answer, though I do think it's main point remains a based on a lack of understanding.

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


text:
How can I set two PWM at two different frequencies?
I'm using the arduino uno hooked up to two LEDs. One is in pin 3 and the other one in pin 5. I know that pin 3 is controlled by timer3 and pin 5 by timer 1. I've tried a lot of things to have two independent frequencies. I really don't care about the PWM, I have it to 50% (constant).
There are resources to set the frequency (http://playground.arduino.cc/Main/TimerPWMCheatsheet), but these are predefined frequencies. I need to have one PWM at 650Hz and the other at 850Hz.
Any recommendations on how to approach this problem?

Have you looked at the datasheet yet?

Since you are already  using two different timers, the key is setting the proper Wave Generation Mode with the appropriate Prescaler and TOP for the desired frequencies.  Look in https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf for ATMEGA328p  or https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf for ATMEGA2560 for "CS10" and "CS30" for the prescaler tables. and WGM10 and WGM31 for Wave Generation modes 8,9,10,11,14, or 15.

The ATMega PWM hardware underlying the Arduino primarily supports changing the duty cycle; the frequencies can only be selected from a few fixed choices.  Typically the timers run from 0 to 255 or 65535 and loop back to 0, and you can select where within that full cycle the output changes on and off.
Since what you want is a simple 50% duty cycle with fine control of frequency, the PWM functions are not very useful.  What you want is tone or frequency control.  The ATMega timers support this too, but it's a different function than PWM. For frequency control, the timer will cycle from 0 to your choice of upper limit.  So for example, you might count up to 200 instead of 255; or to 201 - so you get much finer control of frequency.
Unlike PWM, on the ATMega328p used in the Uno, you can only get one frequency per timer (you can get two PWM outputs per timer - both at the same frequency).  And if you want millis() and microseconds() and delay() to continue to work, you don't want to mess with timer 0 for frequency control (you can get PWM from timer 0 if you accept the default frequencies).
So that leaves you with two frequency controllable timers - timer 1 (16 bit resolution) and timer 2 (8 bit resolution).
See the tone() function in the Arduino library for examples of a single tone at a time.
For multiple simultaneous frequencies (on different pins) see this library: https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation.  You can have two tones at a time, or three if you don't need millis() etc.

There is a great library with functions to change PWM frequency on Arduino microcontrollers, called
arduino-pwm-frequency-library. I hope this helps you.

IF you need to dim leds use:
/*PWM signal on most pins is approximately 490 Hz
On the Uno and similar boards, pins 5 and 6
have a frequency of approximately 980 Hz
brightness1, brightness2 = from 0(0v) to 255(5v)
So make eqution to calculate needed frequency*/

//LED are connected to:
const int ledPin1 = 5;
const int ledPin2 = 6;
byte brightness1 = 100; // ~2v
byte brightness2 = 200; // ~4v
void setup()
{
  // initialize the ledPin as an output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {
    // set the brightness of the LED:
    analogWrite(ledPin1, brightness1);
    analogWrite(ledPin2, brightness2);

}

I recommend you to use two PWM signal with different duty cycles with the same frequency using timer1 and output pins 9 and 10. The next sketch was tested and it works very well.
 /*
 * Este programa genera 2 PWM signals a partir del timer 1. Las dos señales tienen la misma frecuencia (250Hz)
 * lo que varia es el duty cycle independiente para cada señal. Una sale por el pin 9 y la otra por el pin 10.
 */
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  //******** PWM Variable Definitions
**********************************************************
  // Register initilisation, see datasheet for more detail.
  TCCR1A = 0b10100010;
  //Timer/Counter1 Control Register A COM1A1 COM1A0 COM1B1 COM1B0 - - WGM11 WGM10
  // COM1A1 COM1A0 COM1B1 COM1B0
  //   1      0      1      0       Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode)
  TCCR1B = 0b00011001;
  //Timer/Counter1 Control Register B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
  // ICR1 Register is not double buffered. Using the ICR1 Register for defining TOP works well when using fixed TOP values.
  // By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. That's why, I am using WGM 14.
  // WGM13 WGM12 WGM11 WGM10
  //   1     1    1     0           Fast PWM ICR1 - fixed TOP, update of OCR1x at BOTTOM. WGM 14 (Table 13-4).
  // ICNC1 is 0                     the Input Capture Noise Canceler is disable
  // ICES1 is 0                     falling (negative) edge is used as trigger
  // CS12 CS11 CS10
  //  0    0    1                   No prescaling
  TIMSK1 = 0b00000001; // Timer/Counter1 Interrupt Mask Register. The Timer/Counter1 Overflow interrupt is enabled.
  // TOP value is put in ICR1 and is equal to 64000, it means that 16000000 / 64000 = 250Hz (since no prescaling), the frequency of PWM signals
  ICR1   = 64000;
  DDRB = 0b00000110; // Set PB1(DB9) and PB2(DB10) as outputs.
  interrupts ();
}
 void loop() {
  // put your main code here, to run repeatedly:
}

 ISR(TIMER1_OVF_vect) {
  // change duty-cycle every period.
  OCR1A = 16000;// in OCR1A is put the value corresponding to duty cycle, OCR1A output pin is 9. Duty cycle 25%. 16000 / 64000 = 0.25
  OCR1B = 48000;// the output pin of OCR1B is 10, duty cycle 75%. 48000 / 64000 = 0.75
}


text:
How to enable maximum Dead Code Removal?
I am running out of code and data memory space on ATMega328P.
Code size is big as I used several libraries, but, I only use a few functions of those library.
Apparently, the default IDE is only doing a partial job in dead code removal (remove unreferenced code and data).
Some experiments shows:

A normal program that uses several Arduino libraries is 22 kilo bytes in code size.
Rename setup to o_setup.
Rename loop to o_loop
Add
void setup(){};
void loop(){};
Code size is 8 kilo bytes while the program is 'empty' effectively.
Start a new program.
Add
void setup(){};
void loop(){};
Code size is 0.5 kilo bytes

Apparently, the IDE (linker called by IDE) is doing a 'partial' dead code removal job, as reducing code from 22kB to 8kB (case 1 and 2), instead of 0.5kB (case 3).
How can I enable maximum dead code removal function (reclaim code space occupied by unused library functions)?

Be aware that some libraries declare global variables, instances of a class, for which the constructor code (and all its dependencies) will be linked into the final program. Hence the simple fact to #include a library but not use it can still add a lot of code in the link process.

I need all the lib as they are physical hardware chip drivers. But, I only use a few functions of each lib. Could you kindly explain "instances of a class, for which the constructor code"? Global var can be 'optimized/removed' by linker which see that it is declared by never used, by looking at assembly language linkage map, right?

In case 2 did you also remove all the code outside of  loop2 and setup2. E.g. to use the Servo library you'd use #include <Servo.h>  Servo myservo;. Here Servo myservo; actually creates in instance of the Servo class, with all it's memory it needs for its private variables.

Can you list the libraries you require?

I have several hardware sensor boards and each has its own needed lib (driver) to work. For example, the LCD driver has many functions for drawing line, circle, pie, fill, etc. but I only use the draw 3D text mode. In worst case, I can manually delete un-used part of the library source. Can take time as inter-dependency is everywhere. The LINKER should be able to do this task automatically. The question is how to turn it on and command it to perform? Compiler can still allocate code/ram space. linker is final gate keep who has full and latest info, which code where, call who and called by who

For example, many hardware sensor driver lib has 2 function to give SI and Imperial units. I use one only. Some has hardware changeable setting like, range, gain, parameters. I do not need many of these as I use many default settings.

Enable your IDE's verbose of the compile via the preferences. From there you can see exactly what and how it is being compiled.
In short the IDE (and toolchain) will compile everything and anything it can find into an object. Where only the used code is compiled in the linking phase, as garbage collection is enabled with the "--gc-sections" command.
Note that the optimization level is "-Os" or "Optimize for size". In IDE 1.0.+ this appears to be hardcoded. Where as in IDE 1.5.+ the compiler options are configurable, in "\arduino-1.5.6-r2\hardware\arduino\avr\platform.txt" can be customized to meet your needs.
Where you can use the avr-objdump command as described in https://stackoverflow.com/questions/15291750/does-importing-libraries-load-everything-in-arduino/15296808#15296808.
I would recommend 1.5.6r2 and not 1.5.7 as the gcc commands won't run individually without some path manipulation.

you can try to change the -Os to -O2 or -O3 to get smaller. S is supposed to include 2. However, I have seen it in some cases get smaller.

-O2 and -O3 ask the compiler to optimize its output for speed, not for size. Thus the compiled binary will get larger rather than smaller.

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


text:
Lego / Meccano style blocks for 'serious' projects
What can be used like Lego or other construction sets, but is more serious and 'professional'?  E.g. what comes with gears and screws and things like that, but is geared to serious modelling or more permanent projects?

Here is what comes to mind (by no means exhaustive):
billed as "the Industrial erector set", 8020 is legitimately used in industry for that kind of purpose, and if I remember correctly, pretty expensive. It is the most "professional" thing I can think of.
OpenBeam styles itself as the the cheaper, "open sourced" 8020. I've frequently heard of it being used in 3d printers.
These are not as serious or professional, but might be worth mentioning:
MINDSi is pretty close to the mindstorms, but tries to be more rigid/durable. It's aimed at robotics.
Servo City's actobotics is an aluminum modular building system. It is also sold on sparkfun.
I have not used these enough to give good comparisons, but I hope one of these will be what you are looking for.


text:
Opening .h and .cpp files from folders other than the sketch folder
My team has a C++ program from another microcontroller that we are moving to Arduino, which is currently divided into two main folders, the sketch and libraries. We want to be able to open some of the library files in the Arduino IDE along with the sketch, something it will do automatically if they are in the same folder, but not allow otherwise. The files in question are referenced from the other libraries though, which means moving just a few of them results in compilation errors. We don't want to move them all to the sketch folder, since that defeats the purpose, but a few of my teammates are vehemently opposed to having to edit them using another IDE.
So is there a way to have these files open in the Arduino IDE with the sketch? Or do I have to tell my teammates to suck it up and use a second editor if they want to make changes?
Alternatively, a way to get the libraries able to reference files in the sketch folder would also work.

What IDE did they use for the other micro controller?

@geometrikal They were PIC32s, so we used the MPLAB X IDE, which everyone universally disliked.

I've just started moving a project over to netbeans. It was tricky at first but I think it would be much better than the Arduino IDE for a team.

I don't recommend this
A) Because the arduino editor is pretty bad for serious coding
B) Because you will need to have a header guard on all library code that doesn't have one already (even in .cpp's)
But, if you really have to, the only way I can think of is to make a symbolic link to the library file in the sketch directory. It works, but the file gets compiled twice, so you need those header guards on everything.

Yeah, I think everyone agrees on that. But I guess they hate alt+tabbing that much more. I'll look into symbolic links then; the headers all have guards already so that shouldn't be too much of an issue.


text:
Finding arduino bootloader version?
I have problem with WDT reset. After reset the device goes on for a boot loop. from the following link https://code.google.com/p/arduino/issues/detail?id=181
It has been mentioned that there is problem with Bootloader because some of them does not support wdt properly.How can i find which version of bootloader is running in my arduino mega 2560 . Which version of bootloader support wdt properly? where these bootloaders can be found?

In all practicality; put a known boot loader on it. Because if it is a problem version you will need to replace it anyways.
The Mega uses STK500 protocol. Which only shows a command to read its type (or signature) and not its version of firmware.
It is a good exercise, but not really worth the time to go deeper into it, as programmers are cheap and or you can use another Arduino as the programmer.

The watchdog timer will reset the Arduino in case of a timeout. The way to prevent this from happening is to catch the WDT interrupt.
ISR(WDT_vect)
{
  // do nothing
}

This has nothing to do with the bootloader. The fix suggested in the link above only makes the bootloader detect a reset triggered by a WDT event, and have it not add any delay. This delay is normally needed to see if the usb-host is trying to upload a new program.


text:
Guide to code for multitasking and non blocking timers
I'm beginning to do kind of sophisticated things (well.. for my entry level skill) and I have to control a display with 3 LED and 4/5 types of events and status.
I'm using the BlinkWithoutDelay example duplicating all the variables for different status/events but the code is really messy, full of puzzling nested if statements.
How to simplify the things? I don't know what to choose, because OOP could be a choice but I think it will hurt the low-memory thing inside the Arduino Uno/Leonardo. Interrupts could be another choice but I think they are like threads, and following the KISS principle I'd like to stay away from them.
So, can someone advice me some article/tutorial/code-to-read/whatever to understand how to use a lot of LEDs and keep a lot internal status without screw my brain?
EDIT:
It is a little bit hard to reproduce a simple skelton of my messy code, but it looks like this (in pseudocode maybe)
void loop() {
    if(state==0) handleState0();
    if(state==1) handleState1();
    if(state==2) handleState2();
    if(state==3) handleState3();
    readButtons();
    readSensors();
    …
}

// this is a block of variables that I have to copy-and-paste
// every time I have to blink a led (hoping that there is
// nothing blocking that can skrew up everything)
unsigned long previousMillis_1 = 0;
const long interval_1 = 1000;
int ledState_1 = LOW;

void handleState1() {
  // Green led blinking, yellow is fixed
  // this is a copy-and-paste code hard to maintain,
  // easily broken from any blocking call (like also I2C)
  // and hard to refactor or isolate
  unsigned long currentMillis_1 = millis();
  if(currentMillis_1 - previousMillis_1 >= interval_1) {
    previousMillis_1 = currentMillis_1;
    if (ledState_1 == LOW) ledState_1 = HIGH;
    else ledState_1 = LOW;
    digitalWrite(pinGreen, ledState_1);
    digitalWrite(pinYellow, LOW);
}

unsigned long previousMillis_2 = 0;
const long interval_2 = 1000;
int ledState_2 = LOW;

void handleState2() {
  // Yellow led blinking, green is fixed
  // same as before
  unsigned long currentMillis_2 = millis();
  if(currentMillis_2 - previousMillis_2 >= interval_2) {
    previousMillis_2 = currentMillis_2;
    if (ledState_2 == LOW) ledState_2 = HIGH;
    else ledState_2 = LOW;
    digitalWrite(pinYellow, ledState_2);
    digitalWrite(pinGreen, LOW);
}

void handleButtonPressed() {
  // this skrew everything and because is blocking
  // and should be inserted in the main loop with
  // some global variables: active/disable, counter,
  // and non-blocking vars like previousMills, interval, etc etc
  Serial.println("\ndisplayAccessDenied");
  for(int i=0; i<3; i++) {
    digitalWrite(pinRed, LOW);
    delay(100);
    digitalWrite(pinRed, HIGH);
    delay(100);
  } digitalWrite(pinRed, LOW);
}

I feel a little bit lost but all the Arduino example arounds are super simple and to make a middle-level LED interface I have to screw my minds with something that is not working as 100% and other than Arduino I find only super-hard articles on microprocessors with low-level C code. But the pasted example is not working at 100% AND super hard to read, maintain, etc.

I'd suggest you to take a look at Cosa framework for Arduino (https://github.com/mikaelpatel/Cosa): powerful and quite easy to use, fully OOP but still has a small memory footprint and excellent performance.

Could you post your code? Different problems have different (optimal) solutions. PS. interrupts are nothing like threads. Maybe not the best place to start as a beginner, but they can be extremely powerful. I don't think they are against the KISS principle. You could e.g. have the main loop check all the events, and have an interrupt set the led in accordance with some variables set in the loop.

ok I have edited. so.. interrupt are not the devil.. any advice on some middle-level guides/article about it?

You can try:
http://bleaklow.com/2010/07/20/a_very_simple_arduino_task_manager.html It's simple but powerful.

interrupt are not the devil - see Interrupts

It is not really clear what you want here...
If you want to execute things in a certain time, then take a look at http://playground.arduino.cc/Code/Scheduler
Or, if you want more than just that (multiple tasks, preemptive multitasking) https://launchpad.net/arduos (arduOS can also just serve to run things in a certain time, but without having to use a function all the time)
While OOP MIGHT take more program memory, an object without virtual functions only takes the RAM the variables in it take (if you have a byte (1 byte) and an int (2 bytes) in an object it would take 3 bytes)
On the AVR-architecture (the one most Arduinos use) the program is directly executed from a flash-memory and only the variables are in the RAM
The if-state-handling you are doing there can be done easier using arrays like:
typedef void(*handler)(void)
handler stateHandlers[STATES] = {&handle1, &handle2, &handle3 ...
// handle? are functions without the () !
void handleState(int state)
{
    if(state >= STATES)
        return;
    stateHandlers[state]();
}

Obviously, you can also use arrays to store the states of the LEDs.
Also note that HIGH is just 1 and LOW is 0, so technically a bit would be enough to store the states.

Following the KISS principle, I have recently published the Instructable "Simple Multi-tasking in Arduino on any board"
It covers non-blocking delays, non-blocking serial output, non-blocking user input, removing delays from third party libraries, and loop timers, so you can see and adjust the response/latency of your tasks.
Here is some example code
void loop() {
 callTask_1(); // do something
 callTask_2(); // do something else
 callTask_1(); // check the first task again as it needs to be more responsive than the others.
 callTask_3(); // do something else
}

The trick is that each callTask..() method must return quickly so that the other tasks in the loop get called promptly and often. The rest of the instructable covers how to keep your tasks running quickly and not holding everything up, using a temperature controlled, stepper motor driven damper with a user interface as a concrete example.
Finally the instructable moves the code, unchanged, to an ESP32 to add remote control via Wifi, Bluetooth or BLE, to the temperature controlled, stepper motor driven damper.
Drop me a message/email via Instructables or my website, if you are unclear about anything in the instructable.

Cosa supports a large number of mechanisms for multi-tasking. The latest addition is an abstract class for Jobs (delayed or periodic functions) and Job Schedulers. This abstraction allows functions to be scheduled on micro-, milli- and seconds level.
To get started please see the Cosa example sketches. If you have an Logic Analyzer (Salea Logic for instance) there are a number of example sketches that show pulse generation.
There is also a binding of the Job Scheduler to a seconds tick level. This is abstracted to Clock and Alarms.
For higher abstraction of multi-tasking Cosa also implements FSM, Proto-threads, Threads (multi-stacks), UML Capsules, and more.

Does it support forced preemption? Semaphores? I had a cursory look but couldn't find them at glance.

The Threads (see Cosa/libraries/Nucleo) are not forced preemption. It is collaborative, i.e. need to call yield(), delay(), etc. There are semaphores and some basic message passing support. The Job and Job::Scheduler can be used in a forced preemption fashion as the dispatch is from ISR and can be modified to run() within the ISR context. The simplest of all the multi-tasking abstractions is the periodic block (See Cosa/Periodic.hh and the macro periodic(timer, ms)).

Ok, thanks for confirming. For my needs, the lack of forced preemption is already disqualifying.

It is a question about resources. Cosa supports AVR MPU from ATtiny to ATmega. With only 0.5-1 Kbyte SRAM it is a challenge to allow thread stacks and ISR frames and still have memory over for the application. It is very much a trade off. The mechanism in Cosa can be used with forced preemption but that is not in the open-source version. Cheers!

Here's an example of blinking two LEDs independently:
// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  }  // end of setup

void toggleLED (const byte which, unsigned long & whenToggled)
  {
   if (digitalRead (which) == LOW)
      digitalWrite (which, HIGH);
   else
      digitalWrite (which, LOW);
  // remember when we toggled it
  whenToggled = millis ();
  }  // end of toggleLED

void loop ()
  {
  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleLED (greenLED, greenLEDtimer);

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleLED (redLED, redLEDtimer);

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

  }  // end of loop

Note that instead of copying and pasting the blinking code, I made a generic function. That way any bugs are easily fixed.

For more LEDs you could use an array:
const int NUMBER_OF_LEDS = 5;
// Which pins are connected to which LED
const byte LED_PINS [NUMBER_OF_LEDS] = { 8, 9, 10, 11, 12 };
// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long LED_INTERVALS [NUMBER_OF_LEDS] = { 200, 400, 100, 1000, 2000};
// Variable holding the timer value so far. One for each "Timer"
unsigned long timeLEDtoggled [NUMBER_OF_LEDS];

void setup ()
  {
  for (int i = 0; i < NUMBER_OF_LEDS; i++)
    pinMode (LED_PINS [i], OUTPUT);
  }  // end of setup

void toggleLED (const byte which, unsigned long & whenToggled)
  {
   if (digitalRead (which) == LOW)
      digitalWrite (which, HIGH);
   else
      digitalWrite (which, LOW);
  // remember when we toggled it
  whenToggled = millis ();
  }  // end of toggleLED

void loop ()
  {
  // see if it is time to toggle the LEDs
  for (int i = 0; i < NUMBER_OF_LEDS; i++)
    if ( (millis () - timeLEDtoggled [i]) >= LED_INTERVALS [i])
       toggleLED (LED_PINS [i], timeLEDtoggled [i]);

  /* Other code that needs to execute goes here. */
  }  // end of loop

If anything, the above code is simpler, but it blinks 5 LEDs at different rates. Now you can have more sophisticated tests than that, but the general concept is the same.

References

How to do multiple things at once ... like cook bacon and eggs
State machines

Use the NonBlockingSequence library. It has clean examples for applying blinking sequences without delay. (Example Link)
    #include <NonBlockingSequence.h>

class Blinking_Led{

  private:
  // Declare Sequence
  ClassNonBlockingSequence<Blinking_Led> Sequence;

  // led pin
  byte _pin;

  // Define step-functions
  bool led_on(){
    digitalWrite(_pin,1);
    return true;
  }
  bool led_off(){
      digitalWrite(_pin,0);
      return true;
  }

  public:
  Blinking_Led(){};
  void init(byte pin,unsigned long pause){

    // define the led pin
    _pin=pin;
    pinMode(_pin,OUTPUT);

    // This line explain important fact for the Sequence
    Sequence.AttachedObj(this);
    // Sequence should use steps defined inside this class only

    // Add steps
    Sequence.AddNewStep(&led_on);
    Sequence.AddDelayInMillis(pause);
    Sequence.AddNewStep(&led_off);
    Sequence.AddDelayInMillis(pause);
    Sequence.Repeat();
    // repeat the sequence infinite number of times

  }

  Blink(){ // use familiar name for led
    Sequence.DoSequence();
  }

};

// Declare new objects
Blinking_Led Led1;
Blinking_Led Led2;

void setup() {

  //  Led.init( pin , blinking time )
  Led1.init(13,200);
  Led2.init(12,1500);

}

void loop() {
  // put your main code here, to run repeatedly:
  Led1.Blink();
  Led2.Blink();
}

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.


text:
Now at IDE 1.0.5, should I upgrade to 1.0.6 or 1.5.7 Beta for Pro mini and ATMega2560 use?
Do I need to re-install many libraries (or similar 'house keeping' works)? Is the upgrade straight forward?
Apparently, from Arduino web, one need 1.5 BETA series for use with Due. For Pro Mini, UNO and ATMega2560, should one use 1.5 BETA or 1.0.6 (no beta, presumable stable)?
I am running out of code space. Wonder if the upgrade will install a newer gcc compiler and smaller code size?

Old libraries will work with 1.5 Beta, but you will most likely need to copy any of your own libraries over to the new beta installation, depending on if they were installed to the sketchbook location or inserted into the installation before. That should be about all you need to do after installing the beta for it to work.
The Beta supports all the regular boards as well as the Due and Yun. I doubt you will see any change in binary size if you update. I've been using the beta for some time now and it has been quite stable.
Which version you should use is up to you, the differences are relatively minor. I think the beta adds a few convenient features, but there are no changes to the code or functionality like the switch to v1.0 made.

gcc version 4.3.2, dated as WinAVR Dec 2008, was used inside IDE 1.0.5. From https://gcc.gnu.org/releases.html, latest is 4.9.2 dated July 2014. Any idea what is the 'practical' improvement that one can see, after upgrading to 1.0.6 or 1.5Beta, within the Arduino context, especially in code size optimization,  code size reduction and dead code/data elimination.

4.3.2 is deployed with and up to 1.5.6r2. Where it was updated to 4.8.1 IDE 1.5.7. Where the core libraries have been updated as to compile and work with the newer 4.8.1. Mostly the newer GCC was much more strict and produced errors, that were warnings of bad coding style.

if you have your downloaded libraries in your home or user directory e.g. "C:\Users\mflaga\Documents\Arduino\libraries" than the are compatible and work seamlessly. There is a new path format for the libraries as to support multiple platform. But it is optional. And the same goes for sketch's they can be in the same old location. e.g. C:\Users\mflaga\Documents\Arduino. I readily change IDE's. Where I prefer 1.5.6r2. 1.5.7 has a IDE bug on windows that does a full compile every time. 1.5.6r2 does a fast compile.

@mpflaga where can I download selective older version (like 1.5.6r2) you mentioned? The web only has link to the latest version 1.5.7

http://arduino.cc/en/Main/OldSoftwareReleases

@BrettM since 1.5.x uses gcc 4.8.1, final .hex size is a bit smaller. LTO (link time optimization) has been disabled due to a corner case bug: enabling it further reduces size of .hex

I have had trouble with 1.5.7 (Beta), so I would stick with 1.0.6. As for code space, you might want to look into Atmel Studio (Free), which uses a Visual Studio shell as the IDE. It blows the Arduino IDE out-of-water. Atmel is the maker of all the AT chips, so the Atmel Studio IDE is a great IDE for writing AVR code. Lots of tutorials online and there is a Arduino plug in called Visual Micro (Free also).

Is it right that Atmel studio means programming bare chip, without the benefit of library, which is very useful for interfacing to hardware modules without reading hardware data sheet and register level programming?  What Visual Micro actually does, as their web states, "New Arduino users are guided to work within the normal Arduino framework, in a similar manner to the Arduino IDE. Advanced Arduino users have a range of options that allow the simple (but restricting) Arduino rules to be broken." What extra control (like gcc switches) and other convenience can I get from Visual Micro?

You get the extra control via the Atmel Studio. The Micro Plugin allows you to use the arduino libraies, Serial monitor and upload feature.


text:
Can I switch from Arduino IDE to Atmel studio or Visual Micro but still use Arduino library?
If switch from Arduino IDE to Atmel studio or Visual Micro, how to use existing Arduino library?
Library serves important function of 'packaging' real and complex hardware (like NRF24L01 radio board) into functions of 'relatively standard format', like radio.init, radio.write, radio.read, radio.on, etc.
This allows user to easily use the hardware without reading the data sheet.
How can the same be achieved under Atmel studio?

Sorry for hijacking your question. Arduino itself is actually also a library. E.g. pinMode, digitalWrite and delay aren't standard functions. Just like your sketches, a lot of libraries depend on these functions. How would one get these to work as well in Atmel studio?

The thing that I just found is that you need to have Visual Studio, not Atmel Studio. For some reason you cant, AFAIK, add libraries with AS.

Visual Micro supports all Arduino libraries in the same way that the Arduino IDE supports these libraries.
When using Visual Micro in Atmel Studio your sketch code remains identical to the Arduino IDE. You can switch between the two IDEs and see the same compiler results.
If you can not see your user libraries on the "Atmel Studio>Projects>Add/Import Sketch Library" menu then this means you have configured the SketchBook folder path incorrectly.
Arduino and Visual Micro use the SketchBook folder to find user libraries in a sub folder called 'Libraries'.
I recommend leaving the sketchbook folder empty because Visual Micro will then auto discover the SketchBook folder that the Arduino IDE uses and remove the possibility of confusion.
When the sketchbook folder is empty and has not been set in the Arduino IDE the default will be myDocuments\Arduino, therefore your user libraries will be expected to exist in myDocuments\Arduino\Libraries.
@John, in response to your question below. It's a big topic and maybe best answered in our forum.
A few examples are:

Ability to re-define arduino core to use tools such as cygwin, we see
the Arducopter example as a good one for this. They produce a window
SITL program.
Obviously we can all use the flexible Arduino 1.5 config structure to
define our own hardware and build process but we also support the
Teensy customization system which allows windows apps/tools to manage
the build process and tool chains. Visual Micro supports both of
these customizations combined in the same hardware def but also a
number of other build properties.
There is also the ability, in Visual Micro, to add compiler #defines
for project or configuration and the ability to add programmers that
use, for example, the atmel toolchain (if using atmel studio).
Libraries can be referenced with a folder name (unlike arduino) which
allows different projects to use similar libraries but of different
versions. (Library paths are declared for the lib folder roots as
well as individual libraries).
If you consider the various different build properties build
properties of Arduino, Teensy, Energia, ChipKIT and Intel then add a
few on top this describes what you can do in any project regardless
of hardware IDE.

Thanks for the answer which cover (a) as below taken from official web. Can you please state a bit more specific on (b).   From web, (a) New Arduino users are guided to work within the normal Arduino framework, in a similar manner to the Arduino IDE. (b) Advanced Arduino users have a range of options that allow the simple (but restricting) Arduino rules to be broken.

@John Some answers above in the post

At the end of the day, an Arduino library and the Arduino core are just files full of code.
There is nothing to stop you creating a project in Atmel studio (or wherever) and importing all those files into your project.
You will need all the core files (hardware/arduino/core/arduino/*) plus all the files for the libraries you want to use.


text:
Digital pins on Arduino function as both positive and negative terminals?
I'm learning the arduino platform and working on a circuit that connects the two pins of a piezo buzzer -- one to ground and the other to a digital pin of the arduino board. In this configuration, is the arduino's digital pin acting as the positive terminal of the circuit?
The arduino docs seem to suggest it is:

They (the digital pins) can provide a substantial amount of current to other >circuits. Atmega pins can source (provide positive current) or sink (provide >negative current) up to 40 mA (milliamps) of current to other devices/circuits.

Can the digital pins act as both positive and negative terminals in circuits? Does this question even make sense? What resources are out there that can help me better understand the underlying electronics of the arduino and microcontrollers in general?

The answer to your question is basically yes, you can use ATmega I/O pins as +/- power supply terminals for other circuits. But there's a limit to what you can power that way (20mA per pin and 100mA total per ATmega). In practice this means you can only power the simplest circuits (single LEDs per pin, and not many LEDs in total, for example). As a general rule, you should really look for other ways to power anything else.
Also, there's a problem with the citation you gave. That 40mA figure is the absolute maximum current per pin, but that should be avoided. Safest is to use about 20mA of maximum current per pin. Also, the ATmega pins should not have more than 200mA flowing through Vcc and GND (also an absolute maximum that should also be avoided).
Usually, you should either power other stuff off of the regulated +5V that also feeds the ATmega (up to the regulator capacity that depends on the Arduino board - 500mA for the Arduino Uno - 1A for LM7805 regulators - and so on). You could also use the unregulated power in some cases. Then you should use digital pins on the ATmega to switch transistors on and off which in turn will switch your load. Sometimes you can use transistors to switch relays, that in turn will switch even larger loads.

Step one: read the data sheet for the microcontroller.  In there is a nice diagram that shows you exactly how the IO pins work.
The pins can work in 2 modes: input, and output.  You're interested in output mode.
The drive state of a CMOS output pin consists of two MOSFETs, one connecting the pin to Vcc and the other connecting it to GND.  Only one of the MOSFETs is ever turned on at a time, so the output pin is either connected to Vcc through one MOSFET, or connected to GND through the other.
When it's connected to Vcc it's said to be sourcing current, since it's at a positive potential compared to ground and current can flow out of the pin to light an LED (say), and when it's connected to GND it's said to be sinking current because current can flow into the pin to get to ground.
As an example of how it all works, consider how you would connect up and power a capacitative humidity sensor.
These sensors require a square wave at around 1KHz to operate.  The humidity defines the impedance, and as part of an impedance divider (like a resistor divider) the output voltage is relative to the humidity.
Now, they don't just want any square wave, but require a square wave that reverses polarity around a virtual ground point, and that means reversing the polarity of the power across the sensor at 1KHz.  How can you do that with an Arduino? The answer is simple:
Connect the sensor to two IO pins rather than 1 IO pin and GND.
Both pins are set as output, and one is set HIGH with the other set LOW.  So the voltage across it is 5V.
Now you switch the outputs over, so the one that was HIGH is now LOW, and the one that was LOW is now HIGH.  The power across the sensor has been reversed!  It's now (effectively) -5V (compared to what it was before).

So essentially, if the pin is in output mode it is a voltage source, and if it is in input mode it is functioning as a connection to GND?

Yep, that's what I said ;)  But remember you only have limited current available, or the MOSFETs will overheat and the IO pin will die.  40mA absolute maximum, 20mA recommended maximum.

"...if it is in input mode it is functioning as a connection to GND?". No, that's not correct. You misread Majenko's explanation. In output mode, the pin can be either driven high (to Vcc) or low (to GND). In input mode, it's typically high-impedance (neither high or low) so it can read an external voltage.

And I mis-read Jog's comment.  Yes, in input mode the pin is connected to a completely different part of the circuit.  Take a look at Figure 13-2 in the data sheet. The IO pin is split 3 ways - one to the input circuit (bottom), one to the output circuit (middle) and one to the pullup circuit (top).

Step one, for someone beginning an electronics hobby by trying stuff on an Arduino, definitely isn't to read the ATmega data sheet :)

Considering the question was posted on the EE SE then yes, step one is definitely read the DS.  For anyone, regardless of expertise, who wants to understand how the internals work, then step one is, guess what? read the DS!

Arduino's digital output pin can not output a voltage lower than GND.  In other words, the voltage on the digital output is always positive with respect to GND.
Can it be a negative terminal?  It depends.  There is no universal definition for "positive terminal" and  "negative terminal".  If you want to use these terms, you define what "negative terminal" is for each particular case.  Suppose, you want to sink the current through an LED (and a series resistor).  Then you connect the resistor to the VCC and Anode (negative terminal of the LED) to the digital output.  Then you could say that digital output is the negative terminal for the LED.

When a GPIO pin is set to output mode, you can either drive it "high" (ie: VCC), or "low" (GND). They can not, however, drive a negative voltage (ie: -VCC). If you want to create a negative voltage, you'd need some external GPIO expander chip sourced off some negative voltage supply, or you'd need to create a negative voltage rail source via a buck-boost converter or similar to generate it from Vcc.
Fortunately for you, Arduino already has a pieze-electric buzzer library, and wiring it up is dead simple. The relevant GPIO pin is connected to the buzzer's positive terminal, and the buzzers negative terminal is grounded.

Great, so then in this particular example, the piezo is being powered by the connection to digital pin 8 correct? And we could reliably assume that circuit current is definitely less than 40 mA and probably lower than 20 mA before we measure it? Also, technically speaking, could we say that electrons are in fact flowing from the board's GND to digital pin 8?

@Jog I don't know how a piezo-electric buzzer alters current flow, so let's just assume it's limited to Vcc / R at the most. Forget about the flow of electrons, just accept that the "conventional current" is flowing from the output of GPIO pin 8, through the resistor and buzzer, into the ground, as part of a closed circuit. If you need more current than the Arduino can supply, just have the Arduino connects to the gate of a power MOSFET (ie: http://www.hobbytronics.co.uk/image/data/tutorial/arduino-tutorial/power_mosfet.jpg).

@Jog a piezo will naturally pull more than 40 mA due to ohm's law with its resistance; that's why there is the resistor (that little yellow/tan thing there on the + line).

To summarize other people's answers:
Arduinos have a whole bunch of GPIO, or general purpose I/O, pins. They can be configured as digital inputs or digital outputs. Certain pins can also be configured as analog inputs or PWM outputs.
For a simple digital pin, if it is an input, it has nearly infinite impedance. (It looks like an open connection.)
If it's an output, it acts like a current source (connected to +5V) if it's HIGH, and acts like a current sink (connected to ground) if it's LOW.
Arduino I/O pins (on most boards, check your board's specs) have a hard limit of 40mA of current flowing through them, but you should generally keep the current below 20 mA.
Is a ground connection the same as a negative connection? Sort of. Some circuits include ground, one or more positive voltage sources, and one or more negative voltage sources. Audio (analog) circuits, for example, often need ground, +12, and -12 volts.
Arduinos don't deal with negative voltages, and applying a voltage that's less than ground to any pin will likely destroy it.
Think in terms of positive voltage and ground, not positive and negative. It's less ambiguous.
Don't think of Arduino pins as being power sources. Remember that they are LOGIC pins, and only put our very small amounts of current. Trying to source or sink too much current from an Arduino pin may destroy it.
If you need to source or sink more than 20mA, use a transistor as a switch to handle the higher current load.
In addition to all that, you need to watch the total current that you pass through all your logic pins, and also the total current you draw from the power supply. Check the specs on your board and make sure you stay within the limits.

First of all, the Arduino doesn't supply negative voltage. It flows from positive to ground, the reference point that determines voltage.
Anyway, I'm not quite sure of the exact details of the inner-workings of the ATmega chip, but I assume it goes something like this:

A CPU cycle modifies a CPU register (or similar memory/latch somewhere)
To the output of that "register," a circuit is connected that:

Shorts the pin to 5V if HIGH
Shorts the pin to GND if LOW

I suppose the latch could be directly connected to the pin, but I think that the current draw might be too high for the latch circuit, so an external transistor is used.
That above isn't anything that's really technically correct (as these details aren't always released), but its intended purpose is to show you how it basically works from a logic point of view.
You can then manipulate the pin's connection using either of these two pieces of code:
//HIGH (== 5V)
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);

//LOW (== GND; 0V)
pinMode(4, OUTPUT);
digitalWrite(4, LOW);


text:
Can I change font Color and/or Type for IDE 1.5.6r2?
The program becomes harder to read (at least on my particular monitor) after upgrading.
Any way to change font Color to darker color and/or Type to thicker stroke (like B in this question editor) for IDE 1.5.6r2?

Sounds like what you need is a fully theme-able IDE.  Why not give UECIDE a go?

Yes.
Under the file menu select the preferences. From this you can find and than view/edit the preferences.txt file, which has the color settings.
Example preferences.txt

I log on as Admin (Win7) but cannot save the edit due to "access deny". Checked the property and 'ticked' for read, write and full control.

Solved. The one to change is C:\Users\username\AppData\Roaming\Arduino15\preferences.txt

In 1.6.0, or 1.6.1 it does not seem to be possible to change console.color or console.error.color. To be precise, you can change the settings in the preferences.txt file, but they appear to be ignored. Have these become hard coded? Orange text on black is just horrific to read. See How do I change the Console colour of Arduino IDE?

The link is broken (Google Code was shut down).

What about the thicker stroke? What should e.g. editor.font=Monospaced,plain,16 be replaced with (supposedly plain with something else)?


text:
What is arduino_debug.exe for IDE 1.5.6r2?
After installing IDE 1.5.6r2, there are two .exe files, arduino_debug.exe and arduino.exe (which is same name as previously installed IDE 1.0.5).

Pretty sure it's the debug build...

Windows binaries can either be Window or Console applications. A Window application can NOT produce text output. Text output is the easiest way to gather error messages related to bugs.
Hence, arduino_debug.exe should be used by Windows users that have found a bug in the Arduino IDE and wish to contribute submitting an issue on github.