text:
Arduino nokia 5110 lcd screen problem
Hello I have a nokia 5110 lcd display connected to my Arduino. I have looked at so many tutorials and none of them work for me. I am trying to get a bitmap displayed in the screen but only the lights light up and nothing else happens.
I have the lcd connected to the following Arduino pins:

vcc -- 3.3v
gnd -- gnd
sce -- pin 7
rst -- pin 6
d/c -- pin 5
DN -- pin 4
sclk -- pin 8
led -- 100ohm resistor --pin 11

here is an image

Nothing will display on the screen could someone please help me here is my code:
 #include "U8glib.h"
 #include "dht.h"

 #define dht_apin A1
 #define backlight_pin 11

 dht DHT;

 U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

 const uint8_t brainy_bitmap[] PROGMEM = {
  0x00, 0x00, 0x03, 0xB0, 0x00, 0x00, 0x00, 0x00,
  0x07, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x46,
  0x00, 0x00, 0x00, 0x00, 0xFC, 0x47, 0xC0, 0x00,
  0x00, 0x01, 0xCE, 0x4C, 0x60, 0x00, 0x00, 0x03,
  0x02, 0x58, 0x30, 0x00, 0x00, 0x03, 0x02, 0x58,
  0x10, 0x00, 0x00, 0x02, 0x02, 0x58, 0x18, 0x00,
  0x00, 0x03, 0x06, 0x4C, 0x18, 0x00, 0x00, 0x07,
  0x04, 0x44, 0x18, 0x00, 0x00, 0x0D, 0x80, 0x40,
  0x3C, 0x00, 0x00, 0x09, 0xC0, 0x40, 0xE6, 0x00,
  0x00, 0x18, 0x78, 0x47, 0xC2, 0x00, 0x00, 0x18,
  0x0C, 0x4E, 0x02, 0x00, 0x00, 0x1F, 0x86, 0x4C,
  0x7E, 0x00, 0x00, 0x0E, 0xC6, 0xE8, 0xEE, 0x00,
  0x00, 0x18, 0x43, 0xF8, 0x82, 0x00, 0x00, 0x10,
  0x06, 0x4C, 0x03, 0x00, 0x00, 0x30, 0x0C, 0x46,
  0x01, 0x00, 0x00, 0x30, 0x18, 0x46, 0x01, 0x00,
  0x00, 0x10, 0x18, 0x43, 0x03, 0x00, 0x00, 0x18,
  0x10, 0x43, 0x03, 0x00, 0x00, 0x1C, 0x70, 0x41,
  0x86, 0x00, 0x00, 0x0F, 0xE0, 0x40, 0xFE, 0x00,
  0x00, 0x09, 0x1E, 0x4F, 0x06, 0x00, 0x00, 0x08,
  0x30, 0x43, 0x86, 0x00, 0x00, 0x0C, 0x20, 0x41,
  0x86, 0x00, 0x00, 0x06, 0x60, 0x40, 0x8C, 0x00,
  0x00, 0x07, 0x60, 0x40, 0xB8, 0x00, 0x00, 0x01,
  0xE0, 0x41, 0xF0, 0x00, 0x00, 0x00, 0x38, 0xE3,
  0x00, 0x00, 0x00, 0x00, 0x0F, 0xBE, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xCF,
  0x82, 0x0C, 0x86, 0x46, 0x1F, 0xEF, 0xC3, 0x0C,
  0xC6, 0xEE, 0x1C, 0xEC, 0xC7, 0x0C, 0xE6, 0x7C,
  0x1C, 0xED, 0x8D, 0x8C, 0xFE, 0x38, 0x1C, 0xED,
  0x8D, 0xCC, 0xDE, 0x38, 0x1D, 0xCD, 0xDF, 0xCC,
  0xCE, 0x38, 0x1F, 0x8C, 0xF8, 0xEC, 0xC6, 0x38,
  0x1F, 0xEC, 0x08, 0x0C, 0xC2, 0x18, 0x1C, 0xEC,
  0x00, 0xC0, 0x00, 0x00, 0x1C, 0xFD, 0xFB, 0xC0,
  0x00, 0x00, 0x1C, 0xFC, 0x63, 0x00, 0x00, 0x00,
  0x1C, 0xEC, 0x63, 0xC0, 0x00, 0x00, 0x1F, 0xEC,
  0x60, 0xC0, 0x00, 0x00, 0x1F, 0xCC, 0x63, 0xC0,
  0x00, 0x00, 0x1F, 0x0C, 0x63, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x28, 0x2B, 0x4F, 0x67,
  0x42, 0x38, 0x7B, 0xEA, 0x86, 0xB2, 0x28, 0xC7,
 };

 void draw(void) {
   u8g.drawBitmapP( 0, 0, 6, 50, brainy_bitmap);  // put bitmap
   u8g.drawStr(10, 10, "% ");

 void loop(void) {

   u8g.firstPage();
   do {
     draw();
   } while( u8g.nextPage() );

     delay(5000);  // Delay of 5sec before accessing DHT11 (min - 2sec)
   }

I have the same problem ....with NOKIA5110 display ,I gave it a slight downwards press just as I upload the code and then it works ,but as soon as I release it just goes blank.
Hooked up my resistors and made sure wires in correct pins ,so this is what I experience.

There are several possibilities.
Arduino GPIO pins drive outputs to ground or 5V.
The pins on the Nokia 5110 LCDs boards I have are not 5V tolerant. So you might have damaged them when the Arduino's GPIO connected to 5V.
A simple fix is to put a 10k ohm resistor in each signal path, i.e.

sce -- pin 7
rst -- pin 6
d/c -- pin 5
DN -- pin 4
sclk -- pin 8

You could get a level-shift chip, or build a circuit, but resistors are quick, cheap and easy.
I would strongly recommend using a very simple Arduino library to get the display working. Then, once everything is working, continue with your current approach. All you need is a simple test; something which turns pixels on and off to check that it works.
I have had good results with the Arduino Playground Philips PCD8544 (Nokia 3310) driver
I have several Nokia 5110's. A few needed the values loaded at initialisation to be tweaked, to make the display visible.
Specifically in void LcdInitialise(void):
  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.

I have had to tweak Set Temp coefficent, LCD bias mode 1:48 and Set LCD Vop (Contrast) to get make the display clear, without looking washed-out, or all-dark. Using a very simple library like the Philips PCD8544 (Nokia 3310) driver should make it easy to adjust this until things work well.

ok I did this and I used a multimeter to measure the voltage it was 5.01 volts. I didn't have 10k resistors so I used a 6k leading to a 4k and then to the sreen, should that work?

You're just trying to reduce the input current so that nothing gets damaged. So 10k made from two resistors should be fine.

Change your pinouts. HW SPI needs 13 and 11, not 8 and 4. Try this short bit of code:
#
include <U8glib.h>

#define RST 6
#define CE  7
#define DC  5        //  D high is data, C low is command.
#define DIN 11
#define CLK 13
#define Backlight 9  // Don't forget the 330 ohm resistor.

//Declare the display and assign the pins.
  U8GLIB_PCD8544 u8g(13, 11, 7, 5, 6);  // CLK=13, DIN=11, CE=7, DC=5, RST=6

void draw() {
  u8g.setFont(u8g_font_profont11);      // Select font
  u8g.drawStr(0, 15, "Nokia 5110...");  // Put string of display at position X, Y.
  u8g.drawStr(29, 35, "HELLO!!!");
}

void setup() {
    analogWrite(Backlight, 80);  // Set Backlight Intensity, 0 is fully bright, 255 is off.
}

void loop() {                    // Enter the U8Glib Picture Loop
 u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}

Assuming you got your code from this site: https://brainy-bits.com/tutorials/how-to-use-the-nokia-5110/, it seems you edited the code from there to display only the bitmap, but you didn't get rid of everything. You have no DHT temperature sensors, so get rid of all DHT references in your code, including the 5 seconds delay at the bottom of loop(). If you intend to use the code from that site, then use it this way:
void draw(void) {
  u8g.drawBitmapP( 37, 0, 6, 50, brainy_bitmap);  // put bitmap
}

void setup(void) {
  analogWrite(backlight_pin, 50);  /* Set the Backlight intensity */
}

void loop(void) {
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

}

Make sure to get rid of the #define, #include and constructor referring to DHT.


text:
How to ensure electronic components make good connection with breadboard
I just began following the projects in the Arduino Projects Book included in the Arduino Starter Kit.
While using LEDs, as in the first few examples of the book, I am having a difficult time keeping them in contact with the breadboard. I can usually move the LED around until it turns on, but even a push of a button can make it lose contact with the board. I haven't used much more than switches, jumpers, LEDs and resistors, so I don't know if any of the other components behave the same. For the more complex projects, it seems like it would be hard to tell if you have it setup properly if you can't be sure the components are making a connection with the breadboard.
Is there a particular way to get all the components to sit nicely in the breadboard, or to modify them to do so?

Bend the pins as little as possible.

@IgnacioVazquez-Abrams I'm trying not to. Any other tips?

Sounds like you may not be pushing the leads into the board,I find long nose pliers handy for components with thicker leads.

I feel silly! You're right, I wasn't actually pushing the leads into the board, just letting them rest in the slots. Working great now. Thanks

source: Stack Exchange

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

sort: votes


text:
Why is my transistor getting very hot when controlling a 12V peristalic pump?
I have followed this tutorial:
http://www.instructables.com/id/Automatically-water-your-small-indoor-plant-using-/?ALLSTEPS
Every time i try to run my circuit, My transistor gets very hot and breaks.
I have exactly the same parts as the tutorial. I have also tested the circuit with 3.3V Power supply and a diode instead of an engine, this works.
I am super thankfull for any answers.

What do you mean by "breaks?" Can you please add more information to your post? Thanks!

I would be surprised if it worked. As far as I can tell (from the poor instructions) he is connecting the base directly to the Arduino pin. This would overload the chip, although the inbuilt current limiter would protect it. I certainly wouldn't use a PN2222 to switch 300mA.

As @Milliways suggested, you need to add a resistor between the arduino pin and the transistor. Around 1k will do.

Measure the Current through the motor, the PN2222 can pass a maximum of 600mA.
I would guess that just over half an amp would be enough for the motor but you can check what you motor is trying to pull by connecting it to 12 V direct and measure the supply current.
The only thing that will make the transistor hot is excess current

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


text:
Arduino UNO serial send and receive issue
I am trying to send and receive data from a PIC16F88 to an Arduino Uno. My problem is that the serial communication stops when the Arduino is not connected to the USB cable. For my application I need the Arduino to still perform its operations with a battery. I have tried both software and hardware serial. Is it possible for the Arduino to send/recieve data when not plugged into the USB cable?

Yes, it should be possible. But please post your code, there's not much we can do to help you without seeing the code you're using.

You need a common ground between the Arduino and the PIC. Connect both grounds one to each other.

Is the Arduino running at all when on battery?  You could be trying to pull too much current from the battery and killing the circuit.  Another cause is that some programmers pull the reset pin to low when unplugged; took me a while to figure out that one.


text:
USB mouse/keyboard passthrough feasible?
I'm looking to achieve the following:
USB HID Mouse (or Keyboard) -> [ Arduino device ] -> PC
                                       |
                                        `-> Internet

Basically, I want to connect a keyboard or mouse to an Arduino device, do some processing, send some data over the internet and then pass-through the USB data to the PC as if the Arduino wasn't even there.
My question is twofold: what hardware should I use? Right now I'm looking at the following peripherals:

Arduino Uno R3 SMD
Arduino Ethernet Shield
SparkFun USB Host Shield

Since I'm a complete neophyte when it comes to Arduino, I wanted to double-check and make sure my parts will fit together as well as work towards my goal. I was also contemplating the Arduino Leonardo (since it seems to provide mouse/keyboard out-of-the-box without reflashing the firmware), but I'm not sure I understand what that decision might entail.
Which brings me to my second question: is this feasible software-wise? I found this blog which has some information about pass-through connections, but the mouse library seems to be unfinished. I'd hate to invest 150+ dollars into a project that is doomed from the start.
Thank you!

To connect an external USB device to AVR you need USB Host supported on AVR side. Overhelming majority of AVR chips supports USB device only. There is e.g. AT90USB1287 chip exception. It even exists an AVR USB Key 2 device which can be used instead of normal Arduino unless you want make own PCBs.
Arduino UNO Mouse HID emulates USB mouse internally in Arduino. Implementing is easy when you have USB device AVR chip using LUFA library. But it's not case using external mouse. On the other side you can use legacy serial mouse or PS/2 keyboard as workaround.


text:
Arduino to Home Speakers
I know little about electronics in general. I wanted to connect Arduino, and play a tone using tone() through my home speakers.
I've used a 1/8'' audio jack and connect ground to ground and left/right to pin 2. Run it and it was too loud.
Then I read the specification and it says,
Input impedance = 20 kOhm
Input sensibility = 400mV +/- 50mV
Arduino sends 5V so that should be a lot. Did I damage my speaker? They still work.

It's probably not damaged, but you shouldn't do it again.
To get the 5V signal down to 400mV you need to create a voltage divider. As such you will need a:
5V / (400mV / 20kohm) − 20kohm = 230kohm
resistor between the pin and the input. 220kohm should be close enough.

thanks. so input sensibility should say how much voltage I should give them. however, what does input impedance tells me in this particulary case?

Input impedance will give you the resistance you should use to determine how much current will flow for a given signal voltage.

I only had a 470 kOhm resistance and I tried with it because it would result in less volume I believed. It worked. However, should I see 4,7V in the resistor between the pin and the input? My multimeter tells 0,01V.

You'll only see full scale if you're actually outputting full scale. Any sort of waveform will result in a value that is lower than maximum. Also 470kohm || 470kohm = 235kohm.

Two 470 kohm in parallel, right. Thanks for replying.

Sorry, I mean, I should see 4,7V but I see 0,01V in that 470k resistor. It's strange. 5V / (20k + 470k) = 1x10-5 A ... 1x10-5 A x 470k = 4,7V

I'd probably create my own voltage divider, and not depend on the 20kOhm input impedance. I also think you should AC couple (capacitor is series) it, but I'm not very good at this audio stuff, so I could be wrong.


text:
Arduino compiled sketch on sd card
Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

Yes it is possible:
With a different bootloader.
You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).
Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.

what if I had a sketch uploaded to the Arduino that uses about 50% of the flash space or more/less. If I had my really basic kind of language that I can load as a text file into a set of strings in the sketch's progmen. That part is possible. The sketch I write would be able to understand what the text file means.It might be just something like: print "hello world". That part is possible. Now the part I don't know about. When the sketch is finished with that "homemade language programme" it would have to clear it from its progmem and use those strings to load an new homemade language programme

If you were going to do that you could just read the text line by line from the SD card and act on it - no need to program anything into the flash.


text:
Arduino disecting a string
Hello I have a String that contains the following: "println('hello world')".
I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.
    String line1 = "println('hello world')";

Please help me thx.

How can I remove everything except for what is in the brackets from the string?

There are a number of String class member functions that can help with this. First, indexOf(val) will help locate the character of interest. Second, substring() will help cut out the part you want. And as a bonus, using lastIndexOf() will allow brackets within the string.
String s = "println('hello world')";
s = s.substring(s.indexOf('(') + 1);
s = s.substring(0, s.lastIndexOf(')'));

Cheers!


text:
Atmel AVR languages
Hello I recently purchased some atmel AVR chips. You can programme them in Arduino. I was wondering if it is possible to programme them in any other language except for C or Arduino. Also can you use just binary instead of C?

I was wondering if it is possible to programme them in any other language except for C or Arduino.

I have seen this question before. Here is a great answer with a lot of links:
https://stackoverflow.com/questions/6590161/programming-languages-targeting-arduino-avr
There are also a number of libraries/platforms/frameworks as the Arduino core to help you up from "bare metal".
Cheers!

You can program them in C or C++ through the avr-gcc compiler. Arduino uses C++ (-std=gnu++11) and automatically includes a few libraries, as well as generating forward declarations for anything in the top level .ino file automatically.
You can write AVR assembly and translate it to machine code using avr-as (a portion of avr-gcc)
There is nothing stopping you from just writing whatever bytes you want to program memory if you want to write machine code.
You can look through the avr instruction set if you are interested in those last two options.


text:
FTDI stdk 500k not responding
I programming atmega328P bootloaded with an FTDI.
Some tutorial mentions that you have to connect the DTR to the reset pin:
http://electronics-diy.com/FT232RL_USB_to_Serial_Adapter_for_PIC_AVR_ATMEGA_ARDUINO_MCUs.php
Is that so? Because some don't, they just say rx,tx is enough. I still can't program the chip with the error:
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

avrdude: Version 5.11.1, compiled on Oct 18 2011 at 21:17:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : avrisp
         Overriding Baud Rate          : 9600
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding

avrdude done.  Thank you.

I tried different baud rates, no matter what it's not responding. Linux recognizes the FTDI as:
Sat Feb 13 22:52:14 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:52:14 2016] ftdi_sio 1-2.1:1.0: device disconnected
[Sat Feb 13 22:52:19 2016] usb 1-2.1: new full-speed USB device number 73 using uhci_hcd
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device found, idVendor=0403, idProduct=6001
[Sat Feb 13 22:52:20 2016] usb 1-2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Product: FT232R USB UART
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Manufacturer: FTDI
[Sat Feb 13 22:52:20 2016] usb 1-2.1: SerialNumber: A6004mhS
[Sat Feb 13 22:52:20 2016] ftdi_sio 1-2.1:1.0: FTDI USB Serial Device converter detected
[Sat Feb 13 22:52:20 2016] usb 1-2.1: Detected FT232RL
[Sat Feb 13 22:52:20 2016] usb 1-2.1: FTDI USB Serial Device converter now attached to ttyUSB0
[Sat Feb 13 22:56:25 2016] usb 1-2.1: USB disconnect, device number 73
[Sat Feb 13 22:56:25 2016] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0
[Sat Feb 13 22:56:25 2016] ftdi_sio 1-2.1:1.0: device disconnected

Well my questions now are:
1, When I use the Arduino IDE to program a barebone 328P with this FTDI what should be the BOARD and what should be the PROGRAMMER?
Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII
Although I tried almost all... I think something else is wrong.
2, Should I be able to get any result with doing the previous:
 avrdude -p m328p -P /dev/ttyUSB0 -c avrisp -b 9600 -n -v -v -v

command WITHOUT connecting the barebone chip? I think not, since this doesn't act like a fully fledged MCU just like a serial converter.
Thanks

You may get away with quicky resetting the AVR after you started avrdude. The bootloader kicks in at that moment and listens for an incoming flash image. Use arduino for the programmer type. You may have to fiddle with baudrate, not sure what the default baudrate is.

I have used the following commands in the past to program an Arduino without using the IDE: mcu=atmega1280,
freq=16000000L,
baud=57600,
port=/dev/ttyUSB002, avrdude -p$mcu -carduino -P$port -b$baud -D -Uflash:w:./project.hex:i

Poor man's make file for Proof of Concept purposes only.

Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?
See: How to make an Arduino-compatible minimal board
From that page, this is how I hooked up my FTDI cable:

And a close-up:

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.


text:
Shift register on Attiny85 programmed by Arduino
Shift registers need 3 digital pins in order to work (data, clock and latch), but Attiny45/85 chips provides 2 digital and 2 analog pins.
Would I use 1 analog pin as digital pin? How?

http://forum.arduino.cc/index.php?topic=170470.0 this can be helpful

well that's an unanswered question i guess

Thats why its in comments i guess

Claiming only 2 analog pins must mean that you're using attiny instead of arduino-tiny; I recommend that you use arduino-tiny instead.

The ATtinyX5 does not have any analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).

well, I mean if I had to declare them as OUTPUT using pinMode(). Should I use digitalWrite() and digitalRead() on them?

That's how you use digital I/O with the Arduino libraries, so yes.

As Ingnacio has already pointed out, PB0 to PB4 can be used as digital IO ports without problems. It night be a good idea though not to touch PB6, the RESET pin.
Btw, this isn't different from an Arduino, where all so-called analog pins can be used for digital output as well.
If you want to drive shift registers from an ATtiny85 using SPI, you might want to have a look at the tinySPI library written by Jack Christensen. Please note that I haven't used this library personally!

Thanks. I'll read about SPI. I know attinyX5 uses USI, but communication is possible with that library and SoftwareSerial I guess.


text:
Homemade soil moisture analog value reading jumping from 0 to max
I made a soil moisture sensor out of two metal poles, adjustable resistor, for a project I am making. The first run with the project the sensor worked amazing and gave clear and concise readings, 0-800 depending on water. I then unhooked the sensor and left it in the soil while I fine tuned the code (added warnings to the areas that would read to low), and while testing the code without the sensor being hooked up my arduino uno (Sparkfun Pro Mini) would read a value of 330(area). I thought this strange but didnt worry about it.
Well I hooked up my sensor (just power, ground, and to the A1 pin) and now my readout for the readings jump from 0 to 800, 0 to 512, 0 to another random number. I commented out everything in the code BUT the part that sets up the pin and displays the analog reading and its still the same issue. I also checked all my wires, changed the resistor setting, changed to a 10k single resistor, nothing changed.
Does anyone have any idea on what could be wrong?

Could you post the simplest code that is effected by the error?

The sensor could be oxidized. I don't quite get how you've wired the sensor. It sound like you have not connected it in a voltage dividers configuration.

I will post code a bit later (At work now). But here is how the probe is wired up. https://arduinodiy.files.wordpress.com/2012/03/build-your-moisture-sensor.jpg
I doubt the sensor is Oxidized after 30mins of overall use, I have even cleaned the probes and the same effect happens. I will create a video tonight and upload code during lunch hours.

@BrettM Here is a really simplified part of the code.
    #include <serLCD.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
int moistpin = A1;  //Moisture Sensor pin
int moistreading;
int pin = 1;  //SerLCD pin
serLCD lcd(pin);  //SerLCD pin

void setup(){
lcd.clear();
lcd.print("Welcome to");
lcd.selectLine(2);
lcd.print("Water-Me 1.0!");
}
void loop(){
moistreading = analogRead(moistpin);
lcd.clearLine(1);
lcd.print(moistreading);
delay(350);
</code>

Have you tried using Serial.print() to print the value to a serial console? Could be a valid check to eliminate possible errors with the lcd.

@CalebBramwell
Yes, I have even had it just display on my computer and the output still jumps. I think I will buy a moisture sensor that I know will work.
I tried to use different type of wire, different spacing, different resistor values, nothing.

Everyone, I got it to work. After rebuilding the hardware again I found out I had my voltage divider backwards.

You are constantly running .5mA through 2 nails in wet earth. What are they made of, that won't undergo some electrolysis in 1/2 hour? Gerben appears to have hit the, er, nail on the head in one, above.
You can avoid this to an extent by using a.c. drive to the probes, which reverses the effect so they only tarnish at about the normal rate for metal X in soil.


text:
nrf24l01+ with antenna problem
I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.
I'm using arduino nanos and MySensors to create a gateway and a sensor.
The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.
I also tried two nrfs as gateway and sensor, but the behavior does not look good.
What could it be? Wifi router interference? Channel? Baud rate? Data rate?

Try moving them further apart.

Oh, now that I read it again I noticed that you most certainly have clone modules. There are plenty of links online talking about fake NRF24L01+s.

It's likely an issue related to the modules'  electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.
Two things have to be covered with the nRF modules for them to work:

current draw (i.e. power),
decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.
The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.
A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.
An Arduino can only supply power according to it's onboard regulator capabilities.
The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.
Solution:

provide a separate 3.3V regulator for the nRF module(s),
place a capacitor directly at the modules' connector's supply pins.

Link:

https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP

It's always worth giving a shot lowering the power level.


text:
Module and library for self healing large sensor network
I have to build a wireless sensor network with arduinos on my project. It does not need to be a mesh network, but it needs to have self healing capabilities.
I would like to use something cheaper than XBees. I tried the NRF24L01 with maniacbug's, TMRh20's and MySensors' libraries. However they aren't solving the problem and I'm wasting a ton of time trying to figure out how to make them work.
Another thing, I need a lot of repeater nodes between the base and the sensors because the office is 2 km far from the monitoring area and some of these libraries have a limitation of 5 level deep network, so I'd have max 4 repeaters between the base and sensor, which is bad.
And the last, my project is going to be fine with 15 sensors for now, but it'll have 500-1000 nodes in a couple of months and most of these libraries assign 8 bit addresses (256 nodes), which does not cover that amount of nodes.
What do you suggest?

FYI Maniacbug did not write RF24Mesh, TMRh20 did.

A few thoughts:

For ~$20 per unit, the 1mW Digimesh modules will take care of reliable mesh networking plus provide a high degree of configurability and scalability. Depending on the budget for your sensor nodes this might be better than "wasting a ton of time" messing with bare-bones hardware and third party code.
Constrain the mesh network within the "monitoring area" and set up dedicated point-to-point links (with higher power and directional antennae) between it and your office. Set up two or three if you want redundancy.
If you can't afford better hardware but have time to spare, consider reading up on mesh protocols and implementing one you think best fits your project. Many of them are reasonably simple if you are not pushing for maximum efficiency or performance.


text:
Use website to communicate with Arduino WirelessProtoShield
I have a small office with wireless network, is it possible to make a wireless doorbell?
Practical example:
Arduino is connected to the main wireless network and has a static ip,
i have a website that connects through arduino using ftp to activate the "open door" function.
note: "open door" activates a motor to press the button, or i will hack the current doorbell to connect wires :D

Arduino wifi web server: http://arduino.cc/en/Tutorial/WiFiWebServer just modify the webserver to show a "open" button and to receive a post request and open the door.

Whilst you link may answer the question, it would be preferable to include the essential parts of the linked here, and provide the link for citation. Can you please edit your answer?


text:
Error Compiling on raspberry Pi - no error details provided in IDE
I've just cracked out my Franzis Arduino Tutorial Kit (Best Xmas Present EVER!) and I'm already stuck on my second program.
I successfully wrote and executed a basic 'blink' program, however when I wrote out the second program provided in the manual I get an 'Error Compiling' when trying to check the syntax or run the program.
I tried the obvious of unplugging the board and plugging it back in but this didn't work. When I search for help most forum posts refer to the error message, however I have no message, just the orange warning bar stating 'Error Compiling'
This is the code;
// Franzis Arduino
// My second Arduino program

int ledPin = 13; //LED is connected with digital pin 13

// The setup routine configures the digital port
// This routine is executed only once at program start!

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  Serial.printIn("Our second Arduino program");
  Serial.printIn();
}

// The main program is an infinate loop
void loop()
{
  Serial.print("5 + 188 yields");
  Serial.print(5+188);
  while(true)
  {
    digitalWrite(ledPin, HIGH); // Turn on LED
    delay(2000);                 // Wait for a second
    digitalWrite(ledPin, LOW);   // Turn off LED
    delay(2000);                 // Wait for a second
    continue;
  }
}

And here's a screenshot of the error message (or lack of);

Turn on Verbose Compiling: File->Preferences->Show verbose output. Then, add the output to your question.

Both check boxes are already ticked, can you explain 'add the output to your question'?

It's not printIn, but println (as in "print line").

Thank you for the correction, however my original problem still exists

You mean, not getting any error message? Try re-installing the IDE.

Sorry, I did not apply your correction correctly, I used Ln not ln, this is now fixed and running. Thank you so much for your help!

Programming code is indeed case-sensitive. It's a lot more strict than a natural language. One missing ; and all hell breaks lose :-)


text:
How to measure resistance of TFT Touchscreen
I'm using a TFT Touchscreen shield with my Arduino UNO, and I'm running "tftpaint" example by Adafruit.
I've noticed that when initializing the Touchscreen object, a resistance value must be provided. Library default is 300, but a comment in the code says:
// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it

How should I perform such measurement? Where do I put the probes of my multimeter? FYI, my shield is this one:

Would you care to provide a link to the datasheet or at least provide the name of the TFT? The code clearly states X+ and X-, it's not as easy as the board having two pinouts named as such is it?

I couldn't find a datasheet for this particular shield. The board does not show pins labeled like that, but the hint to that was actually in the code, in variables named "XP" ("X Plus") and "XM" ("X Minus). I'll expand this in an answer of my own.

As pointed out in other answers and comments, step one was trying to get a datasheet for this component. I couldn't find a datasheet for the shield, but here is the link from the vendor I bought it from, and they provided with some articles were they explained how to perform the resistance measure. However, I then noticed the answer was in the example code itself.
Btw, the shield it's indeed based on SPFD5408 as correctly suggested by user Michel Keijzers on his answer.
So, in turns out the hint to which pins were X+ and X- was actually in the example code I'm using. Here the Touchscreen object is initialized:
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

Notice the usage of constants XP and XM. The names stand for "X-plus" (X+) and "X-minus" (X-). Now if we look a couple of lines above where these constants are defined, we see this:
#define YP A3
#define XM A2
#define YM 9
#define XP 8

In particular, we see that XM (i.e. "X-") is mapped to analog pin A2, and XP (i.e. "X+") is mapped to digital pin 8.
Now, by looking at how the shield couples with arduino, we can see that analog pin A2 of the Arduino board, connects with pin labeled "LCD_RS" in the shield, and that pin 8 connects with pin labeled "LCD_D0".
This is a picture (found online) of the bottom side of the shield, were we can see the labels for each pin:

Finally, with a multimeter at those pins, I measured the resistance and it was 292 Ohms. Not so different from the default of 300 in the library, but it's still a good thing to have the correct value.

If this was the correct answer then please mark it as accepted (button below the down arrow).

Your TFT seems like this: TFT LCD SPFD5408
I cannot find a datasheet, but normally the X+ and X- are shown on the device... if not, try to find the datasheet and look for the pin numbers.

Thanks, it is indeed based on SPFD5408. FYI, the link you provided points to a wireless module, not this TFT LCD display. X- and X+ where not shown on the device, but the hint to which pins they map was in the code.


text:
How to detect the absence of an RFID tag?
I have installed an MFRC522 RFID reader in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.
I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.
Do you have any advice or experience in implementing something like this?
Thanks!

I don't think it is particularly practical, unless you make your own RFID scanner. The off-the-shelf ones generally only respond once when a particular card is in range, so you can't even detect if the card is left next the reader, or not.
Also, as the range is usually quite limited (a few cm) I don't see how it could tell the difference between you being out of the house, or taking a bath.
What might work better would be to have an active transmitter (eg. a nrf24l01) in your pocket, which every minute or so sent a "I'm home!" message to a central place. The absence of such a message after 10 minutes could indicate you are out.
The other approach would be to "check out" with your RFID scanner. I did an RFID event management system a little while back. You use a special "admin" card to indicate that a person was leaving an event for a while (a pass-out). You could do that, or have a button by the door, which you press. The "I am leaving" button.

Oh Yes it is possible.
I did a project which allows to transmit data from RFID card to a bluetooth device.
You can use below code to identify presence & gone:
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

SoftwareSerial BTserial(0, 1); // RX | TX
int sensorPin = A0;
int sensorValue = 0;
String lastBlock="";
void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin();            // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
//mfrc522.setPassiveActivationRetries(0x9A); // for example
//Serial.println("Scan PICC to see UID and type...");
BTserial.begin(9600);
Serial.println("Scan PICC to see UID and type...");
}
boolean flag=false;
int counter=0;
void loop() {
// Look for new cards
BTserial.println("Scan PICC to see UID and type...");
if ( !mfrc522.PICC_IsNewCardPresent()) {
  if(mfrc522.PICC_IsNewCardPresent()){
    if(!flag){
    byte sector         = 1;
byte blockAddr      = 4;
byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
    0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
};

byte trailerBlock   = 7;
byte status;
byte buffer[18];
byte size = sizeof(buffer);
status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
dump_byte_array(buffer, 16);

    flag=true;
    }
  }
  else{
    if(flag){
    flag=false;
    }
  }
      return;
}
}

void dump_byte_array(byte *buffer, byte bufferSize) {
String a=String((char)buffer[9]);
String b=String((char)buffer[10]);
String c=String((char)buffer[11]);
String d=String((char)buffer[12]);
String str="";
str+=a;
str+=b;
str+=c;
str+=d;
lastBlock=str;
Serial.println(str);
BTserial.println(str);
}


text:
Washing machine controlled by Arduino for homebrewing
So, this question might sound a bit silly at first glance (no, I know, it sounds flat out insane), but not all that silly at second.
I have heard once about a guy who transformed some (presumably old-ish) washing machine into his own personal home-brewing apparatus. It is quite some idea if you think about it. Washing machine can easily solve most issues people have with homebrewing. It can carefully control and adjust temperature throughout the long and complicated process of brewing, it can stir, it can pump in fresh water.
Main question is, how to control washing machine to do what I want it to do.  Most automatic washing machines already have some controllers, but I don't see much chance in trying to simply reprogram them (Am I wrong?). Arduino seems like best choice for its simplicity and expandability. However I am still fairly new to Arduino and have trouble imagining how would connecting everything from washing machine (motor, pump, maybe water and temperature sensors) to Arduino actually look like.
So is it even possible? Are there any projects to "bounce of"? (I couldn't find any, but maybe I looked for wrong projects) Should I expect any major problems?

Sounds like you need a bunch of motor-rated relays.  Older machines used a clock motor and cams to close contacts; newer ones might have relays for some functions already.  It's possible you will find a known, reprogrammable micro inside, but you may also find an obscure or custom part.

There is an article by Atmel, talking exactly about this (not for homebrewing, though). They provide a link to a PDF file that describe in detail a project involving Arduino and a re-created washing machine.
Note that it seems to be some kind of Bachelor graduation project, and that the students seem to build an entire washing machine. They control the rotor using an Arduino, and even provide the code (and a brief history about washing machines..).
Apart from building the entire machine, there are two main directions here as I see it:

Manipulate the existing washing machine's control board using Arduino. The bad news are the it would require some reverse engineering of the existing controller, because, per my understanding (and I'm not an expert on the subject) there is no one standard and any manufacturer seems to use it's own propriety control board (similar to Microwaves or Dishwashers). The good news are that an expert could probably do it, either by dumping the controller memory and examining the hex code or by using JTag.
Another way to go here is interfacing the electrical hardware itself; see this instructable where the guy connected the Arduino in parallel to the start button, by thus allowing an alternative way to start.

As for a beginner, it would make more sense to go for the latter; in-parallel connection with an existing hardware button should be a fairly comprehensible task. Consider the hazards of working with a high voltage/power device such as washing machines. I must say that on first glance such a project doesn't seem fit a novice, but I would be the last one to hold an enthusiast's back. And if you know any, I would suggest asking supervision from someone with a strong EE background.


text:
Where does arduino IDE store the latest board selection?
I'm building a tool to help me automate my uploading process. How do I know where Arduino stores the current preferences - which board, which com port, what serial speed?
If devs are familiar with using multiple boards in the same system ithey'd know it would be really handy to be able to change that

You might consider switching to Platformio. It's command line-driven with a couple of IDEs available. It's trivial to automate uploads and support multiple boards in it. And it's much faster than the Arduino IDE.
http://platformio.org/

I’d suggest bypassing the Arduino IDE and use avrdude directly. If you enable verbose output on upload you can see the actual avrdude command the IDE is calling.

It is stored in preferences.txt in your Arduino data folder.
You can find more about that file, including where to find it, here.
Some of the keys you may be interested in are:

board=uno
serial.port=COM3
serial.debug_rate=115200

However maybe for your workflow the Arduino IDE isn't the best tool for the job.  You may consider arduino-builder, which is the back-end that the Arduino IDE uses to do the actual compiling, or maybe another IDE entirely, such as PlatformIO or UECIDE.

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


text:
Connecting Arduino Due's DAC output to pc sound card with protection
I would like to connect the DAC outputs of my arduino board to my pc sound card input so that I can use my sounds card as an osciloscope.
I have two questions:
1- if I don't use an amplifier,  how can I protect the arduino from being damaged?
2- if I use an amplifier with dual rails,  do i still need to protect the arduino somehow?
Please note that I know little about analog circuitry so a direct solution would be most appreciated. In short how would I use components to make sure I don't end up nuking my dac outputs.
Thanks.

For audio they generally AC-couple the output. i.e. put a capacitor in series with the DAC output.

Does any capacitor do? or should I look for specifics?
I know the DAC output will not go over 3.7 volts, in fact it barely reaches that number.

That not really my area of expertise. Maybe this question will help.


text:
Morse code translator Loop the same sentence
I'm a newbie so forgive my ignorance.
I'am using the Morse code translator to light up the LED which is fine but after it has processed the sentence it turns off. How can I get it to loop the sentence continuously.
Thanks

Add the code and we will be able to tell you something

-1 until some code arrives

I guess this is the sketch you are using. It reads characters from Serial and translates them to Morse code.
What you need to do to make it loop a sentence is, 1) read a sentence into a buffer, 2) loop though the buffer and translate to Morse code.


text:
arduino flexbot drone connected in a wrong way
I have an arduino flexbot, I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.
I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.
But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?

The motors turning on is expected because or the reverse diode in the mosfets driving the motor.
Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.
To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.
To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).

I measured the voltage of pin 1 in U3 without connect it to the USB port and the lecture was 3.0 V, and connected to the USB it was 4.5 V, Does that mean that I can connect the battery directly?

It should have been around 5 volt, not 3.0.  Though at 3v I'd have expected the MCU to work. But maybe they set a higher brownout-detection value. The battery is connected to pin 5 on the pcb. So connecting pins 1 and 5 is the most convenient way of connecting the battery voltage to the 5v rail.

I tried three things, the first one was connecting the battery directly to the pin 1, that  made the motors turn on for a second and then the click came back and motors turned off. The second one was remove the connection between battery and connect the pins 1 and 5, only can hear the click. And finally connect pin 1 and 5 to vcc, only three motors worked less than a second. Please feel free to post all the answers that you want, I'll give a like on each one. Thanks

Sorry to hear, that didn't work. Any chance of finding a replacement part?

Well, actually in my country that's very hard to do, probably I need to do it throw internet and buy it in another place

http://www.ebay.com/itm/LTC3200ES6-5-LTSH-IC-REG-SWTCHD-CAP-5V-0-1A-SOT23-10Pcs-/291634898601?hash=item43e6cb66a9:g:g4wAAOSwcBhWZ30e maybe? Let me know if you need some tips on how to remove the old part and solder the new.


text:
Timer interrupt library for new Arduino based on MCU SAMD21
I'm looking for a timer interrupt library for the new Arduinos based on MCU SAMD21.
I want to wake up periodically the MCU form sleep state, do some task and go sleep again. Using one timer interrupt Arduino wakes up. For new Arduino MKR family.
Do you know a library to do this?

I'm voting to close this question as off-topic because it is a request to find an external library or resource, which is not one of the intended purposes of the stack exchange network.  Try a web search, it seems to yield results.

@ChrisStratton Library recommendations are on-topic, according to Arduino SE's on-topic help page.

Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.
in this particular case, what you wanted to do is quite simple:
1) read through the datasheet;
2) figure out how the timer works;
3) figure out how the power management works;
4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;
5) run the task directly in the isr if is it short or set a flag for its execution in the loop;
6) upon completion, put the mcu to sleep.
all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.
device datasheet is the best friend of any embedded engineer, not the worst enemy.

The question is if anyone knows a library, not how to do that, I know how to do. I'm looking for a similar library to mstimer2 (https://github.com/PaulStoffregen/MsTimer2) which has a generic purpose. I'm asking if anyone knows to avoid lost time doing it. The rest of the process is done in my project, you can find in https://github.com/jecrespo/Arduino-MKR-FOX-1200-Contest/blob/master/MKR1200_SendData/MKR1200_SendData.ino


text:
How to make arduino show cpu usage with 10 leds?
So i want to make arduino show my computer cpu usage with leds, for example if 10% then 1 led will light, if 50% then 5 leds, if 80% then 8 leds...

How you would do that depends completely on what OS you're using.

There's three basic steps you need to cover:

Get the CPU usage of your computer
Communicate that to the Arduino
Have the Arduino respond to the data

We can't really help you with step 1.  That's outside our remit.   You should head over to StackOverflow for that. How you would do it depends on your host OS since each one has its own way of reporting it.
For step 2 you would need to write software for your computer, incorporating what you have learned from step 1.  Once you have the correct data you need to send it over to the Arduino through its serial connection. You'd need to come up with a good way of doing that, but probably just sending the usage percentage as plain ASCII text separated by new-lines is probably simplest.
Step 3 would entail reading in the data you sent in step 2, deciding what the numbers you have got mean, and then turning on the relevant LEDs.
Another option, which might simplify things a little, might be to use something like Firmata, where your PC sends the instructions to turn the LEDs on and off, and the Arduino just becomes a kind of dumb interface that doesn't do much on its own.


text:
How to know the external interrupt origin from the ISR
I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.
I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts
If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.
Is there any memory record which store the external interrupt activation?
This is a general question for any AVR microcontroller.

Is there any memory record which store the external interrupt
  activation?

There is, but I do not think it will be easy to exploit.
At low level, each interrupt is handled by a different ISR. So you will
have INT0_vect handling external interrupt 0 and INT1_vect
handling interrupt 1. These ISRs are all defined by the Arduino
core library. In your case, they will both call the same handler that
you defined. Thus, the information about which ISR fired is now on the
stack: it is the return address of your function.
The reason this information will not be easy to use is that you do not
know how far it is from the stack pointer. It depends on how much stuff
your own handler pushed onto the stack. You could disassemble it and
count, but then your code will be fragile, as the smallest change in the
handler (or compiler version) may change this count.
An easier approach may be to define your own INT0_vect and
INT1_vect, overriding those from the Arduino core. These new ISRs
will both call your handler, but they will pass it an argument to tell
which interrupt fired.
Or you can register a different handler for each interrupt, each calling
a common function. But this adds an extra level of function calls.


text:
Programming Arduino with FTDI via Tx and Rx pins
How program Arduino with a FTDI cable/breakout_board via pins 0 (Rx) and 1 (Tx)?
In case the USB to UART chip (16U2 or other) is broken, you can program Arduino with a FTDI instead of 16U2 or other chip.
What are the connections to reset the Arduino microcontroller automatically when sketch is upload?

has your FTDI a DTR pin?

Yes, DTR and CTS pins

It's exactly the same as for a breadboard Arduino.  That is, connect the DTR pin of your breakout board through a 0.1uF capacitor to the RESET pin. TX and RX then connect to the RX and TX pins of the Arduino respectively, along with of course the ground connection.


text:
SimpleSDaudio giving a lot of static from speaker
I'm using SimpleSDaudio (http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio) to play wav files. The connections are as follows:
MISO pin 12
SCK pin 13
SS pin 4
MOSI pin 11
Speaker pin 9
/*
 Simple SD Audio bare minimum example, plays file EXAMPLE.AFM from root folder of SD card.

 This example shows how to use the SimpleSDAudio library for audio playback.
 You need:
 - An Arduino with ATmega368 or better
 - An SD-Card connected to Arduinos SPI port (many shields will do)
   -> copy EXAMPLE.AFM on freshly formated SD card into root folder
 - A passive loudspeaker and resistor or better: active speakers (then stereo output will be possible)

 Audio signal output is at the following pin:
 - Arduino with ATmega328       (many non-mega Arduinos): Pin 9
 - Arduino with ATmega1280/2560 (many mega Arduinos)    : Pin 44

 Using passive speaker:
    Audio-Pin --- -[100 Ohm resistor]- ---- Speaker ---- GND

 Using amplifier / active speaker / line-in etc.:
    Audio-Pin --||--------------[10k resistor]----+----[1k resistor]---- GND
              100nF capacitor                   to amp

 See SimpleSDAudio.h or our website for more information:
 http://www.hackerspace-ffm.de/wiki/index.php?title=SimpleSDAudio

 created  20 Jan 2013 by Lutz Lisseck
 */
#include <SimpleSDAudio.h>

void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // Using F("...") to avoid wasting RAM
  Serial.print(F("\nInitializing SD card..."));

  // If your SD card CS-Pin is not at Pin 4, enable and adapt the following line:
  // SdPlay.setSDCSPin(10);

  if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
    Serial.println(F("initialization failed. Things to check:"));
    Serial.println(F("* is a card is inserted?"));
    Serial.println(F("* Is your wiring correct?"));
    Serial.println(F("* maybe you need to change the chipSelect pin to match your shield or module?"));
    Serial.print(F("Error code: "));
    Serial.println(SdPlay.getLastError());
    while(1);
  } else {
   Serial.println(F("Wiring is correct and a card is present."));
  }

  Serial.print(F("Looking for on.wav... "));
  if(!SdPlay.setFile("hi.wav")) {
    Serial.println(F(" not found on card! Error code: "));
    Serial.println(SdPlay.getLastError());
    while(1);
  } else {
   Serial.println(F("found."));
  }

  Serial.print(F("Playing... "));
  SdPlay.play();
  while(!SdPlay.isStopped()) {
    ;   // no worker needed anymore :-)
  }
  Serial.println(F("done."));
  SdPlay.deInit();
}

void loop(void) {

}

The problem is when playing the wav files. It plays with a lot of static. I've tried adding a 1k resistor between the speaker and gnd but that just lowered the overall volume. I resampled the wav files in itunes to 32khz, 8bit, mono. If I lower to 16khz then the audio volume becomes very low and the song just plays extremely fast. Here is a google drive link to one of the sounds:
https://drive.google.com/file/d/0B3yAl4G-mcC4dlppN3dtczJvT1k/view?usp=sharing
I really need help. I'm not sure what to do!

Is that sample a source sound or a playback recording?  I don't hear any static in it.

Have you read the documentation in that link you provide? Especially the bit about converting the WAV files to 8-bit mono raw files prior to use?


text:
How to get neopixel to fade colorwipe?
I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.
#include <Adafruit_NeoPixel.h>

Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
void setup() {
  strip.begin();
}

void loop() {
  colorWipe(strip.Color(255, 255, 255), 150); // Red
 colorWipe(strip.Color(0, 0, 0), 150); // Red
 delay(5000);
}

void colorWipe(uint32_t color, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, color);
      strip.show();
      delay(1000);
  }
}

This works! Just had to uncomment the delay within the while

You could change the intensity of each colour in steps till you get to your target colour.
void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
  for(uint16_t i = 0; i < strip.numPixels(); i++) {
      uint8_t curr_r, curr_g, curr_b;
      uint32_t curr_col = strip.getPixelColor(i); // get the current colour
      curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

      while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
        if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
        if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
        if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
        strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
        strip.show();
        // delay(wait);  // add a delay if its too fast
      }
      delay(1000);
  }
}

To use it:
void loop() {
  colorFade(255, 0, 0, 150); // fade into red
  colorFade(255, 255, 255, 150); // and then into white
  delay(5000);
}

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.

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


text:
Long term connection between Arduino and computer
I am looking to make indicator lights for my computer to indicate things such as system load, IO usage, et cetera, using an Arduino and NeoPixels.  I would like to just plug it into my computer, and have some custom software connect to it and send it the data it needs as my computer runs.
The part I am having trouble with is figuring out how to connect the Arduino to the computer in a way that is consistent in the long term.
I have had issues with the Arduino switching which /dev/ttyAMC* port it is assigned, so I looked for options other than the USB serial.  The only other way seems to be USB, as that is the only common general purpose port these days.
This is where my problem lies.  People don't seem to be doing this sort of thing, or at least they don't post about it.
The Teensy can act as a USB HID, but the raw HID feature hasn't been updated in almost a decade, the host side code is based on deprecated libraries, and it seems oriented more for Teensy to computer transfers.
There doesn't seem to be any consumer level USB interface chips available, either.
I found V-USB, which seems like a solution to my problems, in fact someone even used it to do basically what I want to do.  However, I would still need to learn the library.

So, my question is what is the recommended way of interfacing between a computer and Arduino in the long term?  Is USB support really necessary, or have I just overthought the entire thing?

You don't want to use V-USB if you can get an Arduino with a native USB interface (in which case you would use LUFA).

@IgnacioVazquez-Abrams By Arduino with a native USB do you mean something like the Arduino Zero/Due?

Those do have native USB, but they don't use LUFA. I was thinking more like the Leonardo or Pro Micro.

You should check out chipKIT - it has the best usb stack in the industry (I know, cus I wrote it ;) )

And this is me using it for something similar to what you want: https://hackingmajenkoblog.wordpress.com/2017/05/19/adding-an-oled-to-my-computer/

I think the easiest option may be to keep the USB (ACM) link, so you
don't have to do anything special on the Arduino, and try to figure out
a way to identify the correct device on the computer side.
On Linux, providing consistent device names for specific peripherals is
normally the job of udev. You could add your own udev rule to create a
symbolic link for your Arduino every time you plug it in. Then, your
custom software would always open /dev/neopixel-monitor, which would
be a symlink to the proper /dev/ttyACMx device.
Actually, you may not need write your own rule. I took a look at the
udev rules installed by default on my Ubuntu 16.04 and found a file
named /lib/udev/rules.d/60-serial.rules meant to populate the
/dev/serial/by-path/ and /dev/serial/by-id/ directories. Then I
plugged in my Arduino Uno R3 and saw the symlink
/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00
automatically created, which right now points to ../../ttyACM0. In
this name, 0043 is the USB device ID of the Uno, and the following
alphanumeric sequence looks like a serial number. The if00 looks like
an interface number, and may vary (it won't, se Majenko's comment).
The link name should
be a good way to uniquely identify that particular Arduino.

I have a file that makes /dev/boards/arduino/uno1 etc for all my boards. It's a rather massive file (I have a lot of boards), but it's very very useful.

The rule for that one: ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0001", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", MODE="0666", GROUP="plugdev", SYMLINK+="board/arduino/uno1"

Oh, and the interface number (if00) will always be 0 for an Arduino. It's the USB interface in the config descriptor. There's 2 interfaces, but one is a master and the other a slave (that's how CDC/ACM works), and interface 0 is the master in the descriptor. The only way to get the interface to change is to reprogram the ATMega16U2 with a different firmware.

By the way - the command udevadm info -a /dev/ttyACM0 is useful when crafting udev rules.


text:
Picking the time a led on an arduino should turn on, via android
I have created an app which is connencted to my arduino via bluetoth. The user of the app can turn on and off a led which is connented to the arduino. But I want to take it a step further... I want the user to be able to give the time and the date when the light should turn on and additionally the time that sould pass until the led turns off again. Is it significantly harder? I have thought of using an already existing alarm app but I am pretty stuck, so could anyone give me some suggestions?

All you will need is an RTC module, you set an alarm with the module; it will trigger an interrupt when the time and data you set is reached. Then you light up the LED and use a timer to keep track of the length of time its on.

Make the Bluetooth message send how many seconds it is until the light should be on, and how many seconds it should stay on.
Then the arduino code can just handle everything with millis(). You know the millis() you were asked to start, add the delay, and wait for that time.
Delays less than 50 days (wrap around of millis ())  take no effort to handle it you embrace the overflow.
Handling delays greater than 50 days can be achieved by watching for millis() overflows and counting them. You could also make your own timer based counter.
If you care about recovery after power loss / reset you could use an RTC module. Depending on its complexity, it could interrupt you or you poll it to check for a date you saved to Arduino eeprom.  You would have to consider what the system should do it the alarm would have happened during the power loss...


text:
Arduino Mimicking Voltage Dividing Keypad / Matrix
Still very new to Arduino, so bare with me. I've been all over Google looking for ways to hack my alarm keypad. This is my first time using the Arduino to hack something  :smiley-confuse:
The keypad has a 13.7v input. Every other contact I can touch shows 5v or less. I realized quickly that the key buttons were producing various voltages. A quick search revealed that it was a voltage divider. I can see the resistors on the ladder. I though about mimicking the ladder via the Arduino and using a common ground.
I can see two shift resistors that say HEF4094BT. My guess is that these power the led's on the board.
I can also see a chip that reads KSL1 r1342 that I can't seem to find a datasheet on.
I have a few questions, but I guess I need to tell you my end goal. I want to make my keypad an IoT device. I want to be able to read the status of the alarm, and possibly mimick the keypresses to disable the alarm or activate it.
1st. I was thinking I could share a common ground, and read a led state for high/low. Like the "Armed" Led. Thought I'd ask the community before I go and short something  :(
2nd. How can I mimick the keypad's output voltages? Maybe a DAC? If so, what do you recommend?
Other Information: It's a DSC PC1550 - 6 zone alarm. (...and I'm also guessing the Rx/Tx are some DSC proprietary serial connection for security :/ )
Cheers,
Robert.

Also see “text a cell number if my dsc pc1550 home security system alarms”  and  “dsc keybus protocol” and “dsc keybus talk”

Wow! Following one link, to another via the comments led me to [link]https://github.com/dougkpowers/pc1550-interface which makes me feel even more hopeful! I might be able to skip hacking, and move directly to Interfacing! The article didn't really state whether I should connect the wires directly, or use resistors. I'm assuming that the 13.3v is regulated by the arduino, but I'm not sure about the clock and data pins? - thanks @jwpat7

@RobertCole The Arduino I/O pins can take only up to 20mA of current, and a MAXIMUM of 5.5v. But that is not normal operating condition. That is assuming you are using an Arduino Uno, but otherwise the ratings don't change much. Anyway, a simple woltage divider can solve your problem

Reading the leds would work. Depending on the voltage going out of the shift register, you might need to add a buffer chip, to lower the voltage.
For the keypad I'd probably go with a variable resistor, better known as a digital potentiometer.
You could probably add a way to also read the keypad, from the arduino. Which might be useful, maybe.

Glad to hear that  my common ground would work for the leds. But I can't see the logic in the buffer chip?
Digital potentiometer makes sense [link]https://www.sparkfun.com/products/10613
and then pulse various resistances in relation to the resistance of the keypad?

The leds might be supplied with 12v. Connecting this to the Arduino will break if. So in that case you need to convert the 12v signals to 5v signals, using a buffer chip, or some discrete circuitry. The the voltage is around 5v, I would at least put a resistor between the led and the Arduino. PS depending on how the led is wired (resistor 'before' or 'after' led) you might have to connect your wire to the associated resistor. The pot. you linked is what I meant. But you have to measure the resistance of the keypad (while powered off) to see if the 10k version is okay.


text:
Why does my PIR sensor stay high with ESP8266 breakout board?
I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.
When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.
Testing

Tried using separate 5v supply to PIR same thing happens
I have tried both retrigger modes (H & L) and experienced the same result
The same happens with the Adafruit featherwing huzzah board.
I have tested the PIR without a micro-controller and can confirm that it functions correctly -lighting an led
I have tested with an Arduino Nano with the same code and it functions correctly - lighting an led

My Code modified version of Arduino Playground PIR Project
//Sends IFTTT every 5 minutes it detects motion

#include <ESP8266WiFi.h>
//WiFi Settings

// Set up macros for wifi and connection.
#define SSID "my-network"    // SSID
#define PASS "mypassphrase"      // Network Password
#define HOST "maker.ifttt.com"  // Webhost
//-------------------------------
const char* streamId   = "test";
const char* privateKey = "mysecretkey";

//PIR Settings
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

int  interval = 1000; // Wait between dumps
boolean lockLow = true;
boolean takeLowTime;
int ledPin = 1;
int pirPin = 2;    //the digital pin connected to the PIR sensor's output
int nPIR_detect;
int motion = 2;

int minSecsBetweenUpdates = 300; // 5 minutes
long lastSend = -minSecsBetweenUpdates * 1000l;
//-------------------------------

// Begin Setup
void setup(){
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++){
    Serial.print(".");
    delay(1000);
    }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
   nPIR_detect = 0;

  // Test ESP8266 module.
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
 if(digitalRead(pirPin) == HIGH){
       digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         sendData(String(motion));
         delay(50);
         }
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){
       digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

void sendData(String motion){

  //Send the motion to IFTTT value1
  Serial.print("connecting to ");
  Serial.println(HOST);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(HOST, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/trigger/";
  url += streamId;
  url += "/with/key/";
  url += privateKey;
  url += "?value1=";
  url += "motion";

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + HOST + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");

}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Connection");
    return true;
  }
  else{
    Serial.println("No Connection");
    return false;
  }
}

OQ: Why does my PIR sensor stay high with ESP8266 breakout board?
In essence, I never see the serial message "motion ended at.."

What do the measured voltage levels look like?  Is your breakout board to 5v tolerant?

How are you converting the 5v signal to 3.3v?

@Gerben which 5v signal? (from where?)

@Gerben the pir converts 5v to 3v

I'm sure you have probably done both these, but just in case you haven't...
I see from your code you are using Pin 2 for the PIR sensor.  I'm sure your not as dumb as I am every time I program a ESP8266, but check you have connected the PIR to pin 2, that's not the connection labelled D2 its GPIO2, which may or may not be labelled.
Assuming that's right then the next possible problem may be that GPIO2 is shared with TXD1, its possible that this is being used.  So try moving to GPIO4.

Changing from GPIO2 to GPIO4 worked for me.

I have the same issue with Huzzah and a PIR. The PIR is noisy and I get a false high every 10-20s while the code runs without any problem on an UNO.
I think it is a problem of HF coupling from wifi interfering with the PIR's amplification circuit. I will try shielding and caps/ferrites to get rid of the HF on the PIR or use another power supply and couple the signal line via optocoupler.

The solution I found to this problem is use a 10k resistor between the PIR sensor output and the input pin of the ESP8266.
Not sure if 10K is the best value, someone else may find a better value, but for now, for me its working great.
John


text:
char array comparison
I'm having some issues dealing with strings in a small Arduino app.
I wonder why this code works:
mqtt.setServer("192.168.1.42", port);

and this code doesn't:
IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);

Even when strcmp returns 0 when I compare both:
strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality

I've also tried other alternatives, such as creating a char array, with no luck:
String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);

mqtt.setServer(ipchar, port);

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.

What does the mqtt.setServer do? Does it store a pointer reference or does it copy the input string to its own buffers? If you use a constant "192.168.1.42" then that string will be static. WHen you use ip.toString().c_str(), when the ip object is deallocated but .setServer() still has a reference to that char*, it's become invalid. Where is the library you're using?

PubSubClient::setServer(const char * domain, uint16_t port) just saves the pointer, it doesn't copy the string (probably because it expects a static string literal).
(Source)
In your case, when ip goes out of scope, the pointer is no longer valid, so it won't work.
Just use the PubSubClient::setServer(IPAddress ip, uint16_t port) function instead.
(Source)
Always read the API documentation, most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the header files, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.


text:
voltage output at digital pins vs. load
I am trying to convert the signal from digital pin 2 on my Uno to 3.3V.  I set up a voltage divider with 3 x 1000 ohm resistors.  When connected to ground and 5V the divider circuit generates 3.3V correctly, with a calculated input current of 1.7mA.  However I connect it to a digital pin, the digital pin voltage drops from 4.8V to .37V.  I thought the digital pins were to support 40mA, I was assuming 40mA at the 5V supply voltage.  Is my Uno malfunctioning?
Thanks

Sure you got the pin set up as an output and have written a high/1 to it? (have to ask). What's on the output of the voltage divider - i.e. between the resistors? Something with a high/low resistance/impedance?

Just figured out I didn't have the pin mode set, it works fine now, thanks.

Just figured out I didn't have the pin mode set, it works fine now, thanks.


text:
Is my HC-05 broken?
I have an HC-05 wired with an Uno, and am using a sketch to control the HC-05 AT mode and send AT commands, per a variant of this instructable:  DIY Arduino Bluetooth Programming Shield
The error I have is simple in appearance, when AT mode is signaled off by bringing HC-05 pin 34 low after being high, then a low pulse is sent from the HC-05 to the HC-05 pin 32 which is wired to the Uno reset pin per the instructable.  The low pulse should not be occurring and is triggering the Uno to reset, even though it is only 1-2ms.  The low pulse also occurs when the HC-05 is powered on, neither low pulse occurs if the polar command is reset to normal "1,0".
After receiving the "AT+POLAR=1,1" command the HC-05 pin 32 should trigger low when a BT connection is made to the HC-05, that part works correctly.  The other low pulses triggering the Uno to reset when signaling to leave AT mode and when powering on the HC-05 are causing problems with running the sketch so I need to determine how to stop them.  I have checked the AT settings I am familiar with and they are as expected.
Any ideas are appreciated.  Thanks for your help.


text:
What speaker can you drive with output pin?
I'm wondering how to drive a speaker using an arduino output pin.  I am using a pwm playback method with a sound data file.  If you wire a speaker across an output pin and ground then how do you calculate what speaker power and impedence you can use without damaging the arduino?  Is there a reference making these calculations?
Thanks

The Arduino can supply 5V at max 20mA so 5/0.02 ⇒ 250Ω (if you can find such a beast).
NOTE you should use a capacitor to prevent DC flow if using a conventional speaker.
In general the larger the speaker the better. Tiny speakers are inefficient transducers. Hi-Fi speakers are not a good choice, as they are often inefficient, trading efficiency for linearity.
An alternative, if you are a scrounger, is to scavenge a transformer from an old transistor radio - this should give the best match.

Typically the pins of an MCU are current sources, so a smaller load might be fairly harmless (if ineffective). The capacitor will help too in limiting average current.

I thought the sound volume and quality from a smartphone loudspeaker would be about right.  Not the earpiece but the one used for the loudspeaker.  Some are 10x15mm, most are 8ohm, .5 - 1W.  90dB  ex.)  http://www.knowles.com/eng/Products/Receivers-and-speakers/Dynamic-speakers  But I don't now how they are driven, probably a proprietary and expensive amp circuit.  To get the most value in the toy I'm interested in the simplest system, thus the single transistor method.

Milliways - The max current for the Uno is 40mA/IO pin.  Is this really how you size a speaker?  I have been told it has to do with the relative impedance of the devices but I haven't 'googlefound' any good references yet :(  BTW 5V/30mA = 167 ohms and I have found 150 ohm speakers but I still don't know if this is the right way to match a speaker and source.

@perigalacticon That is a rough engineering calculation. I am not sure the Arduino can deliver 40mA @ 5V (I have never measured). In fact the duty cycle would be 50% because the load is only actively driven on half cycle. Any higher impedance less current, lower less voltage swing. Speakers from phones are generally lower impedance, but the have higher powered drive circuitry. You could get more with a simple transistor amplifier.

@Milliways with 20mA due to 50% D.C. for lower impedance the voltage swing would only be reduced if the source was unable to provide the current correct?  Do you know of a source for more calculations?

@perigalacticon The comments were generic. I have not tested the ATMEGA under overload conditions. Engineers generally do not do this - it varies on different systems, which will either limit current or blow up. I always run to 40mA max/20mA per pin recommended of the specification.

Only very small ones with 20-30mA.  Earbud-size and slightly larger. You can buy a 2x3W amplifier which runs on 5V, and gives you two audio channels - but it works fine for mono. It can drive my 4 ohm desktop speaker, and is probably too powerful for that. Read about signal voltage and resistance for speakers. IIRC small audio outputs (like from an mp3 player) switch from -2.5V to 2.5V, giving an RMS of 5V. Or perhaps that was just my player. The only way to know this is to measure it - I played a sine wave and got a circa value. Offhand I can't say how to drive negative voltages from an arduino without extra circuitry. Hope it helps (and show us your code :)

USer400344 - I am trying to get max value into the toy so trying to I prefer to avoid the amp chip.  How do you calculate the size of speaker you can power with a given current?  Thanks.

The max value of your output pin is 5V/30mA (I would limit it to 20mA) - so 0.15W. As I said a speaker needs negative voltage as well. A PC speaker (the builtin kind for beeping BIOS codes) is probably driven by a transformed 5V source.

You need the speakers impedance for this as well, google audio output, 3.5mm TRS and RMS.

And I should add that driving 40mA from an uno pin is advised against by most of the arduino guys at arduino.cc - on USB power you can expect a total (all pins) of 400mA, on voltage regulator (raw/vcc) I would not go above 200mA. If you need to drive something with 40-60mA, you can attach pins in tandem (but keep each pin a few pins away from your other pin), and it will only work with digitalWrite(), not analogWrite()... I did this with a relay than needed 50mA to toggle (S pin), worked well. It's a good method if you have pins to spare, and don't want to add a transistor... offtopic, sorry.

so I can let the pin drive the speaker at 30mA.  If I progrogram the playback code to provide a signal centered at 2.5V then the signal can be 5V p-p.  With an amplitude of 2.5V this is an rms value of 1.7vrms.  Multiply by peak current 30mA gives .053Wrms power, is this what I use for speaker selection?  Do I choose the speaker ohms by 5V/.030A = 167ohms?  How much does the speaker inductance effect the impedence?  Thanks.

That's actually quite clever. I assumed the speaker membrane required negative voltage to 'move back' and positive to 'move forward'. If it just relies on a centered voltage that would make it simpler. Please post your results.

No, try measuring the resistance of a headphone speaker or builtin pc speaker. That's the type you can drive with ~30mA. A small amplifier board will really free you. Mine is tiny, and can drive 2 3W speakers from it. I supply 5V@500mA to the board and hook standard mp3 player audio to it. It does not do anything but amplify. It measures approx. 1.5cm by 3cm, cost me 3$

here are scope traces of a greeting card speaker voltages, and the speaker voltages from my application showing the detail of the pwm pulses.  I need to get the right caps to low pass filter the signal and then I'll try a few circuits.  The reason for no amp is cost, trying to keep the total toy cost under $5.  Greeting card speaker:  https://drive.google.com/file/d/0B-jN2Adg-YnuUG1wYzQxQVY3UzA/view?usp=docslist_api. Arduino pwm speaker:  https://drive.google.com/file/d/0B-jN2Adg-YnuR0VvTFN4NTZpTEk/view?usp=docslist_api

If it's a tiny speaker... those are driven from 3V sources. Have a look at the circuitry and find out how the negative voltage is generated (if it is at all generated). If you want something tiny for PWM, use an ATtiny85, they are very good for that. 8KB flash, 512B sram IIRC. Edit: Use something like the usb-asp ISP for attinys.

Thanks, for the greeting card trace I am surprised to see that the speaker terminal voltages are out of phase.  I was measuring each to ground, maybe the ground wasn't accurate?  How is it possible that one speaker terminal voltage increases while the other terminal decreases, is this expected maybe due to inductance?  I don't understand.

You should really ask on an AV forum.


text:
interrupting an interrupt
What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again?  For example Timer0 ISR(TIMER0_COMPA_vect){} on the Uno.  This is for debugging purposes in a complex program.  Thanks.

the timer will set the Timer Interrupt Flag (TIFR0 register)
The ISR will be called, and the flag will be cleared
you do some long calculations or something
the timer will match OCR0A, and set the interrupt flag again.
you calculations are done, and the ISR function will end.
the uC will jump back to the main loop code, and execute 2 1 instructions.
The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.
You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.

Congrats, that's a pretty good summary of what happens in this situation.

1.- My understanding is that the uC will execute a single instruction (not 2) of the main code before entering the ISR again. 2.- Where did you read that only one ISR per vector can run at the same time? It's the first time I read anything like this.

Note that if you re-enable interrupts inside the ISR, then the same interrupt definitely can re-enter the same vector. This is one reason why re-enabling interrupts inside an ISR needs careful thought... You said it yourself: (step 2) - "...the flag will be cleared."

Apparently I was wrong in the last paragraph. I'm not sure where I got that from, but it doesn't appear anywhere in the datasheet.

It won't be called until the current interrupt is finished. As soon as the current interrupt function returns the pending interrupt would trigger and call the ISR again.

You need to explicitly allow interrupts to be interrupted. For more information I suggest you see section nested interrupts on avr-libc.


text:
Uno timer 2 set up
I am trying to use Timer2 in an Uno in fast PWM mode.  Can someone explain how to set up the TCCR2A & B registers?
Currently I have:
  TCCR2A |= _BV(WGM21) | _BV(WGM20);
  TCCR2B &= ~_BV(WGM22);

  TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
  TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
  TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

I would like to have the inverted value on TCCR2B, but I think it can be inverted using OCR2B ^= 255, correct?  This is to have a varying signal on Pin11 and its inverse on Pin3, the signal is generated by varying the OCR2B value.
Thanks

I realized a mistake, what I need to do is set up pins 11 and 3 (TCCR2 A & B?) to fast pwm mode.  Then I will set OCR2A to a value, and OCR2B to the value's inverse.  Should this work?

I also tried:   TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);  But I'm still not getting output on pin 3.  Thanks.  Sorry for the excessive posts.

If you want to get two complementary PWM signals, you have to set the
same value to both output compare registers. This is necessary to have
the two signals in phase. You also have to configure one PWM in
non-inverting mode and the other in inverting mode. For example:
TCCR2A = _BV(COM2A1)  // non-inverting PWM on OC2A
       | _BV(COM2B0)  // PWM on OC2B:
       | _BV(COM2B1)  //    inverting mode
       | _BV(WGM20)   // fast PWM
       | _BV(WGM21);  // ditto
TCCR2B = _BV(CS10);   // clock at F_CPU / 1
OCR2A  = 84;          // duty cycle ~ 1/3
OCR2B  = 84;          // same signal, complemented

Checked on the scope: when pin 3 goes high pin 11 goes low and
vice-versa.

Thank you.  What I need is both PWM signals in non-inverting mode.  Then I need to invert the duty cycle OCR2B w.r.t. OCR2A.  So as OCR2A increases, OCR2B will decrease the same.  The actual PWM signals are to be in-phase, but complementary duty cycle.  Sorry for the confusion.

Thanks Edgar, I was able to sort through the 328p datasheet and get the registers figured out.  First time I have worked with registers and bit values and bit math so it took me some time to understand this but it works really well now.  Thanks again.


text:
Debugger for Code::Blocks + Arduino
I am not very experienced in this, but I was wondering if Code::Blocks has a way of getting a debugger that runs for Arduino chips, specifically. I understand there is Arduino IDE for but does it allow debugging specific to those microcontrollers (Amtel and such)?

The arduino IDE does not support debugging on chip, and it will take additional hardware to do it (like a JTAG). I don't know if Code::Blocks has any support for this kind on chip debugging though.

If you are interested in on-board debugging or off-board debugging, you will need a programmer/debugger. I would recommend the Atmel AVR Dragon. Atmel AVR Dragon uses the Atmel Studio 6.2, which is a great IDE.

Answer: Code blocks does not currently have an Arduino debugger. The Arduino IDE does not have a debugger.
There is an Arduino debugger in Atmel Studio using the Visual Micro plugin.
That said, you have to use Ms Windows to use Atmel Studio which might not be available to you.
The Visual Micro debugger is simple and uses usb so does not require additional hardware but as your experience grows you might also like to progress to fully blown hardware debug using the native Atmel Studio Tools
Visual Micro debug in Atmel Studio
Atmel Studio Download

Can you suggest a hardware debugger to go with C::B?

I already answered that question so I am not sure what you are trying to achieve by asking it again. Two of us have tried to help you but you seem to want to ignore the answer?


text:
AnalogRead too slow... Faster alternative?
For a program that I'm working on, I want to get an accurate reading from a noisy pressure sensor.  So, the idea that I have is to do a thousand AnalogRead commands on the same port very quickly and then average them.  The pressure readings become very precise, however, the program that I am running becomes very slow.  I need my program to be orders of magnitude faster.
I'm sure that there's a faster way to do AnalogRead commands, especially because I am requesting the same port over and over.  Maybe there's a way that I can take lower resolutions of readings and then average those?  I don't know.  Can anyone help me?  I am an amateur Arduino user looking to learn.
I have done a little bit of research on my own and had trouble finding concrete examples.

And of course you want it on the Due, so my AVR knowledge is little help here. All I can suggest is to crack open the datasheet and learn about the ADC and interrupt facilities on the SAM3X.

Ignacio's proposal is surely a good one if you really need higher sample rates, but I would try another approach:
Average your signal before sampling it! This can be done by connecting a simple RC lowpass to your AD input.
With that you get rid off those high frequency noise you don't need, but without wasting CPU time.

The ADC is rated at up to 15K samples per second.  So reading a 1000 is not a problem.
However, care must be taken in the Vcc used for the ADC (AVcc).  It must be noise free otherwise it will introduce noise into the digital readings, when it actually isn't there in the analogue signal.
See page 256 on the Atmel 328 datasheet for further information.
The RC Lowpass filter should also be used on the AVcc supply, as well as the pressure sensor signal.
I just thought!   Are you using a Serial.print() after each analogRead()???
If so, the serial port will drastically slow down the sample rate.
If this is the case perform a number of analogRead()s then use Serial.print() after some form of processing.

The Due does not use an ATmega chip, and AVcc is already fixed on an Arduino.


text:
Simple question about the SPI clock for Intel Edison
I am doing a project with an Intel Edison Arduino breakout board.
http://store.arduino.cc/product/E000052
http://download.intel.com/support/edison/sb/edisonmodule_hg_331189002.pdf
I have a device that I want to communicate with by SPI.  This device can receive a maximum of 16MHz for its clock.  I want this maximum speed of 16 MHz.  From what I understand, the Edison can output a clock speed of 19.2 MHz.
I don't know much about clocks and I am still learning.  Is it possible to program the Edison to operate its SPI output clock at a speed of 16 MHz?  If so, how would this be done?

SPI.setClockDivider(SPI_CLOCK_DIV2); would make it run at 9.6mHz

Is it only possible to divide the clock by 2?  Not by decimal numbers?

Look into the function mraa_spi_frequency.