text:
Leonardo: disable TX- and RX-LED
I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them by software. What is the reliable way to do it?

Examine the schematic and determine if they are wired to supplies, or to I/O pins.  If supplies, desolder the associated resistors.  If I/O pins, modify the bootloader and USB core to leave them off, or try issuing raw ATmega I/O access to turn them off if the are simply left on after the bootloader and not being constantly re-driven by USB traffic.

@ChrisStratton why not just desolder them in the first place? I don't know why it'd be bad to desolder the LED in the first place...

Just put a piece of tape over them...

Software modifications are cheaper and easier to reverse.  Tape doesn't save power.

How they are driven currently? The straight-forward way using digitalWrite(pin, LOW) does not work. pinMode(pin, INPUT) doesn't work either.

Try adding this to your setup routine:
TXLED0;
RXLED0;

These macros (and their cousins TXLED1, RXLED1) are used to control the TX an RX LED's on Leonardo. They are defined in https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/leonardo/pins_arduino.h#L95-L98

If that doesn't work you can try the solutions suggested here: http://forum.arduino.cc/index.php?topic=145262.0

Switching the IDE to upload to "Micro" instead of "Leonardo" really solved the LED problem.

See my new answer for more elaborate explanation and a maybe better solution.

Alternatively: the pin mapping in the Arduino world is D17 for RX and D30 for TX, so instead of TXLED1 you can also use digitalWrite(30, HIGH).

Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.
Compare:
http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf

The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):

In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:
olimexino32u4.name=Olimexino-32U4
olimexino32u4.upload.protocol=avr109
olimexino32u4.upload.maximum_size=28672
olimexino32u4.upload.speed=57600
olimexino32u4.upload.disable_flushing=true
olimexino32u4.bootloader.low_fuses=0xff
olimexino32u4.bootloader.high_fuses=0xd8
olimexino32u4.bootloader.extended_fuses=0xcb
olimexino32u4.bootloader.path=caterina
olimexino32u4.bootloader.file=Caterina-Leonardo.hex
olimexino32u4.bootloader.unlock_bits=0x3F
olimexino32u4.bootloader.lock_bits=0x2F
olimexino32u4.build.mcu=atmega32u4
olimexino32u4.build.f_cpu=16000000L
olimexino32u4.build.vid=0x2341
olimexino32u4.build.pid=0x8036
olimexino32u4.build.core=arduino:arduino
olimexino32u4.build.variant=olimexino32u4

Create another folder 'variants' inside the olimexino folder.
Inside that, create the folder 'olimexino32u4'.
Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder
Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.
Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:
#define TX_RX_LED_INIT  DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED1          PORTD |= (1<<5)
#define TXLED0          PORTD &= ~(1<<5)
#define RXLED1          PORTB |= (1<<0)
#define RXLED0          PORTB &= ~(1<<0)

I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.

I've tried both values on TXLED and RXLED - one did not work. Only selecting the "Micro" board worked.

This is the best solution. The problem stems from UART activity taking control of the Tx & Rx LEDs. Switching to the 'micro' board just reverses the states of these LEDs. By creating a custom pins_arduino.h board, and defining these macros to nothing will disable their use entirely by the UART, making them simple GPIOs.

The TXled is connected to physical pin 22, or PD5. RXled is connected to pin 8, or PB0. They are connected to the cathode of the led, so they have to be HIGH to turn off the leds.
To turn them HIGH use:
PORTD |= (1<<PORTD5);
PORTB |= (1<<PORTB0);

Not sure what the firmware does, and if it sets the leds back to low every once and a while. So in addition I would suggest also setting those pins to inputs.
DDRD &= ~(1<<DDD5);
DDRB &= ~(1<<DDB0);

The Olimexino-32u4 connect the LEDs to GND, but as written in my comment, this approach does not work.


text:
9 DoF Sensor Accelerometer Readings Inconsistent
I have the following sensor stick: https://www.sparkfun.com/products/10724
It has an accelerometer, gyroscope, and magnetometer.
I have connected it to an arduino and am reading the accelerometer values while the sensor is completely flat and the values jump all over the place:
ie
0
2
3
7
-5
12
35
-3
...
This is how I am reading them:
void Accel_Init()
{
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2D);  // Power register
  Wire.write(0x08);  // Measurement mode
  Wire.endTransmission();
  delay(5);
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x31);  // Data format register
  Wire.write(0x08);  // Set to full resolution
  Wire.endTransmission();
  delay(5);

  // Because our main loop runs at 50Hz we adjust the output data rate to 50Hz (25Hz bandwidth)
  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x2C);  // Rate
  Wire.write(0x09);  // Set to 50Hz, normal operation
  Wire.endTransmission();
  delay(5);
}

// Reads x, y and z accelerometer registers
void Read_Accel()
{
  int i = 0;
  byte buff[6];

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.write(0x32);  // Send address to read from
  Wire.endTransmission();

  Wire.beginTransmission(ACCEL_ADDRESS);
  Wire.requestFrom(ACCEL_ADDRESS, 6);  // Request 6 bytes
  while(Wire.available())  // ((Wire.available())&&(i<6))
  {
    buff[i] = Wire.read();  // Read one byte
    i++;
  }
  Wire.endTransmission();

  if (i == 6)  // All bytes received?
  {
    // No multiply by -1 for coordinate system transformation here, because of double negation:
    // We want the gravity vector, which is negated acceleration vector.
    accel[0] = (((int) buff[3]) << 8) | buff[2];  // X axis (internal sensor y axis)
    accel[1] = (((int) buff[1]) << 8) | buff[0];  // Y axis (internal sensor x axis)
    accel[2] = (((int) buff[5]) << 8) | buff[4];  // Z axis (internal sensor z axis)
  }
}

Am I doing something wrong that these values aren't the same?

What does your circuit look like? That may help...

Its just the arduino and sensor...
sda -> pin A4 && scl -> pin A5

What values do you get when you do shake it?

In 'FULL_RES' mode the number you get is amount of 4mg units.
So 1 is 4mg, 2 is 8mg, -4 = -32mg.
Also note that your current code doesn't interpret the first bit (so the 13th from the right) as the sign bit, so you'll never get negative values. (Question related to this)
PS I think it is actually more like 3.9mg.

How do I go about interpreting it as the sign bit?

Like I said, just follow the link in my answer. Basically just shift left 5 positions and then divide by 32. (accel[0] = (accel[0]<<5)/32)

source: Stack Exchange

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

sort: votes


text:
Arduino gets stuck: battery powered, wireless, dc motor drive
I have a Arduino Mega 2560 connected to

L293D Motor Driver IC connected to two small size dc motors.
MPU-9150 using i2c
Xbee v1.1 arduino shield by seeed
Li-po battery, 7.4 volts, 2200 mah.

All components are tested separately, they all are working fine, the sensor readings showing data on serial monitor, the l293 drives the motors, xbee sends wireless serial data on pc, and li-po is also working fine.
I have checked the wiring alot of times. It all seems to be correct.
The problem arises when i connect all of them together, since I am using a single power source, I power the l293d with the Li-po and the Arduino also with the Li-po.

When the L293D is powered using Li-po and it starts drawing current from the battery, the serial monitor/arduino gets stuck. It doesnt show sensor readings anymore, while the dc motors start spinning. And they continue to spin, until I break connection with the battery.
Without the l293d powered, the sensor readings are working fine, everything is going normal, as it should, but as soon as the l293d is connected, arduino is stuck..

I have searched alot of forums for this, found some info, perhaps something to do analog and digital ground? mpu-9150 is digital ground. So that is why it stops the arduino mega as the l293d starts drawing current. All hell breaks loose.
Can anybody please help me with this? it is giving me headaches ever since!

Can you provide a schematic or wiring diagram?

Did you use decoupling caps or are you challenging the laws of nature?

Try adding a high value capacitor to the 5V. Alternatively try powering the motors using the battery voltage directly instead of (though the regulator) to  5v. Also, what happens if you only disconnect the motor, and not the L293D?

@jippie, many of your readers (like me) have a software background, not EE, and may not know what you're talking about with bypass caps. I've seen them used in regulated power supplies. It would be helpful if you provide a link to you would use bypass caps in a circuit that has both power loads and a micro controller on it.

@DuncanC to be honest, that was more or less the reaction I was hoping for. Check these related questions on EE:http://electronics.stackexchange.com/questions/105820/transistor-rating-with-capacitive-load and http://electronics.stackexchange.com/questions/59325/whats-the-use-of-a-decoupling-capacitor-near-a-reservoir-capacitor/59328#59328 and http://electronics.stackexchange.com/questions/90971/does-my-circuit-need-decoupling-caps/90972#90972 The problem is clearly related to power surges and caps may be able to solve that. BTW OP should really post a circuit diagram, because details unclear.

What do you think of my suggestion of powering the Arduino with a 9 volt battery as a test? That should isolate the large current pulses of the load from the Arduino board, and also keep the high frequency noise from the Arduino from getting to the motor driver.

@DuncanC when done correctly that is a perfect method to identify the cause of the problem, I do not think using two power sources all the time can be considered a good solution.

@DuncanC i have tried two power sources. 7.4v Lipo for the L293D and 9 Volt battery for the arduino, the ground is common between all, i hope that isnt creating problems?

@jippie decoupling caps? can u highlight please?

@Gerben ill show the circuit, where to add the capacitors?
and it WORKS fine without the motors connected to L293D. as soon as the motors start rotating, no more readings.

okay newbie here, how to add image?

Just add the capacitor between 5v and GND. You can't put an image inside a comment. You can however edit you question and add additional info, like an image, to it.

@Gerben the only 5 Volt source that i have is on the L298N motor driver shield. it is basically a voltage regulator, so the 7.4volt coming from LIPO is regulated to 5Volts. now where to add the capacitor

@gerben i mean the L298N has a voltage regulator in it, and it powers the L298N by using the voltage regulator, 7.4volt regulated, used to power the motor driver. and the 7.4volt used to drive the motors.
https://www.google.com.pk/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&docid=7wcBRF2MZnrUtM&tbnid=wpzRFhWuIOknzM:&ved=0CAUQjRw&url=http%3A%2F%2Fwww.ebay.com%2Fitm%2FArduino-Motor-Controller-Shield-L298N-Drive-2-Motors-%2F330521096218&ei=aR3UU5L0L6Sa0QWso4DgDQ&bvm=bv.71778758,d.d2k&psig=AFQjCNEBkuBsnJB0eLBP-aiHp5TO4xN8Cg&ust=1406496486061746

the link given is of the motor shield

Just put it on the arduino's 5v and GND. Aternatively add it to the battery's + and -.

My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.

i tried having two power sources.

Lipo 7.4v for the L293D
9 Volt battery for the Arduino.

there is a ground common between all, i hope that isnt creating the problems?

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


text:
Help with wiring? Fritzing example inside
I am trying to prep my wiring for a 8x8 Led Matrix w/ Bluetooth according to the following instructable:
http://www.instructables.com/id/Arduino-SPI-7-Bi-color-LED-Matrix-Scrolling-Text-D/?ALLSTEPS
Instead of soldering everything together I'd much rather use a breadboard. I'm new to wiring, breadboards, and Arduino's in general. I was wondering if anyone could look over my sketch and see that the connections I've made are valid.
I'm basing my wiring off this image (See original instructable for higher resolution):

I realize the bluetooth module isn't the same. I'm just using this as a reference. The wires leading off the top of the board will be going to the LED Driver module.
EDIT: Thanks for the feedback guys. I have decided to go with the Innogear HC-05 module. I've adjusted the wiring according to that model.
As per the suggestions, I've switched my power and ground rail and eliminated the resistors and ground for TX communication. (I've still kept a ground for the BT).
Here's my new attempt:

I realize that it's not your fault, but a voltage divider is a terrible level shifter. Also, are you sure you're using a 3.3V Bluetooth module?

Sorry, I'm not sure what a voltage divider is. As I said I'm very new to all this. As for the BT module I plan on using the HC-05, just showing the RN-42 for reference (Power should be coming off the 5V rail). I'm open to any suggestions, and I'm certain this isn't laid out as efficiently as it should be.

Which specific Bluetooth module are you using? The one in the top image is not a bare HC-05.

Planning to pick this one up soon. http://www.amazon.com/Arduino-Wireless-Bluetooth-Transceiver-Module/dp/B0093XAV4U/ref=sr_1_2?ie=UTF8&qid=1406274658&sr=8-2&keywords=hc-05+bluetooth

Looks the same as the original so it's good. Except pin53 should have had a green wire instead of a white. Good luck.

@IgnacioVazquez-Abrams Version 1.05 has the 3.3v logic level printed on the back.

Does the wiring color matter? I believe all are the same gauge but I am unsure. I'm borrowing this kit from someone.

I am the author for the Instructable ethanx94's wiring is based on. It seems like the active and helpful members here have already helped iron things out.
If anyone is using the Arduino sketch downloaded from my instructable but is using ethanx94's wiring, do remember to change the SPI SS (Slave Select) pin in the sketch from 10 to 53 to reflect the correct pin used.
Look for the following line in the sketch and change the pin number 10 to 53:
int SPI_CS = 10;// This SPI Chip Select pin controls the MAX7219

int SPI_CS = 53;// This SPI Chip Select pin controls the MAX7219

Welcome to Arduino SE! It's cool that the author of the tutorial is commenting on a question as that doesn't happen much. Feel free to stick around and ask/answer other questions... One note is what about pins 11-13/50-52? Do those need to be remapped in the code, too? (Arduino documentation: http://arduino.cc/en/Reference/SPI)

Sorry for late reply. I am not active here. There is no need to remap the other pins in the sketch downloaded from my instructable except the SPI SS pin.

Those are, in fact, the same board. When you look at this image (from Amazon)...

...you can see that there are really six pins, just two of them aren't soldered.

Your circuit:

On the power rails, you have the 5V and ground switched. It'll work okay, but you're asking for trouble later on when trying to work with it and accidentally plugging a wire into the wrong rail.
Also, from the reviews on Amazon, it says that it can be powered with 5V since the breakout board provides voltage conversion. However, no one specifically mentions the TX/RX, so I'd not risk it. This module (seems to be same chip) costs less and a reviewer specifically says that it converts voltage for both power and the TX/RX.

I'm not going to verify the resistor values, since you don't seem to need them if you get the other module I listed.
If you still did want to do the 5V/3.3V conversion, you should connect the power wire to the 3.3V pin, not the 5V rail on the breadboard

tl;dr: it seems as you just need to skip the resistors for the yellow wire and make a direction connection. I'm not 100% sure about that specific part but there was another one that a reviewer specified that this was okay.
Note: I cannot comment on the other wires for the shields, but at a quick glance it looks good.

Thanks so much for the feedback. I've updated the OP accordingly, as well as cleaned up the overall shape of things.


text:
MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin
I am following this guide. Now I want to create the Create the "ArduinoCore library". But when I am creating a new project, I can not select ATmega16U2 as MCU type.
But my Arduino Due R3-E and UNO SMD R3 both use ATmega16U2.
What shall I do O_o???

They may have it, but you don't actually use it.

What do you mean with this? Why do I not actually use it?

Although you can't do it with the Eclipse AVR plugin, you can change the firmware of the 16U2.

The ATmega16U2 on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.
In the case of the Uno, the main microcontroller is the ATmega328. For the Due, it's the AT91SAM3X8E. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.

Thank you very much for your answer. Like I said, I want to program arduino using eclipse. So when I am prompted to tell the MCU type and MCU frequency, it's about the main MCU and not the USB to TTL serial?

Yes, that's correct. It needs to know about the main MCU because different chips have different features, and that affects how it compiles some of the underlying Arduino code.


text:
Arduino Mega - get mac adress
I am new on Arduino, and I am trying to use the Ethernet shield...
but it need:

IP adress
MAC adress

IP adress is easy to get... but not MAC..
how can I get my arduino MAC adress?

A MAC address must be unique throughout the environment in which it operates, but apart from that is largely arbitrary.  Typically the problem is solved by selling 3-octet prefixes (called OUI's) to manufacturers, who then uniquely assign the remaining 3 octets to individual device units they manufacturer.
However, if you are unable to discovery a globally unique address assigned to your device by its manufacturer, and know that its traffic will be confined to a local network, you can use a privately assigned (ie, "made up") address with the Locally Administered bit set.   An address of the form
02-xx-xx-xx-xx-xx-xx

or any other with the 2's bit of the first octet set will satisfy this criteria as long as you guarantee that it is unique in your system.
Be especially careful not to set the 1's bit of the first octet - if you do so, traffic will be marked as broadcast and so given wider distribution/attention than needed, wasting network capacity and processor time of connected devices.

Arduino doesn't have a MAC address, your Ethernet adapter shield however will. The MAC address is likely printed on the interface and is constructed from 12 hexadecimal numbers, usually grouped 2 hex digits at a time.
If it isn't printed on the box or the shield, then the only way to find out is to connect it to your network, configure a valid IP address on the shield and try to connect to it (eg. ping to the address) from your PC) Then you can list MAC addresses from your PC  with arp -a.
Or when using dynamic addresses and DHCP, you can find the mac address in you DHCP server (probably your home router).
Either way, you need a sketch on your Arduino to configure an IP address.

i cant vote for you... i dont have reputation =(

This answer seems somewhat at odds with the documentation cited in the other - if the shield has to be told its MAC address by the sketch, then you can't meaningfully query it until you have done that.

No MAC address is hard wired, IP address is configured in software @ChrisStratton Arduino doesn't have a MAC address, the Ethernet NIC does. Arduino can probably overrule the hard wired address, but that is advanced use of the shield.

@ChrisStratton according the the other answer some shields come without a hard wired MAC address. When inventing your own address it is essential to make it unique on your network.

Yes, it's quite clear that some come without an address stored in the hardware, what is unclear is that any come with.  Certainly though there are other embedded devices and adapters that have one stored in an eeprom or similar, bridge devices with a network stack in flash and an address stored alongside it, etc.

@ChrisStratton With a regular NIC (network interface card) as the one in your computer, tv, phone, ... the MAC address is always hard wired. This obviously is not a complete NIC, just some sort of bare bone.

Actually, no, it's usually not hard wired in the MAC, but rather stored somewhere outside the MAC chip (an eeprom on a classic ethernet card), queried from there by the software and then injected into a register in the chip by software... serializaton of ICs that aren't otherwise programmable is expensive.

I guess the more the Ethernet interface can offload workload from the microcontroller, the more tasks are done on the Ethernet interface. If you have a Ethernet interface without hard wired MAC, then your microcontroller will be much busier with communications than an interface with hard wired MAC (and related 'accelerating' hardware).

Although I can't comment on all the specifics of this, I can say that the official ethernet library documentation implies that you can choose your own mac with: older Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.

@jippie - normally except in a "promiscuous mode" the MAC chip handles filtering of incoming packets by MAC address (so the processor doesn't have to), but by using an address set in a volatile register - which has to be externally loaded from some other source of information at power on / reset.  If you have something like an ethernet<>serial bridge where the whole network stack is running on a dedicated embedded processor, then that probably does have the MAC address persistently stored, though again, not typically actually within its ethernet functional block but rather elsewhere inside.

Current Ethernet shields come with a sticker indicating the MAC address you should use with them.

(source)

my Ethernet shield doesnt :( it is not the official

Ultimately, all but a few bits of the MAC address are irrelevant - they only need to be globally unique.  There is a range of MAC addresses reserved for "locally administered values" (ie, a range in which you are allowed to make up your own).  Pragmatically speaking, you can also take the address off an obsolete device you physically possess (old ISA bus NIC?) and know is not in use.


text:
Arduino amplifier
I want to drive my model trains (märklin) with my arduino UNO, it requires 32 watt (0-12/24v, 2A MAX(changes))
This is Direct current
How can I amplify the output of the arduino to get my 32 watt?

Usefully driving trains is more than a matter of on/and off, but involves PWM and possibly more complicated waveforms.  I expect if you look on train enthusiast sites you will find documentation of both manual throttles and automated drivers, probably no few of them based on ATmega MCUs if not the Arduino libraries as well.

You certainly can. For relatively small amplifications, you can use transistors. MOSFETs are similar and work well for larger solid state amplification. If all you need is to turn power on or off (no switching faster than ~20Hz) a relay is you best bet, but most standard ones take more power than a raw arduino output can provide so you have to buy one for this purpose. They are all easy to use, for the most part just plug in ground, power, signal, and signal out. You can look up any of these for more details on use, it should not be hard to find.
The easiest pre-built solution is something like this relay board: http://www.sainsmart.com/arduino-compatibles-1/relay/arduino-pro-mini.html

I would love to be able to either adjust the voltage, live: to control the speed of the train, or be able to use PWM, which will also work with my trains.

a transistor/MOSFET can switch fast enough to do PWM. The DC motor driver John referenced will also do exactly what you want.

Definitely go with MOSFETs. Normal transistors will get quite hot when you run 2A through them.

This company, among others, has a range of drivers, meeting your volt/current/PWM speed control requirements, with good documentation, manual and use examples. http://www.pololu.com/category/11/brushed-dc-motor-drivers


text:
Moving an item on a pole, can an Arduino work for my project?
I'm a computer programmer, but I've never done anything with Arduino. I'd like to build something that holds a polisher (this one, in specific: http://www.homedepot.com/p/BLACK-DECKER-6-in-Random-Orbit-Waxer-Polisher-WP900/202516385) on a metal pole, and moves the polisher up and down (vertically) on the pole at varying speeds (I'd like to use arduino to control the motor/speed)?
Is this the sort of thing Arduino would be able to do? If so, can anyone point me to any motors that would work? If not, any tips on where else I should look?

Any MCU will do. Arduino happens to have one.

I'd suggest moving the polisher horizontally. That way motor doesn't have to be as strong, as it doesn't have to contest with gravity.

@Gerben - If you use a vertical configuration with a counterweighted pulley, then the motor would hardly have to contest with gravity at all. It would just need to overcome friction.

I am also a software guy by profession. I've always liked tinkering with electronics, and have recently gotten into Arduino. It is an excellent platform for developing hybrid hardware/software solutions for problems like this. It is very easy to use, both hardware and software.
There is a large ecosystem of add-ons called "Shields" that just plug in. You can probably find a motor control shield that will do exactly what you want.
Your biggest challenge, I think, is going to be mechanical. How will you hold the polisher in position, and make a mechanism that will raise and lower it?
Off the top of my head what I come up with is a U shaped metal bar with a threaded rod in the opening of the U. You'd build a "sled" that would grip the bar and would have teeth that would grip the threaded rod. Then your would have a motor on the end of the assembly that would turn the threaded rod to move the sled up and down on the bar. You'd attach the polisher to the sled. You'd probably need a spring or rubber holder so that the polisher would press gently on the surface being polished but with some freedom of motion.


text:
DC motor makes noise but does not rotate
i am following Jeremy blum's tutorial on youtube. link i have done the exact same circuit design as he has.

but the dc motor just makes a continuous beep sound when i run this code.
int motorPin = 9;

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

void loop()

{
    for(int i = 0; i <= 255; i++)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);

    for(int i = 255; i >= 0; i--)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);
}

I am clueless as to why this is happening. would be glad if someone could help me out here.

What are the specs of your motor (current rating)? What is the transistor model you have used?

Could be an AC motor. Try connecting it directly to a 9v battery or some other power source, and see if it turns

Or just change pin 9 to HIGH to see if your circuit is working right an inertia is stopping the motor from turning.

For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.

analogWrite uses PWM. Is the motor you are using designed for pulsed operation? Try using
digitalWrite(motorPin, HIGH);

The question should be not so much if the motor is designed for pulsed operation, but if the duty cycle, supply, and driver circuit are delivering sufficient power.  Commanding 100% duty cycle in this manner is indeed one of the key tests which should be run (except in the atypical case where the driver is capable of delivering an unsafe amount of power)

I'm wondering if a 10 ms delay between steps is long enough for the motor to respond, especially with a cap across its terminals.  Besides that the whole thing is over in 5 seconds.
It seems to me that AnalogWrite generates a PWM signal of about 500hz or about 2ms wave period.  So in 10 ms you get 5 pulses of the same amplitude and smoothed by the cap.  At low values of "i", say i=10, then the pulse is only 10/255*2ms wide or about 78uS. At low values of i, a 180deg rotation has to occur in the time you apply the pulse for the motor to rotate, well not exactly but close enough.
Most small DC motors are 2 pole, so you're expecting at least one 180degree rotation in 5x78uS or about in 400uS.  That would be a full rotation in about 800uS, say 1mS, or 1000 rotations in 1 second, or 60000rpm, from a standing start if the duty cycle was held constant.  You have very little power at low "i" so I'd be surprised if there is enough to overcome friction and inertia.  On higher values I guess it's still not enough to overcome the inertia.
The motor well may run at the higher values of "i" but then the program immediately counts down again.
So I suggest you start the counter at say 125 or even higher. Also make the delay between counting up and counting back down much longer so you can actually see the effect before it counts down again. I would also want to make the delay between counts higher so there is more time for current to flow in the motor's (inductive) windings.  Remember an inductor resists a change in current. Now that I think about it, this is probably more important than the inertia and friction.
So here is a challenge... Change the delay between counts first, and report your results here.  Then reset that and change a different parameter, and so on. Eventually make a number of changes together...I'm curious to see the outcome.
By the way, I suspect the sound is from the motor laminations changing shape at high frequency.
Cheers
P

I had the same issue, turns out that i had configured the BJT wrong. I had confused the drain for the collector.

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


text:
MakeyMakey + Arduino
I am trying to use the MakeyMakey with the Arduino (not as an Arduino) and then use a USB to TTL module to send the keys pressed to the Arduino. Is this possible? Do I have to reprogram?

No you can't the makeymakey and the usb-to-serial adapter are both usb clients. You need one host and one clients for usb. You could alter the firmware to send serial info using D0 and D1 on the header on the backside, but that's not that easy.

Why not have the MakeyMakey communicate using its USART intead?

Possibility, but the USB host shield worked for me!

one possibility is to use HOST SHIELD
http://www.circuitsathome.com/products-page/arduino-shields
Arduino is now as host
Makey is keyboard


text:
Parsing JSON on the Arduino
I'm using the ArduinoJson library. There is a great example for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:
#include <JsonParser.h>

using namespace ArduinoJson::Parser;

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

  char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \
    {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]";

  JsonParser<32> parser;
  JsonArray root = parser.parse(json);

  if (!root.success()) {
    Serial.println("JsonParser.parse() failed");
    return;
  }

  for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) {
    // unsure of what to do here.

    Serial.println((*item)["data"]);
    // results in:
    // ParseJsonArray:21: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous

    JsonObject something = JsonObject(*item);
    Serial.println(something["sensor"]);
    // results in :
    // ParseJsonArray:26: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous
  }
}

void loop() {}

item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.

does the data parse from above object is for both sensor
how to parse value of each object of jason
LIKE i have
[{"sensor":"gps",
"time":"1351824120"},{"sensor":"temp",
"time":"1351824120"}]

This is how I would write this loop:
for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
{
  JsonObject row = *it;

  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):
for (auto row : root)
{
  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

+1 for a great use case of the for loop.

Got it! Initially, casting the retrieval of the item from the JsonObject before printing was enough.
JsonObject something = JsonObject(*item);
Serial.println((char*)something["sensor"]);

Although, I think this looks better.
char* sensor = (*item)["sensor"];
Serial.println(sensor);


text:
Bluetooth HID module
I try to build custom controller and now searching for bluetooth hid module. Which BT HID module compatible with arduino? (not bluetooth serial)
List of some modules:

BlueSMiRF HID - from sparkfun, expensive (based on rn-42, also available RN-42-EK evaluation board) ✔ compatible
HM-10 bluetooth module - around $10 (aliexpress), based on cc2540 ht
tp://www.ti.com/product/cc2540
HC-05 Transceiver Module  - less $10, maybe supports HID after firmware upgrade(??)
Bluegiga wt12
Bluefruit EZ-HID from Adafruit ~$20 (suggested by mwwalk) ✔ compatible

Thanks

What do you mean by (not bluetooth serial)? Also, what's the objective of the question? All of those should be compatible with Arduino...

Module should support Human Interface Device protocol (HID), after connection to host system you can use it as keyboard/mouse etc, bluetooth serial port works like serial and if you want send keyboard signal you need additional software on computer (serial to hid)

Ahh, apologies I totally missed the whole HID thing... apologies again :)

The HM-10 is a BLE module incompatible with legacy bluetooth.  Some recent smartphones and other devices can talk both protocols, but be sure yours supports BLE (and for your intended usage) before you go with that option.  Also realize you need firmware for the module, either custom or a configuration of a factory firmware which meets your needs.

I'm not entirely sure from your question if you want just the module or a whole breakout board.  If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535

Thanks for your suggestions! I would like to buy this item, unfortunately adafruit don't ship items to my country and don't accept payments from cards.

Anyway, I bought Bluegiga wt12 (bare module) only for $12 from ebay and now making pcb. Bluegiga have very good website and a lot of useful documents.

HC-05 HC-06 and, for example, RN-42 HID are the same looking on hardware design.
Only difference is in firmware.
For educational purposes you can dump firmware from RN42HID and flash HC-05/06 module and you've got a HID module.
The difference in costs of the HID modules is that CSR IDE costs $3000 per licence  + developer seat, and when someone invests in developing wants the incomes to come.
Byron's blog will guide you, you need a SPI programmer, but you can use Arduino as programmer/debugger. And you will need blueflash software to backup some info from Your module (calibration of crystal for example, and IDS/MAC/serial) than you can flash the RN firmware, and you have exact copy of RN, last thing is to restore the settings saved from your original firmware.
Just Google it, here is not much place to put all the data and images.
But yes it is possible.


text:
Arduino + Web Service
I am doing my CBT, and i need help...
I need a Webservice in C#, and it will send commands to my Arduino( Mega 2560 + Ehternet Shield )...
My Webservice will recibe commands from Android and Web

EDIT
I wanna know what kind of C# WebService Project I have to create...

What is your question exactly? If you want to know where to begin: google. Find some tutorials and do them to get familiar with all the different parts of the project. If you run into any troubles with those, maybe we can help you.

Go easy on this forum please. Dont be as strict as stackoverflow.com. Arduino does take a bit of time to learn. Tolerate basic questions please.

The question is probably better suited to another stack exchange forum. The question really isn't Arduino related, but more about web programming on a PC. Once you have that and it is ready to send commands to the Arduino, I hope you'll come back here with your Arduino questions. It sounds like a fun project.

@Siddharth it's not really our opinion that counts. If you'd like a change in policy, propose it on meta. However, this type of question wouldn't be allowed anywhere on SE because it would  be opinion based which often leads to bad content.

@JRobert this wouldn't be allowed on SO for sure. However, yes, we can help with specifics on the Arduino side....


text:
SIM900 + GPS Module making http rest calls
I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.
I found this library. My question is, will I need a microcontroller for this ?

My question is, will I need a microcontroller for this ?

Yes. There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?
People often hope that they can hook up two complex devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.
Well, they're both SPI/I2C/UART/USB/Serial! Why not? Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)
tl;dr: you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.

Going by the cost of Arduino, I am getting inclined to go for SIM900 boards.

@Siddharth does the SIM900 have a MCU that you can program?

I partially agree to Anonymous Penguin's answer.
But if you want go for a deep dive, actually SIM900 / SIM800 GSM modules also have a facility called Embedded AT. Just Google it using "SIM900 Embedded AT". They have a pdf here at the time of writing this.
According to this application note, SIM900 is actually ARM core and using Embedded AT you can utilize most of things you do in External MCU. So if you are thinking of some application, which can be developed into SIM900, Yes you can avoid using external MCU. You can give AT Commands from your application to SIM900 core using API. You even get 1 UART to interface GPS chip with SIM900. If you move to SIM800 family they have more UARTs.
PS: I haven't used it.


text:
Can I use an external power supply and still communicate with my computer over Serial?
I read the following online:
If you plug in both USB power (say from a pc) and external power via the 2.1mm jack, the Arduino chooses power source automatically.
If the external 2.1mm DC is providing greater than 6.6V, the Arduino will take power from it instead of the USB.
Firstly, is this accurate?
Secondly, my real question:
If I am powering my Arduino via external DC, can I still communicate with my Raspberry Pi using serial via the USB?

Related: http://arduino.stackexchange.com/questions/893/arduino-what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-pow?rq=1

Yes you can. It still leaves the data/ground lines intact, it just doesn't bridge the 5V line.
Arduino Uno Schematic v.3:

The USBVCC is directly from the 5V on the USB jack (well, technically there's a fuse there). It then goes through a transistor (T1) that only allows power through when there is no power coming from the 5V regulator (that regulates the VIN voltage).
The USB jack:

You can see pin 1 of the USB jack (5V) goes through the fuse to USBVCC. The next ones D+/D- are the data lines that go through resistors to the ATMEGA16U (used for USB to UART). The last one just ties into ground.

Great answer, penguin! (Voted). Does it matter which order you connect the devices? (Can you run your Arduino via USB, then connect Vin once it's running, OR power it via Vin and connect USB while it's on? It sounds like it's wired to prefer Vin power, so what happens when you are powered over USB and connect Vin? Does it switch power sources on the fly?)

@Duncan it should be fine to connect USB when already powered by VIN (although it will reset when the computer connects to the COM port. As far as VIN while already on USB, it looks like it will switch but I'm not sure if the transistor will let the voltage drop low enough to reset the board. Either way is fine, but it might reset a few seconds in.

The datasheet for the FDN340P MOSFET might provide a little more information: https://www.fairchildsemi.com/ds/FD/FDN340P.pdf


text:
Sending MPU6050 data over serial to Java/C# Program
I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.
UPDATE:
Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this link. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.
Arduino
#ifdef OUTPUT_TEAPOT
        // display quaternion values in InvenSense Teapot demo format:
        teapotPacket[2] = fifoBuffer[0];
        teapotPacket[3] = fifoBuffer[1];
        teapotPacket[4] = fifoBuffer[4];
        teapotPacket[5] = fifoBuffer[5];
        teapotPacket[6] = fifoBuffer[8];
        teapotPacket[7] = fifoBuffer[9];
        teapotPacket[8] = fifoBuffer[12];
        teapotPacket[9] = fifoBuffer[13];
        Serial.write(teapotPacket, 14); //Serial.write(buf, len)
        teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
    #endif

    #ifdef OUTPUT_ACCEL_STR_RAW
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        String accelGyroRaw = "STX,";
        accelGyroRaw += ax;
        accelGyroRaw += ',';
        accelGyroRaw += ay;
        accelGyroRaw += ',';
        accelGyroRaw += az;
        accelGyroRaw += ',';
        accelGyroRaw += gx;
        accelGyroRaw += ',';
        accelGyroRaw += gy;
        accelGyroRaw += ',';
        accelGyroRaw += gz;
        accelGyroRaw += ',';
        accelGyroRaw += "ETX";

        Serial.println(accelGyroRaw);

    #endif

C# Code
class Program
{
    static SerialPort port = new SerialPort("COM7", 115200);
    //static int serialCount = 0;
    //static int aligned = 0;
    //static char[] teapotPacket = new char[14];
    //static float[] q = new float[4];

    static void Main(string[] args)
    {

        Console.WriteLine("****** Serial Console Read ********");
        port.Open();
        port.DataReceived += port_DataReceived;

        Console.Read();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        string s = port.ReadLine();
        string[] accelGyroVals = s.Split(',');
        string[] accl = new string[3];
        string[] gyro = new string[3];

        if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
        {
            accl[0] = accelGyroVals[1];
            accl[1] = accelGyroVals[2];
            accl[2] = accelGyroVals[3];

            gyro[0] = accelGyroVals[4];
            gyro[1] = accelGyroVals[5];
            gyro[2] = accelGyroVals[6];

            Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
        }

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        if (port.IsOpen)
        {
            port.Close();
        }
    }
}

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.

What have you tried so far? Is your problem related to Arduino side or Java side? Can you post some code you have tried until now?

Java and C# are similar, but not the same, so you need to be clear about which you are actually using.  In C# you can use == to compare String contents, but in Java that operator will only compare object instances and you must use the .equals() method to compare contents of Strings.  Given the non-capitalization of "string" it appears your posted code is actually C#, but the "==" will subtly fail if you try to make trivial changes to build and run it as java.

Chirs, Thanks a lot for your comments. You are correct. But what I am actually stuck in is the sending packets from serial to a java program / C# program and use the data packets in some meaningful manner. Anyway thanks for the help Chris.

If your question was about a previous attempt to communicate floats in binary, that can indeed be tricky as the binary encoding of floating point values can easily be different between platforms/languages.  You'd either need to transmit a standard form supported by both, or for simplicity sake use a textual encoding.  The latter might have 3x overhead, but has the huge advantage of making your data easily monitorable with a terminal program during debug.

You may find RXTX java library helpful.
You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.
http://playground.arduino.cc/interfacing/java
Hope this helps

Thanks a lot for your answer John. I'll give it a try. Thanks a lot.

The RXTX is very standard. In fact, the Arduino IDE (on PC side) itself is written in Java, and it can communicate to the serial port (COMxx: port via USB on PC side) via the RXTX Java library (to the Arduino MCU hardware board via the USB power/download cable).


text:
Problem with interpretting and using the IMU data
I am using MPU6050 IMU for getting accelerometer and gyro data. I could read the data using the code from the I2Cdev library here, but the problem I have is that I can't use this data in a meaningful manner. As an example I want to define the motion of an object in x,y,z axis using accelerometer data. Although I get a set of values, I can't understand how to use it.
If I could convert these values to ms-2 units, I hope I would be able to achieve this
Could you provide me some advice, code or reference to work on this?
I also tried the code here to get the raw values.

Assuming it is moderately linear, you should be able to get a rough idea of the scale by aligning the device at rest until two axis read near zero and one reads a large non-zero value, which should correspond to 9.8 m/s/s gravitational acceleration.  Flipping it over would let you determine any offset error on that axis.

You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.
http://www.varesano.net/projects/hardware/FreeIMU
see demo video in which the on screen data mirror physical motion of the sensor
http://www.youtube.com/watch?feature=player_embedded&v=rFvX3vZJHTQ
hope this helps

John, thank you very much for the information. I went through some of the projects they have provided. I can get the yaw pitch roll readings too. But the issue I am having is really in the accelerometer readings. I want to map a path using the accelerometer data. Can you suggest me a way for that?

By using your said software (in original post) or getting it from inside ofthe freeimu (find out where in the code does this task), you can read the raw accelerometer data in x, y, z. You need to read the device data sheet to learn a) the range setting (says plus and minus 2g) b) the data representation. Says, for a particular device (you need specific for your chip from data sheet), reading is plus and minus 1023 for 2g. That is, for 2g, it is +1023. for minus 2g, it is -1024. That, use the scale factor to get g reading in ms-2.

see video https://www.youtube.com/watch?v=C7JQ7Rpwn2k for excellent teaching, 200k viewing, by the factory engineer. 3. What do you want to do with "map a path". In theory, ms-2 gives speed and distance by integration. In practice, it is highly error (thousands % over short time) as explained in the later part of the video. 4. Practical solution use odometer (physical wheel touching ground or camera as optical odometer) to get speed and distance and freeIMU to get roll pitch and yaw (heading and direction of movement). Hope it helps

Best data accuracy is by 9 DOF (degree of freedom) using accelerometer , gyro and magnetic compass and a software to do data fusion, like freeimu. Add GPS, for best long term error.  commercial air liners uses even more multiple sensors and data fusion.


text:
Measure square wave frequency
I'm working with the Arduino Due ans I used the following code:
// period of pulse accumulation and serial output, milliseconds
#define MainPeriod 100
long previousMillis = 0; // will store last time of the cycle end
volatile unsigned long duration=0; // accumulates pulse width
volatile unsigned int pulsecount=0;
volatile unsigned long previousMicros=0;

void setup()
{
  Serial.begin(19200);
  attachInterrupt(6, myinthandler, RISING);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= MainPeriod)
  {
    previousMillis = currentMillis;
    // need to bufferize to avoid glitches
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    float Freq = 1e6 / float(_duration);
    Freq *= _pulsecount; // calculate F
    // output time and frequency data to RS232
    Serial.print(currentMillis);
    Serial.print(" "); // separator!
    Serial.print(Freq);
    Serial.print(" ");
    Serial.print(_pulsecount);
    Serial.print(" ");
    Serial.println(_duration);
  }
}

void myinthandler() // interrupt handler
{
  unsigned long currentMicros = micros();
  duration += currentMicros - previousMicros;
  previousMicros = currentMicros;
  pulsecount++;
}

to measure the frequency.
I can measure frequencies higher than 1.5kHz accurately, but I can't seem to measure lower frequencies.
How can I measure lower frequencies, say 400Hz and above?
Thanks.

What is the output on a 400mHz wave? Just 0 and 0? Or wildly varying results?

It seems you have a problem of concurrent access to duration and pulsecount variables which are inter-related; with your code, it is possible that (and I guarantee that it will):

loop() reads duration value (in line unsigned long _duration = _duration;) but gets interrupted before executing the next line
myinthandler() changes both duration and pulsecount (it cannot be interrupted as it is already triggered by an interrupt)
loop() proceeds to where it was interrupted (after myinthandler() returns) and executes line unsigned long _pulsecount = pulsecount;: the values in _duration and _pulsecount do not match anymore!

To protect the access to pulsecount and duration variables, you have to disable interrupts inside loop() just for the time you get their values:
void loop() {
    ...
    // Disable interrupts while we get and reset duration and pulsecount
    cli();
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    // Now we can re-enable interrupts again
    sei();
    ...
}


text:
How to toggle LED on button press?
I want to have a LED turn on when I push a button and go off when I push the button a second time.
This code doesn't work:
const int buttonPin = 4;
const int motorPin =  10;
const int ledPin = 6;
 int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && x==1) {
     digitalWrite(motorPin , 1);
     x=0;
    }
  if (buttonState == HIGH && x==0){
    digitalWrite(motorPin, 0);
    x=1;
  }
  delay(1);
}

What could be wrong?

So is your LED connected to pin 6 or pin 10? You have pin 6 named ledPin but you are changing motorPin in your loop.

What's your circuit? Can you provide a schematic? Also, what is "doesn't work?" Is it lit up for any amount of time?

Reading your question I also suspect you don't have a pull-down resistor on the input pin.

At the moment, you've got two main problems. Firstly, both your if statements are being triggered one after the other. This is because the first if statement sets x to 0, which is part of the condition the second if statement looks for.
The second problem is that you're not monitoring the previous state of the button. buttonState will appear HIGH every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.
What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently HIGH, and if it was LOW last time round the loop. You also need to make sure your two if statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.
Something like this should work better:
// This will store the last known state of the button
int oldButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.

Don't forget to turn ON the LED:
digitalWrite(ledPin, HIGH);

And OFF:
digitalWrite(ledPin, LOW);

You are not handling debouncing at all. Mechanical buttons typically bounce for a few milliseconds after an "on" press. Arduino software (or some specialist hardware) needs to handle this. This really matters when you expect a button to toggle some output pin.

I just grabbed the version from the ones above here and made is somewhat smaller in terms of code. Feel free to use it in your Arduino app.
// This will store the last known state of the button
int lastButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int currentButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (currentButtonState == HIGH && lastButtonState == LOW) {
     // Switch the state of the output
     digitalWrite(ledPin, !digitalRead(ledPin));
  }

  // Store the button's state so we can tell if it's changed next time round
  lastButtonState = currentButtonState;
}

You don't need a separate variable to store the state of the LED. The output pin register does that already. So you can toggle the LED simply with
    digitalWrite(ledPin, !digitalRead(ledPin));

or if you prefer
    if(digitalRead(ledPin))
       digitalWrite(ledPin, 0);
    else
       digitalWrite(ledPin, 1);

In you code the loop executes many times while the key is bouncing. If you delay by at least 50mS after the key press is first detected, and you have toggled the led and turned on the motor, then you have effectively debounced the button. If you hold the key down continously the led will toggle every 50mS (plus a little overhead)

Pinouts, pullups and logic errors have been addressed elsewhere, so I will focus on switch debouncing.  Debouncing, in my opinion, is best handled in software (rather than hardware) for large volume production costs and lazy programmers (like me).  For small projects a simple pullup / cap circuit offers better reliability and improved speed, but I'm just lazy in my old age.  Also keep in mind that switch bounce worsens significantly over the life of a switch.  I've seen new PB's with bounce < 20 ms worsen to over 300 ms with reasonable usage, so keep that in mind with projects that become semi-permanent.
Here's what I use for a software solution on a fairly bouncy SPST NO pushbutton. In this case, I'm using NO PB to GND with 1K external pullups, since I personally don't want to depend on whether or not the internal pullup still works on older devices I may have abused in a former life.... Of course, arguments could be made for various areas still needing cleanup, improved encapsulation, quicker response, higher quality, etc., but this works for me for now.
inSw.h:
class inSw
{
private:
    volatile boolean swState;           // current state ( 0 / 1 ) of switch

public:
    uint8_t  pinNum;
    volatile unsigned long lastPush;    // Time (millis() ) when last switch push detected
    unsigned long debTime = 30;         // Time (micros() ) required to debounce switch

    void init(uint8_t sw);
    boolean readState(void);
} ;

inSw.cpp:
void inSw::init(uint8_t sw) {
    pinNum = sw;
    pinMode(sw, INPUT);
    swState = 0;
    lastPush = millis();
};

boolean inSw::readState() {
//  swState = digitalRead(pinNum);
return swState;
}
void setupSwitches(void) {
    swS1.init(I2C_SOA);     // pin D20
    attachInterrupt(digitalPinToInterrupt(swS1.pinNum), swS1Press, FALLING);
}

Interrupt Service Routines are placed outside Setup() and Loop(), with the attachInterrupt (above) called from inside Setup().  This allows the switch to break long-running routines, such as Stepper.step(10000) which bangs against the limit switch on step 14....
void swS1Press() {
    unsigned long now = millis();
    if (swS1.lastPush < (now - swS1.debTime)) { // if newly pushed
        RunStop.toggle();
        swS1.lastPush = millis();       // sw last pushed now

        if (RunStop.val == RS_RUN)
            digitalWrite(LED_PIN, HIGH);   // set the LED on
        else
            digitalWrite(LED_PIN, LOW);   // set the LED off
    }
}

Lastly, just remember to check the switch state at various points inside loop().  I use this switch as an emergency stop switch, and the onboard LED to ensure it triggers.

// When first time program launches it confused to press push button twice. Well replace it with this

if (x == 1) {
    // Toggle on
    digitalWrite(ledPin, HIGH);
    x = 0;
} else {
    // Toggle off
    digitalWrite(ledPin, LOW);
    x = 1;
}

What happens if I hold the button? Think about that.

success case tested OK,modified from arduino examples.UNO r3,atmega 328
try it !!!!!
/*  The circuit:
  - pushbutton attached to pin 2 from +5V
  - 10 kilohm resistor attached to pin 2 from ground
  - LED attached from pin 13 to ground (or use the built-in LED on most
    Arduino boards)
*/

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 8;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  // turns on the LED every four button pushes by checking the modulo of the
  // button push counter. the modulo function gives you the remainder of the
  // division of two numbers:
  if (buttonPushCounter % 2 == 0) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
}

check this code. I have made some changes in your code. its working.
const int buttonPin = 2;
const int motorPin =  6;
const int ledPin = 13;
int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  Serial.begin(9600);
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);
//  Serial.println(x);
  if(buttonState == LOW && x == 1)
  {
    Serial.println("buttonState == HIGH && x == 1");
    digitalWrite(ledPin, HIGH);
    delay(500);
    x = 0;
    Serial.println("x == 0");
  }
  else if (buttonState == LOW && x == 0)
  {
    Serial.println("buttonState == HIGH && x == 0");
    digitalWrite(ledPin, LOW);
    delay(500);
    x = 1;
    Serial.println("x == 1");
  }
  delay(1);
}

hello sachleen try this code it working I edited from your code
// This will store the last known state of the button
const int buttonPin = A15;   // change as per your button attached.
const int motorPin =  12;   //
const int ledPin = 13;
 int x = 1;
// variables will change:
int buttonState = 0;
int oldButtonState = LOW;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

Rahul, next time please select your code, and press Ctrl+K to indent it 4 characters. That way it displays better on the page.


text:
How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?
I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer  as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.

The magnetometer will be very difficult to use because you have no idea what the local magnetic field will look like around the user.
The gyroscope can help you keep track of angular orientation data during accelerations, but unless you know exactly how this is going to be attached to the human it will not help because you cannot orient the relative angles to the subject. A person can fall with or without rotating in the air as well, so I don't see it helping much anyway.
Kalman filters are great, but overkill; you are not doing inertial navigation over long distances, so don't bother. Simple averaging will suffice.
The accelerometer should be able to detect falls by itself. The only way it will ever "Zero out" is in freefall, and if that zeroing is long enough and then followed by a very hard acceleration against the direction of gravity (the crash) you can call it a fall. Unless the person has some kind of engine to produce thrust, or is going so fast air resistance is a factor, there will be no accelerations in the air. Simplely calibrating of the threshold for being in freefall, the time necessary to call it a fall, and the necessary strength of the following crash should be able to detect falls or jumps with almost no false positives.
For instance if you want to track short falls where the object is never fully off the ground, a large dip in acceleration data will still be seen, so just set the "zero" threshold high.

Such system, some even has airbag, has been around in university/research/papers for many years.  Presumably, falling means a marked change in 'data values'. One can easily log some data (accel and gyro) by falling on bed and plot the values.
May you find some inspiration in followings
http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0CEMQFjAC&url=http%3A%2F%2Fcourses.daiict.ac.in%2Fmod%2Fresource%2Fview.php%3Fid%3D2430%26redirect%3D1&ei=Ls_WU5-cOob_8QW3v4KoCA&usg=AFQjCNEDUyJKTNYFCi71rX13RMlxoHL8kg&bvm=bv.71778758,d.dGc
https://www.google.com/search?q=human+fall+detection+system&safe=off&tbm=vid&source=lnms&sa=X&ei=ps3WU6jGMYyE8gWxo4LYCA&ved=0CAoQ_AUoAw&biw=1577&bih=800&dpr=1#q=elderly+fall+detection+airbag&safe=off
Hope it helps


text:
How do I proceed with a fall detection sensor?
I am working on a human fall detection system using accelerometer and gyroscope which raises alarm in case of a fall. In all the papers I have read people have used net acceleration magnitude and compared it with a threshold and coupled it with change in orientation to detect fall. My question is would it be better to use acceleration in z-axis(normal to earth's surface) and compare it to threshold as compared to net acceleration as it might reduce false positives as net acceleration can exceed threshold in case of running but that won't happen if i take only acceleration in z-axis. Is my approach right?
How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

When's the last time you had something fall right along its Z axis?

What i meant was that using gyroscope values i will try to get the acceleration in original axis.And i wish to use that z-axis values.Rotating the axis.

Find the derivative of acceleration over time, also known as jerk. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.


text:
Cannot read from 2 I2C slaves consecutively
I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.
I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.
Master:
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.println("Reading from slave 1 now..");
  //Wire.beginTransmission(BLUNO_SLAVE);
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  //Wire.endTransmission();
  Serial.println("Reading from slave 2 now..");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
}

void loop () {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

Slave 1:
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x09);  //slave address
  Serial.println("Serials initialized");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  Wire.write("received master's request");
}

Slave 2:
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x0A);  //slave address
  Serial.println("initialized!");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  delay(60000);  //60 * 1000 = 60 seconds
  Wire.write("Lat: 103.123456, Lon: 1.098765");
}

Output on the master:
Initialized as Master
Reading from slave 1 now..
Reading from slave 2 now..
Lat: 103.123456, Lon: 1.098765

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.
I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference
that each call to the requestFrom() method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:
#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.print("Slave 1: ");
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  readData();
  //each call to requestFrom, RESETs the read buffer index
  Serial.println();
  Serial.print("Slave 2: ");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
  readData();
}

void loop () {
}

void readData () {
  while(Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
 }
}

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?

Using delay inside an interrupt routine isn't adviced. Try using delayMicroseconds(60000000). Also from reading the documentation, you only need to call Wire.onRequest(returnData); once, so you should move that to the setup routine.

@Gerben When I implement delayMicroseconds(60000000), it just hangs there. It does not write to the master at all. Even if I changed it to just delayMicroseconds(10), it does not write to the master.

Slave also cannot execute any codes inside a for loop.

I'm not sure I2C even allows extended pauses during communication. Maybe it just times-out.

I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.
And don't forget the "volatile" keyword for your semaphore.


text:
arduino boot loader problem
I am using atmega 328pu instead of atmega328p-pu. I am trying to upload the bootloader using AVR pocket programmer.
I have changed signature from 0x1e 0×95 0x0F to 0x1e 0×95 0×14.
(Relevant link)
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

How about removing the screendump from the question and pasting the text from the screen in your question so we can actually read it?

@jippie larger image

@Gerben why would I download a 52kB image for under 100 bytes of text? It is less effort to copy the text in the first place and not a single search engine will be able to index the question properly, rendering the question useless for future visitors.

Have you set Tools -> Programmer to AVR ISP?

(Note for the Arduino Uno: you'll need to add a 10 uF capacitor
  between reset and ground.)

From http://arduino.cc/en/Tutorial/ArduinoISP

The cap is only needed on the UNO that is used as the ISP. Where in this case there is a "avr pocket programmer"

It sounds as if you are using the Arduino IDE to "Upload using Programmer". If so; in the preferences enable Verbose output for upload. From this you should see all of the avrdude output. Not just the error message. Hopefully with this you will see signature of the chip you actually read. You will also see the full and exact avrdude.exe command that is being executed. Note the path/filename of the avrdude.conf, to ensure it is the one you changed.
Using this you can attempt it manually, and tweak it. Try adding the -F to it. Or execute the equivalent to :
avrdude -b 19200 -p atmega644p -C avrdude.conf -c stk500v1 -P COM4 -n

where the "-n" is "Do not write anything to the device." just read the signature.
I prefer to use a GUI in front of avrdude. Yuki's GUI is a good example. Just need to point it to the EXE and have a copy of the conf file in the same directory.

I should mention the Arduino way of doing this, is to create a new boards.txt file with this chip and add (not change) the avrdude.conf file. This will allow programing either from selecting the correct board. but that is another subject.

This sounds like the programmer is not seeing the ATMega328 MCU, or the Arduino IDE is not seeing the programmer. Changing the signature won't be of any help as the IDE (or AVRDude) is not seeing the ATmega328.
I would suggest that you double-check your connections, and set the options in the IDE to verbose output - then repost the info here.


text:
Arduino Control over the internet
I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:

User goes to example.com/arduino_switch
Interacts with an HTML form to toggle an action
Sends the data over the Internet (This is the part I have problem understanding)
Arduino receives the data point (how can we do this? polling a url or can we actively send it)
performs the action (easy to do for me)

Any and all help will be appreciated, even if its just pointing me to the right resources.

Check out Xively. You should be able to get something up and running with minimal effort. They have Arduino libraries and example code.

Sounds like a good solution, but I was looking at less of a platform(they tend to have a magical black box approach ) :D.

No problems. There are open source projects, but probably overkill. Are you going to use an ethernet board? A lot of people use Heroku and there are quite a few Arduino examples. As for sending stuff over the internet. Unless you can get a public IP for the Arduino, polling is probably the best bet. Check out the HTML GET, POST and PUT messages.

kiwiron has a great answer, but I have a few things to add:

You don't have to risk security... you can create a VPN to your network or you could just stay inside local LAN. It's just if you want to access it from outside
If you can't get a static IP for your network from your ISP, you can use something like No-IP to give you a name like example.no-ip.biz that's easier to remember and it will change the IP when your IP changes. I've used them before...
A Raspberry Pi might be a good partner in crime to work with the HTTPS connection with a web server like Nginx and with PHP to run a script. I personally like the Arduino better for interfacing with the actual components since it is 5V and has 40 mA per pin, but it's possible that you could use the GPIO pins on a Pi for your server. This might be a little cheaper since you can remove the ethernet shield and replace that with USB.
For the approach of polling a web server, it might be better to have the web server send a GET request to the Arduino and then the Arduino can respond ASAP.

For this, you might want to learn the basics of HTTP headers and try to figure out what goes on behind the scenes.

(how can we do this? polling a url or can we actively send it)

Assuming you're using the Arduino directly, here's roughly what would happen:

The client would request the Arduino for the content for the homepage using HTTP requests
The Arduino would send the content and close the connection
In the HTML there's a little attribute to the form that tells it to send the data via post to response.php. The client hits "submit" and it sends the data via POST to that URL.
The Arduino sees that it's sending data to that URL and reads the data and then process it accordingly. The socket is closed.

You have two choices:

The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.

I feel the first one will meet my needs well (can manage with polling every five minutes). Can you point me to any specific reading material, especially something to learn the process of communicating with a web server and publishing the server.


text:
Connection issues with TI CC3000 & Arduino Uno
I bought a CC3000 Wifi Shield from Sparkfun and attached it to Arduino Uno board.
As first thing I tested the board with the board test example:

SparkFun CC3000 - Board Test
CC3000 initialization complete
Firmware version: 1.24
MAC address: 70:FF:76:01:30:1E
Finished board test

Then I scanned the networks:

SparkFun CC3000 - Scan Test
CC3000 initialization complete
Scanning APs. Waiting for scan to complete.
Access Points found:
SSID: dnhm MAC address: 20:AA:4B:08:AA:CC RSSI: 58 Security: WPA2
SSID: dnhm-guest MAC address: 20:AA:4B:08:AA:CE RSSI: 58 Security: Unsecured
Finished scan test

I set the SSID and the password and tried to connect:

SparkFun CC3000 - Connection Test
CC3000 initialization complete
Connecting to: dnhm
Error: Could not connect to AP
Error: Could not obtain connection details
Error: Could not disconnect from network Finished connection test

SparkFun CC3000 - Connection Test
CC3000 initialization complete Connecting to: dnhm-guest
Error: Could not connect to AP
Error: Could not obtain connection details
Error: Could not disconnect from network
Finished connection test

It did not connect none of the available connections, I reserved an IP address on the router for the mac address, but nothing changed.
I turned on logs on the router (Linksys e2500) and nothing appeared in logs as if the device never tried to connect. (I can see relevant logs when I re-connect with my notebook)
I use wpa2 so I kept the security setting as it is. I also have a 5ghz SSID and it does not show up in the scan. So I did not try to connect to it.
I also tried the smart config example with my ipad and it did not work either, the output:

SparkFun CC3000 - SmartConfig
CC3000 initialization complete
Starting SmartConfig
Send connection details from app now!
Waiting to connect…
Error: Could not connect with SmartConfig
Error: Could not obtain connection details
Looking up IP address of: www.sparkfun.com
Error: Could not lookup host by name
Pinging 0.0.0.0 3 times…
Error: no ping response
Error: Could not disconnect from network
Finished SmartConfig test

Obviously the board works (It can scan/find the networks), but cant connect them. What should I do as next step to troubleshoot the issue?
Here is the sample I used for connection testing: (I double checked the protocol from router's wifi settings to make sure I'm using the correct one)
    /****************************************************************
ConnectionTest.ino
CC3000 Connection Test
Shawn Hymel @ SparkFun Electronics
January 30, 2014
https://github.com/sparkfun/SFE_CC3000_Library

Connects to the access point given by the SSID and password and
waits for a DHCP-assigned IP address. To use a static IP
address, change the #define USE_DHCP from 1 to 0 and assign an
IP address to static_ip_addr in the Constants section.

NOTE: Static IP is not working at this time.

The security mode is defined by one of the following:
WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

Hardware Connections:

 Uno Pin    CC3000 Board    Function

 +5V        VCC or +5V      5V
 GND        GND             GND
 2          INT             Interrupt
 7          EN              WiFi Enable
 10         CS              SPI Chip Select
 11         MOSI            SPI MOSI
 12         MISO            SPI MISO
 13         SCK             SPI Clock

Resources:
Include SPI.h and SFE_CC3000.h

Development environment specifics:
Written in Arduino 1.0.5
Tested with Arduino UNO R3

This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!

Distributed as-is; no warranty is given.
****************************************************************/

#include <SPI.h>
#include <SFE_CC3000.h>

// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// IP address assignment method
#define USE_DHCP        1   // 0 = static IP, 1 = DHCP

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Constants
char ap_ssid[] = "SSID";                  // SSID of network
char ap_password[] = "PASSWORD";          // Password of network
unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
unsigned int timeout = 30000;             // Milliseconds
//const char static_ip_addr[] = "0.0.0.0";

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

    ConnectionInfo connection_info;
    int i;

    // Initialize Serial port
    Serial.begin(115200);
    Serial.println();
    Serial.println("---------------------------------");
    Serial.println("SparkFun CC3000 - Connection Test");
    Serial.println("---------------------------------");

    // Initialize CC3000 (configure SPI communications)
    if ( wifi.init() ) {
        Serial.println("CC3000 initialization complete");
    } else {
        Serial.println("Something went wrong during CC3000 init!");
    }

#if (USE_DHCP == 1)
    // Connect using DHCP
    Serial.print("Connecting to: ");
    Serial.println(ap_ssid);
    if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
        Serial.println("Error: Could not connect to AP");
    }
#elif (USE_DHCP == 0)
    // Connect using static IP
    // ***TODO: Connect using static IP
#endif

    // Print out connection details
    if( !wifi.getConnectionInfo(connection_info) ) {
        Serial.println("Error: Could not obtain connection details");
    } else {
        Serial.println("Connected!");
        Serial.println();

        // Print MAC address
        Serial.print("CC3000 MAC Address: ");
        for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
            if ( connection_info.mac_address[i] < 0x10 ) {
                Serial.print("0");
            }
            Serial.print(connection_info.mac_address[i], HEX);
            if ( i < MAC_ADDR_LEN - 1 ) {
                Serial.print(":");
            }
        }
        Serial.println();

        // Print IP Address
        Serial.print("IP Address: ");
        printIPAddr(connection_info.ip_address);
        Serial.println();

        // Print subnet mask
        Serial.print("Subnet Mask: ");
        printIPAddr(connection_info.subnet_mask);
        Serial.println();

        // Print default gateway
        Serial.print("Default Gateway: ");
        printIPAddr(connection_info.default_gateway);
        Serial.println();

        // Print DHCP server address
        Serial.print("DHCP Server: ");
        printIPAddr(connection_info.dhcp_server);
        Serial.println();

        // Print DNS server address
        Serial.print("DNS Server: ");
        printIPAddr(connection_info.dns_server);
        Serial.println();

        // Print SSID
        Serial.print("SSID: ");
        Serial.println(connection_info.ssid);
        Serial.println();
    }

    // Disconnect
    if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
    } else {
        Serial.println("Error: Could not disconnect from network");
    }

    // Done!
    Serial.println("Finished connection test");

}

void loop() {

    // Do nothing
    delay(1000);

}

// Print out an IP Address in human-readable format
void printIPAddr(unsigned char ip_addr[]) {
    int i;

    for (i = 0; i < IP_ADDR_LEN; i++) {
        Serial.print(ip_addr[i]);
        if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
        }
    }
}

Could you share your sketch code? Also, are you setting the proper security mode, for the Connection Test Examples?

I added the source code into the question, it s the sample that comes with the library. I just replaced SSID and the password. I also checked & verified the security mode from router settings.


text:
Connecting Arduino Android Wirelessy
I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.
As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?

Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.
The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.
The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at the android documentation.
This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.


text:
Serial communication between PC and Arduino via RS232 using C++
I am trying to communicate with my Arduino Duemilanove via an RS232 cord. I simply want to be able to send a byte (or char) to my Arduino from a desktop application.  The Arduino is plugging into USB COM5 on my computer.  I have the RS232 plugged into COM1, and then I have pins 2, 3 and 5 on the other end of the RS232 connected to Arduino pins TX, RX, and GND, respectively.
I found a serial comm class for C++ at the following link: Arduino and C++ (for Windows)
I have added the .h and .cpp files from the above example as Serial.h and Serial.cpp (I think the example uses SerialClass.h and SerialClass.cpp, I just changes the names).

On my Arduino, I have the following code running:
// ARDUINO
char incomingByte = 0;

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

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, HEX);
        }
}

And my C++ program is the following:
// C++
#include <iostream>
#include <Windows.h>
#include "Serial.h"

using namespace std;

int main(void)
{
    Serial port("COM1");

    char* msg = "Hello Arduino!";
    int msgLen = strlen(msg);
    bool writeSuccess = port.WriteData(msg, msgLen);

    cout << "\n\n";
    system("PAUSE");
}

When I use the Arduino's serial port viewer to see what is bring printed, I'm getting very strange values that don't match what I'm sending (as far as I can tell).
When I send "Hello Arduino!", the arduino prints the following:
I received: FFFFFFAB
I received: 3A
I received: 3A
I received: A
I received: FFFFFFFA
I received: FFFFFFEB
I received: 6D
I received: 37
I received: 15
I received: 2D
I received: 23
I received: 21
I received: FFFFFFBD
I received: 0

This does not appear to be the correct hex for "Hello Arduino!", but I have no idea why it's not correct.  Does anyone have any clue what I'm doing wrong?

You cannot connect RS232 cable pins directly to microcontroller pins for two reasons.  First, the excessive voltage will likely destroy the inputs.  Second, the signals must be inverted in sense when moving between RS232 standards and logic level signals used by the ATMEGA's UART.  You need a level translator, or to replace the true serial connection with a logic-level USB-serial one.  Is there a reason you can't use the Arduino's existing USB serial interface?

Additionally the "FFFFFFFA" most likely comes from sign exstension when a mistakenly-signed byte value is implicitly converted to a larger int type. Declare your variable unsigned char instead.

@ChrisStratton The only problem with working with the existing USB serial interface is I cannot figure out how to send data through USB using C++.  It was trivial to learn how to send data through RS232, but I can't find any info on doing it through USB.  Additionally, wouldn't there be a conflict if I tried to have one program writing COM5 while the Arduino's terminal was viewing COM5?

The existing USB interface emulates a serial port, so you would use the exact same serial APIs, and simply a different port name (whichever one you use for downloading sketches).  Also make sure to close the Arduino serial monitor before you try talking to it from your program.

You don't send it through USB, you send it through the virtual COM port.

@ChrisStratton i didn't realize that...well thanks! That did exactly what I was hoping!

It because that in your c++ application you haven't explicitly mentioned serial port speed.
Mention the same baudrate which you have used in arduino here(c++).
Assuming that you have used rs232 to ttl converter, as you are getting some output,
Which in other case wouldn't as you would have already burned your mcu.

You need some voltage converter between arduino and pc. PC uses "real" RS232 and arduino uses TTL level RS232. Check more in this site. You need something like this RS232 to TTL.