text:
Unable to terminate "void loop"
I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.
void setup() {
   Serial.begin(9600);
}

void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end void loop so that TX light goes off.

Stop outputting via the serial connection.

I need to setup multitask in a loop, so I can take a snap shoot of data from the SD reader.

I'm voting to close this question because it shows a fundamental missunderstanding of how Arduino works. The setup and loop model is the very first thing you have to learn before writing your first sketch. It's explained in pag. 36 in the book that's come with Arduino Starter Kit.

HIGHLY recommend you begin by loading the Blink example program and start there.  Then modify it to suit.  As for your little program, your delay is only 1 millisecond.  You might as well not even have it there because the Serial.println takes longer than that.  Change it to 5000 for 5 seconds, maybe.  Also, you never set the A0 pin to be of type INPUT.  But first go back to Blink and try to walk (digital) before you try to run (analog).

I'm voting to close this question as off-topic because of the age of this one and the lack of useful description in the title.

The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the loop() function. Not to be pedantic but to clarify the use of loop, the simple answer is, "you can't". loop() is called from a forever loop in the C/C++ main program, function main(), so returning from it, either with a return statement or by reaching the final close } causes loop() to be called again. This is intentional as the main() function in an embedded system is never supposed to return, thus it must keep re-running the application program.
Update (since this question just reappeared on the front page, I'll add the following to my answer):
loop() reads and prints continuously. If you had wanted that code to be executed only once, you could put in setup() and leave loop() empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty loop() and remaining there until power-down.
A way to execute the loop function once is to write an infinite loop at the end of it, so loop() would never return and thus never be re-executed:
void loop() {

  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);

  while(1)
     ;
}

The TX LED is on, because this sketch is periodically printing the value of the analog pin 0 onto the serial port. The LED seems to be constantly on, because the delay between two Serial.println() calls is only approx. 1 ms.
If you replace the 1 with 1000 for example, the TX LED should flash once per second. Start the serial monitor in your Arduino IDE too see the transmitted analog values. Delete the Serial. calls to remove the serial port functionality altogether.
You might want to read the documentation of the loop() and the delay() functions.

Seeing as questions about turning off the LED, and the nature of exiting loop have been answered, I'll also answer the question they both seem to lead to:
If the overall intention is to "turn off" the MCU, outside of turning off the power supply, it can be put into sleep mode.
Depending on how you configure the MCU before entering sleep mode, it can even be allowed to wake up on further USART communication.

Don't write code in the loop() that should be executed only a few times. Or use a counter. Or an external button. For the permanent light, increase the delay between calls.

Could you elaborate on how to do the stuff you say to do in this answer?

If your question is how to terminate the execution of your void loop code at some interval, I can mention 4 solutions:
1.If you want the Void loop() to execute only once (or a set number of times using for loop), you can use "exit(O);" at the end of the Void loop.
i.e.
Void loop(){
         //code
         exit(0);
         }

Disclaimer: This one might not work for all Arduino boards, but it works fine with my Arduino UNO.
2.Another way would be to keep the "Void loop()" empty and put all of your code in the Void setup function.

use a void loop at the end of the Void loop.
E.g.
void loop(){
//code
while(1){  //infinite loop }
}

The arduino will remain in the infinite loop and won't be able to rerun the Void loop.

Create your own function and call it from the "Void Setup()"
E.g.
 Void setup(){
  myfunc();   //calling your function
 }
  Void myfunc(){
//The code for the function you want to repeat only a set number of times
 }
 Void loop(){
 }

Hope someone finds it helpful.

Is there a good reason to warm up this old question? BTW: There's a difference between void and Void

@DataFiddler - Yup, answer is NFG. The entire Q+A should be deleted, or at least closed as it's obvious the OP will never mark it as answered after 8 years.


text:
Is it possible to extend the reach of a PN532 NFC/RFID shield?
I am working off an Arduino Uno with an AdaFruit PN532 NFC/RFID shield. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.
The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

Note that NFC uses an air-coupled transformer, not an antenna proper.

Thats all greek to me..  the board i am using is the AdaFruit pn532, it looks like an antenna... can you explain the difference?

http://www.adafruit.com/products/364

It's actually a wire that goes through several loops and then connects to another power connection. An actual antenna is unconnected at the end, and the charge within it vibrates to emit EM radiation.

So what's on the board linked above and is there a way to extend its reach?

I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.

is it possible then to build something that will increase that fields diameter?

Useful answer. +1

@erik The board you linked has an inductive loop on it, printed in PC traces. (The loops in the image.) You could probably cut the traces that connect to those loops and connect each end to some bell wire that you wrap around the perimeter of your box's false bottom. If you did that then the whole bottom of the box should serve as an RFID "pad". The thing I'm not sure about is if the circuit could tolerate the changes in resistance and inductance from the larger coil of wire and still work. An EE would be better able to judge that.

source: Stack Exchange

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

sort: votes


text:
Fade in UV lights connected to mains
I have a PIR motion sensor and would like some ultra bright UV led lights to fade in when this is triggered. It is one unit, consisting of 225 led lights connected to 240v mains (Australia). I bought a relay for the basic on/off function but was wondering if fading on and off can be done relatively easily - this is my first arduino project. I would value any suggestions.

You should be able to do that using a PWM signal and the "for" command. But keep in mind that you'd also need some mosfets.

Do you have like a part number for that led unit?

Most LED lights can't be dimmed from the mains supply.
In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")
It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.
If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.
This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.
Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.
There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.

So how does this connect to the mains? Do I still use the relay that I have or can I bypass that and use the arduino to talk directly with the MOSFET to dim the lights? Basically I just have a PIR sensor and when movement detected --> fade in lights.

You could leave your IR light bank powered up all the time, and use the MOSFET to control the duty cycle of the output. However you'd then be running the power supply all the time, probably increasing wear on the IR light. It's probably better to use both a relay AND a MOSFET that controls the duty cycle of the light output.

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


text:
Arduino starter kit example LEDS modification
I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.
The point is to have a green LED shining, and when pressing the button the two red LEDs blink.
This is the code:
int switchState = 0;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

  // the button is pressed
  digitalWrite(3, LOW);

  digitalWrite(4, LOW);
  digitalWrite(5, HIGH);
  delay(250); // wait for a quarter second
  // toggle the LEDs
  digitalWrite(4, HIGH);
  digitalWrite(5, LOW);
  delay(250); // wait fo a quarter second
}

void loop()
{
  switchState = digitalRead(2);
  // this is a comment
  if(switchState == LOW)
  {
    // the button is not pressed
    digitalWrite(3, HIGH); // green LED
    digitalWrite(4, LOW); // red LED
    digitalWrite(5, LOW); // red LED
  }
  else
  {
    // the button is pressed
    digitalWrite(3, LOW);

    digitalWrite(4, LOW);
    digitalWrite(5, HIGH);
    delay(250); // wait for a quarter second
    // toggle the LEDs
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    delay(250); // wait fo a quarter second
  }
} // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.

Thank you, I checked it with different LEDs and with its own resistor and everything ok.


text:
Serial.println(): Where is the text printed?
When I used Serial.println() in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).
#include <Servo.h>

int moveServo;

Servo myservo;

void setup()
{
  myservo.attach(0);
  Serial.println("      Hello Earth");
  Serial.println();
}

void loop() {
}

Can someone tell me just where Hello Earth would be displayed?

The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.
It won't work unless you call the Serial.begin() function in your setup method before the first Serial.print()/println()/write() function call.
Something like this:
//Set up the serial port @ 9600 baud for display back to the computer
Serial.begin(9600);
delay(25);
Serial.println("Hello world!":);

You can open the serial console in the Arduino IDE by pressing ctrl-shift-M (as in Monitor) or selecting it in the menu.
Also, to use the serial interface, you have to initialize it using Serial.begin(9600); in setup() before calling any other function which writes to it. You can use any other baud rate - but this is the default in the Arduino IDE, if you change it, you should change it in the IDE too.


text:
Serial.begin(): Why not always use 28800?
In a lot of the sample code online people add the line Serial.begin(9600) in the setup block.
When I look up what Serial.begin() is on the official documentation, it says that it controls the bit per second data transfer.
So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

FYI the highest an arduino plugged into USB supports is actually 115200, and 57600 is often the second most common baud you see.

Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)
If your program is using the serial port for bulk data transfer, you would choose not to settle.

What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.
Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.
Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.
The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.
Note, this all applies to HardwareSerial, software serial is very different.

Please note 2M is archivable with hw serial, but arduino's implementation seems too slow and send a lot of garbage. See atmega328p ds to find the magic bit to double your speed. Also add that 9800 baud is a very old standard, and a lot of sensors use that value as standard, even if can be configured for more, like xbee, gps, and more. Also serial over usb use auto-baudrate negotiation witch may override selected baudate, but i think is not used by arduino (but it may be on leonardo)

9600 8N1 is also a de-facto default setting. Many devices with a serial interface are delivered with this setting and need to be configured if another speed (or databits, parity bit, stop bit) is required.

"it is more than fast enough" - Good answer, but I somewhat disagree with this point. Most debug output implementations are blocking, so it is very desirable to make the debug output as fast as possible to prevent excessive changes in code execution time.

If you're doing bulk data transfer, Ideally you'd be using SPI, right?

In addition to all the interesting answers, it worth mentioning that setting the serial speed to XXX bits/s does not necessary imply XXX bits/s on the hardware.
Clocks -- even quartz based -- are imperfect and subject to drift. In addition, as the serial clock is usually generated through a power-of-two pre-divisor and (integer) counter, all value cannot be accurately obtained given a base clock frequency. With the help of the start/stop bits, asynchronous serial communication may be tolerant to some clock drift. But this has limits.
For example, if your ATmega328PA is running at 1MHz, you can achieve 9600b/s at 0.2% of error. But at 14400b/s the error is -3.5% (actually communicating at 13900b/s). And at 28800b/s, the error is +8.5% (actually communicating at 31200b/s). All those figures are from ATmega48PA-88PA-168PA-328PA datasheet, p200.
This is not an issue when two identical devices communicate together (as there are in fact communicating at the same speed). It might be an issue when communicating between different devices.
Increasing the base frequency does not necessary improve significantly the accuracy. For example, running the same ATmega328PA as above at 2MHz does not really give better results as those are mostly due to rounding errors. But running it 1.8432MHz give very accurate bps from 2400b/s up to 57.6kHz.

Also, the Arduino Uno does not use a quartz oscillator for the main microcontroller. This introduces an additional 0.5% error, at least for the second serial port (I am not sure about the first).

I think it is a kind of tradition to use a transfer rate that is not the slowest one (300) but also not one that could eventually cause problems in some setups (28800 or even 115200). The PC serial port (most often a FTDI232 USB adapter) can cope with higher rates but your DIY hardware may not. So 9600 bps has established itself as some kind of standard transfer rate for code examples.

Back in the mists of time, the "gold standard" for remote keyboards (using a a telephone modem, and teletypes, if you remember those) was 9600 baud, initially achievable only over a dedicated phone line. Time moves on, slowly; technology advances, rapidly; and memory moves even more slowly than time (it seems). We can routinely communicate, at least over a several meters, at a couple of orders of magnitude faster than 9600 baud. What was once considered a gold standard is no longer gold, but still thought of as standard.
tl;dr: It's history, not technology.

I think the main reason people use 9600 most of the time is that it's the default baud rate in the Arduino IDE. Also, faster data rates could also be unreliable if the serial signal has to travel a long way - although I have no idea why this was selected as an optimum speed.


text:
What is commonly done to stop a servo after reaching desired position?
When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -> motor stop. But in actuality, what I get is motor start -> motor stop -> motor start -> ... forever and ever.
What is commonly done to stop a servo after it is in a desired position? Do I use servo.write(desired position) to keep it from turning? Do I detach the output wire?
What are some of the risks involved?

Could also be that you've got a continuous rotation servo, where 0 is full speed in one direction, 90 is stop, and 180 full speed in the other direction.

You do not "stop" a servo.
A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.
A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.
If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.
Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.
But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:
if(position_target != position_last_set) {
  Servo.Write(position_target);
  position_last_set = position_target;
}

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.

A servo can use a considerable amount of current trying to hold position when a rotational load is applied to the output shaft.

A normal servo doesn't have a "go" function, it only has positional control. That is, whether you run servo.write(90) forever or once, the servo will go to 90 and continue to actively keep that position until you write another position. The only way to turn a servo  off is:
servo.detach();

For a normal DC motor, you will need to turn it on then off and then have kind of state tracking in the loop to never turn it on again, using a variable or millis() etc.
Of course, if you want something to only run once, put it in setup() (maybe within a loop in setup for simple tasks).
Also, you can simulate ending the program by entering an infinite loop with while(true){} or for(;;){}.

Yes, the problem seems to be with the misfit of the arduino loop paradigm with the application rather than anything specific to do with the servo - and the solution could indeed be preventing the arduino main loop from looping by putting another infinite loop to trap execution before the end of it.  Or, in a more complicated system, by watching for some external condition and performing a sequence of operations only once in response to that.

Feh, I don't see what's misfit about it. If you want it to stop you have options as above. And why bother with a microcontroller if you're just going to do one simple thing and stop? What does it do then? Run down the battery?

myservo.detach(); is what you are looking for. Moving it to a location than detaching. This is good when you want to use it to control a servo and not have it continue to take power like when using a battery.  Here is a example.
#include <Servo.h>
Servo myservo;  // create servo object to control a servo

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

void loop() {
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(1);
  // sets the servo position according to the scaled value
  delay(1000);
  // waits for it to get to the position
  myservo.detach();
  delay(1000);
  myservo.attach(9);
  // attaches the servo on pin 9 to the servo object
  delay(15);
  myservo.write(179);
  // sets the servo position according to the scaled value
  delay(1000); // waits for it to get to the position
  myservo.detach();
  delay(1000);

do you have to delay before detach? i haven't done that and never have problems with the servo reaching the position. thus im guessing once the servo pwm signal is sent it is sent and you can move on.

The word servo has a vague definition and can encompass many types of subcomponents. If you want no-power position holding using an electromagnetic motor, then there are four options:

High viscosity grease
Dash pot
Very high gear ratio
magnetic brake shoe / brake band

EDIT: There are some additional possibilities, but it's sort of an effect of some motor designs:

Permanent magnet pole holding torque, or detent torque
Permanent magnet drag torque

The high viscosity grease and dash pot have similar functions; providing a high static friction to resist motion, which then breaks away into movement. (A dash pot is essentially a toothed gear inside a toothed wall container, and which is permanently filled with a high viscosity fluid.)
However both of these will add to the motor load, and when they get hot they tend to become thin and runny and lose holding ability.

A high gear ratio increases the torque required to back-spin the motor. Though note, if any gearbox could have a perfectly frictionless lubricant, no amount of gear reduction could stop back-spinning.
So really this is similar to the thick grease and dash pot, but gear reduction allows just the normal thin lubrication to have enough static breakaway friction, to stop back-spinning.

A magnetic brake gives you active control over the static breakaway friction, and can allow for very high holding ability vs intermittent load spikes on the output shaft. Typically with the power off, a spring engages the brake to hold position with no power.
Note, there are two different kinds of braking: static position holding, and deceleration of a moving mechanism.
The second type both dumps heat into the brake pads and friction plate, and wears down the pads and friction plate. If the brake overheats, the pads usually disintegrate, and the brake now won't hold position.
Unless we're talking about large machinery, usually servo brakes are simple designs without replaceable parts. When the brake fails, you pull the whole thing off and replace it ... including possibly the entire servomotor and gearbox too.
For long service life with magnetic braking, you need to actively decelerate the load using the servo, and then once it has stopped moving, then engage the brake to just do the job of holding position.

Using a magnetic brake for no-power static load holding only, will look like this:

Power up motor, get current position, and begin actively holding position.
Energize brake to release it
Accelerate and move to new position
Decelerate motor and hold end position
Remove power from brake to engage it
Turn off power to motor

The motor is powered up and goes into position holding first, so that the load doesn't suddenly slip in either direction, in the instant between the brake being released and the servomotor then becoming active.

EDIT #1: For some permanent magnet motors, even with the power off there is a resistance to rotation because in certain positions, the magnets and the pole pieces more closely attract to each other, known as detent torque.
This pole positioning is like a low-energy valley and it takes a bit of force to overcome the magnetic attraction and move the rotor in either direction using an external torque.
You can feel this in some brushless fans and stepper motors, where if you rotate the shaft unpowered, it resists continuous motion, and there seem to be high resistance points that the rotor does not want to cross. When spun, the rotor rapidly slows, and may fall into a back-forth oscillation as it settles into one of the magnetic attractive wells.
This can be used to resist external torques without a brake, but making use if it requires stopping the rotor in one of the magnetic wells rather than a specific position you may want. But if combined with a gearbox, the exact specific stopping position may not matter too critically, and there may be a number of wells next to each other where the rotor can stop that provide an acceptable end-effector alignment.

EDIT #2: Permanent magnet drag torque is an effect of shorting all the power wires together. When this is done it takes considerably more force to rotate the shaft than with the stepper coil wires disconnected from each other.
This is because with the coil wires all connected together, when the rotor turns it acts as a generator and current flows through the coils. This current flow creates what is known as counter electromotive force (CEMF), which counters the magnetic field of the permanent magnet.
This CEMF can provide additional resistance against rotation when the servo is unpowered. Although CEMF won't prevent motion, it can help resist continued motion and provide instant deceleration when intermittent load spikes are applied that try to move the unpowered servo.

All of the above is also generally true for linear motor servos. Those don't have gear reduction, but the motion carriage can be lubed with thick grease, be equipped with a dash pot, and have position holding magnetic brakes.

I had the same problem.
I figured out that simply adding myservo.write(90); delay(4000); helps to stop motor.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos =0;    // variable to store the servo position

void setup()
{

  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()

{
  myservo.write(180);
    delay(8000); ////stops motor for 8 seconds
  for(pos = 180; pos>=90; pos-=1)// goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15); // waits 15ms for the servo to reach the position

  }

    myservo.write(90);
    delay(4000); //stops motor for 4 seconds
  for(pos = 90; pos <= 180; pos +=1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);      // waits 15ms for the servo to reach the position

  }

}

i had the same problem i figure out that simply adding myservo.write(90);
delay(4000); //stops motor for 4 seconds   this helps to stops motor

This is a very brief explanation regarding servos.
The type of servo system that you are proposing is a none positional open loop system and is generaly used for accurate movement rate (controlled speed) . The loop in this case is usually a tachogenerator which sends a voltage (which is proportional to the motor speed) to a comparator which compares the tachogenerator voltage to the required adjustable voltage , the output of the comparator then regulates the motor speed, hence the required speed . this type of servo system will continue to run at the constant speed until  A the comparator signal is set to zero or B the motive power is reremoved from the moter ( switched off)   ----Point to point servo control , on the other hand ,, generally uses a position command which is verified with a signal from an encoder at which point the servo will stop until another command is issued from the stack ( EG. another position location or a dwell command (wait) or other )  the most common way to do this is to use gcode which has the ability to give full control of your servo system . If there is no encoding device then accurate servo position control is very difficult if not impossible.

A servo, by nature, is used to hold a position in the presence of disturbances trying to disturb that position. If you just need to move a mechanism that won't try to (or can't) back-drive the motor, your application ay be better served by a geared motor with a shaft encoder or position switches.

Hobby servos are mostly used because they are cheap and abstract out the problem and are not disturbed by typical loads.  Applications with forces that can backdrive the normal variety may be approaching overloading them anyway (some of the high performance servos have internals wguch  are more easily backdriven when off - even by the weight of control surfaces on large models).

@ChrisStratton: I know that the hobby servo can offer a block-box solution in a lot of cases, but my point is that a servo is always active, and if that is undesirable, as implied in the question, another technique may have an advantage.

No, a hobby servo is not always active - if it is not passively sitting in its deadband (comparator satisfied so motor off) or moving to a distinct new position, it has probably been misapplied.  Continued audible action means that either the servo is faulty (common in the $3 class), the linkage binding, or the load excessive.


text:
Why does my Arduino seem to reboot every time that I open Serial Monitor?
Every time that I open the Serial Monitor, my Arduino Uno, seems to go back to void setup(). Is it a normal thing?

That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.
If you want help disabling the auto reset, your options are detailed in Disabling Auto Reset On Serial Connection.


text:
Curious: What would happen if you connect 5V and GND port directly with a wire
Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?
Does Arduino provide internal safety to prevent the circuit board from shorting out?

There is some protection.
When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the data sheet for more details of the part on the UNO.
When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see datasheet for details).  By design, the regulator chip should protect itself from being destroyed.
So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.
The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.


text:
Keyboard Control Not Working As Intended
I'm trying to control a single motor.
If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180
#include <Servo.h>

char key = 0;
const unsigned int BAUD_RATE = 9600;

Servo Servo_0;

void setup()
{

  Servo_0.attach(0);
  Servo_0.write(0);

  Serial.begin(BAUD_RATE);

 // Serial.println("      Arduino Serial Servo Control");
 // Serial.println("Press < or > to move, spacebar to center");
 // Serial.println();

}

/*
a - 97
s - 115
d - 100
f - 102
*/

void loop() {

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("I received: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Turning Motor 1 to 0 deg");
       Servo_0.write(0);

     }
     else if(key==byte(115))
     {
       Serial.print("Turning Motor 1 to 180 deg");
       Servo_0.write(180);

     }

     delay(1000);
}

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

Why not if (key == 'a')?

Hi, I've changed my code to that statement but it still doesn't turn as intended

You say motors, but do you mean servos?  If you put in some servo write commands in setup(), worth a 5 second delay after each do they move?

Does anyone know if I must use "Processing" in order to activate keyboard control??

The problem I see is that your servo is attached to pin 0.
Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.
In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


text:
Building a gps system
I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).
How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.
I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.

I reopened this and cleared out the comments. FYI just be as clear as you can next time :)

"I'd like to build the smallest thing possible, because I have to hide it." ... check out http://www.dx.com/ or similar sources for e.g. "GSM/GPRS/GPS Tracker". I bet building something like this yourself will cost much more and will end in a much bigger size.

"Is it possible to do it?"
Well... everything is possible :-)
"Does GPS require Internet connection?"
GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for this you would need internet - or a large memory).
And of course such a system requires good signals from the GPS satellites.
"What do I need?"
First you need a GPS receiver (see above).
Second, you need a microcontroller unit which runs your application and does all the control of the external units.
Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message.
Don't forget the antenna for connection to the mobile communication network.
Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.
As you may see, if you put all this together you are far from the "smallest thing possible".
Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.
I don't know any, but I'm sure there are products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.


text:
Arduino Uno 3: Stuck at 'uploading...' sketches
I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE
I am not sure if it is my code is the problem or if I broke something...
I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!
This is my code:
// singleServo.ino

#include <Servo.h>

Servo servo;
const int button = 2;
const int led = 13;
const int buzzerPin = 10;
const int duration = 180;

int stateLED = LOW;
int previous = LOW;

void setup() {
    pinMode(led, OUTPUT);
    pinMode(button, INPUT);
    pinMode(buzzerPin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    int stateButton;

    stateButton = digitalRead(button);

    if (stateButton == LOW && previous == LOW) {
        if (stateLED == HIGH)
        {
            stateLED = LOW;
            initAction(duration);
        }
        else
        {
            stateLED = HIGH;
        }
    }

    digitalWrite(led, stateLED);
    previous = stateButton;
    servo.detach();
}

void initAction(int time_iA){
    tone(buzzerPin, 523, 200);
    delay(200);

    shiftServo(180, time_iA);

    tone(buzzerPin, 262, 200);
}

void shiftServo(int angle, int time_sS) {
    servo.attach(9);
    delay(500);
    int position;

    for(position=0; position <= angle; position += 1)
    {
        servo.write(position);
        delay(time_sS / 180);
        Serial.println(servo.read());
    }
    // for(position=angle; position >= 0; position -= 1)
    // {
    //  servo.write(position);
    //  delay(time_sS / 90);
    // }
}

I am a newbie with all things Arduino - Please help!
EDIT:
After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!But I'm going to take the serial functions out too.

Have you tried to power everything down, including the host PC, then upload using the Arduino IDE? What OS are you using?

Check task manager or top or whatever for any orphaned avrdude processes

I know this is really basic, and don't be offended, but have you pressed the buiild button and verified it builds before upload? - Also please double check that the arduino is attached to the USB port assigned in the buildtool.

You have to wait for the first and all other uploads to fail.
If you are not sure, a reboot is the most reliable solution.
Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.

Rebooting helped. But what exactly did I do wrong? Was it the Serial or because I stopped that Upload? Should I stop using the Sublime + Stino IDE?

the problem is normally uploading is an external script has not properly stopped, and its timeout are very high.
Normally killing the process may leave the serial port "busy" (unplua and replug USB solve that), but in arduino ide there is no "kill switch" and you have to wait (note t hat being external command is indipendant from the ide). Seems like stino does the same. About the IDE, use whatever you want, but before posting here check if arduino ide has same poblem!

I checked just that. I couldn't get any sketches uploaded from both ides

yes, that case is a "race condition" over the serial; as serial port can be used only by one program at time, until all precedent upload fail (a lot of timeout time, about 20/30sec for EVERY upload in queue) you can't upload. Also notice removing Serial from sketch does not help in that case, as it is a pc issue. Serial in sketch is problematic only when write too much, but a manual board reset is easyer to do, when you'll learn the rght timing :)

I was reading about that manual reset somewhere else but I couldn't get it at the right time^^ thanks anyway for the explanation

In that case as the upload never start from pc, it wouldn't have worked. Btw just keep pressed reset, attach usb, from arduino choose serial and luck upload, when "binary size blabla" appear unpress reset button. Try again and again xD

I've got the same problem on my Ubuntu.
Eventually, I was stuck at every uploading, even after unplugging+replugging the device.
Killing all avrdude process, remove the problem.
sudo killall avrdude

or with new IDEs:
sudo killall avrdude_bin

I had this happen to me on an UNO R3. I solved the issue by disabling Bluetooth on my laptop. It was causing a conflict on COM5.
I had ruled out the board, cable, and IDE. Finally noticed in Device Manager that COM5 had entries (one being the Arduino and the other being Bluetooth)
Hope that helps someone else that might have this issue in the future.

I had the same problem with arduino uno r3 on win10.
The solution was simple:

open the task manager (Ctrl + Shift + Esc)
stop all open COM processes
and the arduino upload worked again.

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


text:
Sample code for using adafruit servo shield?
I would like to control 16 motors with a servo shield, however, I have found scant to nothing sample code online. The one I was able to find is...strange to say the least
https://github.com/kachok/arduino-libraries/blob/master/Adafruit_PWMServoDriver/examples/servo/servo.pde
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("16 channel Servo test!");

  pwm.begin();

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);

  servonum ++;
  if (servonum > 15) servonum = 0;
}

Im used to controlling motors using servo.write, but with the shield, it doesn't seem very intuitive as to how I should control the motors. How does Servomin and Servomax map to 0 degree and 180 degree?
Someone please elucidate!

The 2 values SERVOMIN and SERVOMAX define the pulse length, which tells the servo what angle to go to.  The example uses 150 for SERVOMIN and 600 for SERVOMAX.  When running the code, the servos travel 180 deg.  I changed the code to read:
#define SERVOMIN  262 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  488 // this is the 'maximum' pulse length count (out of 4096)

and the servo now moved only 90 deg. centered at the same place as the original code.
the tutorial provided by Adafruit describes a way to define the movement by angle:
pulselength = map(degrees, 0, 180, SERVOMIN, SERVOMAX);

found here:  https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library
hope this helps

Adafruit's guide for the shield is here:
https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library
I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.
You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.
Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.


text:
Salvaged Stepper Motor Blues
So recently my company threw away some rather large and reasonably old laser printers. One was a LaserJet 9050dn the other was a Epson printer/scanner combination. Being a little industrial I thought let me salvage them and brought them home.
I managed to salvage a couple of stepper motors. However I am having huge trouble is getting them to step properly. So lets get into the details.
Components used:

1x Freetronics eleven (Arduino Uno compatbile)
1X H-Bridge driver shield(Freetronics rated for 40V/2A max).
1X Old scanner power supply which has a output of 24V/2A.

Currently there are two stepper motors I am interested in using. They have the following part numbers:

1X MITSUMI M42SP-4N
1X Minebea-Matshushita 17PM-J212-G2ST

Just to keep this short I am going to focus on the Minebea-Matshushita 17PM-J212-G2ST. I have been unable to find exact matches on these serial numbers when looking for datasheets but I have managed to find the following sheets on the net.

Minebea-Matshushita 17PM-K datasheets found from Minebea. However I cant match the model exactly.
Minebea Stepper Motor Information & Specifications also carries some useful information.

So it appears that these are 24V steppers(in both cases). The Minebea-Matshushita 17PM-J212-G2ST appears to have a step angle of 1.8 degrees which should give me 200 steps per revolution. I have not been able to find the current needed to drive this motor but judging by the looks of things it will be between 0.8A and 1.2A.
I then used my multimeter to find the pairs of wires. It has 4 wires coming out (Bipolar motor I guess). The colours of the wires are red, yellow,orange and blue. First pair was red and yellow with red being positive/anode. Second pair orange blue with orange positive/anode side.
I wired my power supply into my h-bridge and started using the recipe and quickstart found at the freetonics site. This is where the frustration begins. When asking the motor to do one complete revolution(360 degrees) it does more than 360 degrees at times and other times it does less. I tied a cable tie to the motor so I can confirm it.
So I tried the one-step-at a time sketch to see if I can troubleshoot it. Here is what I have noticed. The steps are mostly correct one step at a time clockwise however every now and again it will jump counter clock wise and then clock wise again. I suppose you can call it a jitter.
Interestingly both these motor show the same behaviour pretty good step action just every 25 degrees or so a jitter. So I suspect that this might not be bi-polar motors but uni-polar? This blog entry points me to believe that this might be the case. However the datasheet in this case points to a M42SP-7.
So my question would be simple how do I figure out if they are bi-polar or uni-polar?
Can someone help me with a proper datasheet?
Any tips would be really appreciated.
Update:
Note that I can get both motors to step clock-wise and counter clock-wise I just cant get them to do a whole 360 degrees without a jitter. Based on the Wiring Mitsumi stepper ( M42sp-4np) with arduino blog  it appears that the Mitsumi is a uni-polar motor with a 2-2 phase excitation. What stumps me is that the wires are paired thus it must be bi-polar?
So last night I tried 2-2 phase excitation with the MITSUMI M42SP-4N and it appears to be solve the problem with this motor in particular. From early observations the motor now steps without jitter, however it was late so I will need to confirm this.
I was previously using 1-1 phase excitation i.e.
Step number: 1a 1b 2a 2b
1            1  0  0  0
2            0  0  1  0
3            0  1  0  0
4            0  0  0  1
5            1  0  0  0

When using 2-2 phase excitation I get a more steady step however this needs to be confirmed a bit more:
Step number   1a 1b 2a 2b
1             1  0  0  1
2             1  0  1  0
3             0  1  1  0
4             0  1  0  1
5             1  0  0  1

Just some added observations. The headache continues but I am learning a LOT about steppers motors.
Update:
Not a 2-2 phase excitation these are definitely bi-polar. I am currently watching the Minebea-Matshushita 17PM-J212-G2ST do 360 degrees both clock and counter-clockwise. I hooked them up to a 12V/1A power supply both motors are running smoother and cooler and stepping relatively jitter free. I suspect the whole issue is a lack of a proper data-sheet.
Will update as things progress and once solved add pictures and sketches so the next lucky sod wont loose as much hair as me.
Update:
Thanks to Chris who made me look at the sketch in detail again. These motors seem to have a minimum rpm of sorts. I was trying to go for a really slow rpm under 5rpm at this speed these motors show the jitter effect. However when moving the speed to 10rpm and up no jitter.

If it's a unipolar, you wouldn't get more than 2 steps out of them. Also, I don't think any unipolar exists with only 4 wires. Try lowering or raising the current limit.

As an experiment, try making the step speed such that it takes a number of seconds to complete a revolution.  If that is really a 24v motor, it's probably going to be disappointing in performance (usually one uses a motor having a coil rated for a few volts, with a chopping current drive with many times that in available supply voltage).  While it's really AC impedance (inductance) that you need to worry about for performance, what do you measure as the DC resistance of a coil?

@ChrisStratton I suspect that these motors might be using 2-2 Phase Excitation for stepping the recipe I am using appears to be 2-1 Phase Excitation. I have tried driving these with both 12V/1A power and 24V/2A power and getting same results. I am going to experiment a little more tonight but I suspect that the cause might be the phase excitation.

That seems unlikely to be the issue - at least when unloaded mechanically you should be able to get movement either way.  Don't rule out your program glitching especially if there are any bad interactions between motor and logic supplies.  Consider having the arduino log to the serial a continuous count of the pulses emitted, and make sure it increases consistently.  And try running it slow enough that you can see each step.

@ChrisStratton thanks. I can confirm that this is the case I have made it step one step at a time and monitor the serial log. I used the one_step_At_a_Time example sketch. All seems well. Smooth increments of counter nothing. Also added an update on the 2-2 phase excitation.

Keeping this here for future reference. It appears these motors have a minimum RPM of sorts and running them on a lower RPM causes the jitter effect described above.
Like I mentioned in the updates when running at 10RPM or above these motors seem to perform very nicely.
Update: I recently bought a ADAFruit motorshield and I am getting much more stable results with this shield and the stepper motors. I am even running them off 6V and they are working perfectly even at lower rpm.

This is a rather mistaken conclusion.  There is no "minimum RPM" to a stepper motor.  However, there can be speed ranges where various resonances cause problems.

@ChrisStratton thanks for putting that so clear. I suspect now in retrospect that the different shields have different driver ic's which indicates the problem is probably with the shields and not the motors. Its been two years since I worked with shields as I started making my own.


text:
Is it possible to make an Arduino send signals to an RC receiver?
I have found bunch of information about how to hack an RC car with a PCB; and how to control an Arduino from a receiver. Also how to run a servo from an Arduino, but I'm looking for a way to make an Arduino send signals to a 27 MHz 3 channel receiver, Using three potentiometers to decide servo location.
Is there any information about this somewhere? - I have an old transmitter lying around if needed.
Links, pointers - anything is welcome.
[It does not have to be 27 MHz AM, it is just what I have on the shelve, without investing in new gear]

Ironically, your cleanest solutions might be to get a toy using an off-the-shelf 2.4 GHz chipset with a protocol that has been reverse engineered (which is to say, almost anything on 2.4 GHz that has been on the market for more than a few months) and just drive it by hanging an appropriate module for that chipset off the arduino, setting the original TX aside.

SO, what you suggest if i may "clean it up" a bit, is that i go and invest in an X-Bee shield and an RC receiever with 2.4ghz signal. If so - Is there any suggestions on how to make this work, in terms of existing arduino code?

No, I would not use an XBEE.  Take a look on rc sites and see the various 2.4 GHz chips commonly used (most are symmetric in that the same chip is used for transmitter and receiver, regardless if there is or isn't "telemetry" from the model back to the controller).  You will probably find that people already have arduino code for driving them.

The easiest way would be to open up the transmitter, desolder the potentiometer used for the stick and solder the cables to Arduino's PWM instead. Then use analogWrite() to simulate stick position. If your TX would use that potentiometer with more than 5 V, you'll not able to use full ppm values. A RC or a RCL filter may be needed between PWM output and RC input to "smooth" the PWM into an analog signal. There are a lot of online calculator to find good R, C and L to polish your signal.
This assuming your TX is using potentiometer like stick; if it is a really cheap one, it may be using buttons. If this is the case, then you connect a transistor in parallel with the button, that way you can keep manual button.
Another way is to program your Arduino to look for ppm signal (normally 50 Hz with high starting value with a period from 500 to 2000 µs) and then look for this signal into the Tx PCB; if found cut the trace of the generator and solder your cable from Arduino. I've seen around a lot of libraries outputting ppm (they are used on drones to mix single ppm channel back to PPM to use only one pin from logic board without having to hack standard RX

Please explain how one would control the transmitter with the Arduino. That's basically the whole point of this question...

Edited to be more clear. Just emulate potentiometer output with a pwm output.

This is unlikely to work without at least filtering, as both devices are varying over time - the Arduino is not outputting an analog signal but something that averages to one, and the transmitter is not measuring the potentiometer voltage continuously but rather comparing a sawtooth to it or reading it with an ADC about 50 times a second.

@ChrisStratton even if arduino pwm is by default at 200hz, problem you described may rise. Added rc and rcl filter. Also added direct injection of ppm signal

Interesting. You're assuming that the pot is wired into a voltage divider, and suggesting cutting the trace on the output of the voltage divider and feeding that trace with a filtered PWM output from the Arduino instead?

I'm assuming the pot is one of the R of the voltage divider.  especially if there is a micro after, it is the cheapest and easiest way to work with pot. but maybe this cheap tx does not use pot but button, then a transistor may be the solution

I will try this out to night when i get home. See if the pots are infact a voltage divider.

Many RC TX have a remote connector where you can input the signal and not having to open them.
In any case, 27 MHz RC are a train of pulses, of variable width, from 2 to 20 ms each, one for each channel, flowed by a 20 ms pause.
This can be recreated in a single output pin.

Such a signal may well exist internally, yes.  But 27 MHz gear tends to be the extreme low end of the market, and unlikely to expose the signal on a trainer or "buddy box" connector, so some internal probing/investigation/modification would be required.

Consider the methods of US patent 9,996,079 (linked URL):
"Radio frequency device detection and intervention": US 20180081354 A1
After reverse engineering the badly written descriptive, you should be able to come up with an Arduino board set.
P.S. Try not to copy the whole patent.

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


text:
Optmizing print code when writing to file, and reducing print time
First things first, I have found some solutions to this problems but they all involved for printing to serial monitor. I am trying to take the information from the sensors and write them to an sd card. Here is my code so far:
//-----Writes Data to SD Card-----//
if(!Data) {
    u8g.firstPage();
    do {
       drawFileError();
    } while( u8g.nextPage() );
    while (1);  // don't do anything more:
}

dcounter++;
if (dcounter=1){

    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
} else{
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();
}

two questions: is it possible for me to reduce this chunk of code into something smaller? is there a way to decrease print time?
Edit: Ahh I see, the problem with my code is that the last few values are floats.Any way to shorten those as well, or do i need to do it individually? I do agree about the adding string parts.

Several Arduino libraries for talking to SD cards are listed at http://playground.arduino.cc/Main/InterfacingWithHardware#Storage . Perhaps one of them is faster than the library you are using now?

Edit you question to state how long it is currently taking to print and what sort of improvements you need.

First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:
//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.print(strutcDate + "  ");
Data.print(strutcTime + "  ");
Data.print(strgpsStatus + "  ");
Data.print(strmodeIndicator + "  ");
Data.print(strlatitude + "  ");
Data.print(strlongitude + "  ");
Data.print(strspeedOverGnd + "  ");
Data.print(strcourseOverGnd + "  ");
Data.print(t);
Data.print("  ");
Data.print(f);
Data.print("  ");
Data.print(h);
Data.print("  ");
Data.print(hi);
Data.print("  ");
Data.print(press_pKa);
Data.print("  ");
Data.println(str);
Data.close();

Like already mentioned, you can append strings with the + operator. This would be the final code then:
//(Include the top part of the code here...)
dcounter++;
if (dcounter=1){
    Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
    Data.println(Header);
}
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.

I would analize what I want to write, extrapolate all numeric value, then create a structure that hold numeric value. So at every write I would write the structure (it is a binary write, so use fixed byte size) followed by all others string(or even place string in different file, but may turn out harder to manipulate or fix in case of problem).
Then to read it you'll need to read back the structure, followed by eventual know number of string. If string may be of unknown number,, just put the number of following string into the struct. Outside string, as you can see, you need no special char to signal the end of chunk of data :)
Unrelated: please, remove all println in the if rather than the header as they are equal to the else; then remove the else statement (but not the else body!) That way the if will open file and add header, and then the code will always add the rest of code. It would be a shame if you edit your else branch and forgot the if, or viceversa. Code style matters, trust me

Maybe this helps with speed. It will however use more memory, so use with caution.
Data.println(Header);
Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
Data.close();

As you suggest yourself, don't ever do code like this on a microcontroller.  This is a likely to overflow the stack.


text:
Aduino Due Can messages
I am trying to read/send CanBus messages using a Arduino Due.
As of now I have used https://github.com/collin80/due_can library to setup my Can Bus interface.
I am using Vector Software CanAylzer to see what CAN message are being received.
This is where I have my issue.
Although the CanAylzer software is being able to detect Can Messages on the line it gives be a Bit error on bit position 119. All the fields of relevance for me ID,Data etc seem to be reported fine.
Here is a snapshot of the CanAylzer Error Frame. Below is my Arduino code . Any help would be awesome.

Here is the ino code:
// Arduino Due - CAN Sample 1
// Brief CAN example for Arduino Due
// Test the transmission from CAN0 Mailbox 0 to CAN1 Mailbox 0

#include <Arduino.h>
#include "variant.h"
#include "due_can.h"

#define TEST1_CAN_TRANSFER_ID    0x18FF0017 //random 29 bits
#define TEST1_CAN0_TX_PRIO       1
#define CAN_MSG_DUMMY_DATA       0xABC

// CAN frame max data length
#define MAX_CAN_FRAME_DATA_LEN   8

// Message variable to be send
uint32_t CAN_MSG_1 = 0;

void setup()
{

   // start serial port at 115200 bps:

   Serial.begin(115200);
   Serial.println("Program Started");

}

void loop(){

   CAN_FRAME frame1, frame2;
   // say what you got:
   Serial.print("Sent Value: ");
   Serial.println(CAN_MSG_1, DEC);

   // Initialize CAN0 and CAN1, baudrate is 250kb/s
   CAN.init(CAN_BPS_250K);
   CAN2.init(CAN_BPS_250K);

   //Initialize the definitions for the frames we'll be sending.
   //This can be done here because the frame never changes
   frame1.id = TEST1_CAN_TRANSFER_ID;
   frame1.length = MAX_CAN_FRAME_DATA_LEN;
   //Priority
   frame1.priority = 0;
   frame1.rtr = 1;
   //Below we set the 8 data bytes in 32 bit (4 byte) chunks
   //Bytes can be set individually with frame1.data.bytes[which] = something
   frame1.data.low = 0xAFAFAFAF;
   frame1.data.high = CAN_MSG_DUMMY_DATA;
   //We are using extended frames so mark that here. Otherwise it will just use
   //the first 11 bits of the ID set
   frame1.extended = 1;

   CAN.sendFrame(frame1);
   while (1) {
   }
}

Update
Ok so here are the printed(via serial port) values of various registers. I don't think it is a problem with the values in the registers. I have cross referenced these with the SAM3X/A (on the due) Micro-controller manual (chapter 41, pertaining to the CAN). The only one I am fishy about is the baudrate one.
Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_SR:( Status Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
      0 | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     0  | 1  | 1  | 0

Bits 23 | 22 | 21 | 20
     1  | 0  | 1  | 0

Bits 27 | 26 | 25 | 24
     0  | 1  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 1  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_MR: (Mode Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 26 | 25 | 24
     0  | 0  | 0
<><><><><><><><><>><><><><>
#####END OF LOOP ######

******START OF LOOP ******
No of Sent frames: 4
<><><><><><><><><>><><><><>
CAN_MID7: (Message ID Register Mailbox 7)
Bits 3 | 2 | 1 | 0
     0 | 1 | 1 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 1

Bits 11 | 10 | 9 | 8
     0  | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     1  | 1  | 1  | 1

Bits 23 | 22 | 21 | 20
     1  | 1  | 1  | 1

Bits 27 | 26 | 25 | 24
     1  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 1  | 1

Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_ECR: (Error Count Register)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
     0  | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     0  | 0  | 0  | 0

Bits 23 | 22 | 21 | 20
     1  | 0  | 0  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

Lastly and most importantly in my opinion:
Serial Port Initialized
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_MSR7: (CAN Message Status Register Mailbox 7)
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 0

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 0

Bits 11 | 10 | 9 | 8
      0 | 0  | 0 | 0

Bits 15 | 14 | 13 | 12
     0  | 0  | 0  | 0

Bits 19 | 18 | 17 | 16
     1  | 0  | 0  | 0

Bits 23 | 22 | 21 | 20
     0  | 0  | 0  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 31 | 30 | 29 | 28
     0  | 0  | 0  | 0

<><><><><><><><><>><><><><>
#####END OF LOOP ######

and the Baud rate register
******START OF LOOP ******
No of Sent frames: 1
<><><><><><><><><>><><><><>
CAN_BR:
Bits 3 | 2 | 1 | 0
     0 | 0 | 0 | 1

Bits 7 | 6 | 5 | 4
     0 | 0 | 0 | 1

Bits 11 | 10 | 9 | 8
     0 |  0  | 1 |  0

Bits 15 | 14 | 13 | 12
     0  | 0  | 1  | 0

Bits 19 | 18 | 17 | 16
     1  | 0  | 0  | 1

Bits 23 | 22 | 21 | 20
     0  | 0  | 1  | 0

Bits 27 | 26 | 25 | 24
     0  | 0  | 0  | 0

Bits 28
     0
<><><><><><><><><>><><><><>
#####END OF LOOP ######

You can find what all the register bits details on Atmel's website or leave some way for me to email the documentation to you.
Any Help would be much appreciated!
Update 2:
I have attached 2 different Oscilloscope readings and deconstructed the entire binary representation of the Can message manually. Furthermore I calculated the associated CRC's of the two different messages, and then compared them to the ones the hardware created and found them(hardware ones) to be incorrect. I have provided a link to Google Drive where the results from the Oscilloscope can be found.
PS: the messages I used had in one 7 A's(hex, i.e 28bits) for the ID and 16 A's for the Data field.
The second one had 7 C's for the Id and 16 C's for the Data field.
Both are 2.0B can extended frames.

Looks like a CRC error. But the CRC calculation is done by hardware, so neither your fault nor the library's. Do you see a chance of monitoring the CAN line? If I'm not completely wrong, CRC for this frame should be 0x5F88

@mic the CANalyzer(pictured above) does that for me. I know its a problem with the CRC but why? And how do I fix it?

Good question! :-) That Vector stuff is not perfect, but the tools (and especially the prices) are made for professional use. The only thing I can imagine at the moment is a slightly different baudrate and/or an improper tq setting in your CANalyzer. What happens if you play a little bit with the sampling point? And again: Do you have a chance to look directly at the CAN line (e.g. using a scope)? It would be interesting to know what the Arduino really transmits.

@mic how do I check the tq settings? I have checked all the registers on the hardware level as well they seem to have the correct information.

@mic also have you used vector software before?

I'm quite familiar with Vector. In Canalyzer, "Configuration" - "Hardware configuration", you will see your CAN channel, and in "Setup" you can adjust the sampling. Play a little bit with the settings and see what happens.

yeah *I did that but the issue was the prescalers dont match up for the baudrate. If I put a prescaler of 4 in my arduino side code it gives me a sync error if i try to put a higher scaler then there is no equivalent in CanAylzer

Of course the baudrates have to match EXACTLY. 250kb/s is a common baudrate for a mid speed CAN network. I'm pretty sure CANalyzer as well as the Arduino offers at least one parameter set for this baudrate. What is your master clock on Arduino?

its the SystemCoreClock defined in the system_sam3xa.h (due's MC) header

Sorry, but this discussion doesn't really show progress. Maybe it's a good idea to post all your Arduino register settings as well as your CANalyzer timing parameters.

@mic updated stuff

@mic you were initially right. I used an oscilloscope to track the signal and found out the CRC doesn't match up to what it should be. This I believe is throwing the bit error. Any advise on how to fix this ? All other fields are correct. Also the frequency and therefore the baudrate are correct. I calculated that from the scope measurements.

This is strange, as you have no influence on CRC calculation. But what I've noticed when analyzing your register settings: In CAN_SR, the "Warn" flag is set. This should not happen after only one transfer. Also the "AERR" is set. This may be ok, if CANalyzer has detected a bit error and thus doesn't send an acknowledge. Can you post the scope screenshot for the complete message?

@mic please See the Section Update 2.

@mic the WARN Flag is set correctly. Firstly because I am sending a message in a loop multiple time not only once. Secondly as per CAN protocol a failed transmission attempt will be followed by multiple re-transmission attempts up to 255 times. At which point the CAN Bus will be disabled. Reference pg 1219 SAM3X/A manual.


text:
Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno
I've researched how to attach multiple buttons to a single analog input using a resistor network. Instructables has a good lesson on this: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/?ALLSTEPS
My requirement is that I need to attach an interrupt to buttons (ie the analog input) before reading the analog value, so that all the buttons can act as a trigger.
This works for voltages in the higher range, but not in the lower range (the trigger input waits for a RISING edge).
Can any one suggest a circuit that steps a >0V+ to +5V input to a +5V output so that any button push would trigger the input?
Otherwise, does anyone have other suggestions on how to use triggers for each button?

Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.
Connect the analog network to both the analog input and D6.
If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have not connected the voltage then configure the comparator to use the internal bandgap reference (ACSR |= _BV(ACBG)).
Enable the comparator interrupt and capture on a rising edge (ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)).
Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (DIDR1 |= _BV(AIN0D), DIDR1 |= _BV(AIN1D)).
Write an ISR that does what you want on comparator trigger (ISR(ANALOG_COMP_vect) { ... }).
Now go back and read all that three more times until you understand it. As always, see the ATmega328P datasheet for details.

Cool. I learned something new today. (Voted). I did not know that ATMega chips include an analog comparator, much less that you can trigger an interrupt based on comparator results. I would have built something using an op-amp, but I like the software-only solution. It looks like the ATMega2560 has the same feature. Cool! (I guess I said that...)

Do you have any links to sample sketches using the analog comparator, particularly using it as an interrupt? The registers and configuration on the AVR family are a little quirky and I find a working example very helpful in understanding how to use them. (I'm an old assembler jockey, so I'm pretty good at this stuff.)

Nope. But there is AVR128.

That'll do nicely. I didn't know that the ACI flag was set when an interrupt condition was met, even if interrupts are disabled. That's very cool, and useful for writing a tight polling loop rather than an ISR.

I re-read this 10 times and I still don't understand it...

http://en.wikipedia.org/wiki/Comparator

Considering the fact that from a functional point of view, you just want to have more digital inputs, I would propose to use a Parallel-In Serial-Out Expander, (e.g. CD4021B or 74HC165).
This IC (i.e. 74HC165) has 8 digital inputs, that can be 'shifted' and send to your Arduino using just 2 wires. Arduino has a built-in function for this (i.e. shiftIn) to read the input and to convert it to a byte.
If 8 inputs is not enough, then you can chain multiple IC to create 16, 24 ... digital inputs.
There is an official tutorial for the CD4021B.
I don't know if this is a requirement, but if you want to register multiple key-presses at the same time, then this is a really good strategy.

I really do not know your level of experience, so please, ignore this if not applicable;
Most cases of a push button will not need an interrupt. It is a human pushing the button and so precise timing is no where close to needing an interrupt.  You would only need an interrupt if you wanted to actually interrupt some looping code. And since timing (of a human by definition) is not that great, simply checking for a button press in your looping code will always be good enough.
That being said, the common resistor networks you have read about will work adequately.
psuedo code;
void loop()
{
  int btn = analogRead(pin);
  if (btn > pin1Level)
  {
    if (btn > pin5level) DoPin5();
    else if (btn > pin3level) DoPin3();
    else DoPin1();
  }
  doOtherStuff();
}


text:
How does serialEvent gets into main()?
Ok, serialEvent "runs after loop()" and it is not an interrupt.
AS far as I know main() has two functions  - setup and "infinite" loop.
So where does serialEvent comes in?
And if I do not want loop()  to run and use only setup than  I cannot use serialEvent.

Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp
"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.
To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.

To be fair, you only need to call serialEventRun() if you define a serialEvent{,1,2,3}() function.

That was what I intended to get across, I'll edit for more clarity.

Thanks,I feel that 120% people using Arduino main() should have this posted on their refrigerator.

To clarify, this "serial event" callback is for handling incoming data over Serial, right? If I'm not receiving any data on the device, and I'm merely Serial.printing things, I should be unaffected if I have an infinite loop in setUp, correct?


text:
Sample average of analog of current sensor
I have two problems in the code below. This ACS712 sensor is too noisy so I am not getting the count value properly, since I need approximate reading I consider curve is linear, and calculate the slope.
My problems are:

When I take a 10 sample average, the first value it reads properly, i.e. 512 is count value, other value taking as 0. I don't why.
Once current exceeds 1A, my relay output should go low. Once it goes low it waits for 30s & again it must high the relay high. Since I am checking output in loop, it making high & low without waiting for 30s. Can someone help me how can I do this?

If you used without MStimer, the newaverage values print 512 which is my reference, but for other 9 values print newaverage as zero.
#include <MsTimer2.h>

#define RELAY1  3
#define RELAY2  4

int num_readings=10;
//int total;
int readings[10];
int index;
float CS_Value;
static float Output_Current;
float mad;
float madstd;
float lowlimit ;
float highlimit;
int count;
int total;
int reading;
static int newaverage;
unsigned long Wait_Time=30000;
unsigned long Current_Time;
static int Tripped_Flag=0;

float standard_deviation(int avg1) {
  total = 0;
  for( int i=0; i<num_readings; i++)
    total = total + pow((avg1 -readings[i]), 2);
  return sqrt(total/num_readings);
}

int  average()
{
  total = 0;
  for( int i=0; i<num_readings; i++)
  {
    total = total + readings[i];
  }
  return total/num_readings;
}

void TakeReading()
{

  reading = analogRead(A0);
  readings[index] = reading;
  index = index + 1;

  if (index >= num_readings)
  {
    index=0;
    int avg = average();
    float std = standard_deviation(avg);
    madstd = mad * std;
    lowlimit = avg - madstd;
    highlimit = avg + madstd;

    total=0;
    count=0;
    for(int i=0; i<num_readings; i++) {
      // Check if the values of the readings are within the limits.
      if(readings[i] >= lowlimit && readings[i] <= highlimit) {
        total = total + readings[i];
        count = count + 1;
      }

    }

    // compute the new average
    newaverage = total/count;
    // send it to the serial port (as ASCII digits)

    Serial.print("Newaverage:");
    Serial.println(newaverage, DEC);
    Output_Current = 0.0336666666667*newaverage - 17.17;
    //return(Output_Current);
  }

}

void setup() {
  // sets the serial port to 9600
  Serial.begin(9600);
  pinMode(RELAY1, OUTPUT);
  pinMode(RELAY2, OUTPUT);
  Relay_Intialize();

}

void loop()
{
  MsTimer2::set(50, TakeReading); // 500ms period
  MsTimer2::start();
  //  CS_Value=  TakeReading();
  Serial.print("current is :");
  Serial.println(Output_Current);
  //if (CS_Value>0.95 && Tripped_Flag==0)
  if (Output_Current>0.95 && Tripped_Flag==0)
  {
    Serial.println("Main Activate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Activate();

  }
  else
  {

    Serial.println("Main Deactivate");
    Serial.print("Tripped_Flag_status:");
    Serial.println(Tripped_Flag);
    Relay_Deactivate();
  }
  Serial.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
  delay(1000);

}

void Relay_Activate()
{
  for (unsigned long start = millis(); millis() - start < 10000;)
  {
    digitalWrite(RELAY1,LOW);
    digitalWrite(RELAY2,LOW);
    Serial.println("RELAY GOT TRIPPED");
    Tripped_Flag=1;
  }

}

void  Relay_Deactivate()
{
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
  Serial.println("RELAY NOT TRIPPED");
  Tripped_Flag=0;

}

void Relay_Intialize()
{
  Serial.println("RELAY GOT INTIALISE....");
  digitalWrite(RELAY1,HIGH);
  digitalWrite(RELAY2,HIGH);
}

Please can you write 1) clearer? I can't understand.

@lesto which point you are not clear about.

" first value it reads properlyi.e 512 is count value other value taking as 0.I don't why." I cant understand what you expect andvwhatvyoubget

Instead of posting output screenshot, could you copy it here as a text? Screenshot is hard to read and impossible to copy.

I didn't have a look at your item 2, but regarding item 1:
Please consider that in function TakeReading(), if the condition is never true, count is 0 when you come to newaverage = total/count;!
I don't know what the Arduino does in case 0/0, but -1 may be a proper return value.

The result of dividing by zero is undefined. It doesn't throw an exception, but will return invalid data. you need to check for and avoid dividing by zero to avoid bad data.


text:
Stacking Arduino Shield (Motor Shield, LCD Keypad, LED Sensor)
I'm building a line follower with arduino, here some part that I'm going to use

Arduino Uno
Motor Shield 2A http://www.dfrobot.com/index.php?route=product/product&product_id=69
LCD Keypad
4 Channel Line Tracking Sensor http://www.aliexpress.com/item/4Channel-Infraed-Line-Tracking-Sensor-Module-w-Connector-Line/2021343637.html

I'm using LiPo Batteries 3 Cell 11.1v for power source.
I'm new in here so I didn't know how to stack that shield, if I recall I can stack up Arduino and the LCD Keypad, and Arduino and the Motor Shield, but didnt know how to stack those 2 together and adding another sensor like that line tracking sensor. May I know how to resolve that? thanks.

What LCD Keypad are you using?

this is LCD Keypad that I'm using http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_%28SKU:_DFR0009%29

The Motor Shield 2A plugs in on top of the Arduino Uno, and the LCD Keypad plugs in on top of the motor shield. [But see Edit 1 below]
There is better information about the  4 Channel Line Tracking Sensor at uctronics.com where you can see that its main board (with the LM339 chip) connects to the Arduino via six lines: Vcc, Gnd, Out1, Out2, Out3, Out4.  That main sensor board does not mount on the stack, but instead can be located whereever is convenient and leaves its four comparator-level pots accessible for adjustment.
Mount the four small boards for the tracking module as convenient and necessary for line following.
For connecting the six lines from the sensor main board to the Uno, you probably will need to solder two headers (rows of pins) to a board in the stack.  Using right-angle headers (see below) will allow the pins to come out of the side of the stack without interfering with other layers of the stack.  One of the headers should let you connect sensor Out1...Out4 digital outputs to four otherwise unused analog or digital pins, and the other header should let you connect Vcc and Gnd.

Edit 1: In the LCD shield page, section 2 (Diagram) shows Vcc, Gnd, and D0-D3 available at the top right corner (the angled corner).  Those six pins probably are a reasonable place to add a six-pin angled header for the sensor board.
Given that the LCD KeyPad Shield is a DFRobot.com model, the summary pinout at shieldlist.org shows that its use of D4,5,6,7 will conflict with use of those same lines by the DFRobot 2A Motor Shield.  There are several ways to handle a conflict like this:  1, use two Uno's, one per shield; 2, make one shield or the other use different lines; 3, share the lines.
Method 2 could work as follows:  Stack the LCD shield directly on the Uno (or any other compatible Arduino).  Besides a header for the sensor board, add a header for a cable to the motor board, and drive the motor board's D4-7 inputs with some other lines from the Uno, eg A4-7.  [Alternately  one could remove the D4-7 pins on the LCD shield and jumper from A4-7 to the D4-7 lines on the LCD shield.  This would leave the boards in a single stack but would make some serious changes to the LCD board.]
Method 3 would work as follows:  The LCD shield only pays attention to D4-7 (which from the DFRobot schematic drive DB4-DB7 on an LCD TC1602 chip) when the TC1602's E line is strobed.  See pages 7 and 8 of Adafruit.com's copy of TC1602 specs, where timing diagrams show about half-microsecond times for writing to or reading from the TC1602.
You would need to run tests with your motors and see if they work ok in spite of the four inputs to the motor shield being random during the occasional half-microseconds that data is being written to the LCD.  You might have to add more diodes or capacitors to  suppress electrical noise due to rapid switching.
DFRobot's motor shield page has links to that board's schematic and to its L298 chip data sheet.  Page 7 of the datasheet says

An external bridge of diodes are required when inductive loads are driven and when the inputs of the IC are chopped; Shottky diodes would be preferred.

The motor shield schematic shows diodes; although not drawn using Schottky diode symbols they might be Schottky anyway (which would give better noise suppression, less heating, etc).  The schematic also shows that JP1, a 16-pin dual row header, has jumpers that control ENA and ENB on the L298.  In a "proper solution" for sharing D4-7 between the LCD and motor shields, you'd drive ENA and ENB low when using D4-7 for LCD i/o, which would allow the attached motors to briefly free run, as opposed to being suddenly commanded to stop or reverse.

Note, I didn't verify whether any of the LCD shield lines conflict with any of the motor shield lines.  As asked earlier, what LCD Keypad are you using?

LCD Keypad just like in DFRobot in here http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_%28SKU:_DFR0009%29 I didn't know how to attach the additional header pin because the top of stack is LCD Keypad and didnt know where to use it

kripton, see edit

based on your method, can I use ardu nano or mini? cause I only have 1 uno at a time. or maybe can I use shiftout just like in this tutorial? http://arduino.cc/en/tutorial/ShiftOut thanks anyway

Neither shield can directly plug into a Nano or Pro Mini (which are about 1/3 as wide as an Uno) but would instead need cables or an adapter shield.  In that case you might as well use a cable from Uno to motor shield.  The Uno has enough lines to do it all.  See edit about "Method 2".

The most elegant approach would probably be to use shields controlled by the I2C bus. I've found LCD+keypad and motor shield offered by Adafruit for example.
The I2C bus is shared by all slaves connected to it, and you should find microswitches on each shield to set its I2C address.
Regular shields should not interfere with I2C lines, so as last resort you can put one shield controlled "traditional way".

By in case of trouble finding do you mean when you need to do some trouble shooting or if you encounter any problems?

@Greenonline sorry for imprecise language, I meant "trouble finding I2C controlled shield for your purpose" and I have edited my answer.


text:
Confusing Arduino Leonardo PWM
I'm having problems with using Arduino Leonardo PWM outputs (I'm actually using YUN board).
I need 4 PWM outputs that generally have the same base frequency of around 10 to 20 Hz or so.
I'm using timer 1 (A-pin-9,B-pin-10,C-pin-11) and timer 4 (A-pin-13)
I get pins 9,10,and 13 PWM output working decent, but for some reason pin 11 PWM frequency is much much higher.
Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.
Here is my code can anybody see anything wrong? thanks!
    #define PWM_4A_PIN  13
    #define PWM_1C_PIN  11

    #define PWM_1B_PIN  10
    #define PWM_1A_PIN  9

    void setup() {
     TCCR1B = TCCR1B & 0b11111000 | 0x05;
     TCCR4B = TCCR1B & 0b11110000 | 0x09;
     analogWrite(PWM_4A_PIN,128);
     analogWrite(PWM_1C_PIN,128);
     analogWrite(PWM_1B_PIN,128);
     analogWrite(PWM_1A_PIN,128);
    }

    void loop()
    {
    }

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Unless D11 is configured as OC0A instead of OC1C, which means that it will work off timer 0.
TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR1A |= _BV(COM1C1) | _BV(COM1C0);
 ...
OCR1C = ...;

Thanks Inacio, I tried your code but the same result D11 has much higher freq than 9 and 10, its very strange!

Did you use analogWrite() on D11? That will reset it to OC0A.

if I replace analogWrite(11,128) with OCR1C=128, then no output at all

Here is the whole code as it is now#define PWM_4A_PIN  13
#define PWM_1C_PIN  11
#define PWM_1B_PIN  10
#define PWM_1A_PIN  9
void setup() {
TCCR1B = TCCR1B & 0b11111000 | 0x05;
TCCR4B = TCCR1B & 0b11110000 | 0x09;
TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR3A |= _BV(COM1C1) | _BV(COM1C0);
//TCCR0A=0;
//TCCR1A=0xb01010101;
pinMode(11,OUTPUT);
OCR1C=128;
analogWrite(PWM_4A_PIN,128);
//analogWrite(PWM_1C_PIN,128);
analogWrite(PWM_1B_PIN,128);
analogWrite(PWM_1A_PIN,128);
}
void loop() {
}

Call analogWrite() once to configure everything else, then perform the assignments in my answer.

void setup() {
TCCR1B = TCCR1B & 0b11111000 | 0x05;
TCCR4B = TCCR1B & 0b11110000 | 0x09;
analogWrite(PWM_4A_PIN,128);
analogWrite(PWM_1C_PIN,128);
analogWrite(PWM_1B_PIN,128);
analogWrite(PWM_1A_PIN,128);
TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
TCCR3A |= _BV(COM1C1) | _BV(COM1C0);
//TCCR0A=0;
//TCCR1A=0xb01010101;
OCR1C=128;
}  D11 as no output anymore, but 9,10,and 13 still works

WORKS NOW!!! you have typo in your answer, TCCR3A should be TCCR1A, I changed that one thing and now it works!! THANKS VERY MUCH FOR YOUR HELP GOD BLESS YOU!!!

Pfft, yes, I suppose I goofed that part. Stupid joint datasheet sections...

why when I write to analogWrite it makes it back to OCOA???

I need to keep changing the PWM duty cycle, so I cant use analogwrite for any pin, only OC1C, OC1A, OC1B fro then on?

analogWrite() does a lot of housekeeping behind the scenes, including preparing the pin for how it thinks it should work. One of these bits is setting D11 as OC0A. Another is setting the PWM frequency. Sometimes the Arduino libraries are handy, and sometimes they interfere.


text:
Burning sketch with I2C
Not a pure Arduino question really. I'm actually using a standalone ATmega168. So far I've been using AVR-ISP programmer (working from AVR Studio) to program the chip. After everything is done, the chip will be covered and I will only have access to the I2C pins. The MISO,MOSI, etc pins will be unreachable.
I was just wondering if there was a way to use the I2C pins to update the program that is burned on the chip. I won't need to burn the bootloader again, but just to update the program if it needs to be.

You need to write a I2C bootloader to the AVR. There seems to be a project that has already created such a bootloader.
Atmel has provided a TWI/I2C bootloader for their XMega processors (not the ATmega168).
Next problem is uploading the code via I2C. You'd need some hardware to convert USB  to I2C. And some software to talk to this hardware. The last part is probably supported by AVR studio, as Atmel has provided an I2C bootloader. Though I'm not sure both of the above bootloaders are using a compatible protocol over the I2C.

Take a look at miniboot. I implemented it as a self-contained bootloader. Instructions about uploading from USB to I2C are also provided. Live long and prosper.

Elaborate the point. Link only answers die of link rot.


text:
Serial input parallel output shift registers with arduino
I need a way to rewrite the switch case part in a more efficient way.
int y , x ;
byte dataArray[6];

void setup () {
   pinMode(8,OUTPUT);
   pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);

   Serial.begin(9600);
   dataArray[0] = 0x3 ; //00000011
   dataArray[1] = 0x5 ; //00000101
   dataArray[2] = 0x9 ; //00001001
   dataArray[3] = 0x11; //00010001
   dataArray[4] = 0x21; //00100001
   dataArray[5] = 0x41; //01000001
}

void loop () {
   while (Serial.available()>0) {
     y = Serial.read();
     x = Serial.read();
     switch ( x ) {
     case 1:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 2:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     case 3:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 4:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 5:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

      case 6:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,dataArray[y]);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;

     default:
        digitalWrite(8,LOW);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        shiftOut(11,12,LSBFIRST,0);
        digitalWrite(8,HIGH);
        delay(10);
        digitalWrite(8,LOW);
     break;
     }
   }
 }

This question appears to be off-topic because it is a programming question.

@MattYoung you are right i didn't take this in mind sorry

unsigned char i;

digitalWrite(8,LOW);
for(i=0;i<=6;i++){
    if(x+i==6) shiftOut(11,12,LSBFIRST,dataArray[y]);
    else shiftOut(11,12,LSBFIRST,0);
    }
digitalWrite(8,HIGH);
delay(10);
digitalWrite(8,LOW);

that s exactly what i need thanks alot (y)