text:
Attiny84A and IR Sensor
I have a GP2Y0A21YK0F Sharp IR Analog Distance Sensor 10-80cm + Cable, Arduino Compatible and its is connected to my Arduino. All works well and I can read the analog data with the following code:
#include <SoftwareSerial.h>
#define RX 2 // receive
#define TX 3 // transmit
#define SEN1 4
SoftwareSerial mySerial =  SoftwareSerial(RX, TX);

void setup()
{

  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{

   int reading = analogRead(SEN1);
   mySerial.println(reading);
   delay(500);
}

When the code runs on the Attiny with the GP2Y0A21YK0F IR Sensor connected, the Attiny84 resets over and over. The Attiny84 and GP2Y0A21YK0F are part of the same circuit e.g. Attiny and GP2Y0A21YK0F share the power and ground rail.
When I disconnect the GP2Y0A21YK0F, the program runs and stops resetting. I was able to reproduce this on an Attiny85 and ATMega328.
The strange thing is, it works fine on the Arduino. Any help is greatly appreciated.

Start by adding 100nF capacitors with short leads as close as possible to the the power pins. One near the ATtiny, one near the IR sensor.

+1 Thanks after some trial and error, placing a 100uf at the source and at the GP2Y0A21YK0F seems to work. Awesome :)!

You really want to use caps in the order of 100nF, that is nano Farad's. The 100uF, micro Farad's, may work now but may not keep up with age. It is fine to use them in parallel. The smaller 100nF caps have a much lower impedance for high frequencies than the 100uF caps and they don't age.

It sounds like the microcontroller is browning out.
IR sensors are notorious for taking a lot of power when they operate; often they will tax a small power supply and cause the voltage to droop low enough to reset/brownout the microcontroller.
Try either putting a fairly beefy capacitor on the power bus, or getting a larger power supply.
Hope this helps!
(edit: I reverted another user's edit to this answer; "droop" is in fact the correct term for what is going on: http://en.wikipedia.org/wiki/Voltage_droop)


text:
Servo library unable to control more than 11 servos
I am working on assembling the ROFI robot from Project Biped (http://www.projectbiped.com/prototypes/rofi) and I have not been able to run any arduino program as they will not function correctly.
To be more specific, when I attempt to run 12 servos on a single Arduino Mega, the servos twitch uncontrollably and do not move to the positions which are set in the program.  At the same time the power light on the arduino mega blinks and does not turn solid (as opposed to if I use less than 11 servos when the pwr light is solid).  I predict it might be the power source but after checking the batteries with the multimeter they check out to be fine (7.6 V).  The circuit is pretty simple, I am using a servo shield connected to a 6V regulator connected in parallel to two 7.2 V 1350 mah LiPo batteries.  The arduino is connected through the dc power jack to the same circuit in parallel.
Here is the code...
   #include <Servo.h>

// 0 Right Ankle (roll)
// 1 Right Lower Leg
// 2 Right Knee
// 3 Right Middle Leg
// 4 Right Upper Leg
// 5 Right Hip (roll)
//LEFT LEG JOINTS
// 6 Left Ankle (roll)
// 7 Left Lower Leg
// 8 Left Knee
// 9 Left Middle Leg
// 10 Left Upper Leg
// 11 Left Hip (roll)

int c=0;

Servo rightAnkle;
Servo lowerLeg;
Servo rightKnee;
Servo rightMiddleLeg;
Servo rightUpperLeg;
Servo rightHip;
Servo leftAnkle;
Servo leftLowerLeg;
Servo leftKnee;
Servo leftMiddleLeg;
Servo leftUpperLeg;
Servo leftHip;

void setup(){
  rightAnkle.attach(0);
  lowerLeg.attach(1);
  rightKnee.attach(2);
  rightMiddleLeg.attach(3);
  rightUpperLeg.attach(4);
  rightHip.attach(5);
  leftAnkle.attach(6);
  leftLowerLeg.attach(7);
  //leftKnee.attach(8);
  //leftMiddleLeg.attach(9);
  leftUpperLeg.attach(10);
  leftHip.attach(11);
}

void loop(){
  rightAnkle.write(90);
  lowerLeg.write(90);
  rightKnee.write(90);
  rightMiddleLeg.write(90);
  rightUpperLeg.write(90);
  rightHip.write(100);
  leftAnkle.write(90);
  leftLowerLeg.write(90);
  leftKnee.write(90);
  leftMiddleLeg.write(90);
  leftUpperLeg.write(90);
  leftHip.write(90);
}

What are the specs of the 6 volt regulator?

It sounds to me like you're exceeding the current limits of your power supply. Add up the current drawn by your servos (and their controller(s), and also the current drawn by your Arduino and any other circuits you have. I bet you'll find that at 12 servos, you go over the current limit of your regulator. You might need a higher current regulator or a second one.

Servo library unable to control more than 11 servos

because the library isn't written to control more.
this approach (https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/) can drive arbitrary number of servos over multiple ports / pins.
it is written for a pic but it has links to AVR implementation as well.

source: Stack Exchange

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

sort: votes


text:
How to serial connect arduino galileo to alarm system
i'm a little new in this.
I have an alarm system panel which has TX,RX wires with 12V output/input.
how can i  read the output with arduino and control it with serial communication?

First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.
After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.
You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.

what is logic level shifter? cant i ues simple voltage divider ?

@NorisS you could from the system to the Arduino but you need a way to increase the signal for the receiving line on the system. A logic level shifter just translates voltages.

can you recommend me specific model?

@Nor my phone isn't loading the datasheet but comments seem to say that this will work: https://www.sparkfun.com/products/12009 remember to use a common ground.

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


text:
Blank Serial Print AdaFruit BTLE
I working on a prototype with an Arduino UNO and an AdaFruit Low Energy Blue tooth
I have an array of uint32_t that I am trying to send via blue tooth to a given device.  I don't think i can send the array so I was trying to send it as a comma separated string.
I can print out each individual index of that array just fine, but its completely blank when i try to make a comma separated String..  See code and comments below.
Ay Array:
uint32_t items[]= {0,3513728,7925384,0,0,0};

In My Loop:
String output = "";

for(int i = 0; i<6;  i++){

  BTLEserial.print(items[i]); // Prints as expected
  output += getStringForUI32_T(items[i]);
  output+=",";

 }
 BTLEserial.print(output); // prints BLANK

I imagine this has something to do with memory but I am at a complete loss.. Please help!

Does it work when printing to the normal serial monitor? BTLEserial.print might not accept a String as an input and instead just print out the pointer address. You might have to copy it to a char buffer first (toCharArray(but,len)).

I doesn't work on Serial.println either..  behaves pretty much the same way.  would you mind showing me how to do the buffer way above.. C is not my strongest suite

There's no reason to concatenate everything into a temporary String - just send each piece in its own call to the sending function.

I'd probably do it directly like:
for(int i = 0; i<6;  i++) {
  BTLEserial.print(items[i]);
  BTLEserial.print(',');
}
BTLEserial.println();

But with the string I think it would be something like:
String output = "";

for(int i = 0; i<6;  i++) {
  output += getStringForUI32_T(items[i]);
  output+=",";
}
BTLEserial.println(output[0]);

But as someone else got it working using String on your adafruit thread maybe this is just barking up the wrong tree.

@ChrisStratton How about that for the String object? I didn't realise you could reference the char array of the String using [].


text:
USB MIDI HID with the ATmega32u4?
There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as MocoLUFA. Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.
Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?
Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?

Note that even with a custom boot loader and in circuit programming with a hardware programmer, you can still use the Arduino IDE to upload, and all libraries should work as normal.

The teensy series from pjrc.com allows USB MIDI natively (full USB speed!).  It works well and does not require any firmware tomfoolery.  It can also do HID keyboard/mouse/joystick natively as well.
There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory.  If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.

DrJohn you mean you don't need to use a specific bootloader to send MIDI messages? You only need to flash a sketch sending midi message and they are usable by several software like ableton etc??? thanks for your answers.


text:
Power supply voltage confusion
I just ran into this article: Arduino: What adapter?.
It says that the external power supply should be 9-12V. That really surprises me, since my Arduino Uno can also be powered via USB, which is 5V.
Later he talks about a 9V pin. But I can only see a 5V and 3.3V pin on mine. Is he talking about a different version of Arduino?
Judging from the picture, his Arduino looks slightly different from my Arduino Uno R3, but I can't tell which version is on the picture.

The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.
Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a dropout voltage.
Looking at the schematic of the Uno we see it uses a NCP1117, which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.
The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).

@MadsSkjern updated my answer with that explanation

A voltage regulator creates a lower stable voltage by burning away the extra volts (turning them into heat). A voltage regulator always has to burn away some voltage to work. So if you only provide 5V to VIN, the voltage regulator will only output e.g. 3.8V (also not very stable).

The power protection circuitry drops a few tenths of volts as well, pushing the minimum to around 6.6V or so.

And the third part of your question: It is possible to bypass the voltage regulator and feed REGULATED 5 volts directly to the 5V pin.
That's how the Arduino is powered using USB. The USB power is already regulated 5V, and is fed directly to the 5V pin.
Beware of doing this yourself however. You better be certain the 5V you're feeding in is a clean, filtered and regulated 5V. If it's not you run the risk of destroying your Arduino (and possibly anything connected to it's 5V lines.)


text:
Arduino Uno R3 not working after shorting 5V to GND
While wiring up my new Arduino Uno R3 on a proto-board, I accidentally shorted the 5V pin directly to Ground. The LED's immediately turned off and connection was lost. It was powered by USB connection. After 3-5 seconds I removed the short. The LED's have remained out, and I haven't been able to reestablish connection with my computer since. I've unplugged and re-plugged the USB cable and tried the re-set button plenty of times. This short shouldn't have fried the board...  what happened? How can I get my Arduino working again??

Have you tried restarting the computer? The computer will shut down the usb port to protect it from a malfunction like this (over-current).

@sachleen can you please post your comment as an answer, so that we don't see this question as unanswered although it has been solved already?

After it is solved you should mark the answer as correct.

Have you tried restarting the computer? The computer will shut down the USB port to protect it from a malfunction like this (over-current).
You can also try the ports on the other side of the computer (or front/back) as they're usually on different controllers.

The genuine Arduino boards feature a digital (temperature based) fuse.
When shorting an Arduino, it will heat up the fuse on the Arduino. When the fuse gets to a certain temperature, it will automatically cut off the power from the USB connection to the Arduino board.
When the fuse cools down, it will conduct again.
The motherboards of most computers these days also work with these digital fuses, so you might have heated up both. It wouldn't hurt to reboot the PC and disconnect the Arduino and give it a minute to cool down.
If it still doesn't work, you might have fried the Arduino or the specific USB port.
Try a USB port that is likely not connected to the same USB controller in the PC. Meaning, don't just try the first USB port next to the one you used, but try a USB port on the other side of the PC / laptop, they are likely to be connected to different USB controllers.


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

TX code:
#include <SoftwareSerial.h>

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

SoftwareSerial   Xbee(10, 11);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


text:
how to push data from an Arduino pin to Bluetooth module
I'm writing a software that can receive data from Arduino via Bluetooth. My software is pretty fine now, at least it can pair with my hardware but when I try to test whether it can receive data via Bluetooth, I'm stuck. My Arduino receives temperature readings from a sensor at Analog pin 0. My Bluetooth module HC-05 connects with Arduino at Digital 0 and 1 (RX and TX pin respectively, as default). I don't know how to push data from Analog pin 0 to the Bluetooth module. Thanks in advance for any suggestion.

You don't. You send a message via Bluetooth that the pin has changed.

Sorry, could you give me more explanation, Ignacio?

Let's start simple. How would you do it if you were using the serial connection?

You meant if the Analog pin 0 is HIGH, set TX pin of Arduino HIGH?

you will need to read this http://arduino.cc/en/Serial/Print And you might want to try some of the basic tutorials you can find online or a book on starting arduino.

The HC-05 looks like like any other terminal to the Arduino so any serial operations that you would use for a wired terminal can be used with the HC-05. See the HC-05's manual for how to set it up initially. Note that HC-05s don't forget their settings and they have no reset command to put them into a known state, so write down your settings for your future reference.
- Read the analog pin value;
- Convert the value into whatever physical units you require;
- Print the result with Serial.print() or Serial.println()

Edit:  You wrote that your HC-05 is connected to Digital 0 and 1, but you created your SoftwareSerial, mySerial, to transmit on Digital 11. In that case your HC-05's receive pin must be connected to Digital 11.

While this is correct, the asker has no idea how to perform serial operations.

Tks guys. I know how to convert my readings into Celcius values and print the result on Serial Monitor by Serial.print but I wonder whether I should convert my readings into bits (I mean analog-digital conversion) before pushing them into the Rx pin of Hc-05; as abovementioned, my sensor is connected to an analog pin while hc-05 is connected to 2 digital pins.

If you're trying to send the readings as text via Bluetooth, just as you would to a wired terminal, you don't need to do anything but replace the serial cable with the HC-05. It is designed to look to the Arduino like a serial terminal.

Could you look at my codes above and tell me if anything wrong, JRobert? I assume I connected HC-05 to Arduino correctly because I watched and followed exactly some tutorials on Arduino and HC-05.

I don't see any obvious mistakes in the code. Have you tried the suggestion in my edit, above? Have you tried replacing the HC-05 with a serial cable to make sure your codes transmits what you expect?

It's my code. Can anyone suggest anything wrong with it if my idea is to push data from Analog pin 0 to Digital pin 11, which is the Tx pin on Arduino connecting to Rx pin on HC-05?
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);
int tempPin=0;

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

void loop()
{
 float reading = analogRead(tempPin); // reading on tempPin
 float voltage = reading*5.0/1024.0; // the resolution of a pin is 10 bit,
 float tempC = voltage/0.01; // 10mV = 1 Celcius
 mySerial.write(tempC);

 delay(3000);
}

looks ok to me. doesn't it work?

You're using mySerial.write() which will send binary data down the serial line.  Were you expecting text?  Maybe try mySerial.println().


text:
What are the current limits on an Arduino Micro?
Just to make sure I don't set my board on fire, is there any information out there about the maximum current per pin/pin group on an Arduino Micro?
This page states I can get 40mA per pin, but are there limits on group of pins?
As stated here, there are pin groups which should not exceed 100mA. But could not find anything about that in the ATmega32u4 datasheet, or any other Arduino Micro related websites.

It's in the notes in section 29.2:

Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100 mA.
  If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater
  than the listed test condition.
Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
  state conditions (non-transient), the following must be observed:
  ATmega16U4/ATmega32U4:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100 mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100 mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100 mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100 mA.

Note that the device will likely not fail if these are exceeded, but the rest of the numbers in the table may no longer apply.


text:
Arduino and visual basic Serial data
I am trying to send command serially through Vb.through serial monitor working fine . But Through VB it not detecting port
My arduino code:
int ledPin = 2; // the number of the LED pin

void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}

void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
else if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}
else // if not one of above command, do nothing
{
//val = val;
Serial.println("Wrong command");
}
Serial.println(val);
Serial.flush(); // clear serial port
}

VB Code
Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
    Shared _continue As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.Open()
        SerialPort1.PortName = "COM3"

        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.Handshake = IO.Ports.Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default 'very important!

    End Sub

    Private Sub Button1_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("1")
        SerialPort1.Close()
    End Sub

    Private Sub Button2_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("0")
        SerialPort1.Close()
    End Sub

End Class

Error I am getting .Arduino port is 3. and configured to port 3 . i dont know why it giving error.
The port 'com10' does not exist.

This Line added as you said
Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
        Dim str As String
        str = SerialPort1.ReadExisting
        Current_Read.Text = str
        SerialPort1.Close()
    End Sub

This is working But data not being updating
Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Current_Read.Text =SerialPort1.ReadLine
    End Sub

You've opened the port before you've configured it.

I removed already those line same error.

@AMPS which lines have you removed exactly? Cn you edit your post to show the modified code that still does not work?

Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Open()
Dim str As String
str = SerialPort1.ReadChar
Current_Read.Text = str
SerialPort1.Close()
End Sub


text:
Battery Monitoring System for Arduino
I need to incorporate a battery monitor using a 10 led bar graph. I am powering the arduino with a 7.4(though it reads 7.67) V  lithium polymer battery through the arduino`s power jack. The goal is to monitor that battery. How would I go about doing this? I have a LM3914 driver to use if I want but I am clueless as to what to do.

Create a voltage dividerm using two resistors, to safely measure the battery voltage. Just note that the voltage drops faster when the battery is getting low (i.e. the relation with battery voltage and remaining capacity isn't linear). Though who cares if the battery is 90% or 80%, we care more about the 20% versus 10%.

Google is your friend - https://learn.sparkfun.com/tutorials/dotbar-display-driver-hookup-guide


text:
Receiver xbee receiving data while the Transmitter is powered off?
My receiver xbee is receiving data even if the transmitter is disconnected , so if i am sending the string hello world , the receiver will repeat this string .
void loop() {
    Serial.println("Hello");
    delay(1000);
}

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

And what is the question?

@Gerben there is no question there is a problem

As @Garben mentioned, we do not know what is your question, problem or whatever...
Provide some more information about wiring. I looked at your question 5 mins and still can't get what is wrong...
What are you doing here??? Sending from Arduino+XBEE to another Arduino+XBEE???
void loop() {
    Serial.println("Hello");
    delay(1000);
}

Here you are resending what you got
void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

So what is your problem? Or is this all your code???
Arduino has to have
void setup(){
//Set up your Arduino here
}
void loop(){
//Code here will run over and over and over...
}


text:
Communication Protocol Best Practices and Patterns
Every time I design a serial protocol to be used between two arduinos, I feel a bit like I'm reinventing a wheel. I wonder if there are any best practices or patterns people follow. This question is less about the actual code, but more about the format of the messages.
For example, if I wanted to tell an arduino to flash it's first LED 3 times I might send:
^L1,F3\n

'^': starts a new command
'L': Defines the command, (L: target this command to an LED)
'1': Target the first LED
',': Command line separator, new value in this message to follow
'F': Flash sub-command
'3': 3 times (Flash the LED three times)
'\n': End the command

Thoughts? How do you usually approach writing a new serial protocol? What about if I wanted to send a query from arduino 1 to arduino 2 and then receive a response?

There are a lot of ways to write a serial protocol depending on what functionality you might want and how much error checking you need.
Some of the common things you see in point to point protocols are:
End of message
The simplest ASCII protocols just have an end of message character sequence, often \r or \n as this is what gets printed when the enter key is hit. Binary protocols might use 0x03 or some other common byte.
Start of message
The problem with just having end of message is that you don't know what other bytes have already been received when you send your message. These bytes would then be prefixed to the message and cause it to be interpreted wrongly. For example, if the Arduino just woke from sleep there might be some garbage in the serial buffer. To get around this you have a start of message sequence. In your example, ^,  in binary protocols often 0x02
Error Checking
If the message can be corrupted we need some error checking. This could be a checksum or a CRC error or something else.
Escape Characters
It could be that the checksum adds to a control character, such as the 'start of message' or 'end of message' byte, or the message contains a value equal to a control character. The solution is to introduce an escape character. The escape character is placed before a modified control character so that the actual control character is not present. E.g. if a start character is 0x02, using the escape character 0x10 we can send the value 0x02 in the message as the byte pair 0x10 0x12 (byte XOR control character)
Packet number
If a message is corrupted we could request a resend with a nack or retry message, but if multiple messages have been sent then only the latest message can be resent. Instead the packet can be given a number that rolls over after a certain number of messages. For example, if this number is 16, the transmitting device can store the last 16 messages send and if any were corrupted the receiving device can request a resend using the packet number.
Length
Often in binary protocols you see a length byte which tells the receiving device how many characters are in the message. This adds another level of error checking as if the correct number of bytes were not received then there was an error.
Arduino specific
When coming up with a protocol for Arduino the first consideration is how reliable is the communications channel. If you are sending over most wireless mediums, XBee, WiFi, etc, there is already built in error checking and retries and thus no point in putting these in your protocol. If you are sending over RS422 for a couple of kilometres then it will be necessary. The things I would include are the start of message and end of message characters, as you have. My typical implementation looks something like:
>messageType,data1,data2,…,dataN\n
Delimiting the data parts with a comma allows for easy parsing, and the message is sent using ASCII. ASCII protocols are great because you can type messages into the serial monitor.
If you want a binary protocol, maybe to shorten the message sizes, you will have to implement escaping if a data byte can be the same as a control byte. Binary control characters are better for systems where the full spectrum of error checking and retries is desired. The payload can still be ASCII if desired.

Isn't it possible that the garbage ahead of the real start of message code could contain a start of message control code? How would you deal with this?

@CMCDragonkai Yes this is a possibility, especially for single byte control codes. However if you encounter a start control code halfway through parsing a message, the message is discarded and parsing restarts.

I do not have any formal expertise on serial protocols, but I've used them quite a few times, and more or less settled on this scheme:
(Packet header)(ID byte)(data)(fletcher16 checksum)(Packet Footer)
I usually make the header 2 bytes and the Footer 1 byte. My parser will dump everything when it sees a new packet header, and attempt to parse the message if it sees a footer. If the checksum fails, it will not ditch the message, but continue adding until the footer character is found and a checksum succeeds. That way the footer only needs to be one byte since collisions don't disrupt the message.
The ID is arbitrary, sometimes with the length of the data section being the bottom nibble (4 bits). A second length bit could be used but I normally don't bother since the length does not need to be known to parse correctly, so seeing the right length come through for a given ID is just more confirmation that the message was correct.
The fletcher16 checksum is a 2 byte checksum with nearly the same quality as CRC but is much easier to implement. some details here. The code can be as simple as this:
for(int i=0; i < bufSize; i++ ){
   sum1 = (sum1 + buffer[i]) % 255;
   sum2 = (sum2 + sum1) % 255;
}
uint16_t checksum = (((uint16_t)sum1)<<8) | sum2;

I've also used a call and respone system for critical messages, Where the PC will send a message every 500ms or so until it gets an OK message with a checksum of the whole original message as data (including the original checksum).
This scheme is, of course, not well suited for being typed into a terminal like your example would be.  Your protocol seems pretty good for being limited to ASCII and I'm sure is easier for a quick project that you want to be able to directly read and send messages. For larger projects it is nice to have the density of a binary protocol and the security of a checksum.

Since "[your] parser will dump everything when it sees a new packet header" I wonder if this does not create problems if by chance the header is encountered inside of data?

@humanityANDpeace The reason for dropping it is that when a packet gets cut off it will never parse correctly, so when do you decide its garbage and move on? The easiest, and in my experience good enough, solution is to drop an bad packet as soon as the next header comes in. I've been using a 16 bit header without issue, but you could make it longer if certainty is more important that bandwidth.

So what you refere to as a header is somewhat of a Magic 16bit combination. i.e. 010101001 10101010, right? I agree it is only 1/256*256 change to hit, but it also disables ever using this 16bit inside your data, else it gets misinterpreted as a header and you discard the message, right?

@humanityANDpeace I know it's a year later, but you need to introduce an escape sequence. Before sending, the server checks the payload for any special bytes, then escapes them with another special byte. Client side, you have to put the original payload back together. This does mean that you cannot send fixed length packets and does complicate the implementation. There are many serial protocol standards to choose from that all address this. Here is a very good read on the topic.

If you're into standards, then you may take a look at ASN.1 / BER TLV encoding. ASN.1 is a language used to describe data structures, made specifically for communication. BER is a TLV method of encoding the data structured using ASN.1. Problem is that ASN.1 encoding may be tricky at best. Creating a full fledged ASN.1 compiler is a project in itself (and a particularly tricky one at that, think months).

It's probably better to keep just the TLV structure. TLV basically consists of three elements: a tag, a length and a value field. The tag defines the type of the data (text string, octet string, integer etc.) and the length the length of the value.
In BER the T also denotes if the value is a set of TLV structures itself (a constructed node) or directly a value (a primitive node). That way you can create a tree in binary, much like XML (but without the XML overhead).
Example:
TT LL VV
02 01 FF

is an integer (tag 02) with a length of the value of 1 (length 01) and value -1 (value FF). In ASN.1 / BER the integers are sign big endian numbers, but you can of course use your own format.
TT LL (TT LL VV, TT LL VV VV)
30 07  02 01 FF  02 02 00 FF

is a sequence (a list) with length 7 containing two integers, one with value -1 and one with value 255. The two integer encodings together make up the value of the sequence.
You can simply toss this into an online decoder too, aint that nice?

You can also use indefinite length in BER which will allow you to stream data. In that case you do need to parse your tree correctly though. I'd consider it an advanced topic, you need to know about breadth first and depth first parsing, for one.

Using a TLV scheme basically allows you to think of any kind of data structure and encode it. ASN.1 goes a lot further than that, giving you unique identifiers (OID's), choices (a lot like C-unions), includes of other ASN.1 structures etc. etc. but that may be overkill for your project. Probably the best well known ASN.1-defined structures today are the certificates used by your browser.

If not, you've got the basics covered. Your commands can be created and read by both humans and machines which is a big plus. You might add a checksum to detect a mal-formed command or one damaged in transit, especially if your channel includes long cable or a radio link.
If you need industrial strength (your device mustn't cause or allow someone to get hurt or die; you need high data rates, fault recovery, missing packet detection etc.) then look to some of the standard protocols and design practices.


text:
4-digit 7 Segment LED displaying numbers in the wrong order
I am a novice Arduino programmer and am currently having trouble with a SH5461AS 4-digit/7-segment LED when using it with an Arduino Uno. I have struggled to find an accurate datasheet/tutorial of any kind for this particular model (It is the LED without the colons in between digits 2 and 3) but I believe I have it figured out.
I currently have it going through a HC595 shift register but when I removed the register and connected the LED directly to the board the problem remained. My code below is with the shift register; I am displaying it this way because it is simpler to view and I thought it would make it easier to debug.
I can display a single digit at a time correctly. However, when I try to display 2+ digits at one time, they are in the incorrect order.
For example, I can count 1-9 on the first digit, then 1-9 on the 2nd digit, and so on and everything displays correctly (other digits are off). But as soon as I try to display multiple digits they are in the wrong order. So if I try to display 12__ with the last 2 digits off, 21__ is displayed with the last two digits off. If I try to display 23, 32 is displayed. If I try to display 1234, 4123 is displayed.
I am at a loss because the code seems like it should be simple.
const int DATA = 0;
const int LATCH = 1;
const int CLOCK = 2;

const int DIGIT_ONE = 3;
const int DIGIT_TWO = 4;
const int DIGIT_THREE = 5;
const int DIGIT_FOUR = 6;

//digits[0-9] corresponds to the patterns for numbers 0 -> 9.
//Add 1 to the digits[X] to turn on the dot.
byte digits[] = {B11111100, B00011000, B01101110, B00111110, B10011010, B10110110, B11110010, B00011100, B11111110, B10111110};

void setup() {
  pinMode(DATA, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(LATCH, OUTPUT);

  pinMode(DIGIT_ONE, OUTPUT);
  pinMode(DIGIT_TWO, OUTPUT);
  pinMode(DIGIT_THREE, OUTPUT);
  pinMode(DIGIT_FOUR, OUTPUT);

  digitalWrite(DIGIT_ONE, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);
  digitalWrite(DIGIT_FOUR, HIGH);
}

void loop() {
  writeDigit(DIGIT_TWO, 2);
  writeDigit(DIGIT_THREE, 3);
}

/*
 * Write a digit to the 4-digit 7-segment LED
 * - digitPin corresponding to the pin on the LED to light up the correct digit.
 * - number 0-9 to display on the LED
 */
void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

So in this instance, I am expecting 23 but 32 is displaying instead.
I am also having trouble with some bleeding (I don't know what the correct term is) where some segments are very faintly glowing even though I am not doing it intentionally. This is a much smaller issue, however, than digits randomly in the wrong order.
If it would help, I can try to post the circuit diagram as well.

Here is a datasheet I found that seems a better macth for your display model (that's the datasheet for a display that I use):
http://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom%2Fupload%2FFile-1356269320.pdf
This is the datasheet I directly got from my local supplier.
According to what you say, the problem does not seem to be a wiring problem.
It looks more like a timing issue:
void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

The first issue when you call writeDigit() is that it forces the cathod low BEFORE having set the shift register, so the digit will first show the current register value, i.e. the one from the previous call to writeDigit().
Then it pushes the new value for the segments on the shift register, that will be fast but not as fast as two consecutive calls to loop().
If we try to roll and expand the loop() call in your example that will be:
// First call: writeDigit(DIGIT_TWO, 2)
  digitalWrite(DIGIT_TWO, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);

// Second call: writeDigit(DIGIT_THREE, 3)
  digitalWrite(DIGIT_THREE, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);

The calls to loop() and writeDigit() are negligible in terms of timing here.
In the sequence above, most of the time is spent in:
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);

So that means your function will:

show the previous value on the new digit for t1 us
show the new value of the new digit for t2 us

with t1 >> t2, hence your eyes will see the opposite of your intent!
To fix that issue you definitely need to introduce some delay to reverse what your eyes will see:
void writeDigit(int digitPin, int number) {
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(digitPin, LOW);
  delayMicroseconds(100);
  digitalWrite(digitPin, HIGH);
}

In the code above:

no digit shows while the shift register is set
the requested digit shows immediately after the shift registry has been written and lacthed, and for a duration of 100us, which will be much longer than the rest of the time.

That code should also get rid of the "bleeding" you observed.

Excellent, detailed answer; thank you! I will try that when I get home to see if it fixes it.

I found the data sheet here:
https://www.sparkfun.com/datasheets/Components/LED/7-Segment/YSD-439AK2B-35.pdf.
It's a horrible bit of writing. Not at all clear.
It looks like it's multiplexed. You use pins 14, 16, 13, 3, 5, 11, 15, and 7 as the cathodes for the segments on a digit (ground the pins for the segments you want to light.) Pin 7 appears to be the decimal place for a given digit.
One of the pins 1, 2, 6, or 8 should be fed a +5V to light a particular digit.
The other pins control the colons and other dots on the display. Let's ignore those.
To light the display here's what I THINK you would do (I'm tired, and didn't study the data sheet that closely, so I may may be wrong here)
For pins 14, 16, 13, 3, 5, 11, 15, and 7: These are the cathodes for the segments in the current digit you are driving. Set the pins you want to light as digital outputs, LOW. Set the others as inputs, which will make them essentially open circuits. The selected pins will be grounded, and the ones set as inputs will not be connected to anything.
Pull pin 1 HIGH to light the selected segments in digit 1. Put it back low, set the segment pins, then pull pin 2 HIGH to light that digit. Repeat, pulling pins 6 and 8 high to light the selected segments in digits 3 and 4.
You'd have to cycle rapidly through the digits, lighting 1 at a time, in order to make them appear all lit at once.
Get that working first without using shift registers. (It will take 11 I/O lines to drive all 4 digits and their decimal places - 1 less if you don't care about the decimal place.)
I think that if your drive all the pins using a shift register then some of the unlit segments will be fed reverse voltage. (When set as an output, sending a LOW connects the output pin to ground, and setting it high drives it to 5V. With all the control pins driven from outputs of a shift register, the off segments will have 5 volts on them, and the off digit select pins will have ground on them.)

That datasheet does not match the OP descriprion, it has a : in the middle.

Yup. I assumed it was a variation on the same item.

It is much more than a simple variation: the one used by OP is common cathode, while yours is common anode!

@jfpoilpret, it sounds like you found the correct data sheet. Why not post either the correct data sheet or an assessment similar to mine based on the specs for the correct display.

Well I guess the OP already understood how to use his display, so it was not necessary IMO to detail further the specs. As I said in my answer the main problem is in the code not the wiring.

I don't have enough reputation to add a comment, but the datasheet link in @jfpoilpret is dead. This link has the datasheet from the same website.
Thanks.


text:
Distance and Serial or SPI
I'm setting up a grid of 200+ slave modules which will be about 12 inches apart and the master will be anywhere from 5 to 10 meters away from the closest module. Each slave module will have a ATtiny85 to manage the sensor reading, LEDs and the network protocol.
The communication packets will be small and will probably be at 115200 baud if using ATTiny85's TTL serial or 1MHz if using SPI. In either case, the modules will be connected in a daisy chain to each other.
Each module will have a resistive touch sensor and be driving about 12 - 16 RGB LEDs (I'm making a step responsive disco dance floor). There will be 12v+ running to each module to drive the LEDs and regulated down to 5V for the ATtiny.
Which brings me to my question. With these constraints, do you think the ATtiny85's built-in serial or SPI would still work well over the 5 to 10 meters from the closest module to the master.
I know some people push towards RS422 or RS485 transceivers for distance applications, but I'd like to keep the total part count down, if possible.

I'm not sure SPI can work at all, since you would need 200 Chip-Select wires running from the master.

I would daisy chained the SPI connection between modules: http://www.maximintegrated.com/en/app-notes/index.mvp/id/3947

Just to be annoying... 115200 is about 10k bytes / sec. Divided by 200 is 50 bytes per second assuming your master is loading up the serial buffer and nothing else. If you have to wait for acks, etc that slows down things again. With daisy chain SPI there will be some delay getting to the 200th node, and getting a reply back. Why not try a tree topology, with routers that control a certain number of nodes. The routers can then communicate back to the master. Or instead of one ATtiny per tile, have one control multiple tiles with a led driver chip with lots of outputs, and multiplexed analog

inputs for the sensors. Sorry for the unsolicited opinion, I may have misinterpreted your design. :P

I have a few years working with DMX, SPI (and other serial) & LEDs. I have worked with DMX and a video dance floor for 10+ years previously. I would offer that "some people" are correct. You will get a reliable system with differential pair signalling (such as DMX).
I have found from experience that over 5m of unbalanced serial starts chancing it. Over 10m and you are likely to come up with at least reliability issues, but more likely garbage.
I have used the TI SN75176B driver a fair bit and is cheap and works.
Depends on your audience. You can afford to chance it for your bedroom, but not paid business.

Sounds like a fascinating project.
It sounds like the majority of signals are driven by one ATTiny85 and received by a neighboring ATTiny85 about 12 inches away, with a good ground connection between them.
Those signals can be directly connected.
If I were you, I would go ahead and get differential transceivers for the 10 meter distance.
If you use daisy-chain SPI, then you need 3 differential line drivers at one end of the cable and 1 differential line driver at the other (and the corresponding line receivers to match); plus GND and +12VDC.
If you use a SN75176BP as a line driver and another one as a line receiver for each SPI signal, that's a total of less than $8 for those 8 interface chips.
(You need fewer line driver chips if you somehow daisy-chain TTL UART serial, since it uses fewer pins, but requires each chip to have more precise baud clock).
The software should not even be able to detect the difference between a simple wire from the output pin of one chip to the input pin of the next chip, vs. a line driver, some twisted pair cable, and a line receiver between those same two chips running the same software.
Many people use the rule of thumb that if a bit time is less than 10 times the time it takes for something traveling at the speed of light to make a round trip from the transmitter to the receiver and back, then you must use differential signaling with line termination.
At 1 MHz, that gives a (1-way) cable length of 15 meters before you must use differential signaling with line termination.
So using the differential line drivers is probably overkill, but I'd rather have the first prototype work rather than cut corners on 100 things that I'm 99% sure probably won't matter, and then spend a lot of time debugging trying to figure out which one or two of those 100 things turns out that it does matter.
In addition to distance, loading might also be an issue.
In particular, the "CLK" and "/CS" pins from the SPI master apparently need to drive every SPI slave.
You can't really expect a single MCU output pin or even a single RS485 line receiver to be able to drive 200+ other chips.
A line driver or other buffer every 10 or so chips is more than adequate.
Related:
"What if the SPI signal lines are very long?"
(this experiment completely neglects the effects of interference from other noisy devices).
AN10364 "Transmitting the I2C signals as differential signals using RS-485 hardware"
(Like SPI, I2C signals were never intended to be transmitted long distances over wire cables.)
"Maximum Unterminated Network Speed Calculator"

Keep in mind that termination and differential signaling are two different issues.  Granted differential signals tend to be conceptually easier to terminate as it is obvious where the return path is, but the concept is applicable and advantageous with single-ended signals too.

@ChrisStratton: Yes. Termination helps prevent a signal from interfering with itself (round-trip bounce). Differential signaling helps prevent other stuff (including "ground noise") from interfering with the signal. Is there a better rule of thumb for deciding whether to use termination or differential signaling or both or neither?


text:
Enable free fall detection using Arduino
I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.
However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.
The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).
Thank you.

From the LSM9DS0 datasheet; "The LSM9DS0 may also be configured to generate an inertial
wake-up
and
free-fall
interrupt
signal according to a programmed acceleration event along the enabled axes.". So it should be possible, just like with the ADXL345.

Hi, thanks for the reply. I got a sort of rudimentary fall detection working. Just wondering if there is any methods in which I can utilize the other two sensors (Gyrometer)/(Magnenometer) to further improve its precision. Much Appreciated

Sitting an accelerometer flatly on a bench will produce a value of 1G in one of the 3 axes.
Free fall of an accelerometer (assuming you haven't reached terminal velocity) should read near zero on all 3 axes.
I am not aware of a mode you can set for this, but if you check the values of the 3 axes and all are close to zero, you are probably in a free fall condition.

Hi, thanks for the reply. I got a sort of rudimentary fall detection working. Just wondering if there is any methods in which I can utilize the other two sensors (Gyrometer)/(Magnenometer) to further improve its precision. Much Appreciated.

I'm not if the gyro will be of use, given that a falling object may or may not be spinning.

Take the root sum squared [sqrt(acc_x^2 + acc_y^2 + acc_z^2)] of your accelerometer readings.  This is your total acceleration vector.  Then write a function that triggers the free fall variable when that equation is less than or equal to a certain threshold near to zero (the value itself depends on your accelerometer).
Your gyro and magnetometer will not help as they relate to the attitude (facing direction) and rotational speed of your thing, not the linear motion.  Test and play with the threshold and you will get the most accurate result possible.

You don't need to take the square root but can just compare against a squared threshold.  And it may not even be necessary to even combine the axis - it's probably sufficient to determine if there is or is not any individual axis reading above, +/-.707g (increased or decreased for reliability), as once the device has rotated through 45 degrees a different axis will start increasing.


text:
Arduino IDE Unable to detect ZumoMotor.H ( PIXY PET )
recently i trying to make the pixy pet work for my project. (https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/playing-with-your-pet).
I used the given code for the arduino IDE, but i keep on getting this error Arduino: 1.5.7 (Windows 7), Board: "Arduino Leonardo"
sketch_sep17a.ino:27:24: fatal error: ZumoMotors.h: No such file or directory compilation terminated.
This report would have more information with "Show verbose output during compilation" enabled in File > Preferences.
The Code, im using, was given by the official maker of the Pixy Pet. Please have a look. ( https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code)
Thank You.

It looks like you need to install the ZumoMotors library.
There's one available at the following link, although I don't know for sure that it's the same one your Pixy Pet requires:

https://github.com/pololu/zumo-shield

That page includes instructions on how to install the libraries. If you get stuck, there's more help in the official Arduino documentation:

http://arduino.cc/en/Guide/Libraries


text:
Relay activation
I am posting my simple code here, I wanted to print the Output_Current Inspite when delay function called.Below is my code.
#include <MsTimer2.h>

int Analog_Pin=5;
int newaverage;
float Output_Current;
#define RELAY1  7
#define MAX_TRIP_COUNT  5
float Current_Limit=0.6;
static int Trip_Count=0;
static int Tripped_Flag=1;
int Serial_Status=0;

void TakeReading()
{
  newaverage = analogRead(A5);

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

void Chk_Relay_Tripped()
{
  if(Output_Current>=Current_Limit)
  {
    Trip_Count=Trip_Count+1;
    if((Trip_Count>=MAX_TRIP_COUNT) &&(Serial_Status==0))
    {

      Trip_Count=0;

  MsTimer2::set(30000, Relay_Activate); // 500ms period
  MsTimer2::start();
     // Relay_Activate();
    }
    else
      if(Serial_Status==1)
      {
        Serial.println("> MODE");
        Relay_Deactivate();
      }

  }
  else
  {
    Trip_Count=Trip_Count-1;
    if(Trip_Count<0)
    {
      Trip_Count=0;
    }

    if(Trip_Count<MAX_TRIP_COUNT && Serial_Status==1)
    {
      Relay_Deactivate();
      Serial_Status=0;
    }

  }

}

void Relay_Activate()
{
   // MsTimer2::stop();

   for (unsigned long start = millis(); millis() - start < 10000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }

    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;

}

void  Relay_Deactivate()
{
  digitalWrite(RELAY1,LOW);
 // Serial_Status=0;
}

void Relay_Intialize()
{
  digitalWrite(RELAY1,LOW);
}

void setup() {
  Serial.begin(9600); // set serial speed
  pinMode(RELAY1, OUTPUT); // set LED as output
  //digitalWrite(RELAY1, LOW); //turn off LED

  pinMode(Analog_Pin,INPUT);
  Relay_Intialize();
}

void loop(){
  TakeReading();
  Chk_Relay_Tripped();
  Serial.println(Output_Current);
   //while (Serial.available() == 0); // do nothing if nothing sent
  int val = Serial.read() - '0';
  if (val == 1) { // test for command 1 then turn on LED
    Serial.println("RELAY on");
    digitalWrite(RELAY1, LOW); // turn on LED
    Serial_Status=1;

  }
  else if (val == 0) // test for command 0 then turn off LED
  {
    Serial.println("RELAY OFF");
    digitalWrite(RELAY1, HIGH); // turn off LED
    Serial_Status=0;
  }
  delay(500);
}

In above code everything working fine. But as soon as this function called . It wait 30s. after that it will print data. But i wanted to print data on serial monitor even if this function called. Please let me know how can i do this. Main intenstion of code is when current >1A trip the relay , wait for 30S and connect back. I wanted to print output even in 30S
void Relay_Activate()
{

   for (unsigned long start = millis(); millis() - start < 30000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }

}

I totally don't understand what you're trying to achieve. Reading the code doesn't make it any clearer. A better description would be helpful.

@Gerben this code clarify it. I wanted to print all data within 30S delay

I read you code as: check the output current every 500ms. If it exceeds the limit more than MAX_TRIP_COUNT times, set Relay_Activate to run after 30secs. In Relay_Activate, write HIGH to the RELAY1 over and over for 30 seconds:
void Relay_Activate()
{
  for (unsigned long start = millis(); millis() - start < 30000;)
  {
    digitalWrite(RELAY1,HIGH);
    Serial_Status=1;
  }
}

I don't think you really mean to do this, especially as after the 30 seconds you are not writing LOW to turn it off. Maybe you mean that after 30 seconds it should start checking the current again?
void Relay_Activate()
{
  digitalWrite(RELAY1,HIGH);
  Serial_Status=1;
}

What you want is a state machine so that your delays don't hold up your loop. Here is some pseudo code:
loop {

* read current
* print out current

switch(current_state) {
  //Normal operation
  case 0:
    * check if tripped
      - if tripped change state to 1
  //Turn on relay
  case 1:
    * turn on relay
    * set state_timer = millis()
    * change state to 2
  //Turn of relay after 30 seconds
  case 2:
    * if millis() -state_timer > 30000 turn off relay
    * change state to 0
}
delay 500ms
}

So post your updated code along with an explanation of what you did, and accept it as the answer to your question. That way your question becomes a way for others to learn.


text:
Class TKPotentiometer has no member named 'read'
I am testing a set-up using the TinkerKit shield for Arduino Uno, and a few TinkerKit inputs and outputs. I have an issue with the code provided on the TinkerKit website for the potentiometer component:
#include <TinkerKit.h>

// creating the object 'pot' that belongs to the 'TKPotentiometer' class
TKPotentiometer pot(I0);

// creating the object 'led' that belongs to the 'TKLed' class
TKLed led(O0);

int brightnessVal = 0;  // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps
  Serial.begin(9600);
}

void loop() {
  // read the potentiometer's value:
  brightnessVal = pot.read();

  // set the led brightness
  led.brightness(brightnessVal);

  // print the results to the serial monitor:
  Serial.print("brightness = " );
  Serial.println(brightnessVal);

  // wait 10 milliseconds before the next loop
  delay(10);
}

I get an error message when compiling:
Class TKPotentiometer has no member named 'read'

According to this webpage, though, read should be a member of the class. Why am I receiving this message?

As soon as I finished writing the question, it came to my mind that perhaps I misspelled something, so I looked for a file in the Menu's sketchbook that I could load.
With my surprise, I found the same exact code as I posted, with a little difference:
pot.read() was substituted with pot.get()


text:
Cannot drive DC motor with Arduino PWM
I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.
But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.
How can I fix that??

Welcome to Arduino.SE. It would be helpful for us to see your source code and a circuit diagram.

A few questions: what motor model do you use (a link to a datasheet would be good to look at); have you put a resistor between Pin 3 and the transistor base? Which value? Does your program use Serial? Could you post the code (or the relevant parts of it if it is too long)?

I second the resistor between pin 3 and the base of the transistor. The rest sound fine; you've even thought of the flyback diode, and connected the two grounds together.

4N4007? Do you mean  1N4007?

I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.

It's hard to know without an oscilloscope, but as a guess you might be seeing voltage spikes on Vcc at the reset pin due to inductive load dumps from the motor.  Per Atmel app note AVR042, you might try a 5V zener diode from the reset pin to ground and/or a capacitor to snub the spikes.

In addition to the zener or a cap (that should be reasonably close to the motor) you can also use a flyback diode (which is a normal diode wired parallel to the motor) to suppress interference from the motor. See https://en.wikipedia.org/wiki/Flyback_diode

You might also want to consider purchasing a simple and popular L293D motor driver chip.  I teach basic Arduino classes and learning to use this chip is much easier than using transistors and diodes.  The other advantage is the motors can go both forward and backward!
On the following link you can purchase one chip for under $1.00 USD and each chip will driver two motors both forward and backward.
http://www.ebay.com/itm/New-L293D-L293-L293B-DIP-SOP-Push-Pull-4-CH-Four-Channel-Motor-Driver-IC-/371198300958

This is not an answer to the question which was asked.  Additionally, the L293/L298 are antiquated devices with high internal losses which really should not be used for new designs.

Do you have an alternative design that would work better?


text:
Do we need another controller when using ArduPilot?
I'm a newbie on the all Arduino platform and I'm currently building a drone with Autopilot functionality. I've heard about ArduPilot and I'm wondering if that is all I need, in terms of controllers (I'm excluding the ESC, engines, and the rest). Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?
Cheers,
r

There are a few key points worth making before answering your question:

Ardupilot has undergone a re-branding and is now known as APM; this change was made to reflect that the technology has grown beyond strictly using an Arduino environment. You can see this for yourself at their website.
The term(s) Ardupilot/APM have been used somewhat interchangeably for both the hardware and software. This can be confusing so I'll refer to the hardware as an "APM Kit"

Can I simply program the ArduPilot, connect a Wireless interface to it and merrily be able to control it ?
Yes, 3DRobotics offers APM Kits that are plug-and-play hardware packages with preloaded firmware. They (optionally) supply all of the components needed to operate a small unmanned hobby aircraft including:

Power module
Transmitter and receiver for the APM-to-Ground-Station link
GPS module w/ compass

The user is generally expected to provide:

Airframe
Batteries
Servos
RC transmitter and receiver
An additional voltage-regulator/BEC if using high-torque servos
A computer (groundstation)

However, the unspoken question is:
How easy is it to setup Ardupilot/APM to work safely and correctly?
In truth, it takes considerable effort to put together a properly working system. The plug-and-play hardware saves you a great deal of trouble but tuning and operating an RC aircraft requires a different skillset. If you're experienced in RC, this may not be a problem.
From experience, you can expect to spend a number of weekends configuring and tuning APM (the software) even if you have a perfectly tuned RC aircraft.


text:
Arduino Yun - not enough i2c & interrupt pins?
I'm trying to build a small personal weather station. The rain sensor, and wind speed sensor use interrupts. The barometric sensor uses i2c SDA and SCL.
Reading the Arduino Yun manual, it says there are 5 interrupt pins, but 2 of them are SCL/SDA (pins D2 and D3), and 2 of them are serial comms between Linio and the 32U4 (pins 0 and 1).
This leaves me with 1 interrupt pin left (pin 7).
Is there a work around to get my 2 digital sensors AND SDA SCL pins connected?
If I do use pins 0 and 1 (Linux serial), what do I risk? I will need to use the Bridge to relay information to the internet.

Any of the port B pins on the ATmega32u4 can interrupt on pin change. Unlike the external interrupts however, these pin change interrupts share the same interrupt vector. So in the interrupt routine you have to work out which one fired.
The port B pin change interrupt is not support by the Arduino core library so you have to download a third-party library. This one seems fairly recent:
https://code.google.com/p/arduino-pinchangeint/
Then you connect your two interrupt lines to spare Port B pins and monitor for pin changes.

Worked effortlessly after installing the library. Thanks!

OR the interrupt lines together so that you only need 1 external interrupt. Then when an interrupt is triggered, poll the devices until you find the one that triggered the interrupt. If the interrupt outputs are open-drain then you can wired-OR them together, otherwise you will need something like the 74LVC32 to OR the push-pull outputs together.

And I was going to show you how to do it here, but there's no schematic button in the editor.


text:
If I connect a battery to the vin pin on the arduino, will the 5V pin be activated?
My wording might be a bit confusing, if I plug an 8 volt battery into Vin, will the arduino be powered and will the 5V pins work?

Yes, that's what the Vin pin is for: unregulated voltage or a voltage higher than 5V. Then the 5V pin will be at 5V, regulated by the on board regulator. You would only connect a source to the 5V pin if the source is already a regulated 5V.

VIN. The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

source


text:
How to implement setSyncProvider and verify it is working with PC
I'm trying to retrieve / synchronize time from PC using this Time lib function:
setSyncProvider( requestSync);  //set function to call when sync required

It sends ASCII BEL (07) character to PC, but I'm getting no response using Serial.available. What am I missing?
Do I have to run a specific app on the PC to get a response? The docs do not specify that.

Yes, you'll need something running on the PC which is monitoring the serial port, and which will provide a response in the appropriate format.
The download on this page contains a Processing sketch which will do this for you. After you've unzipped it, look in Time/Examples/Processing/SyncArduinoClock. Open the sketch in Processing, run it, and then start your Arduino.
If you're not familiar with it, Processing is a free programming language / environment based on Java. It's aimed largely at beginners and non-programmers, and is quite commonly used for communicating with Arduino projects via Serial. You can download it here:

http://www.processing.org


text:
How to control Android app with Arduino
I'm trying to connect Arduino Leonardo to an Android tablet. I would like to make the Arduino send commands (using pushbuttons or a slider for example) to the tablet to switch between pages, to select a file on the desktop, to scroll up and down the screen, etc.

Perhaps this is not exactly what you are looking for, but from your examples it seems like using navigational commands from the keayboard/mouse would accomplish a lot of what you are requesting.
Android has USB HID support from honecomb, so you should be able to create a sketch to emulate a keyboard and mouse based on the IO data and it should work with your android device just by plugging the USB cable (if emulating a mouse, it will display the mouse cursor as soon as it is connected).

First, get a Lightblue Bean, http://punchthrough.com/bean/
It has everything you need:
- arduino
- bluetooth
- API
- code example
- android sdk
- ...
Develop your product using this platform.
If you want to scale and build your own platform, then you will have a foundation to validate your work.

Half you answers refer to this product. Are you associated with it? You need to disclose any personal stake in it if you are.

not associated with the company, but a happy customer of their product.

It is a good idea to use a LightBlue Bean, only if you are using the Android SDK!
 https://bitbucket.org/littlerobots/beanlib
You can read more about the SDK, and get advice from people who are actually using it.
http://beantalk.punchthrough.com/t/announcing-unofficial-android-sdk/394

Android code:
function OnStart() {
    //Create a layout with objects vertically centered.
    lay = app.CreateLayout("linear", "VCenter,FillXY")

    //Create a toggle button.
    btn = app.CreateToggle("LED On/Off", 0.4)
    btn.SetOnTouch(btn_OnTouch)
    lay.AddChild(btn)

    //Add layout to app.
    app.AddLayout(lay)

    //Create USB serial object.
    usb = app.CreateUSBSerial()
    if (!usb) {
        app.ShowPopup("Please connect your Arduino and restart")
        return;
    }
    usb.SetOnReceive(usb_OnReceive)
    app.ShowPopup("Connected")
}

//Called when user touches our toggle button.
function btn_OnTouch(isChecked) {
    if (!usb) return;

    //Send LED command to Uno.
    if (isChecked) usb.Write("ledh")
    else usb.Write("ledl")
}

//Called when we get data from Espruino.
function usb_OnReceive(data) {
   console.log(data)
}

Arduino code:
void setup() {
  pinMode(2,1);
  serial.begin(9600);

  loop() {
    if (serial.Read()="ledh) {
      digitalWrite(2,1);
    }
    if (serial.Read()="ledl) {
      digitalWrite(2,0);
    }
  }
}

The Arduino code has clear syntax errors; please review.

this doesn't answer the question. OP wants to use USB HID capability (emulate keyboard) of the Leonardo

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


text:
How can I make ultrasonic sensors resistent to splashes and dirt?
I wasn't sure where to ask this question, but since it's actually an Arduino project, I'll try it here.
I want to upgrade my old car with ultrasonic parking sensors: I've already bought HC-SR04s as sensors and started to play on my breadboard.
But what I'm still unsure about: if I place them in my car's rear bumber, how can I make them resistent to rain or dirt or something like that?
As pictured on Wikipedia, the sensor is covered with a small piece. But what could I use to cover the holes in the bumper, without interfering with the ultrasonic measuring?

I'd try thin rubber (e.g. from a latex glove). Or some other kind of thin plastic. Just try out some of the plastics from food containers you'd normally throw out.

I don't think you'll be able to cover that sensor in a way that will still allow it to work. There are waterproof ultrasonic sensors out there, here's one on Amazon, for example.
The other thing you might want to look at is IR instead of ultrasonic. That's easier to weatherproof since the IR emitter/receiver are already covered. You'll probably have less range with IR, though.

Maybe at a minimum for testing you could point the sensor downwards and then use a reflector to discourage water and dust. Something like: http://letsmakerobots.com/content/cyperbolic-reflector-review


text:
Webserver with Arduino Yun without SD
I'm trying to set up a simple web-server with Arduino Yun without an SD card, i.e via REST, if I understood it right (I'm new to some of these stuff). I want to be able to "get" data (sent by Arduino) through a jQuery script and show the user a formatted HTML page.
Here I provide you a simplified version of my Arduino sketch:
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

const byte internalLED = 13;

YunServer server;

void setup() {
  pinMode(internalLED, OUTPUT);
  digitalWrite(internalLED, HIGH);     // Turn the led on to advise about bridge begin in progress
  Bridge.begin();          // Let's activate the Yun Bridge...
  ledBlink(150);           // ...bridge activation done (user sees a blink)
  // server.listenOnLocalhost();       // Listen for incoming connection only from localhost (no one from the external network could connect)
  server.begin();          // Let's acrivate the Yun server...
  ledBlink(150);           // ...server activation done (user sees a blink)
}

void loop() {
  YunClient client = server.accept();  // Get clients coming from server
  if (client)                          // Is there a new client?
  {
    client.print(77);                  // Send a "77" to client (e.g. browser)
    client.stop();                     // Close connection and free resources.
    ledBlink(500);
  }
  delay(50);
}

void ledBlink(int delayTime) {
  digitalWrite(internalLED, HIGH); // Turn (or keep) the LED on
  delay(delayTime);
  digitalWrite(internalLED, LOW);  // Turn (or keep) the LED off
  delay(delayTime);
}

My Arduino Yun is connected via WiFi with static IP (192.168.1.98) to the same network of my laptop, and they can ping each other. Right now, if I insert into my browser the address
http://192.168.1.98/arduino/whatever

I correctly receive a simple «77» (no quotes or \r\n)
But I cannot "get" it when opening the page get_test.html (which is on my harddisk, not in the SD):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $.get("http://192.168.1.98/arduino/whatever", {}, function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
</script>
</head>
<body></body>
</html>

This is strange to me because this html code works if I change the address inside the "get" request with https://dl.dropboxusercontent.com/u/12389503/demo_test.txt which consists only of a «21» (no \r\n). The problem is I don't even receive the alert when the address is the IP of Arduino, but the board is receiving the request since I can see the led blinking once, as expected.
I'm running out of tests, any suggestion is welcome.

Whenever making ajax calls from/to different hosts (as your pc and the yun) you should use JSONP.

Thank you, I finally got it working today. I created a JSONP message as you told me. I changed in the sketch from client.print(77); to client.println("temperature({\"value\": 77});");. My jQuery request is now $.ajax({url: 'http://192.168.1.98/arduino/api/temperature', dataType: 'jsonp', jsonpCallback: 'temperature', success: function(result){alert("Value received through JSONP is "+result.value)}});


text:
What is the simplest way to "ask" the arduino which input pins are HIGH?
I am trying to build a 36-line cable tester, using the Digistump DigiX (99 i/o pins). Digital pins 0-35 are outputs, connected via the cable in question, to (in a perfect world) digital input pins 36-72. The plan is to have 36 neopixels (to conserve DigiX pins), one corresponding to each line in the cable. Currently they light up green for connection and red for no connection.
It's easy to check if output 0 goes to input 36, but there are more potential problems in a cable than no connection...
What if there is a short and output 0 goes to 36 and 42? It will still show up as correct when it tests 0 to 36... I somehow need to "ask" it what, if any, inputs (pins 36-72) are HIGH when only output 0 is HIGH.
I'm not sure how I'm going to display this extra data yet (Lcd maybe? Or maybe any pins shorted together all use a unique led color...), but I want to make sure the idea will work before I move on to that. Here is what I have working so far, just using a 3-line cable for now. And yes, I'm new to this. Any advice would be greatly appreciated!
#include <FastLED.h>
#define NUM_LEDS 3
#define LED_PIN 6
CRGB leds[NUM_LEDS];
#define brightness 25
int var = 0;

void setup() {
  for (int sendPins=0; sendPins <= 2; sendPins++) {
    pinMode(sendPins, OUTPUT); }

  for (int recPins=3; recPins <= 5; recPins++) {
    pinMode(recPins, INPUT); }

    FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
    FastLED.clear();
}

void loop() {
  while (var < 3) {    //so it only runs once for each line in the cable.
    var++;
  for (int sendPins=0; sendPins < 3; sendPins++) {
    digitalWrite(sendPins, HIGH);

    int recPins = map(sendPins, 0, 2, 3, 5);  //made more sense to me than another for loop.

     int recPin = digitalRead(recPins);
     if (recPin == HIGH)
     {
      leds[sendPins].g = brightness;
      leds[sendPins].r = 0;
      FastLED.show();
     }
     else
     {
      leds[sendPins].r = brightness;
      leds[sendPins].g = 0;
      FastLED.show();
     }

      digitalWrite(sendPins, LOW);
      delay(250);      //just for testing so i know it's going through them all.
  }
 }
}

Low-level access to the ports, which will give you all input bits at once.

If you are testing for shorts, but sure to only set one pin to output at a time. If all pins 0-36 are outputs, and you set pin 0 to HIGH (and the rest to LOW). Then in you example a short between inputs 36 and 42 would mean there's also a short between outputs 0 and 6. Which would mean there is a dead-short between a HIGH and a LOW output, resulting the AVR browning out and maybe even damaging the output pins.

There is a technique, which I used some 40 years ago to test for changes on a set of input pins. This can easily be configured to test serially.
Put a 1 on an output pin say 5. Create an integer e.g. 010000 with a 1 in the appropriate position. Read ALL inputs and XOR with the created integer. If one and only one input is 1 the resultant value will be 0. This is easy to implement in a loop just by shifting the 1 left each time.
The technique works if you can read all inputs into a integer. This was OK for our 32 bits, but could be extended.
It is probably easier to code than explain, but depends on what you have to do to read all inputs.

I believe you can read the port register that contains the current state for your pin. The port names take the form of "PORTA" - "PORTE". (The number of port registers varies with the processor in your arduino, and the pin to port mappings are also different across processor models, so this approach will tie you to Arduino models that use the same processor chip)
Another approach would be to store the state you write to each pin to a boolean variable and just read that. Create a central method that takes a pin number and a new state. That method would save the new value to an array, indexed using the pin number, and then also set the pin. You could then write a method that would read the current pin value from the same array .

Use nested loops.  Test each pin one by one.  For each one pin test, look for the correct wire to be on and check all the others and either look for an "on" or count how many bad on's there are.
HTH.


text:
need help hooking up an oled display
recently i bought this oled display .

http://www.wvshare.com/product/0.96inch-OLED-A.htm
how can i connect it with arduino . Driver Chip is SSD1306 . Supported Interface are 3-wire SPI, 4-wire SPI, I2C . it's can display two colors Yellow and Blue.
i need some guidance on how to hook it up with arduino lets say using i2c protocol . and is there any existing library ?
Note : on the wvshare website there's only code sample for STM32 Microcontrollers .

Did you read the datasheet? https://www.adafruit.com/datasheets/SSD1306.pdf

Are you prepared to resolder the resistors on the back?

@jippie i read the datasheet. it seems i can use the DIN and CLK pin as SDA and SCL. i tried that but its not working .  Ignacio, which resistor ? i know some basic soldering. thanks

You have to remove the 0-ohm resistor BS1 from the 0 position and move it the the 1 position.

has anyone tried it with i2c? been 2 days now trying to make it work .resolder the resistors but dosn't want to work.
and after the soldering wich library should i choose ?

it's working with u8glib.  but i am using  4-wire SPI.
constructor for U8GLIB
U8GLIB_SSD1306_128X64 u8g(13, 11, 10, 9,8);

Pin configuration was
Arduino -   Oled Display
13 -    CLK
11 -    DIN (SI)
10 -    CS
9 - D/C (A0)
8 - RES

the reset pin is required. i used 3.3v  arduino pin for vcc .

Yes, that is what the silkscreened chart shows the installed resistors as selecting for operating mode.  Gerben had been suggesting you could do i2c if you changed them.


text:
Resurrecting a fried Arduino (Bluno) USB port
Slightly distractedly, I went and connected 5V to the 3.3V pin on my DFRobot Bluno (the pins are right next to each other!)
The magic smoke leaked out of the AMS1117 3.3V regulator in a neat little puff. The sketch that was loaded on the board still runs fine, but the Bluno is no longer recognised by my Macbook Pro when I plug it into USB (I have tried different ports and different cables; they're all fine—it's the USB on the Bluno that's fried.)
In an attempt to repair it, I've replaced the AMS1117 (check the third paragraph of that tutorial—ha!) with an LF33ABV; this went well and I'm now getting a stable 3.3V on the 3.3V pin. Check out my handiwork:

However, the Bluno still isn't being recognised by the USB ports on my Mac.
Is there another way to upload new sketches to the Bluno? Theoretically you can do so over BTLE, but you need another Bluno to act as the "peripheral" and I don't have one to hand. I have various other Arduinos laying about if that helps.

Since the CC2540 is powered using the 3.3v, you might have also blown that chip by giving it 5v instead of the 3.9V, which is its maximum rating. Does BT still work? (Great fix with the regulator though; look awesome)

I think I might have :-(. The Bluno isn't showing up on any of the BTLE-sniffer apps I have on the iPhone.

Upload via ICSP. See those six pins next to the regulator you so expertly tacked on? Those are the ICSP pins. You'll need a second controller or programmer to do it.
http://arduino.cc/en/Tutorial/ArduinoISP

Funnily enough I remembered I had a USBtinyISP laying around. With it (and these instructions I've successfully managed to upload a new sketch to the board. Now to see if I can talk to it via BTLE...


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

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

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

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

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

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

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


text:
GSM arduino to webservice not working
I have setup a arduino with a SIM300 based GSM board. I have

Tx of Arduino connected to the Rx of GSM board
Rx of Arduino connected to the Tx of GSM board
Gn of Arduino connected to the Gd of GSM board

The GSM has a Vodafone 3g sim, activated with 3g. The GSM board has 2 LED's, one remains ON and the other blinks ever 4-5 seconds. Which I guess means that its configured to work with the SIM.
I then run the following code.
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  mySerial.begin(9600);

  Serial.println("Serial ports initialized");

   delay(500);
   Serial.println("AT+CGATT=1");
   delay(500);
   Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\",\"0.0.0.0\",0,0");
   delay(500);
   Serial.println("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
   delay(1000);
   Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
   delay(2000);
   Serial.println("AT+CIICR");
   delay(5000);
   Serial.println("AT+CIFSR");
   delay(500);
   Serial.println("AT+CIPSTATUS");
   delay(500);
   Serial.println("AT+CDNSORIP=1");
   delay(500);
   Serial.println("AT+CIPSTART=\"TCP\",\"http://myec2DNS-us-west-2.compute.amazonaws.com:myportnumber/mywebservice/myreques/Authentication/Request?identity=somecode&identityType=sometype\",\"myportnumber\"");
   delay(500);
   Serial.println("AT+CIPSEND");
   delay(500);
   Serial.println("AT");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

On cutecom I get te following
Serial ports initialized
AT+CGATT=1
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET","0.0.0.0",0,0
AT+CDNSCFG="8.8.8.8","8.8.4.4"
AT+CSTT="TATA.DOCOMO.INTERNET","",""
AT+CIICR
AT+CIFSR
AT+CIPSTATUS
AT+CDNSORIP=1
AT+CIPSTART="TCP","http://myec2DNS-us-compute.amazonaws.com:8080/myservice/mycommand/Authentication/Request?identity=%somecode&identityType=1","8080"
AT+CIPSEND
AT

When I run `tail -f  /var/lib/tomcat7/logs/localhost_access_log.2014-09-20.txt' on my webserver, I get nothing from the arduino.
What am I missing here ?

it seems like you are using the wrong serial interface. I see Serial and mySerial.
After mySerial.begin() you write to Serial, not to mySerial which runs on pins 10 and 11.
What's when you send the AT Commands from your Serial connection to the Arduino? It Should redirect them to the GSM board.

I welcome your answer. Shouldn't the loop method take care of that ? I did also get OK's for all AT commands.

The loop() redirects incoming commands from Serial to mySerial and vice versa.  If i'm not mistaken the AT Commands in setup() are sent to your computer and not to the GSM module. Where does the OK's come to?

The OK's come on the cutecom ttyUSB0. I think its working that way.

You might want to implement error handling for the AT commands.
Though if you believe this answer has fixed your question press the ✔ below the ⇩ on the left side of the question.


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

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

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

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

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

  analogWrite(MOTOR_PIN, motorSpeed);
}

Previous example with capacitors:

Code:
#include <Servo.h>

Servo myServo;

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

int alpha = 0.8;
int rawReading;

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

  Serial.begin(9600);
}

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

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

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

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

I added the info about the other example.

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

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

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

I need help i need to use a push button not a potentiometer

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

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

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

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

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

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

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