text:
Arduino shield stacking
I have an Arduino GSM Shield mounted on an Arduino Uno. Can I stack this GPS shield above Arduino GSM shield? Will there be any pin configuration problem?
In GSM Shield hardware pin’s configuraton are as below:
0 - Not connected
1 - Not connected
2 - GSM Rx
3 - GSM Tx
7 - Modem reset

If there is any problem, how can it be solved? I would be happy if there are any alternatives for the GPS shield.

Addendum
The schematic of the Arduino GSM shield:

The schematic of the SparkFun GPS shield:

Start by finding the circuit diagrams of both shields and lining them in your question.

According to the GPS shield quick start guide (https://www.sparkfun.com/tutorials/173), it seems possible to select different pins for serial communication than the default ones (2 & 3) that conflict with yout GSM shield. So that should be OK.

@jippie - I've added the schematics

Photo by John Boxall
Which pins do they use?
To determine if two shields are compatible, you have to read the specifications of both shields.
The best source for this information is the data sheets supplied with the shields. However there is also this Shield List
Can you reassign pins?
Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).
Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.
here is one example:

You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Are any alternatives for the foo shield
I notice that Arduino.cc now point people to the list referenced above. They used to have their own list.
Product recommendations are off-topic here but, obviously, you can search

+1 for the link to Arduino shields references, and for the go-between shield as a generic solution to this kind of issue. However, in this specific case, a go-between shield seems useless as the GPS shield allows changing the TX/RX pins (2 & 3 are just the default pins) quite simply.

@jfpoilpret: Good point. I'll update answer.

From the shield description, the TX and RX of the GPS are mapped on pins 2 & 3, like your GSM, so you'll have to change that.
I'm using Adafruit GPS + flash card shield, which is a bit cheaper (and uses pins 7&8).

But my GSM shield uses pin 7 uses modem reset. Will It create any problems by placing GPS shield on the GSM shield ?

Yes, very same thing. Depending on what you want to do, why not use a breakout plugged on a breadboard ? You'll be able to choose pin assignment.

This answer does not directly address the pin conflict issue, but rather skirts around it.
I have been looking into this same issue for over a month now and have come to the conclusion that the best option is to either purchase, for around $30:

or make, for around $20 (+$60 for the modules)

a shield that uses the SIM908. The SIM908 comes with both GPRS/GSM functionality, and GPS functionality, whereas the SIM900 only has GPRS/GSM. Now, there is no longer an issue with pin conflicts, as instead of two separate shields, only one is required.
The only disadvantage is that if you already have a GPRS/GSM shield, then that purchase will become redundant.
As an aside there is an alternative of a 3G (WCDMA and HSPA) and GPS, using both assisted-mobile (A-GPS) and mobile-based (S-GPS) modes, combined shield, from Cooking Hacks. A bit more pricey though, at $160.


text:
client.connect() fails except the first time
I am communicating with the Web server's database via Arduino GSM shield + GPRS connectivity
void loop()
{
  if (client.connect(server, port))
     {
       .......
      }
  else
     {
      Serial.println("Server not found");
      }
  delay(1000);
}

The first time when the loop() runs in the serial port, the code works perfectly and stores in my server's db. The second time when the loop() runs after some delay, It is unable to connect to the server and results "server not found" . I don't know what is the problem.
Please let me know if there is a way to connect continuously. Thank you

You need to provide a bit more information in your question: what is client? How has it been initialized? In which library (header file name and link to library) is it defined? Also, it might be interesting to describe what you do (not necessarily with all the code, it depends how much that is) in the the first block of the if (...) statement.

Welcome to Stack Exchange! I've noticed that in two of your three questions on the site are "cross posted" with Stack Overflow. Those are both closed. Next time if it's closed, flag for a moderator to "migrate" it to a different site if they feel fit. Thanks!

You have to disconnect before being able to connect again otherwise the controller will crash due to memory starvation. Every connect you do takes some memory to register state information. Not sure of the exact commands involved, but it'd look a bit like this:
   if (client.connect(server, port))
     {
       .......
       client.disconnect( .... );
      }
  else
........

Alternatively you can check if you are already connected, and only do a reconnect when necessary, but I don't know which library you are using, let alone if there is a proper check available in it.

void loop()
{
 if (client.connect(server, port))
 {
   .......

   client.stop();
  }

 else
 {
  Serial.println("Server not found");
  }
 delay(1000);
 }

Can you please add some explanation to this code? Thanks!

Are you sure about the closing } before the client.stop?

Sorry, Its mistake in the code. It will be inside the parenthesis .. Thanks for correction i have updated the code..

If possible, do a check, if it's still connected with the server. Close the connection when work is done. You might also keep using the open connection, just try whatever works best for you.
But avoid opening a second connection, when you still have an open one. As an example:
void loop()
{
    if(!client.connected())
    {
        if (client.connect(server, port))
        {
            ...
            client.disconnect();
        }
        else
            Serial.println("Server not found");
    }
    else
        client.disconnect();
    delay(1000);
}

source: Stack Exchange

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

sort: votes


text:
Playing audio files with sine wave from arduino
So, when searching for a way to play audio files through the Arduino, I came across this site: How to play WAV audio files with Arduino Uno and MicroSD card
This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?

The library works fine, and you'll find details from the developer of the PCM audio library here.

http://playground.arduino.cc/Code/PCMAudio

I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.
It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)
From GitHub's wiki:

All 328 based boards: Arduino Uno, Nano, Duemilanove, etc
Mega Types: 1280, 2560, etc
No Due support currently.

You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).
Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.
Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.

Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.

If you want to take a look, go to this page for more informations on the advanced features
A last thing that I have to say is that the functions are really straightforward:
TMRpcm audio;
audio.play("filename");    plays a file
audio.play("filename",30); plays a file starting at 30 seconds into the track
audio.speakerPin = 11;     set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc.
audio.disable();           disables the timer on output pin and stops the music
audio.stopPlayback();      stops the music, but leaves the timer running
audio.isPlaying();         returns 1 if music playing, 0 if not
audio.pause();             pauses/unpauses playback
audio.quality(1);          Set 1 for 2x oversampling
audio.volume(0);           1(up) or 0(down) to control volume
audio.setVolume(0);        0 to 7. Set volume level
audio.loop(1);             0 or 1. Can be changed during playback for full control of looping.

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


text:
arduino 16u2 stk500v2_command(): command failed
I'm trying to fix arduino uno r3 that was burned-out.
I changed m16u2 chip on it. and now I need burn in:  Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
I'm using stk500v2 and connecting it to isp of arduino. Output log file of avrdude:
C:\>avrdude -c stk500v2 -P COM4 -p m16u2 -U flash:w:1.hex -vvvv

avrdude: Version 6.1, compiled on Mar 13 2014 at 00:09:49
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v2
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
avrdude: Recv: . [1b]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [0b]
avrdude: Recv: . [0e]
avrdude: Recv: . [01]
avrdude: Recv: . [00]
avrdude: Recv: . [08]
avrdude: Recv: A [41]
avrdude: Recv: V [56]
avrdude: Recv: R [52]
avrdude: Recv: I [49]
avrdude: Recv: S [53]
avrdude: Recv: P [50]
avrdude: Recv: _ [5f]
avrdude: Recv: 2 [32]
avrdude: Recv: t [74]
avrdude: stk500v2_getsync(): found AVRISP programmer
         AVR Part                      : ATmega16U2
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC6
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           eeprom        65    20     4    0 no        512    4    128  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           flash         65     6   128    0 yes     16384  128    128  4500  45
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           hfuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           efuse          0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           lock           0     0     0    0 no          1    0      0  9000  90
00 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           calibration    0     0     0    0 no          1    0      0     0
 0 0x00 0x00
                                  Block Poll               Page
      Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  Max
W   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ---
-- ---------
           signature      0     0     0    0 no          3    0      0     0
 0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel STK500 Version 2.x firmware
         Programmer Model: AVRISP
avrdude: Send: . [1b] . [02] . [00] . [02] . [0e] . [03] . [90] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [02]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [15]
avrdude: Send: . [1b] . [03] . [00] . [02] . [0e] . [03] . [91] . [86]
avrdude: Recv: . [1b]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [14]
avrdude: Send: . [1b] . [04] . [00] . [02] . [0e] . [03] . [92] . [82]
avrdude: Recv: . [1b]
avrdude: Recv: . [04]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: . [0a]
avrdude: Recv: . [1b]
         Hardware Version: 2
         Firmware Version Master : 2.10
avrdude: Send: . [1b] . [05] . [00] . [02] . [0e] . [03] . [94] . [85]
avrdude: Recv: . [1b]
avrdude: Recv: . [05]
avrdude: Recv: . [00]
avrdude: Recv: . [03]
avrdude: Recv: . [0e]
avrdude: Recv: . [03]
avrdude: Recv: . [00]
avrdude: Recv: U [55]
avrdude: Recv: E [45]
         Vtarget         : 8.5 V
         SCK period      : 0.1 us

avrdude: Send: . [1b] . [06] . [00] . [0c] . [0e] . [10] . [c8] d [64] . [19]
[20] . [00] S [53] . [03] . [ac] S [53] . [00] . [00] 5 [35]
avrdude: Recv: . [1b]
avrdude: Recv: . [06]
avrdude: Recv: . [00]
avrdude: Recv: . [02]
avrdude: Recv: . [0e]
avrdude: Recv: . [10]
avrdude: Recv: . [c0]
avrdude: Recv: . [c1]
avrdude: stk500v2_command(): command failed
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude: Send: . [1b] . [07] . [00] . [03] . [0e] . [11] . [01] . [01] . [00]
    avrdude: Recv: . [1b]
    avrdude: Recv: . [07]
    avrdude: Recv: . [00]
    avrdude: Recv: . [02]
    avrdude: Recv: . [0e]
    avrdude: Recv: . [11]
    avrdude: Recv: . [00]
    avrdude: Recv: . [01]

    avrdude done.  Thank you.

My question is what block with error does? can it be I shorted due soldering? or maybe burned chip? any issues? how I can check?
ps. programmer works perfect. checked!

All I can tell from this log is that communication with the MCU does not work at all, i.e. it fails on the very first command sent to it (all the preceding communication is with the controller).
There could be numerous causes for this (chip rotated by 90 degrees, etc). I would start by attaching a logic analyzer to the MISO pin and see whether there are any wiggles there at all.

One important question to be sure: Arduino UNO has 2 ISP connectors, one for the ATmega328, and one for ATmega16u2 (used for USB connection); are you sure you are connecting to the 2nd one?

yes i'm sure. its connected to ATmega16u2. @microtherion does the sended bits and received bits must be same?

@Klasik it’s a bit beyond the scope of a comment to explain, so I’ve made it an answer.

Here’s a decoding of the crucial pair of messages exchanged here. Protocol is documented on Atmel’s site.
Your machine sends:
[1b]                              Beginning of message
[06]                              Message sequence number
[00] [0c]                         Message body length (big endian)
[0e]                              Beginning of message body
[10]                              Command: CMD_ENTER_PROGMODE_ISP
[c8] [64] [19] [20] [00]          Various programming parameters
[53]                              Response value to look for
[03]                              Response index
[ac] [53] [00] [00]               Enter programming mode command
[35]                              Checksum

This causes the programmer to send the 4 bytes 0xAC 0x53 0x00 0x00 to the MCU, and look for the value 0x53 in the third of the 4 response bytes, as specified on page 260 of the data sheet. However, the programmer answers:
[1b]                              Beginning of message
[06]                              Sequence number (matches message previously sent)
[00] [02]                         Response body length
[0e]                              Beginning of response body
[10]                              Command: CMD_ENTER_PROGMODE_ISP (Matches message)
[c0]                              STATUS_CMD_FAILED (This is the error message)
[c1]                              Checksum

That means that tyne very first command sent to the microcontroller “failed” (most likely by not returning the expected answer byte).

is it called post code or something?

I'm afraid I don't understand your question, @Klasik.

how thous codes called? )

Btw. the solution was resoldering SMD.


text:
Using 3.3V XBee with Arduino Pro Mini 5V Version
The Xbee requires a 3.3V power input and the Arduino Pro Mini (5V version) only provides a regulated 5V.
Question: What will be the simplest way to provide a 3.3V rail to the XBee from the Arduino Pro Mini?
If we use a voltage divider consisting of 2 resistors, the ratio should be 66/100, but how do we choose the resistor values?
If we choose a 3.3V voltage regulator, will the STMicroelectronics L78L33ACZ be suitable?

Between the voltage divider and voltage regulator, which is the preferred method? Is there a better alternative?

There is a second part to this - does the XBee talk to the Arduino? Connecting a 5v device to a 3.3v device requires a level shifter to protect and interface between the different voltage devices. While both power and IO can be interfaced using simple voltage divider resistors - personally I recommend regulating the 3.3v supply and using a simple MOSFET level shifter for IO. If you update the question for this, I can post a relevant circuit to accomplish both.

@RonJ. Yes XBee is communicating with Arduino. How can you use the MOSFET level shifter for IO? Will be great if I can have a look at your circuit :)

Is there any particular reason that you need a 5V Pro Mini? If not, then it would be much more appropriate to use a 3.3V Pro Mini in its place.

This is part of a Fritzing circuit I used to control the x'mas tree lights (the relays and sensors have been snipped out) with an XBee. This circuit uses a 3.3v LDO you may have to change the capacitor values depending on your regulator specs. I chose to use a separate 5V regulator (not shown) but it will work off the Pro Mini's +5V power rail.
There are two FETs that do the actual level shifting, the bonus transistor allows you to reset the Arduino and thus gives you the ability to program it over the air via the XBee (beyond the scope of the question, but if you want to go wireless, go wireless all the way - do the Google for wireless programming over XBee if needed). Note the 0.1uF across the XBee power pins, I recommend this capacitor be placed as close to the XBee as possible to minimize noise (I solder it across the back of the XBee interface board).

In what ways can noise across the XBee's power inputs affect it?

@Nyxynyx I don't remember exactly where it was specified, may have been in the XBee datasheet. The XBee is after all a 2.4GHz transceiver, and electrical noise [could] [may] disrupt communications. A 3 cent disc capacitor certainly doesn't hurt things.

You can use a voltage regulator to get the supply voltage down to 3.3v.
For the Serial Lines, the best way forward is to use a good level convertor like https://www.sparkfun.com/products/11978 from sparkfun.
If you don't want to buy it, you can also make it using a couple of Mosfet's and resistors. Here's the schematic from Sparkfun.

Please do not link to external content.  When the URL become invalid, this answer becomes useless.

The simplest way, as you ask, is probably a resitor-based voltage divider; its main drawback is the waste of energy in the resistors.

To calculate the "best" resistor values, you'll need to know the amount of current needed by the XBee module.
So you have:

Vin = 5V
Vout = 3.3V
Iout = to be determined (check XBee spec sheet for that)

Then you have to resolve the following equations to calculate the resistor values you shall use:
R1 = R2 x (Vin - Vout) / Vout
Iout = (Vin - Vout) / R1 - Vout / R2

These equations simply come from applying Ohm's law and Kirchhoff's circuit laws.
This site calculates the ideal resistor values for you.
For Iout = 100mA, it gives the following values:

R1 = 17 Ohm
R2 = 33 Ohm

Another simple way is to use a 3.3V zener diode if you have one on hand. You can google for good circuit examples.


text:
Figuring out some numbers for a mini pump
I'm just now getting into electronics (I don't know why I waited so long) and I'm just figuring out some stuff.  I picked up an Arduino kit from Vilros.com and a few other parts for my project.
I'm currently trying to work on a project that is basically a humidor keeper.  Living in So.California, it's extremely dry here and I would like a perfectly controlled environment for my humidor.  I purchased a few things like some humidity sensors (as an input obviously), a humidifier (basically a water canister with a sponge and tubes) some tube splitters and twist valves and most importantly, a small air pump.
The small air pump is what I'm having problems with at the moment.  This is the pump. Obviously it's a 3v pump.  I will be using the supplied 9v battery cable when the project is ready, so I understand I'll have to use resistors to bring the voltage down so I don't burn out the pump.  As I said, I'm new to this, so I'm trying to figure out ohms law to find out what kind of resistor(s) I will need.  The problem is, I don't know the amperage.  Where would I find this?
I looked at the details for the pump and what looks like amps (or milliamps) is really just the product number.  Can anyone help me out?
Right now, I have my equation as r=6v / ?i  But where do I find the current?

The current used by a motor can vary. Normally the motor's datasheet would give you typical values. But in any case you don't want to use a voltage divider for this.

There are two serious problems with your approach, which you will need to change in order to end up with a sound solution.

If by "9v battery cable" you mean that you intend to use a 9v battery, this is highly unsuitable for motor applications given its low power storage capacity and high internal impedance - without extreme care to use sleep modes, it probably can't even run the Arduino alone for a week.  It would be much more appropriate to use a larger capacity lower voltage source - 4 or 5 C or D cells for example.  A power supply could be another option, though given the water involved, be very careful to pick an isolated one and use a ground fault protected outlet.
Resistors are a poor way of reducing the supply voltage to a motor, as they are not only wasteful, but the applied power will depend too much on the load.  A professional solution would use pulse with modulation to apply the supply voltage at a reduced duty cycle - something you can try with one the various motor shield, but you will need to be careful not to overheat the motor by using too high a duty cycle.

Probably your best bet would be to buy a pump with a 6 or 7v motor (as is showing up in the associated products at the bottom of that page), or even replace the standard-form-factor motor in that pump with a higher voltage one.  A 7v or so supply voltage can then be a compromise solution for running both the motor and the arduino.

Great post! So much to say, but so few characters! Luckily, I purchased a 6v air pump before I purchased the 3 (the 6v shipping was going to take forever) so I will use the 6v instead.  I didn't even connect the dots on the PWM spots, I will look into that instead.  I'm not sure of the amperage, so I'm not sure how long this system would last even with larger mAh batteries.  I see someone said the Arduino draws about 25mA while running code.

You can reduce the current consumption of the processor by using sleep mode and only occasionally waking up to monitor, using the internal RC oscillator or at least a clock divisor, etc, however this may be tricky to do when using the arduino libraries.  Additionally, other components on the board including the regulator may waste power.  Make sure you never leave a signal driven against a pulling resistor.  If you ultimately go with batteries you may want a custom board with a low frequency clock, low quiescent current regulator, and no onboard communication interface.

all great points.  I guess I just want to do this as a prototype (as the Arduino is supposed to be used) and then find someone to flash a chip/board for me for this purpose alone.  Is that reasonable as well?

Doing a simple proof of concept before chasing battery life can be worthwhile, yes.  There is some risk of boxing yourself into a corner it will take work to exit if you ultimately want to run on batteries, but re-implementing things a second time based on lessons learned will obviously take less time than the first attempt.

Unlike voltage, which depends on the source, the current depends on the motor itself. To find the current, you need to run the motor and measure it with a multimeter:
              +------------+
    +---------+ Multimeter |
    |         +--------+---+
+---+---+              |
| Motor |              |
+---+---+  +--------+  |
    |      | Power  +--+
    +------+ source |
           +--------+

Note that when the motor is actually pumping, it will draw more current.

It also depends on how the motor is running. The more torque the motor is exerting, the more current it needs.

Aah I see. Luckily it's just an air pump so when the motor is pumping, it should be at its highest needs.  A friend told me about a DC power supply that is variable, so I could run it at 3v and measure the current from there without risk. Would this be the same thing?

@ntgCleaner I think that would work.

It will be at its highest needs when blocked. Put a circuit breaker between the full speed and blocked currents so that you don't burn out the motor.

good call! I purchased a DC variable power supply (1.5-15v) from Tekpower.  Whether I need it or not for this project, I'm sure I'll be able to use it sometime!


text:
If I put a shield on an Arduino, can I use the Arduino for anything else?
I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.
So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?
Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?

Normally, yes, you may plug other components to your setup after you plug your shield, but it depends on the shield exposing the unused Arduino pins through additional female headers.
Some shields even provide a little protoboard or perfboard to make it convenient for plugging or soldering additional components. Below are some examples:

Arduino shields are normally designed to be stackable, so you can plug one on top of the other. See more on Arduino shields from this WikiPedia article. See below one example of stacked shields, shamefully stolen from this great answer by RedGrittyBrick.

Photo by John Boxall
But note that you need to study carefully what pins each of the shields use to avoid conflicts between the boards. Such conflicts may lead to damages.

There are several distinct concerns to consider:

Physical interference: are headers provided to make it possible to stack the two shields on top of one another?  Do any protruding components block stacking?  Do any components have metal shield cans (for example the USB connector on the Uno itself) which can short out an adjacent PCB?
Pin assignments: generally you cannot use the same pin for two different purposes.  Many shield provide a way to alter the pins used in order to avoid those used by another shield.  Sometimes you can share a pin, for example two SPI devices can usually share their clock and data lines provided they have separate selects, and you may be able to even use those signals for other purposes while the SPI select is de-asserted.  Sometimes you can move a part from an unavailable hardware peripheral to a software emulated one, for example using software serial, bitbang SPI, or interrupt based PWM.
MCU resources: Not specifically the shields themselves, but driver libraries may end up consuming large amounts of program memory or RAM, using up timer channels, needing interrupts frequently services with low latency, etc, so combinations may not be possible or may require alterations to library code.

As long as the shield uses stackable headers (or provides alternate headers) it doesn't block any (broken out) pins, either input or output. It is possible to add more shields or components, but the circuit must still be "valid" (all inputs must be either be connected to an output or have the pullup enabled, no more than one push-pull output connected together, etc.), otherwise components may be damaged.

Yes, but sometimes it interferes with the output and the input pin, and most shields use up the
CS, MOSI, MISO, SCK pin. Even through on some shields like wireless SD shield you can switch from USB to MICRO, this is going to interfere with your program. Say, when you want to access
the info on your SD card to run your Motor Shield.


text:
How to receive data from my server database to a variable in my Arduino?
I am learning to work with the client - server communication. I am able to communicate with my server and able to store values in the table. But I want to receive one of the specific data from the database.
Here I want to get the 'abc' value from the 'Current' column to store in a variable in my Arduino.
Below is the code that I have done until now. I would be really happy if you could solve the problem.
Here is my database structure
---------------------------------------------------
| Device |  Previous |  Next |  Distance |  Current|
---------------------------------------------------
|katup123| xyz       | abc   | 2.600     | abc     |
---------------------------------------------------

Here is my PHP code:
locator.php
<?php
$con=mysqli_connect("your_domain.com","peter","abc123","locate");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Current FROM locate WHERE Device='katup123'");

while($row = mysqli_fetch_array($result)) {
  echo $row['Current'];
  echo "
";
}
?>

Here is my Arduino code:
// Include the GSM library
#include <GSM.h>
#define PINNUMBER ""
// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APNgpsll
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password
// initialize the library instance
GSM gsmAccess;
GSMClient client;
GPRS gprs;
// URL, path & port (for example: arduino.cc)
char server[] = "your_domain.com";
char path[] = "/locater.php";
int port = 80; // port 80 is the default for HTTP

void setup() {
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;
  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected) {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) & (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("connecting...");
}

void loop() {
  char result [20];
  Serial.print(" Connecting to server Database ");
  if (client.connect(server, port)) {
    client.print("GET /locator.php?");
    Serial.print("GET /locator.php?");
    client.println(" HTTP/1.1");
    Serial.println(" HTTP/1.1");
    client.println("Host: www.your_domain.com");
    Serial.println("Host: www.your_domain.com");
    client.println("User-Agent: Arduino");
    Serial.println("User-Agent: Arduino");
    client.println("Accept: text/html");
    Serial.println("Accept: text/html");
    client.println("Connection: close");
    Serial.println("Connection: close");
    client.println();
    Serial.println();
    Serial.println("\nCOMPLETE!\n");
    client.stop();
  } else {
    Serial.println("connection failed");
    Serial.println("\n FAILED!\n");
  }
  delay(5000);
}

Here I want to store the 'abc' value to my 'result' variable. I don't know how to do it.

To get data from a webserver to the arduino, just make a hph or html page with the value written on the page. That way you can get the value from the webserver by requesting the page and then use the value in your code. Since you already have the submit done, just make another page that writes out the value from the DB.

After you send the GET request, you read the response to fill the char result [20] variable you declared:
int i=0;
...
if (client.connect(server, port))
{
  client.print("GET /locator.php?");
  ...
  Serial.println("\nCOMPLETE!\n");

  // Read response from server
  i=0;
  while (client.available())
  {
    result[i] = client.read();
    Serial.print(result[i]);
    i++;
  }

  client.stop(); // disconnect
}

This is an example, result will contain the text output by locator.php. You will need to tweak this code to apply to your case. The above code has no error checking of any kind. Also, you should perform a check and only make the web call one time.
In locator.php you should replace echo "
"; with echo "\n";. And for good measure, make sure there is no white space before <?, and remove the trailing ?>.

If you have your Arduino on tcp/ip your answer can be found in O'Reilly's Arduino Cookbook: Recipe 15-4.  As Sourcery mentioned you need to make a new page on the PHP side that spits out just the data you are looking for and then use a web client on the Arduino side to download that data.
If you don't have your Arduino on the network then you have to stick the data over the serial line.  One way would be to bake it into your source and recompile/reburn the Arduino.  A smaller hammer would be to build-in something to your Arduino sketch that can deal with getting the data via USB serial and have a shim on the computer side to pull the data from PHP and send it to the Arduino.  Serial communication with Arduino and Processing shows something similar where he is running Processing on the computer which is passing data to the Arduino.

the first link is for authorized users only, and the second is a 404.

I fixed the second URL.

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


text:
Can I speed up the Leonardo bootloader?
Inspired by an example question before beta, can I make the Leonardo bootloader take less that 8 seconds to run? It is very slow and I want to speed it up somehow.

Can you give us more details about your development environment (IDE you use). Did you burn the bootloader yourself, or did the board came with the bootloader already loaded? Do you have a link to the bootloader code on the net? Also, do you know if this delay is normal of all Leonardo boards? Because 8s seems to be an awful lot of time for a dev board to boot.

It's the default IDE (this wouldn't make any difference, but OK), and i used the stock bootloader that came with the board.

What version of the official Arduino IDE? I'm trying to determine the exact bootloader code base. But it won't be helpful because the bootloader you're using didn't come from your IDE. Since it came installed from factory, we may never know which one it is. The only hope is for you to burn the bootloader from your IDE into the board and report the same delay. If you decide to do it, just beware of what you're doing.

Or someone may give it a try and post an answer assuming one given version of a given bootloader out there. It's possible, but not optimal.

Are you talking about the time it takes to flash a new sketch with the bootloader, or a boot-up delay on reset before an already flashed sketched starts running?

@ChrisStratton the boot up delay

Yes, you can shorten the value of TIMEOUT_PERIOD in caterina.c - see  http://www.leonardomiliani.com/2013/accorciamo-i-tempi-del-bootloader-della-leonardomicroesplora/?lang=en But beware that a shorter value may make it harder to recover if you load a sketch that breaks the USB support.

@chris - make that an answer, i will accept it!

Detailed instructions on how to shorten the bootloader time of Leonardo etc. are explained [here] (as stated by @Chris Stratton).
The crux of the matter was to redefine the timeout period
/* ./arduino/hardware/arduino/bootloaders/caterina/Caterina.c */
#define TIMEOUT_PERIOD 8000

to a lower value.
However I do not have such issues with Leonardo it boots very fast.
So this issue depends on your environment.
There is also OptiBoot, an alternative bootloader that really boots faster link:


text:
How to map PID output to actuator control?
I'm building a control system for the heating of a house. A sensor reads the temperature inside and is then used as the input in the PID control. The temperature is then controlled by a servo which opens and closes a shunt were water runs to the radiators. I understand all the inner workings of the PID library for Arduino and PID in general, but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive. In what way should the output signal correspond to how open or closed the shunt is?
I understand I can simply map the output signal to the servo signal, but is this the correct way? And with what angle coefficient should I map it with, cause that is basically set with the P parameter, isn't it? Is there some standard way to map the output signal to the actuator "signal", so that that tuning parameters are somewhat "standard".
Hope someone understands anything of what I tried to explain :)

For a radiator TBH is easier to understand, implement, configure and fine tune.

What are the limits of your actuator range?  I don't use 'standard' tuning parameters, with a map(), I use the P term as a conversion of input error units directly into actuator units.  For example P=20 could mean 20 degrees of valve-turning per degreeF of error.  Or P=20000 could mean 20000 milliseconds of on-time during a 3600 second heating cycle.

@jippie --Thanks.  I found https://wiki.purduesigbots.com/software/control-algorithms/take-back-half-tbh-controller  a good reference for the Take-Back-Half algorithm.  From that article, rather than the EDN electronics-based ref, I see TBH as backcalculating the integral sum (for PID-style algorithms) each at each crossing, or as a Newtons-method search for  the proper output value for bang-bang-like control, depending on a history of the last two setpoint crossings.

I don't think you would need to use a PID library (or any control loop for that matter) to control a radiator. You could use a simple threshold code, like this:
Pseudocode:
Check temperature
If radiator is off and temperature > (ideal temp - threshold)
  turn radiator on
If radiator is on and temperature > (ideal temp + threshold)
  turn radiator off

If you can't find some actual info regarding applying PID to a water-based radiator system, then I'd suggest the following principles.
First, I assume that the output of the PID algorithm appears as an An Arduino PWM output at some rate. This could be a fast rate, like in the hundreds of Hz (if the load is DC), or fractions of Hz, or even 10 sec or more cycle time.
Next, I assume that the PID algorithm is likely designed to expect that a linear change in output has a linear effect on the heating output. That is to say, as though it's controlling an electric heater, where, for example, 25% ON-time produces 25% of full heat output.
If these are true, then you need to determine how that relates to what you can control on your shunt valve.
Is it acceptable for the valve to be turned full on/off on a proportion-of-10-seconds basis? Probably not.
Can the valve be set to an intermittent position if fed with a 10 Hz or 100 Hz PWM signal, perhaps so.
If the latter, then a further question is how does the PWM range of values correspond to actual angle of the valve, and more to the point, how does it correspond to flow rate, and ultimately to heat delivery. Perhaps a 33% PWM signal is required to deliver 25% of the full-range heat, for example.
(At a guess, I'd assume that heat delivery is proportional to flow, but as I think you anticipate, flow is not proportional to valve angle.)
You might just mock up your system, program the Arduino to output particular PWM values to the valve, and measure the resulting flow, and if possible, heat delivery. Then, interpose in the PID library the inverse function, perhaps as a lookup table.
So when the PID library wants to command 25%, that number gets looked up in the table, which (continuing my example) translates it to a 33% PWM signal, and your program sends that value to the PWM output.
Hope that provides some ideas.


text:
Is the Sparkfun RedBoard pre-loaded with a blink sketch?
As soon as I plugged my brand new RedBoard (Sparkfun's Uno) into my computer, I saw the onboard LED (for pin 13) blink on and off every 1 second. This was before I even sent the first demo sketch to blink the LED. After I uploaded a sketch to change the blink time, the LED's blink cycle changed as I expected.
But why was the LED blinking before I sent my very first sketch? Is the RedBoard pre-loaded with a sketch?

If it's not behaving like you expected it to without a sketch, then I'd say that the answer is yes.

What is the standard behavior for a brand new OOB Uno or RedBoard when it's first connected to power? Does it differ if that power is from the wall or USB?

@KatieK wall or USB should not make a difference.

Yes, the RedBoard is preloaded with the blink sketch (or at least the two that I've purchased have been).


text:
Arduino sizeof Servo array objects is.. wrong?
After searching for a quite long while over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.
I'm doing some tests using some servo motors, trying to move them almost together using millis() and Servo object.
It is, of course, working either for single Servos and multiple servos.
The case, more detailed, is about this:

Move one, two or more servo motors together.
Force them to take ALMOST the same time to accomplish any action.
Have a dynamic number of servos.

About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.
However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:
String stringArray[] = {"string1", "string2", "and so on, I love it."};

So, after wondering a while, I've tried this:
Servo servObject;
Servo servObject_2;
Servo servObject_3;

Servo servos[] = {servObject, servObject_2, servObject_3};

And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.
What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use sizeof(servos); the value returned, surprisingly, is 2....
Moreover, if I only push two servo objects instead of three into the servo array, its sizeof returns 6.
By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.
The board I'm using is an Arduino nano w/ ATMEGA 328.
Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?
ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the loop()
Regards,
briosheje

What you describe is weird; could you please post the exact code that calculate the size of the array and displays it (I suppose this is through Serial)?

@jfpoilpret: arduino supports the standard sizeof construct available for any array object. Therefore, any array (ex. int elements[] = {2,3,1,3,9};) outputs its correct value (in the previous case 5) and I'm getting the value directly from the Serial port. In any case, tonight, I will upload the whole code, I'm not and home and can't really paste it from my Nexus 5 :P

It would help if you post a version of your code cut down to the minimum necessary to demonstrate the erroneous returns.

@JRobert: Tonight I'll post the whole code, even though, as I said above, the array is declared (and filled) right before the setup and even if I print the sizeof at the start of my loop, it still outputs the same value as in the function where I'm using it. Also, is there any alternative to check if an array element exists? If it's possible, then I could make my own sizeof prototype.

My point was that it's easier for someone to try a simple or trivial program showing the error that to try your - likely hardware dependent - full program. To answer your question, I use this macro #define countof(a) (sizeof(a)/sizeof(a[0])) to find the # of elements in an array, but since it depends on sizeof() it's won't be much help to you.

What you describe seems to be a common issue that many C or C++ developers can get (or have got) with sizeof.
Take a look at the following code:
char a[3];

int size(char b[]) {
    return sizeof b;
}

void setup() {
    int size1 = sizeof a;
    int size2 = size(a);
}

In that code, size1 will be evaluated, by the compiler, to 3 which is the real size of a variable, whereas size2 will be 2.
Why so?
This is just because sizeof a is evaluated by the compiler, and the compiler knows that a is an array of 3 char; but when a is passed as an argument to function size(), it is converted to a pointer (to the first element of the array), hence its size is the size of a pointer, which is 2 bytes on AVR ATmega MCU.
This subtlety of sizeof may explain strange values as you describe.
How to fix the issue?
Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.
Here is a sample code:
Servo allServos[] = {...};
#define NUM_SERVOS (sizeof(allServos) / sizeof(Servo))
...
void handleServos(Servo *servos, int numServos) {
    for (int i = 0; i < numServos; i++) {
        servos[i].write(...);
        ...
    }
}

void loop() {
    handleServos(allServos, NUM_SERVOS);
}

It is common practice in C to declare an array and immediately after, define its size as above.

Oh, thanks, I didn't know that sizeof, in that case, would have refered to the pointer of the Array. So, is there any way to get the true size of the above array of Servo objects? Am I supposed to count each element and use a counter?

@briosheje see the latest edit to my answer.

Thanks! It works! :) I've already confirmed the answer as solution but still, thanks for the clear explanation!


text:
How to read a Text file from server and store to a separate variable?
I am working on reading a text file from the server, using http://arduino.cc/en/Reference/GSMClientConnected. It gives me this code:
char path[]="/asciilogo.txt"

I want to store only the contents that are inside the text file to a variable (String). But client.read(); only reads a single character at a time. Also, it takes all the HTTP, GET, TIME parameters together.
How to store only the contents that are present in the text file to a string variable?

Here is what I found:
You need to have a special character like  "*" (a delimiter), from which important data will flow through.
char z = '*';
int s=0;

void setup()
{
  // usual initialization
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    // Serial.print(c);
    if (z == c)
    {
      s=1;
    }

  if(s == 1)
  {
    int i=0;
    k[i] = c;
    i=i+1;
    // Serial.print(k);
  }

  place +=k;

  Serial.print(place);

  }

.......
}

that'll work but you have to declare i outside of the loop() because the way it is now, it'll always be 0.


text:
What is the advantage of using a motor shield if I want to use a stepper motor?
I know that it is possible to connect a stepper motor directly to an arduino (as displayed here). I know that another option is to use a motor shield (for example the Arduino Motor Shield or the Adafruit Motor Shield).
What I would like to know: What are the actual advantages of using a motor shield?
Is it just a question of convenience? Or does a motor shield do something that could not easily performed without a shield? Does it allow me to connect more motors than I could connect directly without a shield (power supply comes to mind)?

The example you linked to isn't actually connecting the Arduino directly to a stepper motor. It's going via a ULN2003A driver. That's a very common Darlington transistor array, which basically just lets you use a small current to switch a larger load.
That's necessary because the Arduino pins can't safely source enough current to drive the stepper motor directly. It might work for a while, but it would damage your Arduino sooner or later.
Motor shields usually have a similar driver in them, but can also provide additional functionality which you might find useful. For example, the Adafruit shield you linked to is controlled by the I2C bus, and has its own on-board PWM. That means you can control several motors without needing any extra output pins on your Arduino.
In short, motor shields aren't necessary. They can be helpful though, especially if you aren't familiar with the underlying electronics, or you don't want to build it yourself.

Mechanical stability of the whole thing is probably the main advantage. I'd personally opt for a generic module or loose components. The main disadvantage of shields is pin conflicts when using more than one shield.

I'm using a adafruit motorshield v2 for my solar tracker project with two stepper motors atm.
i'm quite a new to arduino and coding and i think the shield made it a lot easier for me to get a hang of it - easy to code and nicely stack able on the ardiuno (little soldering to assemble but not too difficult).


text:
GSM and GPS shield pin conflict
I have an Arduino GSM shield and I plan to purchase an Adafruit GPS shield. The GPS module uses Pin 7 & 8 for Rx and Tx, but the GSM shield uses Pin 7 for Modem Reset.
Will the overlap on pin 7 affect it in any way? If it does cause issues, how can the problem be avoided?

This looks like a duplicate of a question you asked a few days ago (here). Are you wanting to ask something specific that wasn't covered there?

Yes, there they suggested me to go for the adafruit GPS shield. But the shied overlaps with Pin 7. I want to know, If I place this shield on the modem reset pin, how it will affect my application.

You might want to ask on the Adafruit forums.

Looking at the PDF for the Adafruit GPS shield, pin 7 is indeed hard wired to Rx and pin 8 is hard wired to Tx.

These can not be changed.
Looking at the guide for the Arduino GSM shield pin 7 is indeed reserved for modem reset:

Digital pins 2, 3 and 7 are reserved for communication between the
  Arduino and modem and cannot be used by your sketches. Communication
  between the moden and Arduino is handled by the Software Serial
  library on pins 2 and 3. Pin 7 is used for the modem reset.

As this is the case, should you stack the two shields together, without modification, then the overlap of the Rx pin on the GPS shield will cause resets to the modem on the GSM shield.
So, it seems that your best option is to use the solution provided by RedGrittyBrick, to your previous question Arduino shield stacking, the Go-Between Shield

You hear it all the time in the Arduino community, “will this shield
  work with my other shield?.” I think we’ve all been disappointed to
  find that two of our favorite shields compete for control of a digital
  pin here or a serial pin there. While there are sometimes some clever
  workarounds from elegant code modifications to aggressive
  ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution
  thus far: The Go-Between Shield.

Once you have used the Go-Between shield to reassign the Rx pin to something that the GSM shield does not use, (as 2, 3 and 7 are already used, let's say you use pin 6), then in the File -> Examples -> Adafruit_GPS -> Parsing sketch, you will need to change the line
SoftwareSerial mySerial(3,2);

to
SoftwareSerial mySerial(8,6);

instead of
SoftwareSerial mySerial(8,7);

which is recommended in the PDF.
I hope that this answers your question(s). Let us know how you get on.

Addenum
The schematic of the Arduino GSM shield:

The schematic of the Adafruit GPS shield:


text:
How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor?
Hi we are using Arduino Leonardo with some electric paint and Capacitive Sensor Libraries. We have a lot of variance in our Serial output from our sensors, we believe if we grounded the Arduino we would have more concrete values.
On the Capacitive Sensor doc, it reveals to use a small capacitor to put on one of the pins. More details!
Another guide somewhere says to wrap the Arduino in plastic and tin foil. These are vague, and we have not landed success when we tried.
Has anyone had success grounding Arduino Leo? Thank you.

Can you please link the datasheet of the sensor? Thanks!

@AnnonomusPenguin - the sensor is typically homemade, just some "plates" or in this case it seems areas of conductive paint.  There's an edit in the queue to add a link to http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.
However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.
One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.
Another could be to run two parallel traces in a spiral filling a large area
Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline.  Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.

The simplest way to ground an Arduino is to attach the ground pin, found on the power header, to a grounded surface, like a metal pipe. As for the capacitor you mentioned, that is called a smoothing capacitor. It is a small capacitor, about 1microfarad, and goes between the supply of the sensor and the ground line.

Actually, no - the recommendation is for an approximately 100 pF cap across the sensor surface (surfaces?).  You are speaking instead of a power supply capacitor, but there isn't really any applicable place to add that except on the Arduino board itself, which would normally be well bypassed.

It might help if you follow the diagram for connecting a button, that way the value of the capacitor sensor wont fluctuate...
Photo from http://arduino.cc/en/tutorial/button

Huh?  Yes, you could use a button as an input sensor instead of cap sense.  Or you could use a button to trigger a calibration routine but it's very clear how you meant this to answer the question?


text:
Receive SMS example gives me a garbage values
When I run my Receive SMS example code, By default every time I get the same thing.I am trying to send sms to my sim card present in the Arduino GSM shield. I don't want this message. How to solve this problem ?

I

Where is it getting the "trend alert" message from? It's not in the example code.. so is that not the text that it's receiving??

That is what I am too confused. Every time I run this code, I get this message again and again ...

This looks like an ad sent to your SIM phone number by your phone operator. Try to use the SIM on a real phone and check if you can get rid of this ad from there.

@jfpoilpret  No, I am not receiving such sms in my mobile..

Could you perhaps just copy and paste the text (~200 bytes) instead of pasting an unreadable 100kB image (which also is more effort having to upload it)? And while you are at it, obfuscate the spamvertized domain.

This is obviously an ad as this links (with complaints about unsolicited SMS ads from this company) shows: http://www.complaintboard.in/complaints-reviews/lenskart-l298415.html

I have activated DND to my phone, now Its working ...

Dungeons & Dragons?

Do not Disturb (DND).

Can you post this as an answer so that this question is resolved?

Most Telecom operators agree for sending advertisements and promotions to their customers for certain business and some money. You can stop these promotion for your mobile by making (Do Not Disturb)DND active. In India, just do the following for DND Activation
 ( Fully Blocked Category )

 Send SMS at START 0 to 1909 or Call at 1909

 Partial Blocked Category

Send SMS at START 1 to 1909 to block Banking – Insurance – Financial Products – Credit Cards
Send SMS at START 2 to 1909 to block Real Estate
Send SMS at START 3 to 1909 to block Education
Send SMS at START 4 to 1909 to block Health
Send SMS at START 5 to 1909 to block Consumer Goods & Automobiles
Send SMS at START 6 to 1909 to block Communication – Broadcasting – Entertainment – IT
Send SMS at START 7 to 1909 to block Tourism

See more at: http://www.techsiren.com/how-to-activate-do-not-disturb-india-registration/#sthash.F87Pfj5V.dpuf


text:
What's the deal with Uno's pin 13 LED?
(I have a Sparkfun RedBoard, but this question seems to apply to R3 Unos and Uno-compatible boards.) As I was building the first circuit in my SIK guidebook (add a resistor, LED, hook it up and make it blink from code), I noticed a blue LED on the board itself did everything that the circuit's LED did - blinking according to the programming.
Why is this LED here? What use cases is it for?
What kind of circuits will I have to adjust to account for this LED?
Is pin 13 traditionally a debug or a troubleshooting pin? Where did this convention come from?

Why is there a scroll wheel on a mouse? It's convenient, but not needed.

The LED on pin 13 is used by the optiboot loader (the one used on UNO):

at Arduino boot time (the LED blinks a few times)
when uploading a sketch to Arduino

I haven't checked other bootloaders, they may provide the same behavior as the optiboot.
For optiboot, there are optional defines (at compile time) to modify this behavior:

LED_START_FLASHES defines the number of flashes of pin 13 LED at boot time (can be set to 0)
LED_DATA_FLASH will use pin 13 LED during sketch upload if defined at compile-time

These defines are explained in hardware/arduino/bootloaders/optiboot/optiboot.c from within your Arduino IDE install directory.
If you want to change these, you will have to recompile the optiboot loader first and then burn it to your Arduino through an ISP programmer.
I guess one other reason for the LED on pin 13 was to simplify the demonstration of the "Hello World" sketch for Arduino, namely the Blink sketch, without the need for any extra component.

What kind of circuits will I have to adjust to account for this LED?

You'll need to take it into account if you're using that pin as a digital input.

NOTE: Digital pin 13 is harder to use as a digital input than the
  other digital pins because it has an LED and resistor attached to it
  that's soldered to the board on most boards. If you enable its
  internal 20k pull-up resistor, it will hang at around 1.7V instead of
  the expected 5V because the onboard LED and series resistor pull the
  voltage level down, meaning it always returns LOW. If you must use pin
  13 as a digital input, set its pinMode() to INPUT and use an external
  pull down resistor. Arduino - DigitalPins

I just ran into this problem while using a 1wire temperature sensor.  I couldn't enumerate the bus due to that LED interfering.  I noticed some odd spikes on my oscilloscope when using that pin. I moved to another pin and all was good.

What everyone else said, plus: if you find the digital-13 LED gives you a problem, you can always remove it from the circuit, either by removing the LED, or the series resistor.
This might be useful if you are running out of digital I/Os, or you want several contiguous I/O bits and don't want one of them to behave differently from the others.

Yes, pin 13 is traditionally an output pin that drives an LED. But the blue LED should not be blinking as it is the "power on" indicator - do you have a grunty power supply to your board?
You can experiment with PWM to the pin13 LED, which will control its apparent brightness. There are plenty of example sketches on the web.

I don't know what a grunty power supply is; power was supplied via USB.
It looks like RedBoards are pre-programmed with the Blink sketch, which uses pin 13.

"Grunty". LOL. I think he means a very high current power supply. I use the term "stiff", meaning it resists voltage droop at higher loads.


text:
Can I turn off a device using the 5V and analog pins?
Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside  a sketch?
edit: I'm using a Due based boad, the digix http://digistump.com/wiki/digix/tutorials/basics

Provided you do not need to switch the load many times a second, your simplest solution to a task like this will be a shield with either magnetic or solid state relays on it - while transistor/FET solutions can be engineered to work, relays dramatically lessen the chance of the load coupling noise or damaging voltage spikes back into the Arduino.

You would use a transistor. Something like this would work.
In this case the Arduino controls a transistor to drive a brushless motor.
Source: Arduino Cookbook: (https://www.inkling.com/read/arduino-cookbook-michael-margolis-2nd/chapter-8/figure-8-9)
Update:
For the sake of clarity I should point out that the TIP102 is the device to use for the 1A required (not the 2N2222). And as pointed out by others the 5V supply of most Arduino boards would not be sufficient to supply 1A, so an external supply would be advised.

Thanks for this. Theres no reason why the motor power source and ground couldn't be 5v and gnd respectively,  right?

The 2n2222 is nowhere near up to the job, especially not the plastic TO-92 cased PN2222 shown.  And no, using the Arduino's 5v rail to power a high current external device is not a good idea.  Use a common ground, but a distinct supply.

Short answer: NO. It would fry your Arduino.
Long answer:
The current of Arduino pins is very limited (40mA max on UNO).
If you need to draw 1A, then you need a transistor between the Arduino pin and your device.
In such case, what you would normally do is:

connect any Arduino logical pin to the transistor base (through a resistor),
plug your device between a 5V supply (capable of 1A current providing) and the transistor collector,
connect the transistor emitter to the Arduino GND pin (and connect that pin also to the 5V-1A supply)

Note that you don't need to use an analog pin for that, a logical pin is enough if you just want to switch the device on or off.
Now notice that I specified a 5V 1A supply, that should normally be distinct from the 5V pin of the Arduino.
So the next question is: can you draw 1A out of the Arduino 5V pin?
The Arduino UNO page does not specify the current limitation on that pin. However it mentions the following:

5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V).

So the max current on this pin depends on 2 factors:

what is the power supply for the board: it is either USB, or an external power supply, which can be connected to the power plug or to the Vin pin.
the specs of the 5V regulator voltage on the Arduino board

If you use USB as power supply, then you are limited to 500mA as stated in the Arduino UNO page:

The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

If you use an external power supply that provides at least 1A, then we have to find out the max current by ourselves.
If we take a look at Arduino UNO schematics, then we see that this regulator is referenced as "NCP1117ST50T3G" (this is "U1" on the top-right corner).
The spec sheet for this regulator mentions that it can supply 1.0A.
So in theory, that should work, however, you also have to consider that this regulator also supplies current to the Arduino borard itself and all its pins.
If you love your Arduino and don't want to fry it, you should probably stay away from using its 5V pin for your purposes.
Now if you're open to experiment, you may try it :-)

What if I used the 5V pin and the ground and put a transistor between them and attached that to a analog line?

According to what I understood from the question (load wired between 5V and ground board pins), the limiting factor will be the voltage regulator, and not the ATmega MCU. The 40mA absolute maximum current applies only to the MCU, which in my opinion is not the case. See my answer for more details.

The simpler solution is to power Arduino from some external supply, then fork that power through a relay to controlled device.
Then you can switch the device by controlling that relay through your digital pin.

A standard magnetic relay cannot be driven by an Arduino Digital pin because of current requirement and inductive kick-back from the relay coil.

Have you try using a digital potentiometer name AD5220, it let you adjust the resistance
with using your hand. You can find more info about it at www.analog.com. I would upload an
image of the schematic but i just don't know how.

A digital potentiometer doesn't particularly sound like a solution for this problem.


text:
SMS in modem's memory
I am working on SMS communication with my phone and Arduino. My intension is simple. When somebody send an SMS, the Arduino should read a text file located on my server and forward the content to the same number.
The problem here is, when I send an SMS to my Arduino, which is waiting for my message, it does not read my message. But when I separately run this example code, I see my SMS is received. It means my SMS is already present in the modem memory. But why does this happen? How to solve this? Here is my code:
// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

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

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

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

char k[30];
char z = '*';
int s=0;
String place;
char remoteNum[20];  // telephone number to send sms

void setup() {
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("SMS connected");
    // connection state
    boolean notConnected = true;
    while(notConnected) {
        if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
           (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
            notConnected = false;
        else {
            Serial.println("Not connected");
            delay(1000);
        }
    }
    Serial.println("GPRS connected...");
    Serial.println("Server Connecting.");
    // if you get a connection, report back via serial:
    serverr();
}

void loop() {
    if (sms.available()) {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
    }
}

void smss() {
  // I just want phone number
    if (client.available()) {
        char c = client.read();
        //***************************************************
        //       Filtering a specific message
        //**************************************************
        if (z==c) {
            s=1;
        }
        if(s == 1) {
            int i=0;
            k[i] = c;
            i=i+1;
            // Serial.print(k);
        }
        place +=k;
        //Serial.print(place);
    }
    //***************************************************

    if (!client.available() && !client.connected()) {
        sms.beginSMS(remoteNum);
        Serial.print("Place =");
        Serial.print(place);
        sms.print(place);
        sms.endSMS();
        sms.flush();
        Serial.println("MESSAGE DELETED");
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
        // do nothing forevermore:
        for(;;)
            ;
    }
}

// if you didn't get a connection to the server:
// Serial.print(server);

void serverr() {
    if (client.connect(server, port)) {
        client.print("GET /current.txt");
        Serial.print("GET /current.txt");
        client.println(" HTTP/1.1");
        Serial.println(" HTTP/1.1");
        client.println("Host: www.yourdomain.com");
        Serial.println("Host: www.yourdomain.com");
        client.println("User-Agent: Arduino");
        Serial.println("User-Agent: Arduino");
        client.println("Accept: text/html");
        Serial.println("Accept: text/html");
        client.println("Connection: close");
        Serial.println("Connection: close");
        client.println();
        Serial.println();

        Serial.println("\nCOMPLETE!\n");
        //client.stop();
    } else {
        Serial.println("connection failed");
        Serial.println("\n FAILED!\n");
    }
}

Show the content of smss() function, so that we can see how you read the SMS and then delete it.

I have given the function definition.

It would help if you told what debug messages get displayed on your serial monitor when running this program. Also, can you confirm that remoteNumber is defined as char remoteNumber[20];? Finally, I wonder if you can flush() an SMS without reading its content first.

In the serial monitor, It just waiting for my sms and stays static.But when i run this                 code, I receive that sms.  Ya the its 'char remoteNumber[20];'.

the latest code you posted is obviously wrong: the smss() function  is never called. The global structure is just a mess as you did not break down behavior into different functions; instead some functions do a mix of unrelated actions.

I see one problem with the global structure of your program; everytime loop() is run, it:

checks if an SMS is present, and gets the originating phone number if present, otherwise it just goes on, ie smss() function returns without modifying remoteNumber
send an SMS to remoteNumber

One problem here is that your loop() will repeatedly try to send an SMS to the same remoteNumber even if no SMS was received; actually, to solve this issue, you should modify smss() to:

either wait (forever) for an SMS to be received and return only in this situation
or return a value (eg bool) that indicates whether an SMS was received or not; then an SMS should be sent if and only if an SMS was just received.

Here is an example:
void setup()
{
    GSM and GPRS initialization
    Connection to server
}

void loop()
{
    if (smss())
    {
        Reading the txt file content in server

        sms.beginSMS(remoteNum);
        sms.print(txtMsg);
        sms.endSMS();
    }
}

bool smss() // I just want phone number
{
    if (sms.available())
    {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
        return true;
    }
    return false;
}

Note that this code does not integrate error support as it should; indeed sms.remoteNumber() may return error codes (any value >1), in which case you should consider no SMS was received at all.

Will the sms.flush() will delete the content in remoteNum ? Because its in smss().

I have updated and added my void loop() in the question. But still,giving same problem

You've added much more to your code than just my suggestion; now we see how you get the text content from your server. And once again the whole logic of your program does not seem correct: write a function to fully read the complete content from your server (there must be a while inside it) instead of reading byte per byte at every call of loop(). And this problem is not linked to this specific question anymore.

I think, It would be better, If I give the complete code. I have updated the complete code. I have found a problem, If I don't run the serverr() function, I am able to receive sms, It means the server() conflicts the sms. Is my serverr() function correct ?


text:
digital pin's current limit, ohm's law and DC motor
A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since V=RI, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!

If you connect a motor to the Vcc pin, you are not connecting to an output! This is an input pin, for the processor's power... If your motor draw is OK for your power supply, then the motor will spin. If not, you will overload your power supply and (at best) the arduino will brown-out, probably rebooting repeatedly. You may as well just omit the arduino though. The point to watch with the 200mA limit, is 50mA x4 = 200mA so you can overload the chip with each output being individually fine..

The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a Totem Pole driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground.  Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.
The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible.  At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it will be notably less than the supply.
Connecting your motor to an ATmega pin is an extreme, far out of spec.  When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low.  Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage.  Finally, your motor will produce inductive kickback, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it.  Latchup is another possibility - a sometimes temporary condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a miniature space heater.
There really are no components on your typical Arduino board designed to directly control a motor.
Instead, for unidirectional control you should use a circuit with an NPN bipolar transistor, NMOS FET, magnetic relay, or solid state relay.  The latter are commonly available pre-assembled on shields.  With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.
For bidirectional control, look for a motor shield based on an H bridge IC such as the TB6612FNG or the less efficient bipolar L298 or L293/SN754410.  This basically puts a high current Totem Pole driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.


text:
Sending information through Bluetooth 4.0 (LE) with Tinyduino
My task is to measure distances quite rapidly and send the data to a computer. I need to do it with the following equipment:

Tinyduino Processor board
Tinyduino Bluetooth LE shield
Tinyduino Cell Battery
Ping))) Ultrasonic Distance Sensor

Distance

I have found the distance already and it is right now stored in an int.
Bluetooth

For the bluetooth I am using the BGLib
As mentioned above the distance is measured many times rapidly so I want to either transfer the data quickly or store the data somehow until measurement is done (after approximate 3 seconds). I have established connection to a connection already (GAP discoverabled undirected connectable).
Because I am using the Tinyduino Bluetooth LE shield, it already have a firmware that I cannot change. It consists of 2 charateristics: TX and RX. My problem is now I do not understand how to send the specific data to computer.
Do I need to write a response to a command by the computer, or do I send a command with the sendCommand function, or even a third?
And just another thing; is it better to store the data and wait till the measurement is over or should I try to transfer it while I measure it.
(if there are some comments you would like to know what means, just write because they are Danish)
My current code:
#include <BGLib.h>
#include <BGLibConfig.h>

#include <SoftwareSerial.h>
#include "BGLib.h"

//Uncomment denne linje for at debugge via USB
//#define DEBUG

//BLE er forkortelse for Bluetooth Low Energy

// ================================================================
// BLE FORBINDELSESTILSTAND
// ================================================================

// BLE TILSTANDSDEFINITONER
#define BLE_STATE_STANDBY           0
#define BLE_STATE_SCANNING          1
#define BLE_STATE_ADVERTISING       2
#define BLE_STATE_CONNECTING        3
#define BLE_STATE_CONNECTED_MASTER  4
#define BLE_STATE_CONNECTED_SLAVE   5

// BLE state/link status
uint8_t ble_state = BLE_STATE_STANDBY;
uint8_t ble_encrypted = 0;  // 0 = not encrypted, otherwise = encrypted
uint8_t ble_bonding = 0xFF; // 0xFF = no bonding, otherwise = bonding handle

// ================================================================
// HARDWARE FORBINDELSE OG GATT STRUKTUR SETUP
// ================================================================

#define LED_PIN 13  // Status LED-pin
#define PING_PIN 11  // Ping pin til at ultralydssensor

#define GATT_HANDLE_C_RX_DATA   17  // 0x11, supports "write" operation
#define GATT_HANDLE_C_TX_DATA   20  // 0x14, supports "read" and "indicate" operations

// Brug softwareSerial på pins D3/D4 for RX/TX (Arduino side)
SoftwareSerial bleSerialPort(3, 4);

// Opret BGLib objekt:
//  - use SoftwareSerial port for module comms
//  - use nothing for passthrough comms (0 = null pointer)
//  - enable packet mode on API protocol since flow control is unavailable
BGLib ble112((HardwareSerial *)&bleSerialPort, 0, 1);

#define BGAPI_GET_RESPONSE(v, dType) dType *v = (dType *)ble112.getLastRXPayload()

// ================================================================
// ARDUINO SETUP OG LOOP FUNKTIONER
// ================================================================

// Kør under startup
void setup() {
    // Klargør status LED
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);

    // BGLib lyttere
    ble112.ble_evt_system_boot = my_ble_evt_system_boot;
    ble112.ble_evt_connection_status = my_ble_evt_connection_status;
    ble112.ble_evt_connection_disconnected = my_ble_evt_connection_disconnect;
    //ble112.ble_evt_attributes_value = my_ble_evt_attributes_value;

    // Åben Arduino USB serial, hvis vi skal debugge
    #ifdef DEBUG
      Serial.begin(38400);
    #endif

    // Åben BLE software serial port
    bleSerialPort.begin(38400);

    my_ble_evt_system_boot( NULL);
}

// Main loop
void loop() {
    //Få afstand i microsekunder
    int *x = ping();

    // Bliv ved med at spørge efter ny data hos BLE
    ble112.checkActivity();

    // Få Arduino LED at blinke baseret på tilstand:
    //  - konstant = STANDBY
    //  - 1 puls per sekund = ADVERTISING
    //  - 2 puls per sekund = CONNECTED_SLAVE
    //  - 3 puls per sekund = CONNECTED_SLAVE med kryptering
    uint16_t slice = millis() % 1000;
    if (ble_state == BLE_STATE_STANDBY) {
        digitalWrite(LED_PIN, HIGH);
    } else if (ble_state == BLE_STATE_ADVERTISING) {
        digitalWrite(LED_PIN, slice < 100);
    } else if (ble_state == BLE_STATE_CONNECTED_SLAVE) {
        if (!ble_encrypted) {
            digitalWrite(LED_PIN, slice < 100 || (slice > 200 && slice < 300));
        } else {
            digitalWrite(LED_PIN, slice < 100 || (slice > 200 && slice < 300) || (slice > 400 && slice < 500));
        }
    }
}

int *ping()
{
    //Variabler til at lagre målte værdier
    int microseconds, cm;

    //Send ping, som bagefter skal læses
    pinMode(PING_PIN, OUTPUT);
    digitalWrite(PING_PIN, LOW);
    delayMicroseconds(2);
    digitalWrite(PING_PIN, HIGH);
    delayMicroseconds(5);
    digitalWrite(PING_PIN, LOW);

    //Aflæs tiden
    pinMode(PING_PIN, INPUT);
    microseconds = pulseIn(PING_PIN, HIGH);

    //Konverter mikrosekunder til cm. Det går 29 microsekunder pr centimeter.
    //Halver afstand, fordi vi vil ikke have afstanden både frem og tilbage, men derimod kun den ene vej.
    cm = microseconds / 29 / 2;

    #ifdef DEBUG
        Serial.print(cm, DEC);
    #endif

    return &cm;
}

// ================================================================
// APPLICATION HÆNDELSES FUNKTIONER
// ================================================================

void my_ble_evt_system_boot(const ble_msg_system_boot_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tsystem_boot: { ");
        Serial.print("major: "); Serial.print(msg -> major, HEX);
        Serial.print(", minor: "); Serial.print(msg -> minor, HEX);
        Serial.print(", patch: "); Serial.print(msg -> patch, HEX);
        Serial.print(", build: "); Serial.print(msg -> build, HEX);
        Serial.print(", ll_version: "); Serial.print(msg -> ll_version, HEX);
        Serial.print(", protocol_version: "); Serial.print(msg -> protocol_version, HEX);
        Serial.print(", hw: "); Serial.print(msg -> hw, HEX);
        Serial.println(" }");
    #endif

    // SYSTEM BOOT betyder at systemet er på standby
    //ble_state = BLE_STATE_STANDBY;
    // ^^^ Spring over fordi vi alligevel skifter til advertising nedenunder

    // Sæt advertisement interval to 200-300ms. Brug alle advertisement kanaler
    // (NOTE: min/max parametere er i 625 microsekunder)
    ble112.ble_cmd_gap_set_adv_parameters(320, 480, 7);
    while (ble112.checkActivity(1000));

    // USE THE FOLLOWING TO LET THE BLE STACK HANDLE YOUR ADVERTISEMENT PACKETS
    // ========================================================================
    // start advertising general discoverable / undirected connectable
    ble112.ble_cmd_gap_set_mode(BGLIB_GAP_GENERAL_DISCOVERABLE, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    while (ble112.checkActivity(1000));

    // set state to ADVERTISING
    ble_state = BLE_STATE_ADVERTISING;
}

void my_ble_evt_connection_status(const ble_msg_connection_status_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tconnection_status: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", flags: "); Serial.print(msg -> flags, HEX);
        Serial.print(", address: ");
        // this is a "bd_addr" data type, which is a 6-byte uint8_t array
        for (uint8_t i = 0; i < 6; i++) {
            if (msg -> address.addr[i] < 16) Serial.write('0');
            Serial.print(msg -> address.addr[i], HEX);
        }
        Serial.print(", address_type: "); Serial.print(msg -> address_type, HEX);
        Serial.print(", conn_interval: "); Serial.print(msg -> conn_interval, HEX);
        Serial.print(", timeout: "); Serial.print(msg -> timeout, HEX);
        Serial.print(", latency: "); Serial.print(msg -> latency, HEX);
        Serial.print(", bonding: "); Serial.print(msg -> bonding, HEX);
        Serial.println(" }");
    #endif

    // "flags" bit description:
    //  - bit 0: connection_connected
    //           Indicates the connection exists to a remote device.
    //  - bit 1: connection_encrypted
    //           Indicates the connection is encrypted.
    //  - bit 2: connection_completed
    //           Indicates that a new connection has been created.
    //  - bit 3; connection_parameters_change
    //           Indicates that connection parameters have changed, and is set
    //           when parameters change due to a link layer operation.

    // check for new connection established
    if ((msg -> flags & 0x05) == 0x05) {
        // track state change based on last known state, since we can connect two ways
        if (ble_state == BLE_STATE_ADVERTISING) {
            ble_state = BLE_STATE_CONNECTED_SLAVE;
        } else {
            ble_state = BLE_STATE_CONNECTED_MASTER;
        }
    }

    // update "encrypted" status
    ble_encrypted = msg -> flags & 0x02;

    // update "bonded" status
    ble_bonding = msg -> bonding;
}

void my_ble_evt_connection_disconnect(const struct ble_msg_connection_disconnected_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tconnection_disconnect: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", reason: "); Serial.print(msg -> reason, HEX);
        Serial.println(" }");
    #endif

    // set state to DISCONNECTED
    //ble_state = BLE_STATE_DISCONNECTED;
    // ^^^ skip above since we're going right back into advertising below

    // after disconnection, resume advertising as discoverable/connectable
    //ble112.ble_cmd_gap_set_mode(BGLIB_GAP_GENERAL_DISCOVERABLE, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    //while (ble112.checkActivity(1000));

    // after disconnection, resume advertising as discoverable/connectable (with user-defined advertisement data)
    ble112.ble_cmd_gap_set_mode(BGLIB_GAP_USER_DATA, BGLIB_GAP_UNDIRECTED_CONNECTABLE);
    while (ble112.checkActivity(1000));

    // set state to ADVERTISING
    ble_state = BLE_STATE_ADVERTISING;

    // clear "encrypted" and "bonding" info
    ble_encrypted = 0;
    ble_bonding = 0xFF;
}

/*void my_ble_evt_attributes_value(const struct ble_msg_attributes_value_evt_t *msg) {
    #ifdef DEBUG
        Serial.print("###\tattributes_value: { ");
        Serial.print("connection: "); Serial.print(msg -> connection, HEX);
        Serial.print(", reason: "); Serial.print(msg -> reason, HEX);
        Serial.print(", handle: "); Serial.print(msg -> handle, HEX);
        Serial.print(", offset: "); Serial.print(msg -> offset, HEX);
        Serial.print(", value_len: "); Serial.print(msg -> value.len, HEX);
        Serial.print(", value_data: ");
        // this is a "uint8array" data type, which is a length byte and a uint8_t* pointer
        for (uint8_t i = 0; i < msg -> value.len; i++) {
            if (msg -> value.data[i] < 16) Serial.write('0');
            Serial.print(msg -> value.data[i], HEX);
        }
        Serial.println(" }");
    #endif

    // check for data written to "c_rx_data" handle
    if (msg -> handle == GATT_HANDLE_C_RX_DATA && msg -> value.len > 0) {
        // set ping 8, 9, and 10 to three lower-most bits of first byte of RX data
        // (nice for controlling RGB LED or something)
        digitalWrite(8, msg -> value.data[0] & 0x01);
        digitalWrite(9, msg -> value.data[0] & 0x02);
        digitalWrite(10, msg -> value.data[0] & 0x04);
    }
}*/

Not an answer to your question, but your code has a potentially big issue: it is very bad programming practice to declare a variable in a function (cm in ping()) and returns a pointer to that variable (return &cm;) as its value will be overridden by the first call to any function after the return (ble112.checkActivity(); in your case). Just do return cm; in ping() instead.

Hello Highace2 have you made any headway with the tinyduino and the bluetooth Le Module? I am having a similar issue which I have posted about here please take a look I would really appreciate the help.

@har I'm afraid not. The project was submitted with an alternative solution because neither my team nor my teacher (who is a low current engineer with 10 years of experience) could get that thing working. The library is just plain rubish to people with little understanding of bluetooth 4.0 protocol (where it should be rather clear).

Highace2 thank you for your response, if you don't mind me asking what the alternative solution to your problem was? Did you still use BLE? Thank you.

@har No, we did not. Our goal was to use an accelerometer inside a plastic bottle but ended up using a range finder on top of tube in which the plastic bottle flew. That was our solution.


text:
Problems with using example code for Wi-Fi shield (arduino)
I have problems with the Wi-Fi shield example code.
#include <SPI.h>
#include <WiFi.h>

char ssid[] = "*****";          //  your network SSID (name)
char pass[] = "*****";   // your network password

int status = WL_IDLE_STATUS;
char servername[]="google.com";  // remote server we will connect to

WiFiClient client;

void setup() {
    Serial.begin(9600);
    //disable SD SPI
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    Serial.println("Attempting to connect to WPA network...");
    Serial.print("SSID: ");
    Serial.println(ssid);

    status = WiFi.begin(ssid, pass);
    if ( status != WL_CONNECTED) {
        Serial.println("Couldn't get a wifi connection");
        // don't do anything else:
        while(true);
        }
     else {
     Serial.println("Connected to wifi");
     Serial.println("\nStarting connection...");
     // if you get a connection, report back via serial:
     if (client.connect(servername, 80)) {
         Serial.println("connected");
         // Make a HTTP request:
         client.println("GET /search?q=arduino HTTP/1.0");
         client.println();
      }
    }
}

 void loop() {

}

The Wi-Fi Shield has connected with the internet Wi-Fi, but the last printing was "Starting connection..." I can't get to connect to (google.com), why?

insert a Serial.println(status); and which WL_status is returned? Did it actually connect (WL_CONNECTED) or is it some other result?

Have you upgraded the firmware in your wifi shield? If not, it will have problems connecting. Compile and upload this sketch. If it shows the firmware version as 1.0.0, then you need to upgrade the firmware. If it shows 1.1.0, then it is current as of today.
#include <SPI.h>
#include <WiFi.h>

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while(true);
  }

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());
}

void loop() {}

Please Note: The chips are numbered differently but run the same Wi-Fi firmware. You can upgrade the firmware without any worries.

I had this problem aswell. The problem was a bug with the official editor of arduino. I fixed this by downgrading the editor to version 1.0.3. (from 1.0.5) You can find a download link for it at the Arduino website.
Hope this helped!
-Kad

#include <WiServer.h>

#define WIRELESS_MODE_INFRA 1
//#define WIRELESS_MODE_ADHOC   2

// Wireless configuration parameters ----------------------------------------
unsigned char local_ip[] = {146, 227, 174, 29};      // Indirizzo IP
unsigned char gateway_ip[] = {146, 227, 175, 254};      // Indirizzo gateway IP
unsigned char subnet_mask[] = {255, 255, 248, 0};   // Subnet Mask
const prog_char ssid[] PROGMEM = {"enduroam"};      // SSID access point

unsigned char security_type = 3;    // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

// WPA/WPA2 passphrase
const prog_char security_passphrase[] PROGMEM = {"EAP-MSCHAP V2"};  // max 64 characters
// setup the wireless mode
// infrastructure - connect to AP
// adhoc - connect to another WiFi device
unsigned char wireless_mode = WIRELESS_MODE_INFRA;

unsigned char ssid_len;
unsigned char security_passphrase_len;
// End of wireless configuration parameters ----------------------------------------
// This is our page serving function that generates web pages
boolean sendMyPage(char* URL) {

    // Check if the requested URL matches "/"
    if (strcmp(URL, "/") == 0) {
        // Use WiServer's print and println functions to write out the page content
        WiServer.print("<html>");
        WiServer.print("Hello World!");
        WiServer.print("</html>");

        // URL was recognized
        return true;
    }
    // URL not found
    return false;
}

void setup() {
  // Initialize WiServer and have it use the sendMyPage function to serve pages
  WiServer.init(sendMyPage);

  // Enable Serial output and ask WiServer to generate log messages (optional)
  Serial.begin(57600);
  WiServer.enableVerboseMode(true);
}

void loop(){

  // Run WiServer
  WiServer.server_task();

  delay(10);
}

Please add information about your code: what does it do? how does it work?