text:
Determining which section of code uses the most flash
I'm running into the 32k flash ceiling of my 328p. The code is pretty compact but I need help making it smaller.
Is there an analysis tool (part of avr?) that can tell me which functions take up the most space?  Obviously looking at the source code won't help because I don't know how the compiler decides to reorganize things.
I've moved strings to PROGMEM, but I'm still hitting the ceiling.
What are some tips for space saving?
What are some ways of seeing what's taking up the most space?

For knowing which functions take the most space, I generally use
avr-nm. This command is intended to display the symbol table of a
compiled program. It is one of the tools that you get when you install
the Arduino environment, so you already have it. avr-nm provides the
same information as avr-objdump -t, but it can display it in a nicer
format.
As an example, I ran the following command on the basic blinky program:
avr-nm --size-sort -Crtd blink.elf

And this is the output:
00000148 T __vector_16
00000118 T init
00000114 T pinMode
00000108 T digitalWrite
00000082 t turnOffPWM
00000076 T delay
00000070 T micros
00000040 T loop
00000026 T main
00000020 T digital_pin_to_timer_PGM
00000020 T digital_pin_to_port_PGM
00000020 T digital_pin_to_bit_mask_PGM
00000016 T __do_clear_bss
00000010 T port_to_output_PGM
00000010 T port_to_mode_PGM
00000008 T setup
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000001 b timer0_fract

The first column is the size of the object referenced by the symbol.
Second column is the type, where ‘t’ (upper or lower case) means “text”
(code and PROGMEM data), ‘d’ means “initialized data” (stored in flash
and copied to RAM at startup) and ‘b’ means “uninitialized data” (a.k.a.
“BSS”, occupies no flash, only RAM). The last column is the symbol's
name. In this example you can see that the biggest function is
__vector_16 (the ISR for timer 0 overflow), and it takes 148 bytes of
flash.
The options I passed to avr-nm are the following:

--size-sort, obviously, sorts the symbols by size. It also displays
the size, instead of the address, on the first column.
-C is for demangling the C++ symbols. For example, instead of
displaying “_ZN14HardwareSerial5beginEm”, it would display
“HardwareSerial::begin(unsigned long)”.
-r means “reverse sort”. This is for having the biggest functions at
the top, instead of at the bottom.
-td is for displaying the sizes in decimal instead of hexadecimal.

Since you are only interested in flash usage, you can ignore the symbols
in BSS. On a unixish OS, you could just pipe into grep -iv ' b '

Moving strings to PROGMEM will only exacerbate the problem, since PROGMEM is the 32k flash.
You can easily get your "symbol table" from the compiled .elf file by using avr-objdump -t <.elf file>.
It results in a list something like this:
... scrolls past ...
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
00800110 g       .bss   00000000 __bss_start
000008a2 g     F .text  00000022 main
00000126  w      .text  00000000 __vector_4
00000000  w      *ABS*  00000000 __heap_end
00000126  w      .text  00000000 __vector_9
000003ae g     F .text  000000d0 delay
00000126  w      .text  00000000 __vector_2
00000126  w      .text  00000000 __vector_21
00000126  w      .text  00000000 __vector_15
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
008001c3 g       .stab  00000000 __heap_start
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
000008ff  w      *ABS*  00000000 __stack
0000008d g     O .text  0000000a port_to_input_PGM
00800110 g       .data  00000000 _edata
008001c3 g       .stab  00000000 _end
00000126  w      .text  00000000 __vector_8
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000a08  w      .text  00000000 exit
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
00000126  w      .text  00000000 __vector_14
00000126  w      .text  00000000 __vector_10
000002a8 g     F .text  00000090 __vector_16
00800100 g       .data  00000000 __data_start
00000480 g     F .text  00000076 __vector_18
00000126  w      .text  00000000 __vector_20
00000108 g       .text  00000000 __do_global_ctors
... etc ...

The lines you are interested in are .text sections.  The first big number is the HEX location in memory.  The second one is the important one - that is the size.
You can see from that snippet that the function delay is located at address 0x3ae and is 0xd0 bytes in size.
If you're on Unix or OSX you can employ the more advanced searching tools that are at your disposal.  For instance, to just list the "global" .text entries:
$ avr-objdump -t <elf file> | grep '\.text' | grep ' g '

Which for my test program results in:
00000079 g     O .text  0000000a port_to_mode_PGM
00000918 g     F .text  00000040 _ZN5Print7printlnEv
00000a00 g       .text  00000000 __tablejump__
000006c2 g     F .text  00000040 _ZN14HardwareSerial4peekEv
000008c4 g     F .text  00000054 _ZN5Print5writeEPKhj
000000d4 g       .text  00000000 __trampolines_start
00000a0c g       .text  00000000 _etext
000006a0 g     F .text  00000022 _ZN14HardwareSerial9availableEv
0000012a g     F .text  0000002a loop
00000774 g     F .text  00000080 _ZN14HardwareSerial5writeEh
00000126 g       .text  00000000 __bad_interrupt
000000d4 g       .text  00000000 __trampolines_end
00000200 g     F .text  000000a8 digitalWrite
00000592 g     F .text  0000010e _ZN14HardwareSerial5beginEm
00000182 g     F .text  0000007e pinMode
00000097 g     O .text  00000014 digital_pin_to_port_PGM
000000d6 g       .text  00000000 __dtors_end
00000754 g     F .text  00000020 _ZN14HardwareSerial5flushEv
0000051c g     F .text  00000076 __vector_19
00000990 g     F .text  00000026 _ZN5Print7printlnEPKc
000000f8 g       .text  00000000 __do_clear_bss
000000ab g     O .text  00000014 digital_pin_to_bit_mask_PGM
00000000 g       .text  00000000 __vectors
000009fc g       .text  00000000 __tablejump2__
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
000008a2 g     F .text  00000022 main
000003ae g     F .text  000000d0 delay
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
0000008d g     O .text  0000000a port_to_input_PGM
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
000002a8 g     F .text  00000090 __vector_16
00000480 g     F .text  00000076 __vector_18
00000108 g       .text  00000000 __do_global_ctors

From that I can see that the function _ZN14HardwareSerial5beginEm is the biggest and takes up 0x10e bytes.  That strange named function is a "C++ Munged" name.  It actually corresponds to HardwareSerial::begin() and is the parent class name for Serial.begin().

Nice answer! But two comments: 1) Moving strings to PROGMEM does not worsen the problem: whereas PROGMEM strings eat flash, non-PROGMEM strings eat both flash and RAM. 2) With avr-objdump you can use the options -t .text to list only the .text section, and -C to demangle the symbols.

A number of compilers I use put constant values in .rodata instead of .text, so it is useful to know how to do custom filtering with grep et al - that way you can filter it exactly to your needs.  Of course, if you're a wincan't user then you're pretty much screwed...


text:
Connect push button to ArduiMU
I've got an ArduiMU V3+ and would like to connect an ordinary push button to it.
How would I connect it to it.

Presumably connect it between ground and an unused input, then activate a pullup resistor on the input.  This really depends on the software you are running, and on any unique requirements of your application (such as acceptability of various types of failure).

May I use analog-inputs as well?

This site realy exists as a fallback for things which are not covered in or not clear in the documentation, not as an alterantive to it.  Please start with http://www.arduino.cc/en/Tutorial/AnalogInputPins

source: Stack Exchange

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

sort: votes


text:
WLAN module compatible with ArduiMU V3+
Current I use my ArduiMU V3+ with a Bluetooth Mate (from Sparkfun) but I've got a lot of connection problems with it.
I'm looking for a better solution involving WLAN and am wondering whether there are compatible modules?

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


text:
Store floats in and reading them from flash
How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)
The storing part doesn't seem to be so difficult as this compiles:
PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

There is a helper macro in avr-libc that is designed just for this purpose:
#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space.

Use it like:
PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);

I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.
const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};

then retrieve thusly:
float val = pgm_read_float(&pmdata[idx]);

what "&" means on &pmdata


text:
How to use Ultrasonic Sensor's trig pin, and why it is needed?
I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?
(With Arduino examples, I generally use Echo pin more than trig pin.)

I wonder how you can get anything meaningful from Echo, if you do not use Trig. Are you sure that Trig is not activated by some library you might be using? Or you might have some circuitry driving Trig for you?

This is a reasonable question, as the Arduino example assumes a 3-pin device where Trigger and Echo are combined, but most suppliers provide a 4-pin one where they are distinct.

Yes, you do need it.
The purpose of the TRIG pin is to cause the module to send out a "Ping".  It's what makes the whole thing work.  As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking.  8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.
If you don't use the TRIG pin the module won't be able to do anything at all.

There are two versions of this device. In the threepin version you trigger the measurement and receive the echo pulse on the same pin. In the four pin version trigger and echo are on separate pins.
Possibly your Arduino example is written for the three pin version.

If we can use it with three pins, why do we need it with the four? And Is it meanful with using four pinned one in any project? How? What is the difference?

Two different solutions to the same problem. Both works. You have to interface the version you have. Do you need help with modifying your code?

No, thanks. I learnt how to do. You are kind. Thanks.

I stumbled across your topic while working in a personal project. As people said earlier, your doubts must be related to the different versions of this board.
Keep in mind that, when using the 4-pin you can keep the ECHO full online as an input, while in the 3-pin version, you need to cancel the ECHO to use it as Output for the TRIG.
This is particularly useful when you need to make a environmental analysis to different responses to different actions.


text:
Can a connection of HC-05 and Arduino Nano receive audio and display waveform on computer?
Working to receive Music for Bluetooth Speaker via HC-05

No, it can't.  The HC-05 is a Bluetooth Serial device, Bluetooth speakers are Bluetooth Audio Sink devices.
It's like asking "Can my bicycle fly?"

I think you'll agree the answer is "NO".
The only possible way of doing it using the HC-05 is to receive the audio using your computer then pre-process it and send the important information to the Arduino through the HC-05, so the Arduino can then send it back to the computer for displaying.  But then, what really is the point of the Arduino...?!

So what bluetooth modules should I use to make a Bluetooth speaker?

Like I said - a bluetooth audio sink module. I don't know if there is a "module" as such available - you are probably best off getting a real set of bluetooth speakers or a bluetooth headset and ripping it apart.

Bluetooth audio modules are sold, often at a price premium.  It's possible that in some cases they may just be a different firmware on the same silicon, but as that is typically not released its not really a do-it-yourself modification.

http://arduino.stackexchange.com/questions/9890/install-bluetooth-inside-a-home-theater-how   I too asked...


text:
Arduino Yun used as Wi-Fi hotspot
I use for a project an Arduino Yun with Node.JS + socket.io to provide interactivity between a smartphone, driving through a webpage different devices.
I would like to enable this service for several smartphones at the same time. However I would like to work in the very same conditions that a (well configured) hotspot does:

I want to ensure that no user can see the other users on the network,
I want to have a limited number of connections on the Yun at the same time,
I want to force the different users when connected to the Wi-Fi to be routed to a captive portal on the first connection.

Does anyone know first if it is possible with an Arduino Yun (maybe some actions must be performed on a NodeJS virtual server as point 2). If yes, do you have a tutorial or any clues (do I have to use LuCi)?
Last question, in the same topic, I would like to use a fast granted access using NFC tag emulation to provide Wi-Fi credentials. Has anyone tried this with Arduino Yun and a shield?

Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using socket.io and giving a limitations of the number of users.
First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file /etc/init.d/network.
Including the lines:
config 'interface' 'wan'
        option 'proto' 'static'
        option 'ifname' 'your_interface_name'
        ipaddr xxx.xxx.xxx.xxx

or by using the LuCi interface.
For more information about the way to properly configure the network in OpenWRT, see Network configuration.
Then the router is set to authorize only few IP addresses.
The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router gives the way to do this.
Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.
In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.
In socket.io, I took the id that is given to any connected client and the IP address to ensure that I have a same user.
About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.
I finally get at the end a device:

Connected to an existing network and accessing the internet,
Serving the webpages I want using my node serve,
Able to push any information on any other devices on the network through my nodeJS server,
Enabling access to people to local or network content,
Serving some specific local information through the NFC shield.


text:
Yun as bluetooth master
How does one make an outgoing bluetooth connection?  I have already installed packages for bluetooth, and have run hcitool scan to find the BT address. And I'm using a USB BT dongle.
Output of lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 058f:6254 Alcor Micro Corp. USB Hub
Bus 001 Device 003: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Bus 001 Device 004: ID 058f:6366 Alcor Micro Corp. Multi Flash Reader

Outgoing connection to what?

what connects matters?

Yes, it matters. You use different commands to configure different kinds of connections.  Bluetooth is a vast topic, so you have to be specific or we'll be here for the next month.

I'm trying to stream audio from an sd card to a headset

@Majenko Is generic pairing instructions possible?

No, as I said you use different commands for different devices.  I don't have BT on my Yún at the moment to play, but this may help you: http://unix.stackexchange.com/questions/96693/connect-to-a-bluetooth-device-via-terminal

@Majenko No Bluez-tools for yun... :(

There's "bluez-utils" - have you looked at that?  Different package systems name things differently.

Also, in my experience, getting bluetooth audio to work on Linux has meant integration with Pulse Audio, which I doubt you'll have on the Yùn.


text:
ACS712 to build doorbell sensor - Arduino Hangs up
I have a ACS712 module that I am connecting to my Arduino Uno to read the current spike when my door bells rings (and then trigger some events in my "sketch").
In my country doorbells use the ~115 VAC at ~60Hz. So, I just opened the doorbell and connected the ACS712 module in series.
I do not know how much amperage my doorbell draws, but it is hardly the 30A supposedly supported by the module.
At this point I am not connecting the OUT pin to the Arduino, only VCC and GND to the +5V and GND of the Arduino Uno. (I am also tried connecting the OUT pin to A2 in the Arduino).
What happens is that as soon as I ring the doorbell the Arduino hangs up. Sometimes I even have to physically unplug the Arduino to get it back to life.
It doesn't necessarily happens in the first bell, but it does not survive 3 rings in a row.
The ACS712 chip is supposed to provide 2.1 kVRMS of isolation... it doesn't seem likely that the "kickback" from the bell would be 2100 VAC... so I cannot imagine how/why my Arduino is hanging up, when it is supposed to be completely isolated from the AC (that's the whole point of the Hall Effect current sensor).
I added some capacitors to the VCC/GND pins with no luck.
So... any ideas on 1) how to protect the Arduino from hanging up?, 2) what is making the Arduino hang up?.

Your second link to the reference sheet points to the downloads folder on your PC - we can't see there :)

How are you powering the Arduino? And what is the voltage (measure with a multimeter between VCC and GND) when the doorbell is pressed? If it drops much below 5v, the arduino may decide there is not enough power and shut down, to be reenabled when the power comes back.

Powering Arduino: USB port of laptop to be able to monitor what is going on. 2) VCC voltage: I haven't been able to measure it (due physical layout, and also because the doorbell doesn't last even 1 second), also: why would the voltage change? the module is supposed to isolate the the two circuits. I'll try to measure it (again) anyways.

The module will isolate the doorbell, but the module will also use some power to do the measuring. I have had issues in the past where running a motor, which draws a high current, from a battery, caused the voltage to drop down too low for the Arduino to keep running. Some USB ports have over-current protection on them, resulting in the same effect.

There are two probable solutions to your problem:

The ACS712 is a hall effect based sensor and also door bells have a solenoid attracting a hammer to hit the bell. Try and place the sensor away from the bell, this could avoid any possible magnetic interference. (This is less likely to happen but there is a fair amount of chance)
May be, there is a problem with the code OR the laptops USB. Connect the Arduino to the sensor and the OUT pin to an analog input. Run the following code:

  void setup()
  {
     Serial.begin(9600);
  }
  void loop()
  {
     Serial.println(analogRead(A2));
  }

If this doesn't work, probably there's a problem with the sensor or the connections.
Give me more details about your connections, code and post a picture of your project for more help.


text:
Is my Arduino fried?
I am worried that my Arduino is fried from a previous attempt at connecting a servo to it. To test my concerns, I changed the circuit to see if Arduino could even power a simple LED:
Code:
int led = 13;

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

void loop() {
    digitalWrite(led, HIGH);
    delay(4000);
    digitalWrite(led, LOW);
    delay(4000);
}

Wiring:

In that pic, the Arduino is connected to a 9V battery. When I test the purple connections with my multimeter, the power bounces between ~5V and a weird 1.65V value every four seconds. I assume thats power being applied to the output pin in keeping with my code.
However, the LED does not light up. Any ideas as to what could be going wrong or how I could troubleshoot?

Have you tried putting the led the other way around?
Led's do have polarity, so they won't lit up when they're put in the other way around. And also, are you sure the LED is working?

LEDs have a longer and shorter lead. The longer one is positive. The way your diagram is drawn, it looks like you have it in backwards.

As noted in the previous answer, being able to upload a new sketch indicates an Arduino is ok in general – in particular has a functioning CPU – but of course that does not test all features.  For example, individual inputs and outputs can be damaged.
You can easily change your sketch so that it drives some range of outputs, as shown below.  Thereafter, try moving the red wire (that now connects on 13) to some other of the outputs in the selected range.
enum { LedLo=2, LedHi=20}; // Set lo and hi limits of range

void setup() {
  for (int led=LedLo; i <= LedHi; ++i)
    pinMode (led, OUTPUT);
}

void loop() {
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, HIGH);
  delay(4000);
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, LOW);
  delay(4000);
}

If the LED 'ON' is lit, the board has 3.3v power.
Does the LED 'L' blink? It is also on pin 13, the one your sketch controls.
If so, perhaps your breadboard circuit is likely at fault.
Do you have a multimeter? Does the voltage on whichever pin # your sketch controls change as you would expect it to?
If both are correct, then if you recompile your sketch to use a different pin #, and adjust your connections to match, does your breadboard LED light then?


text:
Multiple LEDs & HC-SR04
I want to use a distance sensor like the HC-SR04 to power a stop light like parking sensor for my garage. I have seen a lot of tutorials on how to use the HC-SR04 to power a single LED and found the schematic below on how to control up to 14 LEDs by hooking them onto the 5v and using a transistor. I have added a box where I would hook the sensor in. My question is, would it work if I had the sensor hooked into the 5v as well. The plan is to have 3 sets of 14 LEDs and have one set on at any given time. I plan on using an Arduino Uno.

Thanks for all your help and encouragement. The link http://www.arduino.cc/en/Main/ArduinoBoardUno says that there is a 5 v output straight from the board's voltage regulator. Is that not separate from the output pins?

If you power your Arduino through the Vin pin, the current limit will be given by the 5 V regulator. According to it's datasheet, it's actually a power dissipation limit: the higher the Vin voltage, the lower the current limit (power = current × (Vin − 5 V)). Check the thermal pad size on your Arduino and refer to Fig. 21 (p. 8) of the datasheet.

Edgar, would I have enough current to run those LEDs and a distance sensor from the 5 v pin if I had a 9v 1A charger?

@user2969 If you hooked the power to VIN and GND, then that should be more than enough for the HC-SR04 and a handful of LEDs. On a side note, please ask another question if you have another question. Thanks!

140 mA × (9 V − 5 V) = 0.56 W. The regulator can dissipate up to 0.6 W with the minimum pad size. Then, assuming the Arduino complies with this required minimum, you should be (barely) fine.

Thanks Everyone! That answers my question. Sorry for all the confusions

If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring).  As a function of the distance measured, you want ONE of LED A, B or C lit.
Since you are using an Arduino, you have GPIO pins.  Connect a different GPIO to each of A, B and C.   You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of  "if" statements which will choose which of the GPIOs to set HIGH and the others LOW.  The GPIO set HIGH will switch on the corresponding LED.
In fact, its going to look a lot like this Instructable:
http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

I think you are understanding. I was just concerned about running both the LEDs and the distance sensor off the 5v output. I didn't think it would matter as long as I always had one set of lights on so the sensor would have power

The main difference with the link you posted is the LED is being powered by the GPIO. I was under the impression that the GPIO pins wouldn't supply enough voltage (or current, I'm not sure... I really am just starting). Here is where I got the original schematic: http://electronics.stackexchange.com/questions/78096/power-14-red-leds-and-arduino-from-same-source#

The maximum amount of current through a GPIO pin is rated at 40mA.  If an LED sinks about 20mA then you can series wire 2 LEDs.  If you need to power more LEDs when a GPIO pin goes positive, then you have choices.  You can use a transistor or something like a 4050 IC (drive up to 6 higher current devices).  The maximum output current through an Arduino is 200mA ... so if you are to power everything from the Arduino, you need to ensure that you are less than this in total.

Which brings me back to the schematic above. The LEDs are powered via 5v connection, which if I have read everything correctly, can support greater current (900 mA) because it doesn't run through the Arduino

In the schematic, we see one GPIO controlling a bunch of LEDs which is not what I understand the plan to be.  The schematic also shows that the LEDs are being powered by the output 5V from the Arduino.  The Arduino spec says that it can source a max of 200mA.  Now, if you need 900mA then you connect a source that does NOT come from Arduino and give both the Arduino and the driving source a common ground.

I'm not trying to be difficult, but everything I find says the GPIO pins are current limited, but the 5 v supports more. I just double checked http://www.arduino.cc/en/Main/ArduinoBoardUno and it specifies a current limit for the 3.3 v but says nothing about the 5 v and other posts have suggested the 5 v. I am not sure how much I actually need, the LEDs in the set up above only draw about 140 mA according to the post linked. Essentially I planned on having three of those led chains each hooked up to their own transistor and GPIO pi and selecting a set based on readings from the distance sensor

Perhaps I have jumped too far into the deep end :-/

Please don't get discouraged ... the good folks on communities like this are here to help and before long, you too will be offering assistance.  Here is the official page on the specs of the Arduino.
http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
It seems to be unambiguous that the Arduino can source a total of 200mA.  This is irrespective of the voltage pin used.

Thanks for all your help and encouragement. The link http://www.arduino.cc/en/Main/ArduinoBoardUno says that there is a 5 v output straight from the board's voltage regulator. Is that not separate from the output pins?

@Kolban: The 200 mA figure you quote does not relate to the Arduino's 5 V pin: it's the maximum current the ATmega328P can sink on its Vcc pin. It's also the total current the Arduino can source on all its GPIO pins combined, plus the ATmega's own consumption.


text:
Fastest wireless communication
Hy guys,
I am currently working on a quadcopter stabilization algorithm for an indoor quadcopter. I now need to setup a wireless communication between my onboard Arduino and my controlling Arduino (and/or RasperryPi (not shure yet)).
My question is: What would be the fastest wireless communication possibility?
I am not worrying about distance; they won't get far apart from eachother. I want to keep a lot of resources on the stabilization algorithm and to keep down resources used for the communication and thus get the fastest communication on very few resources.
What are your opinions and experiences, what is going to be fastest?

There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).
If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.
I personally do not know much about Bluetooth modules, so I cannot comment there.
Hope this helped.

Be careful of the distinction between throughput vs latency.  WIFI may have great throughput, but what the poster's application requires is to move a small amount of data with low latency, and simpler schemes often do better at that.  nRF24L01+ and compatible are already in widespread use as one of the three main chipsets for manual control of flying toys, so do seem worth investigating.

Good point Chris, typically a packet has to move from the quadcopter to a router and then to your PC/phone. Which might take longer as a direct link. But you should specify requirements, otherwise it will be a witchhunt on the fastest method. Also,  it's realtime and shouldn't have random  delay spikes.


text:
Detect my position
I'm new to Arduino, but I have this idea for a game I would like to build.
I need the Arduino to be able to determine my relative position on a straight line - 20 feet (6 meters) long.
What would be the best way to achieve that?
Priorities:

Durable (Outdoors proof)
Easy for a newbie
Cheap

EDIT. Some more context - I want to play Pong over a physical area (A grid of LEDs to act as pixels), and I want the use player's position on a line to set the position of the paddle.

Whether it's outdoor proof or not depends on the housing where you put your electronics.
For position tracking, there are basically 2 ways:
1. GPS
2. Acceleration sensors
For the given distance, a (cheap) GPS solution is not accurate enough (See https://www.sparkfun.com/tutorial/GPSTracking/clamped_edit2-L.jpg, for instance). And it may be too slow for your purpose.
Acceleration sensors also have a simple serial interface, but handling the data to get accurate results is not really easy (However I'm sure that someone has already written a public available software library)
Luckily, for position tracking on a straight line, there's another solution:
3. use a ultrasonic sensor
Maybe there are even better solutions; to evaluate, it would help if you could specify your project more detailed (how exact shall the relative position detection be? Static or dynamic calculation? If dynamic, how fast will the movement be? ...).
Edit:
It could be worth considering the following alternative:
4. Use a rotary encoder, mount it to a retractable dog leash and hook this to the player's waist. The other end of course must be mounted to a steady pillar. Perhaps this is mechanically tricky, and it limits the mobility of the players, but electrically it's very easy.

Ultrasonic would be worth trying.  It was disappointing to see your mention of Acceleration sensors in a positioning application.  I see that further in you recommend against that, but it's not a case of it "not being easy" but rather one of it just plain not working as sensors you can buy are inaccurate enough to be meaningless after double integration - and that's assuming you somehow have perfect orientation information to map acceleration axis to environment coordinates.

If it's a grid of LEDs you may be able to place pressure sensors at points up and down the grid. Then you need to step on them in order to place the paddle at that point. Doesn't sound like you need 'exact' position, just a point on a grid. And you may be able to set up such pads to step on relatively cheap: force sensitive resistors or even whip up your own w/ cardboard and thin metal (foil?) separated with foam. We did similar for a halloween prop that was activated by stepping on the doormat.


text:
RESTful API with ESP8266 and arduino mega
Anybody had worked with ESP8266 to post data to RESTful web service? I was trying but it's not posting anything. Tried with a test server:
http://www.posttestserver.com/

Serial.println("\nSetting AT+CIPSTART");
String client_conn = "AT+CIPSTART=\"TCP\",\"";
client_conn += SERVER;
client_conn += "\",";
client_conn += PORT;
Serial.println(client_conn);
Serial2.println(client_conn);
delay(3000);
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
    Serial.println('\n\r');
}

It showed me that it got connected
Now I created POST string
String data = "{JSONBODY}";
String post = "POST /post.php HTTP/1.0\r\n";
post += "Host: posttestserver.com\r\n";
post += "Content-Length: ";
post += data.length();
post += "\r\n";
post += data;

Transmitting data
Serial2.print("AT+CIPSEND=");
Serial2.println(post.length());
delay(1000);
if(Serial2.find(">")) {
    Serial2.println(post);
    while (Serial2.available() > 0) {
        c = Serial2.read();
        Serial.print(c);
        if(c=='\n\r' || c == '\r\n')
            Serial.println('\n\r');
    }
    delay(5000);
    Serial2.flush();
    delay(5000);
}

Returned nothing
Closing connection
delay(1000);
Serial2.println("AT+CIPCLOSE");
while (Serial2.available() > 0) {
    c = Serial2.read();
    Serial.print(c);
    if(c=='\n\r' || c == '\r\n')
        Serial.println('\n\r');
}
delay(5000);
Serial2.flush();

Connection closed
But It returned nothing. posttestserver returns data path where it stored.

There must be two CRLFs between the headers and the data, thus replace post += "\r\n"; by post += "\r\n\r\n";. 2) c == '\r\n' does not make sense, as \r and \n are two different characters.

Thanks man, I will try it and let you know @EdgarBonet :)

@EdgarBonet Thanks man. Another thing I had to do is, I had to add a 1000uF capacitor across VCC and GND as due to data transmission it fall short of power.

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


text:
Read signal from USB mouse on an Arduino ?
I've got a project where I'd need to read my mouse's signal. My mouse is a G700S (so USB) and the thing was I don't really know how to do and even if it's feasible.
I'm using an Arduino Micro and my initial idea was to get a PS/2 to USB Adapter (I already have one) and then to plug it to something like this wired to my Arduino.
So my question basically is "will it work ? and if not, why ?"
The main idea is not to use USB (like an USB Host Shield) because Arduino doesn't have any USB mouse driver.
Thank you in advance

You won't be able to operate a USB peripheral without something that can act as a USB host controller.  USB host "shields" are not cost effective, but there are options out there which both have USB host ports and are far better embedded computers than an Arduino, at lower price.  Both the KL25Z and KL46Z freedom boards can do this, as can the STM32F4 Nucleos, and likely some others.  In the KL25Z case the chip itself actually costs a few cents less than an ATmega238p, and has twice the flash and four times the RAM. But you will be using a traditional toolchain or mbed.org rather than Arduino.

Is there any way to discuss with you about this ?

This would be possible only if the mouse actually supports PS/2. USB to PS/2 adapters are entirely passive, and in order to function it requires that the controller in the mouse is designed to communicate in both protocols. Modern mice, especially wireless ones don't tend to have this capability anymore as PS/2 is all but a dead standard.

Mmh ok so I should try if my mouse works with the adapter prior to buying the stuff for the Arduino, right ?

@ThomasKowalski Yes. I would see if you can find a datasheet for your mouse (or at least a spec sheet) which should tell you its capabilities.

Well I tried to find a datasheet or something but I didn't find anything on Google. And I didn't find anything about backwards compatibility for PS/2. Anyway it's there if it can help.

I would say it's "unlikely" at best.  Better to buy a cheap PS/2 mouse and have done with it.


text:
Can't use base class and derived class functions
I have made two libraries and one test program.I have made my custom uart library.first i have included all functions for printing in single uart library file.but then i have made print library for printing functions only.my files are listed below.i have not posted my code directly so it can be read separately.
uart.h
uart.cpp
print.h
print.cpp

Test.cpp

#include <avr/io.h>
#include "uart.h"

int main(){
    uart.start(9600);
    uart.print("Test");
}

and i get this error..

Error

src/print.cpp
src/print.cpp: In member function 'void PrintClass::print(unsigned char)':
src/print.cpp:4:12: error: 'write' was not declared in this scope
write(data);
          ^
src/print.cpp: In member function 'void PrintClass::print(char*)':
src/print.cpp:13:22: error: 'write' was not declared in this scope
write(string[index]);
                   ^
.build/uno/Makefile:47: recipe for target '.build/uno/src/print.o' failed make: *** [.build/uno/src/print.o] Error 1
Make failed with code 2

i have referred default arduino libraries like hardwareSerial and LiquidCrystal and i made my library like that but i cant get rid of that.
Please Help me.

Any functions that the base class needs to call that will be defined in the child class must also be defined in the base class.  They should be defined "virtual" so they can be overridden, and can even be "pure virtual" so they have to be defined in the child class.
So for any function in the child class that the base class needs to access, add this to the base class's definition (print.h):
virtual void write(unsigned char data) = 0;

The = 0 bit defines it as pure virtual, and any classes than inherit this class without defining their own copy of the void write(unsigned char) function will thrown an error.
Instead of pure virtual you can provide a default function that a child can override if they want to, which can be useful if most classes will work the same way (define it in the parent) but some want to do it differently (override it in the child), in which case you treat it like a normal class function but add the virtual tag.
The whole topic is called polymorphism and is an incredibly powerful system.  It's discussed in detail here: http://www.cplusplus.com/doc/tutorial/polymorphism/

if you dont mind,can you explain with my code..please

All you should need is the one line of code I show there - add it to print.h

I dont know how can i thank you.thank you for helping again. :) .


text:
Control air conditioner using Arduino
I followed a couple tutorial on how to receive and send IR codes to control air conditioner the receiving part is working fine and I copied the IR data of the remote control but the problem I am having is sending these codes via IR led can't seem to get it to work can someone help me please.
This the code to send the date via IR LED
#include "IRremote.h"
IRsend irsend;
void setup()
{

Serial.begin(9600);
}

int khz=38; //NB Change this default value as neccessary to the correct modulation frequency
// ON and 2O C° with 1 FAN heat
unsigned ON[] ={4400,4300,550,1600,550,500,600,1550,550,1600,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,600,500,550,1550,600,1550,600,500,550,1550,600,500,550,500,600,500,550,1600,550,1550,550,1600,550,1600,550,1550,600,1550,600,1550,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,550,550,550,500,550,1600,550,500,600,1550,600,1550,550,500,600,1550,550,1600,550,1550,600};
unsigned OFF[] ={4350,4350,550,1550,550,550,550,1600,500,1600,550,550,500,550,550,1600,550,550,500,550,550,1600,500,550,550,550,500,1600,550,1600,550,500,550,1600,550,550,500,1600,550,1600,550,1600,550,1600,550,500,550,1600,550,1550,550,1600,550,550,500,550,550,550,500,550,550,1600,500,550,550,550,500,1650,500,1600,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,500,550,500,600,1550,550,1600,550,1600,500,1650,500,1600,550};

void loop() {

irsend.sendRaw(ON, sizeof(ON)/sizeof(int), khz);
delay(5000);
irsend.sendRaw(OFF, sizeof(OFF)/sizeof(int),khz);
delay(5000);
}

The problem is my A/C doesn't detect IR codes.

How is your IR system wired?

Don't know I am kind of a beginner at this. How can I tell ? @Majenko

You should know how it's wired, since you wired it up. Show us a photo, or at least a wiring diagram.

Possible duplicate of control air conditioner using arduino


text:
print data after being plugged back into USB
I have an arduino uno powered by a battery on a buggy with a sonar distance sensor.  I have a program that calculates the speed it's going, and I want to correlate speed with stopping distance.  I can measure the stopping distance manually, but I want the arduino to report to me the speed it was going when the motor was turned off.  I don't have an LCD display - I wanted to print the number to the serial monitor, but plugging it back into the USB port resets everything I think, or at least the serial monitor.
Without buying more components, can I get the data (calculated speed) somehow?

There are ways of disabling the auto-reset feature: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see:
http://www.arduino.cc/en/Reference/EEPROM


text:
PIR motion sensor stuck in a loop
I've bought an HC-SR501-compliant PIR motion sensor (like this one) and connected it to a Teensy 3.1. The circuit seems fine, and the LED lights up. However, when nothing is moving in front of it, the sensor keeps reporting HIGH and LOW in suspiciously constant intervals. The monitor reads like this (numbers in milliseconds)
motion detected  4113
motion stopped   7234
motion detected  4114
motion stopped   7274
motion detected  4113
motion stopped   7204
motion detected  4111
motion stopped   7184

When it detects movement, it stays on the triggered position for longer, but even then goes back to predetermined intervals, e.g.
motion detected   4113
motion stopped   17204
motion detected   4111
motion stopped   41754
motion detected   4113

This is the sketch (as found on Adafruit):
int ledPin   = 13;              // choose the pin for the LED
int inputPin = 1;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val      = 0;               // variable for reading the pin status

unsigned long lastTime = millis();

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input

  Serial.begin(9600);
}

void loop(){
  unsigned long currentTime = millis();

  val = digitalRead(inputPin);   // read input value
  if (val == HIGH) {             // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {

      // we have just turned on
      Serial.print("motion detected ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = HIGH;

      // Save time for measurement
      lastTime = currentTime;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH){

      // we have just turned off
      Serial.print("motion stopped ");
      Serial.println(currentTime - lastTime);

      // We only want to print on the output change, not state
      pirState = LOW;

      // Save time for measurement
      lastTime = currentTime;
    }
  }
}

Could this be a faulty device? I'm thinking about getting a new one for testing. While I can compensate for the gaps when triggered, I can't think of a way to make sure that it's not actually being triggered by this weird internal interval.

Try powering the PIR motion sensor with a higher voltage.  I get the same problem you're seeing when powering it with the 3.3v output of an Adafruit Huzzah ESP-12, but it works just fine when I power it with the 5v USB power.

From the Adafruit page:  "Runs on 5V-12V power (if you need to run it off of 3V you can do that by bypassing the regulator, but that means doing a bit of soldering)."  So powering it from the Teensy's 3.3V may be the problem.


text:
How to avoid that my arduino clicks eternally?
I have accidentally implemented a program that imitates the click of the mouse.
The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.
Can I solve this problem?

That is actually pretty funny. Now I'll be sure never to write a program on my Arduino that resets my computer :+)

Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer.  Load Blink.ino into the IDE and compile it.  Press the UPLOAD button in the IDE and move the mouse to somewhere "safe".  Release the RESET button.
Do those last three steps in rapid succession and you should be fine.


text:
Arduino UNO button LED brightness vary
I am using an Arduino UNO and I am trying to vary the brightness by steps by 0.5 volts till it gets to a max of 5.0 V using buttonA and decrease the brightness of the LED by 0.5 volts with buttonB. The Problem I have is that when I push buttonA the LED steps it's voltage by 0.5V all the way to 5.0V and with buttonB its steps down to 0. I would like to have the LED step each time I press the button not all at once. Here is my code that I have so far can someone help me with telling the Arduino to Step each time a button is pressed. CODE IS DIFFERENT from another post I did
HERE is my code:
int ledPin = 9; // must be a PWM digital pin
int buttonApin = A2; //buttonA to analog 2
int buttonBpin = A1; // buttonB to analog 1
int maxBright = 255; // between 0 and 255
int ms = 1500;    // delay in milliseconds
int buttonPushCounterA = 0; //counter for the number of button presses
int buttonStateA = 0; // current state of the button
int lastButtonStateA = 0; // previous state of the button
int buttonPushCounterB = 0; //counter for the number of button presses
int buttonStateB = 0; // current state of the button
int lastButtonStateB = 0; // previous state of the button

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW) //if buttonA is pushed
   {
      buttonStateA = digitalRead(buttonApin);

     if (buttonStateA != lastButtonStateA)
     {
        if(buttonStateA == LOW)
     {
        buttonPushCounterA++;
     }
    }

// fade from min to max in increments of 25.5 points: basically (0.5 volts)
for (float n = 0; n <= maxBright; n +=25.5)
{
 // sets the value (range from 0 to 255):
 analogWrite(ledPin,n);
 delay(ms);
}
  }

  if (digitalRead(buttonBpin) == LOW) //if buttonB is pushed
  {
     buttonStateB = digitalRead(buttonBpin);

       if (buttonStateB != lastButtonStateB)
         {
            if(buttonStateB == LOW)
              {
                buttonPushCounterB--;
              }
         }

     // fade from max to min in increments of 25.5 points: basically (0.5 volts)
     for (float n = maxBright; n >= 0; n -= 25.5)
    {
     // sets the value (range from 0 to 255):
     analogWrite(ledPin, n);
     delay(ms);
    }
  }

  lastButtonStateA = buttonStateA;
  lastButtonStateB = buttonStateB;
 }

possible duplicate of Arduino UNO coding problem voltage varying

Yeah it was my other code I had changed and fixed some things

I don't see where in your code counter is changed; with this code, it will always be 0!

One problem in your original code is that you are only storing the current state of the buttons if they are pressed.  The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.
This would be my replacement for your loop() code:
loop()
{
    int currentButtonStateA = digitalRead(buttonApin);
    if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
    {
        currentBrightness += BRIGHTNESS_INCREMENT;  // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
        if (currentBrightness > MAX_BRIGHTNESS)     // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
        {
            currentBrightness = MAX_BRIGHTNESS;
        }
    }
    lastButtonStateA = currentButtonStateA;

    int currentButtonStateB = digitalRead(buttonBpin);
    if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
    {
        currentBrightness -= BRIGHTNESS_INCREMENT;
        if (currentBrightness < MIN_BRIGHTNESS)     // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
        {
            currentBrightness = MIN_BRIGHTNESS;
        }
    }
    lastButtonStateB = currentButtonStateB;

    analogWrite(ledPin, currentBrightness);
}

Hopefully this is pretty self explanatory.  The current button A state is read and stored in a local variable.  If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value.  Next the current button state is stored as the previous state ready for the next run through the loop.
Similar actions are performed for the B button, but with a decrement rather than an increment.  Finally the LED brightness is set regardless of whether any buttons have been pressed.
You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables.  You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).
You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX_BRIGHTNESS 255".
The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.

THANK YOU THANK YOU THANK YOU!! this made perfect sense and it works!! thank you!!

okay quick question.. i have wired it up and ran the program but sometimes when I push buttonA the voltage steps from 0 - 1V or from 1.0v-3.0V and not taking the half step intervals. is there anyway to fix that problem?

I think this is call bouncing.  As the button physically changes, the connection is made, broken, made and broken repeatedly causing several button clicks.  There are probably better ways to debounce, but a simple way would be to add a delay into your code.  Try delay(100) in the loop.  That would mean it only reads the buttons 10 times a second, which will probably be fast enough.  If it is not, reduce the delay a bit.

You forgot to check to see if the button was actually pushed or if it was just held down. See the State Change Detection example to understand how to perform edge detection.

Awesome! would I use the stateChange functions before or after the if Statement of "if (digitalRead(buttonApin) == LOW)" ?


text:
SFML Packet and Arduino
Can the sf::Packet class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino

Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be HUGE.  So, "No!" is the answer.
You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?

I'm sending complex packets that must be deconstructed in a specific way. So I would prefer to have a way to send and receive data in such a way that it will always be the same.

That's what structs are for.


text:
LiquidCrystal_i2c and Pin 2
I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD.
I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.
I wrote the following code who works perfectly:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library
#include <DHT.h>

#define DHTTYPE DHT11
#define DHTPIN 13      // Digital

DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  while (!Serial) {
  }
  Serial.println("Serial OK!");

  dht.begin();
  lcd.begin(20,4);
  lcd.setBacklight(0);
  lcd.clear();
  lcd.print("Hello! ");

  Serial.println("Init finished!");
}

void loop() {
  delay(2000);

  float DHT_hum = dht.readHumidity();
  float DHT_temp_c = dht.readTemperature(false);
  float DHT_temp_f = dht.readTemperature(true);

  if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
    Serial.println("Failed to read from DHT sensor!!");
    lcd.clear();
    lcd.print("fail! ");
    return;
  }

  float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);

  Serial.print("Humidity: ");
  Serial.print(DHT_hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(DHT_temp_c);
  Serial.print(" *C ");
  Serial.print(DHT_temp_f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(heat_index);
  Serial.println(" *F");

  lcd.clear();
  lcd.print("Humi: ");
  lcd.print(DHT_hum);
  lcd.print("%");
  lcd.setCursor(0, 1);
  lcd.print("Temp: ");
  lcd.print(DHT_temp_c);
  lcd.print("C");
  lcd.setCursor(14, 0);
  lcd.print("HI: ");
  lcd.setCursor(14, 1);
  lcd.print(dht.convertFtoC(heat_index));
  lcd.print("C");

}

As you can see, I use pin 13 for the DHT11 (DHTPIN).
If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result).
The serial display
Serial OK!
Init finished!
Failed to read from DHT sensor!!

and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"
I'm lost... The LCD lib I use is the very common one from fm
https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

I'm self answering..
On my Arduino Leonardo, the SDA and SCL pin used for the I2C connexion to the LCD panel, are the same pin than the Digital pin 2 and 3. So using SDA/SCL remove ability to use pin 2 & 3.

LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Are you not using pin 2 in the LiquidCrystal_I2C constructor? So you can't also use it for the DHT sensor.

I withdraw that suggestion.

Can you please try saving some RAM?
Use the F macro with your prints, eg.
  Serial.print(F("Humidity: "));
  Serial.print(DHT_hum);
  Serial.print(F(" %\t"));
  Serial.print(F("Temperature: "));

Ditto with the lcd.print() calls.

From my understanding, the pin used in the constructor, are the pin used by the logic chip on the LCD panel, not on the arduino. I don't have anything from the LCD connected on pin 2 and LCD works. If I changed '2' to another (not used) pin, the LCD no longer work.

I don't see how that could be right. Why would the code care what pin is on the LCD logic chip? It needs to know what pin on the Arduino it uses for certain functions.

Because all LCD panel are not wired the same way. see https://arduino-info.wikispaces.com/LCD-Blue-I2C "Set the pins on the I2C chip used for LCD connections"

Hmm, that's odd. I see what you mean. Please see revised answer.


text:
MQTT for GSM/GPRS sheild
I want to publish sensor data to server using MQTT protocol via GPRS/GSM modem.
I googled MQTT for Arduino, AQTT Arduino available only for Ethernet shield or will MQTT Arduino Ethernet shield work in GSM modem?

Nick O'leary published an MQTT client for Arduino.
I use it extensively.  You can find it here: http://knolleary.net/arduino-client-for-mqtt/.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem.  I have used it successfully on:

the Arduino GSM shield
the Seeeduino GPRS IoT panel
a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router

Do you have an example for the GSM shield?

Arduino MQTT Library for SIM800 (and SIM900) GSM Modem is available at ElementzTechBlog, ElementzGithubRepository
Functionalities:
Auto connect

Automatically connect to TCP and to MQTT server.

connect function

This function can be used to connect your client to MQTT broker.
Use only if you do not use Auto connect functionality.
Optionally  you can use username, password, WILL topic and WILL
Message.

OnConnect CallBack function

This call back function is called when MQTT connection is
established.
You can call subscription and publish functions inside it (according to your need).

publish function
 - This function can be used to publish messages to different topics.

You can select  QoS levels and RETAIN flag according to your need.

subscribe function

This function can be used to subscribe messages from different
topics.

OnMessage CallBack function

This callback function is called when messages are received from
subscribed topics
Topic, TopicLength, Message, MessageLength are the arguments of
OnMessage callback function.
Inside this, you can write your custom code.

unsubscribe function

This function can be used to unsubscribe from a previously subscribed
topic.

disconnect function

This function can be used to disconnect your client from MQTT broker.

Keep Alive

You can specify your KeepAlive duration while initializing.
Ping requests are sent and received automatically.

Subscribe Publish examples are also provided.

MQTT is an TCP/IP protocol. MQTT-SN is for wireless serial and is slightly different but you can bridge the two.  Since you can establish a TCP/IP session over GSM, I would expect that functionality would not be duplicated in any way by MQTT, but would instead depend on your GSM hardware providing the TCP layer.
And the final comment, I doubt if you would ever see this on an Arduino. Simple alternative, use a common smartphone as a wifi hot spot, done.

MQTT is a "light weight" messaging protocol for use on top of the TCP/IP protocol.


text:
DS1302 as a counter/count-up timer
I would like to use the DS1302, as a count up timer.
My goal is to have the arduino time the amount of me driving my car.
So it DS1302 will be used a count-up timer ie accumulate time. however when the car is switched off, I don't want to lose the value, and when I use my car again I would like to the time to continue accumulating. The resolution can be in minutes, as this will probably be the best.
I would like something like an odometer of a car, except its going to be the time, instead of distance.
Q: Can this be done with the DS1302 Module? and also how can I do this? Is there a sample code for a count-up timer?

The Arduino can do the whole task by itself well enough.

In theory yes, but in practice it's become unreliable.

In practice the DS1302 is unreliable - as noted on the page you reference. Perhaps starting with "My Arduino does not time things as well as it should be perfectly able to - here is what I have tried in adequate detail - any ideas?" question may be a good start. Adding known bad hardware to a bad software or hardware issue may not help. || Arduino needs to be powered on when car is off OR stay on long enough to save data to non volatile memory. Either should be "easy enough".

"I don't want to lose the value" -> store it in non-volatile memory before shutting down the Arduino or in regular intervals -> e.g. EEPROM -> look for questions how to do this on this site / google.

What's the maximum time you want to record? Days, months or years?

@Ricardo it would be days, if the average engine life is 400,000km at an average speed of 40 km/h that would result to 400,000/50=10,000 hours of use, 10,000 hours = 417 days to record. But I am thinking this number would be significantly less. For example if the average speed is 45 kph its 370 days etc. If the engines life is only 250,000km @ 40kph = 260 days to record.

Do you mean only accumulate during powered/driving, or also during standing still?
If the former, just get the start time in setup, then in loop continuously get the time and calculate the difference between it and the time read in setup. Since you don't know when power is lost you need to continually write the elapsed time to some form of non-volatile memory. You could use the Arduinos EEPROM, but that can wear out over time. It's better the use the DS1302s 31 byte of battery backed RAM. Next time the arduino starts up you need to read out this value and add this to the difference.
In case of the latter, you can halt the DS1302 so it stops incrementing time.

I'm only after the time the keys are on the ignition, I don't care if they're sitting my car and listening to the radio or driving on the freeway, I'm just after the time the car is 'on'. Q: Is there any alternative methods in obtaining this data/statistics?

In that case use the first part of my answer. If you don't mind a bit less accuracy, you can even drop the DS1302 entirely. Just use the arduino millis function for tracking time. The crystal on the arduino is not that accurate, but you can measure the inaccuracy and account for this in code. You can probably get to less than 1 minute of drift per day.

What you're describing is the equivalent of a digital Hobbs hour meters. You can read up about them if your are interested. The old ones (not digital in today's sense) clicked an odometer-like movement every 0.1 hours (typically). I don't think you need a real-time clock module as long as you're not interested in when you drove the car, but only in the accumulated duration.
A simple way would be a 1-minute delay loop that increments a counter and writes it to EEPROM. The EEPROM has a write-endurance spec of 100,000 writes, equivalent to over 800 hours, used this way. You'll lose the last fraction of a minute, whether it's a few seconds or nearly a while minute, whenever you shut down the Arduino. There are ways around this, if it matters, but that's an "exercise left for to the reader" as my textbooks used to say. Clock your micro with a crystal, not with its internal resonator, for best accuracy.

When I rent out my car, I already have an analogue gauge for reference, The only way of seeing it would be physically being next to the car. I want the arduino to sms (gsm shield) me the hours every so often (every 8 minutes). Q: Do you know if the digital hobbs hour meter can be tapped into by the Arduino?

I've no idea, but wouldn't it be much simpler to let the Arduino do the whole job - timing + communication? I didn't mean to suggest you should install a Hobbs meter; just that you might get some ideas by reading about them. I think an AVR chip and the GSM module would probably do just what you want.

The comms are at a later stage -I just want to do the timing at the moment. You might be right, letting the Arduino do all the work might be easier.


text:
Exiting from one loop and get ready for another
I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.
What I am trying to accomplish is to set two passwords, namely pass1 and pass 2.
The condition is that this circuit is attached to a gate, if user 1 lets say knows pass1, after entering the pass the gate will unlock for 10 seconds and the pass1 becomes invalid i.e. can not be used in future. However if user 2 comes and knows pass2, after entering the pass2, the gate will open for 10 seconds and then pass2 becomes invalid; so each password can be used only once. I am attaching the code I already have below.
The problem with this code is that when pass1 is executed, the system does not take pass2 until unless the system is reset.
Kindly tell me a solution to fix this.
#include <Password.h>
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
Password password1 = Password("1234");
Password password2 = Password("4567");
int ledpin = A5;
int a = 0;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columns

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = { 8,  9, 10, 11};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
    lcd.begin(16, 2);
    keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop() {
    keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
    switch (keypad.getState()) {
        case PRESSED:
            lcd.println(eKey);
            switch (eKey) {
                case '*':
                    checkPassword();
                    break;
                case '#':
                    password1.reset();
                    password2.reset();
                    break;
                default:
                    password1.append(eKey);
                    password2.append(eKey);
            }
            return;
    }
}

void checkPassword() {
    if (password1.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code1 OK");
        delay(2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password1.append('1');
        lcd.clear();
        return;
    } else if (password2.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code2 OK");
        delay (2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password2.append('2');
        lcd.clear();
        return;
    } else {
        lcd.setCursor(0, 1);
        lcd.println("Wrong");
        delay(2000);
        lcd.clear();
        lcd.print("Wait for 5 Sec");
        delay(5000);
        lcd.clear();
        return;
    }
    return;
}

Regards
Fawad

Password 2 contains password 1 while it's being typed. You need to empty out Password 2 when password 1 is accepted and vice versa.

As a matter of courtesy for those who read your question, you should at least try to properly indent your code, as this makes it easier to read. I've done it for you now, but please do it yourself in the future.

You are never really invalidating the passwords. The statement
password1.append('1');

adds '1' to the guess, it does not change the password itself.
If you really want to invalidate the password, you should change it to
something that cannot be typed on the keypad. For example
password1.set("X");  // untypable password

Whether or not you do invalidate the previously used passwords, you
should reset the guesses once a password has been checked. This can be
done in checkPassword(), or in keypadEvent() as follows:
switch (eKey) {
    case '*':
        checkPassword();
        password1.reset();
        password2.reset();
        break;
    ...
}

BTW, all your return statements are useless, and the first
switch/case in keypadEvent can be replaced by
    if (keypad.getState() == PRESSED)

which would be easier to read.

Thanks Edgar, I am sorry for the indent part as you can tell I am very new to the community.
I will try these changes, and will get back to you!!
Could you kindly elaborate the change in the indent code at the very last.
Regards Fawad

@Fawad: Statements that are at the same logical level should be lined up. There are various common indent styles. They are all OK as long as you pick one and use it consistently.

I tried your suggestion to reset password in the case loop but it only resets it thus eliminating the main requirenment of one use per password...

@Fawad: This requirement is not fulfilled in your current code: typing '#' allows to reuse passwords. The reset() I suggested has nothing to do with this requirement either: it's meant to allow the use of the other password, and to give a second chance if you mistype the password. If you want to enforce single-use, issue passwordN.set("X"); once password N has been accepted, as I already mentioned in the answer.


text:
Transmitting sketches to Yun with Autobahn - a byte at a time?
I am using this tutorial to connect an Arduino Yun with a browser using Autobahn.
In the python file in the above repo, there is this code:
def controlLed(self, turnOn):
    if turnOn:
        payload = b'1'
    else:
        payload = b'0'
    self.transport.write(payload)

Here's the thing - I need to send whole sketches to my Yun, not just '1' or '0'. I tried sending more to the payload (like payload = b'this is part or all of a sketch') but that doesn't work. I experimented with some other data types but at the moment these are shots in the dark.
How can I send some proper data (like 100 lines of Arduino sketch) with this mechanism? The end goal is that my existing sketch receives the new sketch commands via serial and runs them.
if (port->available()) {
  int commands = port->read();
  // Run commands here
}

I would be hugely appreciative of any help. Thank you!

Partial answer: to send more information than just a single byte, it is possible to run:
# python
payload = "Here is a longer string"

# arduino
String commands = port->readString();           // Reads the whole thing
String commands = port->readStringUntil('\n');  // Reads until the given separator


text:
How to read bytearray from arduino pin in arduino sketch
I'm using the DYP-ME007TX sensor with arduino uno.
The output from this sensor comes in packets of 4-bytes:
Data[0]= 0xFF: Packet Header
Data[1]= 0x0-0xFF: Data Most Significant Byte (MSB)
Data[2]= 0x0-0xFF: Data Least Significant Byte (LSB)
Data[3]= 0x0-0xFF: Data Checksum: = (0XFF + MSB + LSB) & 0xFF

Data is in MILLIMETERS
16 bit value in mm = Data[1] << 8 | Data[2]
How can exctract this packet in arduino sketch and extract millimeter number?

This is a serial data stream. Connect the device's OUT to your Arduino's RX, then read the documentation on the Serial library.

I want to use two and more this kind of sensors, so I think I just can't use Arduino's TX. I used SoftwareSerial library: http://www.arduino.cc/en/Tutorial/TwoPortReceive

I found the answer from forum.arduino.cc
There is a sketch
#include <SoftwareSerial.h>

// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7

SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;

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

  mySerial.begin(9600);
}

void loop() {
  bitpos = 0;
  while (mySerial.available()) {
    // the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
    // if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
    if (bitpos < 4) {
      mybuffer[bitpos++] = mySerial.read();
    } else break;
  }
  mySerial.flush(); // discard older values in the next read

  mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
  Serial.print("PING: ");
  Serial.print(mili/10);
  Serial.println("sm");
  delay(500);
}


text:
Arduino does not work on battery
The day before I got my used full package arduino uno. I tested it on USB plug. Everything worked fine. I wrote a piece of testing code and uploaded. After I have accomplished with the test I have unpluged arduino from PC and connected to battery and I see that it does not work. I have used a multi-tester to find out the voltage. It showed 4.7V. Now I wonder should I buy a new battery or there is another reason for this. Anybody, please suggest me what to do.
Update
The battery came with arduino set. It is written that it is a 9V battery. I am plugging it to the battery input in my arduino uno. Polarity is ok. The same program working on connection via usb, does not when connected to battery.

What kind of battery? How did you connect the battery to the Arduino? Did you check the polarity?

@EdgarBonet updated by question.

Do you read 4.7 V between "Vin" and "GND" or between "5V" and "GND"? Does the "ON" LED light up?

@EdgarBonet I think I got the point, the "ON" ligth has not turned on. So it means that the power supplied by battery is not enough to run the arduino?

What does your DMM say?

Do you have any other components plugged in anywhere, motors, leds etc?

Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

@bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

@zazu I'm glad that it worked okay!

@bpinhosilva - If you made your comment an answer and expanded upon it a little, then the question could be marked as accepting an answer...

Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.
(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).

@bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)

Check the serial number of your board. Some boards were shipped with a defective boot loader, which has the loader stuck in an infinite loop when powered off and on again. Just Google the serial range of possible defective boards, and check if your board is in that range.

Try to use a battery that provides at least 7-12 volts. The voltage regulator will regulate the needed 5 volts for the arduino.

simply you can weld a little electrolytic capacitor eg. 4 or 6 microfarads, 12 or more Volts, with the positive wire on the reset pin and the negative on the GND pin. in this way you can solve the restart without the USB connection.
This is what I did
Enjoy with Arduino.
By Daniele

This seems to address a different issue :)

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


text:
Interfacing WM8731 code to Arduino Due
WM8731 codec was successfully interfaced with Atmega328 like variants in Arduino. It was first done successfully by Open music labs who are the makers of the breakout board for WM8731. Taking this library as reference another library was developed for atmega2560 Arduino and it also works fine. But now I am trying to get it work with Arduino Due which unlike other AVR micro-controllers in the Arduino family is an ARM. I found some useful code.It compiles well and is able to communicate with the WM8731 codec in I2C. I will post the original library and also explain in parts how the code for Due is built.
Original library is here:
http://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/AudioCodecNew.zip
My code split looking at the AudioCodec.h file.

#include <Wire.h>
#include <SPI.h>

#define LINVOL 23
#define RINVOL 23
#define LHPVOL 121
#define RHPVOL 121
#define ADCHPD 0
#define SIDEATT 0
#define SIDETONE 0
#define DACSEL 1
#define BYPASS 0
#define INSEL 0
#define MUTEMIC 1
#define MICBOOST 0
#define SAMPLE_RATE 44

volatile boolean l;

unsigned int temp = 0,temp1=0;
int temp_spi[4];
int m1[301],m2[301];
//TC1 ch 0
int left_in,right_in,left_out,right_out;
void TC0_Handler()
{
TC_GetStatus(TC0, 0);

    temp = random(65535);
    //temp = left_out;
    //temp1 = right_out;
    temp_spi[0] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
    temp_spi[1] = SPI.transfer(10,lowByte(temp),SPI_CONTINUE);
    temp_spi[2] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
    temp_spi[3] = SPI.transfer(10,lowByte(temp),SPI_LAST);
    //left_in - (temp_spi[0]<<8)|temp_spi[1];
    //right_in = (temp_spi[2]<<8)|temp_spi[3];
    /*Serial.println("Hello");
    Serial.println(temp_spi[0]);
    Serial.println(temp_spi[1]);
    Serial.println(temp_spi[2]);
    Serial.println(temp_spi[3]);*/
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t     frequency) {
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk((uint32_t)irq);
    TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
    uint32_t rc = VARIANT_MCK/128/frequency; //128 because we selected TIMER_CLOCK4 above
    TC_SetRA(tc, channel, rc/2); //50% high, 50% low
    TC_SetRC(tc, channel, rc);
    TC_Start(tc, channel);
    tc->TC_CHANNEL[channel].TC_IER=TC_IER_CPCS;
    tc->TC_CHANNEL[channel].TC_IDR=~TC_IER_CPCS;
    NVIC_EnableIRQ(irq);
}

void AudioCodec_init() {
    randomSeed(analogRead(0));
    SPI.begin(10);
    SPI.setBitOrder(MSBFIRST);
    SPI.setClockDivider(10,21); // select to ss pin 10, 4 MHz
    SPI.setDataMode(10,SPI_MODE0);

    // setup i2c pins and configure codec
    // the new Wire library has trouble with 0x00, so (uint8_t) is added
    // To change the Wire interface speed, go to:
    // <path_from_arduino>\hardware\arduino\sam\libraries\Wire\Wire.h
    // and change the parameters TWI_CLOCK, RECV_TIMEOUT and XMIT_TIMEOUT
    // to the desire frequency.
    int temp_wire1;
    int temp_wire2;

    Wire.begin();
    Wire.beginTransmission(0x1a);
    Wire.write(0x0c); // power reduction register
    Wire.write((uint8_t)0x00); // turn everything on
    temp_wire1 = Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x0e); // digital data format
    Wire.write(0x03); // 16b SPI mode
    temp_wire2 = Wire.endTransmission();

    //Serial.println(temp_wire1);
    //Serial.println(temp_wire2);

    Wire.beginTransmission(0x1a);
    Wire.write((uint8_t)0x00); // left in setup register
    Wire.write((uint8_t)LINVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x02); // right in setup register
    Wire.write((uint8_t)RINVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x04); // left headphone out register
    Wire.write((uint8_t)LHPVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x06); // right headphone out register
    Wire.write((uint8_t)RHPVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x0a); // digital audio path configuration
    Wire.write((uint8_t)ADCHPD);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x08); // analog audio pathway configuration
    Wire.write((uint8_t)((SIDEATT << 6)|(SIDETONE << 5)|(DACSEL << 4)|(BYPASS << 3)|(INSEL << 2)|(MUTEMIC << 1)|(MICBOOST << 0)));
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x10); // clock configuration
    #if SAMPLE_RATE == 88
      Wire.write(0xbc);
    #elif SAMPLE_RATE == 44
      Wire.write(0xa0);
    #elif SAMPLE_RATE == 22
      Wire.write(0xe0);
    #elif SAMPLE_RATE == 8
      Wire.write(0xac);
    #elif SAMPLE_RATE == 2
      Wire.write(0xce);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x12); // codec enable
    Wire.write(0x01);
    Wire.endTransmission();

}

void setup(){

    pinMode(2,INPUT);
    pinMode(10,OUTPUT);
    Serial.begin(115200);
    Serial1.begin(9600);
    Serial.println("Hello");
AudioCodec_init();
startTimer(TC0, 0, TC0_IRQn, 2000); //startTimer(TC1, 0, TC3_IRQn,   44100); //TC1 channel 0, the IRQ for that channel and the desired frequency
}

void loop(){
//Serial.println("Hello");
/*for(int i =0;i<300;i++)
{
m1[i]=map(analogRead(0),300,800,-400,400);
m2[i]=map(analogRead(1),300,800,-400,400);
}*/
//for(int j =0;j<300;j++)
//{
/*Serial1.print("a");
Serial1.print(m1[j]);
Serial1.print("b");
Serial1.print(m2[j]);*/
//Serial1.println(left_in);
Serial.print(temp_spi[0]);
Serial.print(" ");
Serial.print(temp_spi[1]);
Serial.print(" ");
Serial.print(temp_spi[2]);
Serial.print(" ");
Serial.println(temp_spi[3]);
//Serial1.println("c");
//Serial.println("In loop");
//h23}
}

So on atmega328 the clockout from the WM8731 was give to T1 pin and on atmega2560 timer 5 was used and clockout was attached to pin T5. I am just starting with Due and I dont know much about ARM but I set the code to TC0,TC0 timer and pin 2.
As described here in this link:
http://forum.arduino.cc/index.php?topic=130423.0
Some how the SPI part in this code and the timer is not working as I cannot get any voice out from the codec.I am also printing the temp_spi[x] variables over serial port and all of them are just zeros all the time. Could some one help me make this code work with the codec? The code compiles fine for Due in the arduino IDE.


text:
Which type of sensor should i use to get RPM of an engine?
Using Arduino (i got leonardo and uno),
I'm looking for a way to get the RPM of my car's engine.
I know this can be done using an OBD2 connection however i'm looking for a different way.
Sensing?
I need a reference for a sensor / a creative way to get this data.
Having said that, these approaches came up:

guessing the RPM by reading the amps in the car's 12V connection
recording the sound of the engine using a microphone and setting thresholds for certain RPM values

If you wrap a few loops of wire around one ignition wire you can probably messure the ignition pulses. But that could kill your arduino, because even the induced voltage in the wrapped wire may be over 1000 Volts. So be carefull!!! Perhaps a diode (Fast Schottky) might help. But that's a question for the electronics site http://electronics.stackexchange.com/. These guys know more about that than I do.

I think it will depend on whether you have access to the tachometer feed (assuming one is available).  Otherwise, if there is something "rotating" at the engine speed, you can attach various types of sensor for measuring revolutions (eg. IR reflection or hall effect magnet sensing).

Paint a white of black spot on the drivebelt, and use an reflective optical sensor (e.g. tcrt5000) to see how many times the spot passes the sensor.

Could you state the reasons why OBD2 is not an option?

I would think something like this would benefit you greatly. If your vehicle was produced after 1996 it will have an OBD port near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.

What about measuring the speedometer? I suspect that would be easiest - you may get away with hooking up the speedo directly to the Arduino analog (but measure with multimeter first!).

The question seeks engine RPM, not speed.  Transmissions have various ratios, and they slip, so the two are not directly related.

Most speedos have RPMs. I meant "the rpm line on the dashboard" (that part of the dashboard being referred to as the speedo, even the parts that aren't).

I'm doing this with a TCRT5000 and a LED+phototransistor, you can find them all over Amazon and eBay. I painted one quarter of a camshaft pulley white, and the other three-quarters flat black, and mounted the optical sensor over the edge of the pulley. This is on a Subaru, where the cam pulley and timing belt are all underneath a shroud, which keeps out ambient light. It works quite well.
Plus a .1uf capacitor next to the Arduino, because the transitions between high and low were pretty noisy without it.


text:
How to start Arduino programming?
I am totally new to and don't know where to start, I am interested in building new system with combination of hardware and software and every time I search how to make that embedded system it finally reaches to Arduino and don't know anything about that what to buy and I also have some more question like

Is one Arduino device required for each Arduino project ?
Should I have to buy more then one device for each project ?
If not then how I will make that project run without Arduino ?

An Arduino is basically a Microcontroller on a handy PCB with built-in programming interface.  It also has a simple programming environment to get you up and running quickly.
The chip on the board can be thought of as the "brain" of the system.  It's what you program and it's where you upload your software to.

Is one Arduino device required for each Arduino project?

Yes and no.  You can't "remove" your Arduino from your project and expect it to still work - it'd be like beheading someone - they cease to function without their brain.  However you can replicate the Arduino in your system fairly easily so you don't have to embed the whole Arduino into it.  You can get a blank chip the same as is on the Arduino reasonably cheaply and program the bootloader (the serial interface for programming it) into the chip using your existing Arduino, then build a new circuit around it.  More information here:

http://www.arduino.cc/en/Main/Standalone

Should I have to buy more then one device for each project?

That depends if your project is complex enough to warrant more than one "brain".  Using the "standalone" instructions above you could make multiple chips from one Arduino and embed them all in your one project.

If not then how I will make that project run without Arduino?

There are other Arduino boards available that are designed to be embedded in your project.  These are much smaller than the "development" boards like the Uno etc.  They are also cheaper, being typically the absolute bare minimum you need to get you going.  These can be a great way of saving time compared to the Standalone system above, and at the same time saving money compared to using the full blown Arduino boards.  Boards include the Mini and Nano range of boards.

http://www.arduino.cc/en/Main/ArduinoBoardMini
http://www.arduino.cc/en/Main/ArduinoBoardNano

Please add one basic tutorial form where I can start like hello world programme we write in every language

Those kind of tutorials are all included in the Arduino IDE.  The normal one is "Blink" which flashes an LED (the equivalent of "Hello World".)

Where I can buy Arduino  easily in India

I don't know, I'm not from India, nor have I ever been there, let alone shopped there.  Have you asked Google?  Try eBay for a start.

Forth mentioning the standard book to get started: "Getting Started with Arduino" http://www.makershed.com/products/make-getting-started-with-arduino-3rd-edition


text:
Determine XBee Packet Route
I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode).
Setting up the network and sending packets is easy enough.
Is it possible to trace the route a packet travelled from the end-device to the coordinator?
Example:
I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator. Path: end-device->routerB->routerA->Coordinator.
Is it possible to know the end-device is in area B as it is the first router device the packet travelled through?

I'm not sure what you mean by  “Coordinator”.  If it's an ordinary computer, run traceroute (or tracert) on it

The "Coordinator" refers to the device type used in the ZigBee network protocol. Every network must have at least one Coordinator. Just note, the ZigBee mesh network is not like standard WiFi protocol. But thank you, I found the answer.

It is done by using Source Routing
The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.


text:
sim 900 sending wrong sms -" Ü " to mobile phone from arduino
i am having a problem while sending sms from arduino to a specific number. cell phone getting sms but every time it gets same unicode -" Ü " . plz help us
//--------------------------
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

void setup()
{
    mySerial.begin(115200);
    mySerial.print("\r");
    delay(1000);
    mySerial.print("AT+CMGF=1\r");
    delay(20000);

    mySerial.print("AT+CMGS=\"+91..........\"\r");

    delay(20000);
    mySerial.print("Hello!\r");   //The text for the message
    delay(10000);
    mySerial.write(0x1A);  //Equivalent to sending Ctrl+Z
}

void loop()
{

}

So you try to send "Hello!", but receive "Ü"?

yahhh...do you know the reason?

Ü in SMS has the same value (0x5E) as ^ in ASCII. Nothing helpful there. The delays seem a bit long to me. Try lowering those.

which delay ? is it after ' mySerial.print("Hello!\r") ' ?

The 20000 and 10000 ones. Waiting 10 or 20 seconds is extremely long.


text:
Arduino processing serial comunication - losing data?
I'm trying to send an array back and forth between Processing and an Arduino UNO. But I think data is being lost along the way. I simply iterate over the array in Processing and send the Values separately. A new set of data is indicated by the character <. On the Arduino the data gets added to a string and sent back for testing.  When I print out the string in processing, some data changed to -1.
The array contains {1,2,3,4,5,6,7,8}
The Output looks like this:
12345678
12345678
1234-1-1-1-1
12345678
12345-1-1-1

Is there something I'm missing in terms of implementation, or is this simply a hardware related problem (like slightly different clock speeds)? Is there any way to improve this?
Arduino Sketch:
int srr[8];

int content; // Data received from the serial port
void setup() {
  Serial.begin(9600); // Start serial communication at 9600 bps
}

 void loop() {
   String str = "val:";
   int test;
   if (Serial.available()){ // If data is available to read,
     content = Serial.read();
   }

   if (content == 60){
     for(int i=0; i<=7; i++)
   {
       str+=Serial.read();
   }
   Serial.println(str);
   }
}

Processing
Serial myPort;  // Create object from Serial class
int arr[]={1,2,3,4,5,6,7,8};  //The array to send

String str;
void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  //write
  myPort.write("<");
  for (int i =0; i<=7;i++){
    myPort.write(arr[i]);

  }
  //read
  if ( myPort.available() > 0){  // If data is available,
    str = myPort.readStringUntil('\n');         // read it and store it in val
    println(str); //print it out in the console
  }

}

Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).
if (Serial.available()) { // If data is available to read,
    content = Serial.read();
}

If there is at least one character available in the buffer then read one character into the variable content.
if (content == 60) {

If the variable content is 60 (better to use '>' so you can see what it is), then ...
 for(int i=0; i<=7; i++) {
     str+=Serial.read();
 }

... read 8 characters from the serial buffer whether there are any characters in there or not.
That last bit is the crunch point.  You have an unknown number of characters in the buffer.  You had at least one, and that one you read into content.  You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.
If you take a moment to read the documentation on Serial Read you will see this:

Returns
the first byte of incoming serial data available (or -1 if no data is available) - int

The simplest fix is just to make your loop blocking so it waits for a character to arrive before reading it:
for(int i=0; i<=7; i++) {
     while (!Serial.available());  // Wait for a character to arrive
     str+=Serial.read();  // Read it
}


text:
Convert a Serial string to a sketch command on Yun?
How can I convert a string like the following:
"pinMode(2, INPUT_PULLUP)"

or

'Keyboard.print("Hello world")'

into actual code that the Arduino can act on?

You can't - not directly.
There are two things you can do:

Build your "command" into a sketch and compile it, then upload it in to the Yun's AVR chip.  The compiling will have to be done on your PC, and the HEX file uploaded to the AVR (you can do it directly through the Yun's web interface).
Don't send sketch code, but send pre-defined instructions like "Turn on pin 3" which your sketch then interprets.  That could be as simple as two bytes "P3" for instance.  It's entirely up to you how you craft that.

Firmata might help with option 2 if uploading a new sketch every time isn't what you want to do.

There is a third option: install an interpreter on the Arduino, then
just send it the program you want it to run. There are a few such
interpreters available. A quick search showed:

Bitlash, a C-like language
iArduino, another
C-like language
FlashForth, a
Forth
implementation
FINF Is Not Forth, a Forth-like
language

There are probably many others.
The difference between this option and Majenko's option 2 is that this
would allow you to send a complete program, with functions,
conditionals, loops, etc., whereas with a Firmata or similar approach
you would keep the program logic (functions, loops, conditionals) on the
host computer, and only send simple commands to the Arduino.

You might also try the Firmata library, too.
It provides similar functionality, and there are some libs for the computer side of it, if you are so inclined.