text:
Controlling EL wire or panels with arduino
I understand that el wire and paper needs a special power source known as an inverter to light it up.
If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?

upstream slow blinking
The simplest approach:
Use a relay to turn the lights on and off. Control that relay with an Arduino.
("How to turn a relay on and off with an Arduino?" is a separate question).
Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"),
and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.
power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
           +--------------------------------+    +---------+

downstream slow blinking
Alternative approach:
Use at least 2 pieces of EL wire.
Wire one always-on;
use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).
                                   always on
power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
           +----------+    +---------+   +-------------------------------+

Control that relay to control the EL wire with an Arduino, same as before.
dimming and PWM
Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours.
If you want to blink faster than that (and most people dim EL lights by blinking them much faster than that), you'll have to use something other than a relay.
Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.
Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR).
("How to wire a SSR to an Arduino?" is a separate question).
power source ---- EL inverter
          +-----------+   | |
                          +----- EL wire (always on)
                          | +-----+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          ... etc.

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire --
some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc.
(A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).
The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire(c)(d);
Diana's SparkFun EL Sequencer(e)(f)(g);
the seeedstudio EL Shield(h)(i)(j)(k);
Tully Gehan's Cool Neon Arduino Shield(m)
etc.
uses such zero-crossing optocouplers, triacs, etc.
(requires a separate EL inverter).
According to some people on the Arduino forums talking about EL wire(n)(p),
some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.
Some people save a few more pennies by skipping the optocoupler,
wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac.
(q) (r) (s) (t)
If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.
always-on
The "extra" always-on bit of EL wire is because some people say
"never run the inverter without at least 1 foot of EL attached"(a) because running some EL inverters with no load "can damage the inverter"(b).

You could connect the Arduino to the light using a relay or any electronic switches (transistors and etc) that can take around 10 to 15mA per meter (so its distance dependent). You could use this link https://learn.adafruit.com/el-wire/soldering-to-el-wire to find out where to solder the switch connections to

EL wire runs on high voyage AC power. So you can't just use transistor. A relay or triac should be used.

Well, there are transistors that can withstand high voltages but I do agree a relay or triac would be more appropriate. Just listing out the options.

So the arduino would control the relay that is between the inverter/power source and the light either allowing current to flow or resisting it?

Yes. EL wire > Relay > Source

Yup, but note that you wont be able to use PWM according to Adafruit due to the characteristic of the EL wire

If I'm using the 5v from the arduino and this inverter (http://elwirecraft.co.uk/el-products/portable-inverters/mini-portable-1xaaa-battery-inverterdriver-for-1m-el-wire-or-50sq-cm-el-tape/) what kind of relay should I buy?

I'm not sure how much is the voltage output of the inverter in the link but the Adafruit one has an output of 100VAC so you might need a relay that can handle a voltage of 100VAC or more (contact voltage). In addition to that, the relay would also need to support a coil voltage of 5v. Coil resistance then depends on the model of Arduino you are using. For example, you'll need a coil resistance that will give 40mA or below for Arduino UNO or you could control a transistor to switch the relay as suggested by this link http://forum.arduino.cc/index.php/topic,17227.0.html

For a simpler option, there are Arduino shields for controlling El Wire.  Sparkfun makes a couple and they have some sample code and projects.
https://www.sparkfun.com/products/10878


text:
How can I be engaging the arduino mega with OBD-II UART card?
Currently I have been doing a project where I need to know the speed of the vehicle, I have implemented the following code but the results have not been good because when the vehicle is in motion always prints STOPPED.
I connected the OBDII-UART card from Sparkfun with Arduino MEGA.
The connection of the cards shown in the image attached below

  1.   char rxData[20];
  2.   char rxIndex = 0;
  3.   String inputString = "";
  4.   boolean stringComplete = false;
  5.   void setup(){
  6.   Serial.begin(9600);
  7.   Serial1.begin(9600);
  8.   Serial.flush();
  9.   Serial1.flush();
  10.   //Reset IC
  11.   Serial1.println("ATZ");
  12.   delay(1500);
  13.   getOBDResponse();
  14.   Serial.println(rxData);
  15.   clearBuffer();
  16.   getOBDResponse();
  17.   Serial.println(rxData);
  18.   clearBuffer();
  19.   //Sets IC to defults
  20.   Serial1.println("ATD");
  21.   delay(1000);
  22.   getOBDResponse();
  23.   Serial.println(rxData);
  24.   clearBuffer();
  25.   getOBDResponse();
  26.   Serial.println(rxData);
  27.   clearBuffer();
  28.   Serial1.println("ATSP0");
  29.   delay(1000);
  30.   getOBDResponse();
  31.   Serial.println(rxData);
  32.   clearBuffer();
  33.   getOBDResponse();
  34.   Serial.println(rxData);
  35.   clearBuffer();
  36.   Serial1.println("010D");
  37.   delay(1000);
  38.   getOBDResponse();
  39.   Serial.println(rxData);
  40.   clearBuffer();
  41.   getOBDResponse();
  42.   Serial.println(rxData);
  43.   clearBuffer();
  44.   Serial1.println("ATDP");
  45.   delay(1000);
  46.   getOBDResponse();
  47.   Serial.println(rxData);
  48.   clearBuffer();
  49.   getOBDResponse();
  50.   Serial.println(rxData);
  51.   clearBuffer();
  52.   //Bus initiation
  53.   Serial1.println("ATSI");
  54.   delay(3000);
  55.   getOBDResponse();
  56.   Serial.println(rxData);
  57.   clearBuffer();
  58.   getOBDResponse();
  59.   Serial.println(rxData);
  60.   clearBuffer();
  61.   Serial.flush();
  62.   Serial1.flush();
  63.   }
  64.   void loop(){
  65.   /*
  66.   if(stringComplete){
  67.   Serial.println(inputString);
  68.   inputString = "";
  69.   stringComplete = false;
  70.   }
  71.   */
  72.   Serial1.flush();
  73.   Serial1.println("010D");
  74.   getOBDResponse();
  75.   Serial.println(rxData);
  76.   clearBuffer();
  77.   getOBDResponse();
  78.   Serial.println(rxData);
  79.   clearBuffer();
  80.   }
  81.   void getOBDResponse(){
  82.   char inChar = 0;
  83.   while(inChar != '\r'){
  84.   if(Serial1.available() > 0){
  85.   if(Serial1.peek() == '\r'){
  86.   inChar = Serial1.read();
  87.   rxData[rxIndex] = '\0';
  88.   rxIndex = 0;
  89.   }else{
  90.   inChar = Serial1.read();
  91.   rxData[rxIndex++] = inChar;
  92.   }
  93.   }
  94.   }
  95.   }
  96.   void clearBuffer(){
  97.   int i;
  98.   for(i = 0; i < 20; i++){
  99.   rxData = '';
  100.   }
  101.   }
  102.   void serialEvent1(){
  103.   while(Serial1.available()){
  104.   char input = (char)Serial1.read();
  105.   inputString += input;
  106.   if(input == '\r'){
  107.   stringComplete = true;
  108.   }
  109.   }

I have based on the example is the page of the card https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide/connecting-to-an-arduino, but when I set the protocol sends me Ok, but when I ask for the speed I send a message from Seeking I do not understand.Information truck tried to read from the console on a laptop
How can I accuratley get the speed of the car?
Well, now I require to get the speed I have entered the command according to the command table ELM327 I quickly attached.

I haven't studied the linked code in detail, but could you please add some more information? Comparing the example on the linked website (respectively on https://github.com/sparkfun/OBD-II_UART/blob/master/Firmware/obdIIUartQuickstart.ino), your commands are totally different. The linked sources send "010D" for vehicle speed and "010C" for RPM, what seems to make sense.

I have not achieved anything, still no answer card I tested with different cars but still showing me an error, someone who can help me please

Only was a baudios

On behalf of @Alejandro: I've been trying to make this circuit work but the only thing I am receiving after de 010D command is "SEARCHING......." "STOPPED" "SEARCHING......." "STOPPED" "SEARCHING......." "STOPPED". Do you experienced this problem? Or can you please share the code, bauds configuration, etc, that you used? Thanks in advance

source: Stack Exchange

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

sort: votes


text:
Sense Whether Circuit is Closed
How can you sense a closed circuit? I want to have 4 pins with disconnected wires and when touched with a fifth wire play a specific note on a piezo buzzer until disconnected again.
This project loops through several keys and checks whether they are being touched using the Capactive Sensor library. I want to do something similar, but not with capacitive sensing. Alternatively, it may work to have the buzzer always trying to play a note, but only sounds when one of the 4 circuits is close. I'm just not sure how that would work in the code.
Here is their code that uses capactive sensing:
#include <CapacitiveSensor.h>
#include "pitches.h"

#define COMMON_PIN      2    // The common 'send' pin for all keys
#define BUZZER_PIN      A4   // The output pin for the piezo buzzer
#define NUM_OF_SAMPLES  10   // Higher number whens more delay but more consistent readings
#define CAP_THRESHOLD   150  // Capactive reading that triggers a note (adjust to fit your needs)
#define NUM_OF_KEYS     8    // Number of keys that are on the keyboard

// This macro creates a capacitance "key" sensor object for each key on the piano keyboard:
#define CS(Y) CapacitiveSensor(2, Y)

// Each key corresponds to a note, which are defined here. Uncomment the scale that you want to use:
int notes[]={NOTE_C4,NOTE_D4,NOTE_E4,NOTE_F4,NOTE_G4,NOTE_A4,NOTE_B4,NOTE_C5}; // C-Major scale

// Defines the pins that the keys are connected to:
CapacitiveSensor keys[] = {CS(3), CS(4), CS(5), CS(6), CS(7), CS(8), CS(9), CS(10)};

void setup() {
  // Turn off autocalibrate on all channels:
  for(int i=0; i<8; ++i) {
    keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF);
  }
  // Set the buzzer as an output:
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  // Loop through each key:
  for (int i = 0; i < 8; ++i) {
    // If the capacitance reading is greater than the threshold, play a note:
    if(keys[i].capacitiveSensor(NUM_OF_SAMPLES) > CAP_THRESHOLD) {
      tone(BUZZER_PIN, notes[i]); // Plays the note corresponding to the key pressed
    }
  }
}

Connect your fifth wire to ground. Set the four inputs to INPUT_PULLUP. The four inputs will default HIGH, and be pulled LOW when connected to the ground wire.

Inversely, you can also set the inputs to INPUT_PULLDOWN and have the fifth wire connected to +5v, which will pull the pin HIGH when connected, and LOW when not.

Assuming you're not using a AVR of course, since those only have pullups.

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


text:
USB D+ D- to Arduino Mega RX TX
Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?

Actually it is possible with some passive components to get close enough to the USB spec to usually be able to bit-bang the lowest speed version in software.  I believe on the ATmega328 you can do this with fairly arbitrary GPIOs, presumably you can on a mega as well.

Despite the answer to the contrary it IS possible to access USB directly from digital I/O pins. As TX & RX are also standard digtal I/O pins they could be used for this purpose BUT you need dedicated bootloader code to do this and it has inferior performance if a USB to serial converter is available. The eg ADAFruit Arduino Trinket uses this system.

No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.

Thanks. I knew it but I was thinking may be arduino mega has an option to go through the 2560 UART. I thought it would be the serial port 0 as it is the port for PC serial monitor.

The Arduino Leonardo has a ATMega32u4 witch also supports USB directly. An entire board might be easier than just a raw chip.

Well, I have few couple of Arduino Mega, so, I don't really need to have a Leonardo I think. :)


text:
Unusual LCD behaviour
Can someone please tell me what's going on with my LCD screen and how I can fix this issues below?
I have the following:

Arduino Uno R3 w/ ATMEGA 328P-PU
16x2 LCD
TowerPro MicroServo SG90
DPDT Slide Switch w/ 120 ohm resistor

Objective:
Read the sensor value (If switch is on or off), and move a servo accordingly while displaying switch state on LCD.
Issue:
LCD display seems to receive random data during program run (see image). All starts up well, and as soon as a few seconds have lapsed in the void loop(), the screen becomes garbled. Also, the switch value (while debugging) gets a zero reading while HIGH, acting accordingly as if the switch was off. The servo motor runs as it should, but gets random pulses every now and again where it starts to buzz, but doesn't turn.
Images:
Three images below.

Schematic:

Coding:
#include <LiquidCrystal.h>
#include <Servo.h>

const int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
int oldPos = 0;
int pos = 0;
int oldStat = 0;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo servo;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.setCursor (0, 0);
  lcd.print("Starting up FSS!");
  delay(700);
  lcd.clear();
  lcd.print("Init SERVO...");
  delay(500);
  servo.attach(9);
  lcd.clear();
  lcd.print("SERVO Success!");
  delay(400);
  lcd.clear();
  lcd.print("Testing SERVO...");
  servo.write(0);
  delay(200);
  servo.write(90);
  delay(200);
  servo.write(45);
  delay(300);
  lcd.clear();
  lcd.print("SERVO Running!");
  lcd.clear();
  lcd.print("Select AUX Source");
  pinMode(ledPin, OUTPUT);
}

void loop() {
  lcd.clear();
  lcd.setCursor (0, 0);
  lcd.print("Select AUX Src");
  lcd.setCursor(0, 1);

  sensorValue = analogRead(sensorPin);
  Serial.print("Sensor: ");
  Serial.println(sensorValue);

  if(sensorValue == 0){
    //if(sensorValue = oldStat){
      oldStat = sensorValue;
      digitalWrite(ledPin, LOW);
      lcd.print("Switch is OFF");
      pos = 45;

      Serial.println("Switch is OFF");
    //}
  } else{
    digitalWrite(ledPin, HIGH);
    lcd.print("Switch is ON");
    pos = 120;
    Serial.println("Switch is ON");
  }

  if (pos != oldPos){
    servo.write(pos);
  }

  oldPos = pos;

  delay (700);
}

Insufficient decoupling. Put a 100nF cap on the supply lines at the LCD and a 100uF cap on the supply lines at the servo.

I'll need to get the 100nF and then I'll install that. I'm also going to build a voltage supply apart from the base. If the decoupling works, I'll mark as answer. Thanks!

Get a dozen or so. They're one of the most common to use.

Electronics is not my strong suit (obviously) so what's happening here? The arduino is behaving correctly (and probably reading the value correct) but it just can't display it because of noise from the servo affecting the transmission to the LCD? So a Serial.println would print the correct value or not?

@Madivad: The servo has caused the power to the panel to go pear-shaped, so you can't even know if the electronics in it are in any shape to be sent any commands or data.


text:
Controll LED Strip with Arduino BLE
I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with this Arduino (its not an Uno). I have setup every thing correctly according to this instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.
What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.

Is this the article you mention ? It does say to connect directly only for 1 or 2 LEDs and you are right : typical limit is 40mA per Arduino output pin. And it won't work directly if you have common anodes like in the schematic.

Addressing individual LEDS on a simple strip with LEDs in series and/or parallel connection is just not possible.
Connecting the strip directly to an output pin is completely nonsense. Forget it.
You need a strip with digital LED controllers populated, as described (for instance) in another link mentioned in your second link: http://www.adafruit.com/products/306
Have a look at this, then I'm sure you will come back with more detailed questions ;-)

Nice ! Have you tried this type of LED strip, I'm very curious about it ?

@FredP: I didn't try. But I found a really awesome project with a similar type. Have a look at this: https://www.pjrc.com/teensy/td_libs_OctoWS2811.html


text:
RS-485 with Arduino
I have two Arduinos on a RS-485 line, one acting as a Master and the other as a Slave.  The Master simply transmits information to the Slave, which parses it.
They work fine when the Master is turned on first and then the Slave is turned on.  However, I'd like to  make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).
Here's the code from the Slave's loop
  void loop()
     {

       if (RS485Serial.available() >0 )  //Look for data from other Arduino
       {
        char byteSend = RS485Serial.read();    // Read received byte
        String str = String(byteSend);
         if (str == "<")  {      //  beginning of the transmission
       // does stuff here
      }
   }

}
Here is the relevant section of Master's loop:
  output_value ="<1,1,1,1,1,1,1>";
 RS485Serial.print(output_value);
 delay(250);
 RS485Serial.flush();

Any advice is appreciated...

What is the problem ? Have you already tested without success?

@bluefeet - this is not an Arduino question.  It is a protocol question which happens to be implemented on Arduinos, but what is important is the protocol, not the platform, and dumping it to the Arduino site merely disconnects it from other similar issues that don't happen to use that platform.

@ChrisStratton: I agree, but I wish you would say which site you think is better for protocol questions like this one.

    char byteSend = RS485Serial.read();    // Read received byte
    String str = String(byteSend);
     if (str == "<")  {      //  beginning of the transmission
   // does stuff here
  }

This is an extremely inefficient way of testing for one character. Much better would be:
    char byteSend = RS485Serial.read();    // Read received byte
    if (byteSend == '<')  {      //  beginning of the transmission
   // does stuff here
  }

However, I'd like to make it so that the Slave can be disconnected and reconnected to the line and re-discover the connection (ideally without resetting either Arduino).

I know I'm not supposed to ask questions here, but what is stopping you?


text:
Connecting a Long Stem Thermometer to an Arduino to automate the recording of temperature in an experiment
Is there a way to connect and read the output of a long stem thermometer like this one to an Arduino?

That won't be easy. You'll have to break one open, and see what's inside. Maybe a thermistor, which you could connect to an arduino analog pin, but you'd have to manually calibrate it.

I actually found one here: https://blog.safaribooksonline.com/2013/07/25/an-arduino-powered-bbq-thermometer/ do you think I can do these? I am not really in to electronics just need this for my biorector for thesis.

If that unit also contains a thermistor, you can indeed follow that guide. But you'd have to open it first to find out.

Interfacing with a temperature sensor such as the DS18B20 (https://www.sparkfun.com/products/11050) would be much simpler than trying to interface with a thermometer with unknown internals.
Theoretically, yes, you can use the thermometer you posted, but it won't be simple. The only way to know what you would have to do to interface with it is to open it up and see what's inside. You would still have to calibrate it though to make any sense of the readings you get from it.


text:
Where can I find beginner resources on using voltage regulators with Arduino circuits?
I'm trying to concurrently learn electronics and Arduino, and have recently moved from simply powering LEDs to servos. In all my attempts with servos and reading about them (especially multiple ones, and when using external power supply plugged into the board), experienced users often mention you use voltage regulators.
I've seen some Arduino schematics with servos and voltage regulators, most that include some capacitors, but I can't seem to find any tutorials or resources that explain why, when and how to use these parts when learning electronics & Arduino. (I'd like to go from there to transistors, mosfets, etc.)

Try reading the datasheet of the regulator you want to use. Most supply a sample circuit with recommended capacitor values. Datasheets can be scary, but you don't need to understand everything. Come time, you'll begin to know the meaning of more and more values inside any datasheet. At least, this is what happened (and is still happening) to me.

My understanding is that the capacitors smooth the signals. This helps the internal workings of the regulator not overshoot when compensating for a change in the input or the output. If the capacitors are not there then there is a chance of oscillation.
A search of google for Voltage Regulator Tutorial will give you quite a few results, here is one that I found (obviously this could change so if it does just do a search and go from there)
regulator basics
The link above is a good explanation that is not too in depth. But as stated in the comments look at the datasheet for specific values needed.
I also did a search for 'what are the capacitors for on a voltage regulator' and found some good info about why they are needed.

You are missing a link or something in your answer. When you update it, please include some valuable information in your answer instead of just linking to another website.

@sachleen, sorry it is not up to your standards but Gregir has asked for links to good tutorials I have supplied him with one. If you click on the words 'regulator basics' you will find the info requested (I hope).

It's not @sachleen's standards, it's common sense. Links change or pages disappear. So a future visitor may not get the information. Including some useful information or excerpts from the link(s) you supply means your post continues to be useful regardless of what happens to external resources. See http://meta.stackexchange.com/questions/72000/should-there-be-a-policy-about-one-link-only-answers and http://stackoverflow.com/help/how-to-answer

Good search suggestions here. Not sure why my Google efforts were so fruitless, but I'm starting to find more info now. Thanks.

In order to get a smooth signal to your power regulator you should use some capacitors before and after the voltage regulator. It will look something like this when you use the 7805 voltage regulator.

Note: This schematic is from a dutch website. Uin means Vin and Uuit means Vout. C2 and C3 are bipolar capacitors.
It's also smart to put a diode before the voltage regulator to make sure the voltage flows only to one direction. The values of C1, C2, C3 and C4 and pretty standard and coul be used for the other Voltage regulators as well.
The voltage Regulators come in different fixed values and tey have a minimum and maximum voltage they can handle. Here's a small table of the most common VR's with their minimum input voltages.
Part Number     Output Voltage (V)      Minimum Input Voltage (V)
7805            +5                      7.3
7806            +6                      8.3
7808            +8                      10.5
7809            +9                      11.5
7810            +10                     12.5
7812            +12                     14.6
7815            +15                     17.7
7818            +18                     21.0
7824            +24                     27.1

Also note that the output currents of these Voltage Regulators listed above is max 1A. When they're called like 78S05 or 78S09 it'll be a 2A Voltage Regulator.
Another thing that could be important when you're using the minimum input voltages. If you put a diode before the Voltage Regulator there will be a small voltage drop. For a 1N4007 the voltage drop will be around the 0.5V. The voltage drop will only occur before the voltage regulator though, so when you don't use the minimal input values you don't have to mind about it.

Thanks. Calling out the diode and minimum input voltage stuff is helpful. I missed/glossed over that stuff before.


text:
Basics with DHT11
I just bought the sensor DHT11 and trying to test it with the library code provided by the IDE, but I always get the same error on .read() . Code -2
/*####################################################################
FILE: dht11_functions.pde - DHT11 Usage Demo.
VERSION: 2S0A

PURPOSE: Measure and return temperature & Humidity. Additionally provides conversions.

LICENSE: GPL v3 (http://www.gnu.org/licenses/gpl.html)
GET UPDATES: https://www.virtuabotix.com/

  --##--##--##--##--##--##--##--##--##--##--
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ## DHT11 SENSOR ##  ##  ##  ##
  ##  ##  ##  ##  ##FRONT ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  | ##  ##  ##  ##  ##  ##  ##  ##  ##  ## |
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##
  --##--##--##--##--##--##--##--##--##--##--
      ||       ||          || (Not    ||
      ||       ||          || Used)   ||
    VDD(5V)   Readout(I/O)          Ground

HISTORY:
Joseph Dattilo (Virtuabotix LLC) - Version 2S0A (27 May 12)
-Rewritten to with more powerful Versalino functionality
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.5 (11/11/11)
-Made Library Arduino 1.0 Compatible
Joseph Dattilo (Virtuabotix LLC) - Version 0.4.0 (06/11/11)
-Fixed bugs (squish)
Mod by Rob Tillaart - Version 0.3 (28/03/2011)
Mod by SimKard - Version 0.2 (24/11/2010)
George Hadjikyriacou - Original version (??)
#######################################################################*/

#include <dht11.h>

dht11 DHT11;

void setup()
{
    DHT11.attach(2);
    Serial.begin(9600);
    Serial.println("DHT11 TEST PROGRAM ");
    Serial.print("LIBRARY VERSION: ");
    Serial.println(DHT11LIB_VERSION);
}

void loop()
{
    Serial.println("\n");

    int chk = DHT11.read();

    Serial.print("Read sensor: ");
    switch (chk)
    {
        case 0: Serial.println("OK"); break;
        case -1: Serial.println("Checksum error"); break;
        case -2: Serial.println("Time out error"); break;
        default: Serial.println("Unknown error"); break;
    }

    Serial.print("Humidity (%): ");
    Serial.println((float)DHT11.humidity, DEC);

    Serial.print("Temperature (°C): ");
    Serial.println((float)DHT11.temperature, DEC);

    Serial.print("Temperature (°F): ");
    Serial.println(DHT11.fahrenheit(), DEC);

    Serial.print("Temperature (°K): ");
    Serial.println(DHT11.kelvin(), DEC);

    Serial.print("Dew Point (°C): ");
    Serial.println(DHT11.dewPoint(), DEC);

    Serial.print("Dew PointFast (°C): ");
    Serial.println(DHT11.dewPointFast(), DEC);

    delay(2000);
}

And this is my ouput:
DHT11 TEST PROGRAM
LIBRARY VERSION: 2S0A

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

Read sensor: Time out error
Humidity (%): 0.0000000000
Temperature (Â°C): 0.0000000000
Temperature (Â°F): 32.0000000000
Temperature (Â°K): 273.1499938964
Dew Point (Â°C): nan
Dew PointFast (Â°C): nan

The wiring:
-left pin: 5v
-right pin: gnd
-middle pin: 5v - digital2 - through 10kO resistor

UPDATED:
I found a library that works. I also changed the wiring because I found out the sainsmart dht11 switches the pins:
-left: signal with 10kO and to 5v
-middle: 5v
-right: GND
Now just a question.
What is the difference between these two dht11 sensors.
Dht11 basic
dht11 with board
The one from sainsmart has a piece of circuit I don't know what it is.(I have a lack on electronics I try to fix step by step...)
It is a resitor, capacitor? it says 103.
How does this affect to the wiring?

In the code you linked, it says that you are reading pin 2 for input, but on your image, your wire is in pin 3.

Hi, thanks for the answer. You are right. It was a problem in the wiring. After fixing it I was still getting errors. The problem was the library version, that was giving some problems with read response for dht11 sensors

The DHT11 sensor is available as-is and integrated on a break-out board. The break-out board shows following differences:

the order of PINs is changed, e.g. in one version: 1 -> signal, 2 -> +, 3 -> GND (left-to-right, pins down, looking at the front)
the unused pin is not connected
the board already has a 10 KOhm pull-up resistor connected

Thus, when you have a DHT11 on a break-out board you have to adjust schematics that use it as-is - e.g. in this example you have to remove the external pull-up resistor and connect the pins in the correct order.
Be aware that there may be different versions of DHT11 breakout boards available - i.e. ones where the order of pins is different. You can look out for PIN markings like S (-> signal) and - (-> GND). Also, you can look at both sides of the breakout board to trace the connections.
The resistor usually comes as SMD on such a board - and if it has a marking it uses a special code. For example, 103 means 10 * 10^3 Ohm, i.e. 10 KOhm.
The adafruit DHT library comes with an example sketch that prints the sensor values over serial.

It seems you wiring is ok, although I think you already have pull-up resistor on breakout board (look for a small 103 resistor).
Maybe you can try another library for DHT?
I have used one made by adafruit (https://github.com/adafruit/DHT-sensor-library) and everything worked just fine.
Regards,
Ian

Thank you for the answer, but it didn't work. I tried with and without resistor(I saw the 103 in the dht11's board). Also tried with the adafruit library and then I get the "Failed to read from DHT sensor!" error. I debugged the example and readHumidity readTemperature get errors on reading. Maybe my sensor is broken. I ordered a new one to check...

The DHT11 board + sensor already has the resistor. I use those with arduino directly, no extra components required.


text:
Using PROGMEM to save RAM
I am successful putting and retrieving a char array into Arduino flash memory using PROGMEM char arrays.
I am building my application using header files with a class definition / implementation and would like to keep the strings in the same header file.
If I define another PROGMEM char array neither one can be executed. In other words, these PROGMEM are global arrays as far as the Arduino compiler is concerned. They compile, but they won't show up.
Here is my test code:
  lcd.clear();
  lcd.print(*strFlashDebug[0]);  // in CDebug
  lcd.setCursor(0,1);
  lcd.print(*strFlashTrack[0]);  // in CTrack

If I put both definitions in the same header file, it only works with only one lcd.print enabled, not commented out.
It appears that multiple PROGMEM arrays can be defined and compiled, but only one is actually usable. What is the explanation?

Please post your array definitions as well, or better even, a complete compilable example with just enough code to illustrate the issue.

The important thing to know for PROGMEM is that the AVR chip you’re using does not have a single flat address space. I.e., it does not use a von Neumann architecture; instead, it uses a specific version of what is known as a Harvard architecture: it has separate address spaces for RAM, program memory, and EEPROM. All of them start at 0. Which means that while dereferencing a null pointer is technically still undefined behavior in C++, it can be (and often is) perfectly valid in Arduino code.
The short version is: If you have a PROGMEM pointer, whatever function you pass it to must work on PROGMEM pointers. lcd.print does not, and as far as I can tell there isn't any way the function could possibly detect this is not a RAM pointer. You have to call a different function, assuming there is one in the first place.
See PROGMEM (Arduino reference) for examples on how to use PROGMEM data.

To add to this excellent description, you could, as a workaround, temporarily copy to RAM the PROGMEM data you need to pass to lcd.print() and pass it this copy. A wrapper function, say lcd_print_PMEM() could encapsulate the details, and the RAM used would literally only be allocated for the duration of that call.

A PROGMEM variable definition (i.e., declaration) allocates memory in FLASH. You need use an extern clause in the header file and a physical declaration in the C code which is linked in your code. It's pays also for potential static class properties.
Also check if lcd.print() accepts a PROGMEM array, i.e., if the overloaded procedure is defined and called.
Just note I recommend using much more effective string formatting via file streams (FILE) and fprintf_P().

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


text:
Debugging a RadioShack Arduino motor/sensor shield
I bought a cheap "Make" kit at RadioShack, which includes some sort of proprietary Arduino Uno compatible motor/sensor shield. Naturally, the documentation is pretty bad. The documentation and Arduino code for the kit is here:
https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit
It includes a circuit schematic (2770168-CorePCB_schematic.pdf), but I'm still having trouble mapping the pins to the Arduino's pins. Can anyone help me make sense of this?
What I've made out so far is the shield's screw terminals appear to be connected to quadruple h-bridges. However, there are several other pin headers that I can't quite make out. I think it also directly exposes 4 of the Uno's ADC pins and 4 DIO pins. There are four pins for dual IR line sensors, but there's a lot of circuitry between these and any Arduino pins. Almost everything feeds into a DC6688F2SCN chip, but I can't find a datasheet anywhere, so I have no idea what it does.
The manual says jumpers on J16 need to be removed in order to connect to the Uno over USB, so it looks like I can't use the shield with the board and debug via USB at the same time. Is this board worth investigating or should I trash it?

http://www.dragonchip.com/TechDoc/DC6688.htm

@IgnacioVazquez-Abrams, Yeah, I found that too. It contains no documentation...unless you count a Windows exe as "documentation". When did people stop publishing datasheets as PDFs? Either way, that doesn't help me on my Linux box...

That seems to be a PDF in an encrypted SFX zip, but I haven't actually tried running it yet.

The DC6688F2SCN is clearly a microcontroller, so what matters is not really its data sheet, but rather its custom firmware.  The schematic appears to show it connected to Arduino Digital Pins 3 and 4, so you'd need a software serial on those to exchange commands with it, once you figure out its baudrate and language.  In the version of the schematic provided, there doesn't seem to be any cross connection to digital pins 1 and 2, but if there were that would interfere with the USB-serial (while allowing use of the ATMega's hardware serial to talk to the DC6688F2SCN).

Probably your most productive course of action is to see if there is example code somewhere.  Failing that, you could also cut the traces to U6 & U7 and wire those (through resistors) to digital pins instead of the DC6688F2SCN (which you would basically ignore).

@ChrisStratton, Actually, my link should also include some sample code. You're right, it does appear to be a microcontroller connected to the arduino via serial, which accepts commands encoded as specific bytes. However, the code's not very well documented either, so reverse engineering the pinouts from the commands and port mappings is still a challenge.

Just out of curiosity, did you get this working? I am trying to hook it up directly to a Raspberry Pi, based on the source it's clearly communicating via pins 1 and 2 (RX/TX). I connected those pins via a voltage shifter to the RPi's TX/RX pins. With a sample script that just turns on the IR sensors and reads them, I'm getting an echo of the send commands, but otherwise no response. The source is so simple I'm running out of ideas on what could be wrong... Very interested if you had any success with it...

I'm voting to close this question as off-topic because link rot. The schematic linked by the OP doesn't longer exists and the question is now unsolvable.

I fixed the broken link, carry on.

There is a bit of info on the DC6688F2SCN here: Chip Selection Guide, but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.
If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.
That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the Bs can do a full Amp.
The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.

A google search for DC6688F2SC  returns spec sheet under Dragonchip (here). It's actually a rather nice chip when you look up the specs on it.

Unfortunately, this does not add much over the comments already made. Please see Ignacio's comment from last year. If you could expand your answer, then that would be great.

@Greenonline please see http://meta.stackexchange.com/questions/117251/what-should-be-done-with-questions-that-have-been-self-resolved-as-a-comment-ins. "Answer stealing" from a comment is considered okay on Stack Exchange

@AnnonomusPenguin -  Granted, but I was just trying to encourage thomas to expanded the answer somewhat, if at all possible. :-)

@Greenonline yes, the OP should expand the content of their post.


text:
Resistance in Switch (negative vs positive logic)

I tried in my Arduino the negative logic to get a digital input from a switch (with 10 KΩ resistance). If I want to use the positive logic what kind of resitance I have to use? For me seems that 10KOhm it to big and probably a smaller resistor should be used. How do we compute the value of the resistor? The schemes of Negative and Positive Logic from Valvano's notes/ebook - University of Texas gives 10 kΩ in both cases. Is it correct?

From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be HIGH or LOW depending on the logic you used to wire your switch.
The resistor must be present for 2 reasons:

to avoid producing a shortcut between +5V and GND when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)
to make the voltage pin attached to the pin the "winner" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin

The value of the resistor should  be:

high enough to limit the current between +5V and GND when the switch is closed, preventing damage and limiting overall power consumption of your circuit
not too high to allow providing a voltage level to the input pin

Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from +5V to GND, which is generally acceptable in terms of consumption and cwill not damage your power supply.
Note that the input pin is "high impedance" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).
Finally, it is good to know that Arduino MCU offers the INPUT_PULLUP mode for digital pins, where an internal resistor pulls up the pin input to 5V.  This enables you to directly connect your switch between the pin and GND. So you just have to code:
pinMode(XXX, INPUT_PULLUP);

instead of:
pinMode(XXX, INPUT);

For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.

thanks a lot . As I understood the INPUT_PULLUP is a ~50kΩ embedded resistance (in ATmega328P chip) that protects the digital input. For example if you connect directly the +4 Volt to a digital input the chip is already protected.. right?
So the 10 kΩ resistance is just a protection of the shortcut between +5V and GND.
Here stackexange - electronics Q says that digitalWrite(13, HIGH); Turns internal pull-up on and digitalWrite(13, LOW);  Turns internal pull-up off.

Maybe this way of turning internal pull-up on/off works but this is not the recommended way; the preferred (and official) way is just pinMode(13, INPUT_PULLUP);

INPUT_PULLUP requires 1.0.1 of the IDE.  The documentation states that prior to that release the digitalWrite HIGH/LOW mechansim was used.

Who's still using pre-1.0.1 of Arduino IDE? For those people, maybe it is time to upgrade.


text:
Why can't I connect more than one Arduino Uno + Ethernet Shield to my network?
I'm using 3 Arduino Uno boards with Ethernet shields. Each is connected to my home Internet switch with an Ethernet cable.  I assigned a different local IP address to each Arduino and gave each board a different MAC Address.
Each Uno is collecting temperature/humidity for a bedroom in my house.  The data is sent to a MySQL Database using PHP/HTML.
They work fine for a while (5 minutes) and then they conflict each other.  If I use one Arduino at a time it works fine, but I can't get them to work together.
Any idea how to solve the problem?

Did you set the MAC address from the Shield? Or set it to an unique MAC address?

Where is the conflict? On the network? In your router? In the Database?

post the ethernet set-up code. And perhaps an Admin should migrate this to the Arduino stack exchange

How do you know where the conflict is? Are you assigning IP address in the DHCP range? If so, it might be conflicting with other devices on your network.

Well I create 3 sketches and put different IP Addresses to each one 192.168.0.177; 192.168.0.178 and 192.168.0.179. They work fine for a while without conflicts but after lets say 5 minutes the website become unavailable and it timed out. Its hard to explain and frustrating.

One Arduino has the MAC address printed in the sticker and the rest of the Arduinos I set it manually (different MAC address of course)...

It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?
Some things to try:

Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.
Run the command arp -a (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.
Try to ping the Arudinos. Do they respond?
Use WireShark or tcpdump to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).
Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with tcpdump).


text:
How do i wire a switch to control Leds on a arduino nano
I am wiring some LED's with buttons to trigger them but i don't know if i have the wiring right?

Code
    /* switch
 *
 * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 * a minimum delay between toggles to debounce the circuit (i.e. to ignore
 * noise).
 *
 * David A. Mellis
 * 21 November 2006
 */

int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
}

void loop()
{
  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else
      state = HIGH;

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}

note
  The code is not set to the pins yet.

Its not working or what? The schematic looks right. Only you have 2 inputs and 2 outputs. And in code you define wrong pins

@Martynas So i have the wiring right?

Yes. Only thing. Don't use voltage from batteries 4x1.5=6 for input. Feed arduino from batteries, and use 5V output to feed buttons

@So you mean plug the battery to Ground and Vin then run the 5 volt rail to the breadboard?

Correct. Thats in case :) It should work in this way, but there is always but :)

@Martynas Like that

@Martynas Also how do i do it with a 2 pin switch??

sorry, did't understood. What do you mean 2 pin switch? you mean http://cmuems.com/2011/b/wp-content/uploads/2011/10/button_sch.png

Let us continue this discussion in chat.

The wiring is correct, but inPin in your code is set to 2, which is D4 on the Nano, while you have your signal wires going to D7 and D6 in your schematic.
Similarly, outPin is set to 13 in your code, which is D9 on the Nano, but your schematic shows the LEDs connected to D5 and D4.
I would also put the resistor going from the other pin on the switch to 5V, having the digital input connected directly to GND, but I'm not sure if that will affect power consumption, so it's probably more just a matter of personal preference.


text:
Controlling bigger motors with an arduino board
i am german and my english is not the best, anyway i hope you will understand my problem.
At the moment i construct a little car with some friends. We have still completed the frame and now we think about controlling it in a electronic way. For example with a controller of a playstation or with our smartphones, however, it should be electronic, so i think about to do this with an arduino board.
We have two motors. One for the direction and the other one for the movement.
The first has about 8 ampere and about 12 volt, the other has 800 watt, so around 40 ampere and 24 volt.
My question is, whether it is possible and if so how to control them (or one them) with an arduino board and what do i need in addition?
It would be great if you could help us :)

How much money do you have and how much are you ready to invest? It is totally possible.

Until 600 euro it is okay

Nice :)) In this case if yo do not have much experience in electronics i would suggest to buy ready to use DC motor controller. Like this http://www.pololu.com/product/1383 and control it with android

okay, thank you, i will try :)
if there are questions, could i ask you?

Sure why not. There will be about communication between arduino and android or any other device

DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power.  See this link for info on basic microcontroller DC motor control.  If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor.  Some applications could use this.  However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power.  Such FETS such as these could be used to properly control such a motor using the microcontroller.  Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch.  Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.

One of the best ways to controll a motor is to look in to the motor shields from the arduino. You can buy seperate motor controllers with different throughput, some advanced with breaking and some without.
But motorshield is about the best way to get started.


text:
How do functions outside of void loop work?
I am used to Arduino sketches with a void setup() part that runs once, and a void loop() part that keeps looping. What happens when you have void functions outside of the main void loop()? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?
For example in the code below, when will the void receiveData(int byteCount) and the void sendData() functions run?
//I2C_test

//This code demonstrates communication via an I2C bus between a raspberry pi and an arduino.
//When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this
//data to control a motor. After the Arduino has recieved data from the master, it then collects
//data from the external environment via a sensor and sends this data back to the Raspberry pi.

#include <Wire.h>
int number = 0; //Declare variables
int val = 0;

void setup() {
  //Anything between the curly brackets runs once when the arduino is turned on or reset
  pinMode(0, INPUT);
  //Set pin 0 as input and 3 as output
  pinMode(3, OUTPUT);
  Serial.begin(9600);
  //Set the data rate for serial transmission at 9600bps
  Wire.begin(0x04);
  //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address
  Wire.onReceive(receiveData);
  //Define callbacks for i2c communication
  Wire.onRequest(sendData);
}

void loop() {
  //The code between the curly brackets keeps repeating
  delay(100);
}

void receiveData(int byteCount) {
  while(Wire.available()) {
    number = Wire.read();
    //Set the variable "number" to the data sent by the master
    analogWrite(3, number);
    //Write this number to pin 3 (PWM). This controls the motor speed
  }
  val = analogRead(0);
  //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023
}

void sendData() {
  Wire.write(val);
  //Send the data read from the sensor to the master.
}

This looks interesting. I wonder if you could post links to the source of the code (and details of connections between Arduino and Pi).

@Milliways I used this* tutorial to write the code on the arduino uno and Raspberry pi (B+ model), however I made a few small changes.Connect the SDA and SCL pins of the two boards, as well as the ground pins if they are connected to different power supplies. I then had pin 3 connected to a sensor configured in a potential divider configuration, connected between the +5V and Gnd pins. Pin 0 and Gnd is connected to a motor drive board.

The setup() and loop() functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.
Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within setup() or loop()), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)
For example, pinMode() is a function just like any other. It only runs when you actually put something like pinMode(3, INPUT) in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).
The example code you've posted is quite interesting. Look at these lines in setup():
Wire.onReceive(receiveData);
Wire.onRequest(sendData);

These lines are telling the Wire object to call receiveData() and sendData() in response to I2C events. It does this by passing function pointers which are stored and used by Wire.
I'd recommend searching for information about C/C++ function pointers online if you want to learn more about this. You may also be interested to explore Arduino's attachInterrupt() function.

Thanks for your answer. This is starting to make more sense now. However, if the receiveData() and sendData() functions are not run unless they are called, then why are they called within the void setup() function and not the main void loop() function? Surely these functions will never be called unless the rare chance that there is an i2c event while the instruction pointer is still within the void setup function? Would it not be better to call these functions from within the void loop function so whenever there is an i2c event, the function is called?

@Blue7 These functions are not called in void setup(), they are passed as the parameter of onReceive and onRequest, they're callbacks as the comment states. In very short summary : this tells the (code from the) Wire library to call these functions when specific things happen (http://arduino.cc/en/Reference/WireOnReceive, http://arduino.cc/en/Reference/WireOnRequest ...)

@FredP Ah okay. Thanks for the links, I'll check them out when I'm not on my phone. I have a quick question in the meantime though, if you don't mind. Are these callbacks always ready and waiting for an i2c event? i.e, no matter where the instruction pointer is, these callbacks will instantly call the function as soon as an i2c event happens?

@Blue7 It will presumably be using interrupts to monitor I2C activity. When an interrupt executes, it takes control away from the main program temporarily.

@Blue7 The callbacks are not waiting (Arduino is not multithreaded), as @PeterRBloomfield says, the Wire library enables I2C interrupt through twi_init() when you call Wire.begin. When there is I2C activity the µC stops doing its current task (unless ... nevermind for the moment :-) and goes in the code of Wire library, that then calls the (appropriate, depending on what is happening) function you registered as callback (receiveData for example). A callback is the generic name for functions like receiveData or sendData, they're called by an interrupt handler inside Wire.

Is it not that case that setup() is called once and loop() is called repeatedly?
i.e. that there is an unseen main() which might look like this:
void main(){
  setup();
  while(True){
    loop();
  }
}

Apologies as I'm just looking into the Arduino and have almost no C/C++ experience; I'm trying to get a handle on this loop() situation myself.

Basically, yes. There is also a call to init() which gets the timers going for millis, delay etc. So init() is for general initialization, setup() is for your initialization, and loop is for, well, looping. You can write your own main if you want to take full control.

Nice post. BTW ; is not required after the penultimate } :-)

There is also call of serial_event() is it not?

I can't comment on Dee's response. The actual code that is executed in the main loop is here:
    int main(void) {
    init();
    initVariant();

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

And yes, setup() gets called once and loop() is being called repeatedly (together with some serial stuff).

It works as normal function, it must be called to make sense. loop()/setup() are called from a main() function which is compiled from Arduino directory and linked in. receiveData/sendData are to called from your program which root is in loop/setup functions.


text:
Extract arduino collected data periodically
I'd like to extract data collected by a battery powered arduino for example once a day without stopping it and not using SD card.
It's posible, when I want to extract the collected data, to connect a laptop through the USB and then get data because Arduino is, at regulat time intervals, calling 'Serial.println(...)'?

What do you need help with exactly?

Please be aware thqt most Arduino models will reboot when you plug a cable to the USB port and have your PC open communication. This may not be what you want as all data stored in SRAM will be lost.

Would you consider having a second arduino to collect the data wirelessly? This second. Arduino could be connected to a computer collecting the data. Asking since I'm not sure if the solution absolutely can only include a single arduino.

This is a bit crude, but I think you could use an FTDI cable (which is a USB to UART converter) to have a program in your laptop talk to the Arduino using its UART (serial) interface.
To do it, you could plug the USB side of a FTDI serial cable to your laptop. The other end of the cable has a plug with 6 pins, 2 of which are the TX and RX serial signals. You could plug those two signals to pins D0 and D1 (RX & TX) of your Arduino using male-to-male jumpers.
In terms of software, you could code the Arduino sketch to listen on the serial port for a command from your laptop. When the command arrives, it would output the stored data (could be comma separated values with CR+LF as end of line). Your laptop would then listen for the answer and retrieve the data.

Yes, you can do it. Depends how much data to have enough storage space. You also need consider potential memory endurance. E.g. external I2C ferromagnetic memory is good option. Of course it's not on Arduino board, you implement extension.


text:
Is my Arduino UNO fried?
The title sums it all up. While testing  the new proximity detector I bought off of Amazon, a spark flew from some random area and my Arduino's On LED went off while its Loop LED stayed in a dim state. I am here to ask you guys if this basically counts my Arduino as fried and that I need a new one, or if I should wait and see if it works again, being that I wrote this 5 minutes after the thing happened.
Thanks in advance,
afroraydude

It's hard to tell without further testing. Do the following:

Remove the Uno from the faulty circuit, making sure you remove all the wiring from the Arduino board.
Plug the Uno into the USB port. Does the ON LED light up? Does the built-in LED on D13 blink three times? (this should happen if you had the optiboot bootloader)
Remove the USB cable and plug the Uno to a 9V source through the barrel power connector. Do the same test above.
Can you upload the Blink sketch? If you can, does it make D13 LED blink once a second?

Report your findings by updating your question.

I did the unplugging and stuff, the ON LED is dim now, and the LED on D13 does not blink 3 times, it just stays on but is dim. I cannot upload the Blink Sketch, the computer does not get the Arduino on the COM port.

That's really bad... I think that this is enough evidence that it's fried. Can you check with a digital multimeter what's the voltage on Vin, +5V and 3V3 pins?

The microprocessor also gets warm, forgot to mention that.

Definitely fried. Post your circuit so we can tell you what went wrong.

i cannot due to the stuff i used, external stuff, i have realized that i shorted it

Don' get all fustrated now. It might be just the chip, the arduino chip is fairly cheap, and can be removed by lightly wiggle a screwdriver below it, buy one like $5 and replace it and burn a new bootloader on it.


text:
How to send RPM data as analog input from arduino to Xbee
I am new to arduino and Xbee these stuff.
Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.
It seems XBee analog input read a range of 0 volts to 1.2 volts.
However, not quite sure how to implement and write the corret code.
Following are Arduino code and schematic circuit.
Any idea?
I really appreciate your help.
int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
   Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
}

void loop()
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

analogWrite(pin_out,(int)rpm);

Serial.print("RPM=\t");

Serial.print(rpm);

Serial.print("\t rps= \t");

Serial.print(rps);

Serial.print("\t dt=\t");

Serial.println(val);

}

analogWrite() generates PWM output (oh, PS : except on Mega, but certainly not on Uno), not a purely analog output. And, though I'm not yet familiar with Xbee, I'm not sure you'll achieve analog transmission with it. You could try using some form of DAC, but as suggested below it would be better to send info in digital form.

I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use float and then convert it to int, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.
Here is my code:
#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
  Serial.println("I am ready to send some RPM!");

  // set the data rate for the SoftwareSerial port
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

/*Print RPM every second*/
If(millis()-time>1000){
  Serial.print("RPM=\t");
  Serial.print(rpm);
  Serial.print("\t rps= \t");
  Serial.print(rps);
  Serial.print("\t dt=\t");
  Serial.println(val);
  time = millis();
 }
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}

Thank you for suggestion Martyans. You mentioned On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx but in Arduino uno isn't pin 1 for Tx and 0 for Rx. Please excuse me if I am wrong. and one more thing I just want to send rpm from arduino to xbee and then xbee send rpm  wirelessly to another xbee. Is it necessary to use Rx in Arduino?

Arduino uno has one Hardware Rx,Tx. I use it to communicate with PC(SerialMonitor). Programically i make pins 9,8 Rx,Tx two have second serial communication. Thats why i need library #include <SoftwareSerial.h>

And about sending data. All the information is stored in byte shape, so it is easier to give Xbee byte and send to another Xbee. In your case, you give arduino "analog value". How he knows what value it is? How he can messure it correctly? There are to many risks to loose data and it is inaccurate.

I got error message --> invalid operands of types 'float' and 'int' to binary operator for  floatToByte[i] = (rpm >> 8*i);   //Float to Byte

I got these   arduino_to_xbee_serial.ino: In function 'void loop()':
arduino_to_xbee_serial:45: error: invalid operands of types 'float' and 'int' to binary 'operator>>'
arduino_to_xbee_serial:57: error: 'If' was not declared in this scope
arduino_to_xbee_serial:57: error: expected `;' before '{' token

reduced to this arduino_to_xbee_serial.ino: In function 'void loop()':
arduino_to_xbee_serial:45: error: invalid operands of types 'float' and 'int' to binary 'operator>>'

Yes, zalt. I was in a hurry, see updated answer.

It worked. Now, how I can see the received serial data on X-ctu? I mean how should I set the parameters on X-ctu in order to see received serial data?

I realized now, still I can not receive data.

Hello zalt. To get data on Xctu you have to connect xbee to pc. If you use other arduino to receive data, then you can use Serial.print. Could you try to start from zero. Step 1: Test communication, send something from one arduino and read same on other, then proceed next steps. Next steps: calculate RPM; next: Send calculated RPM; Last: Confirm received data is correct


text:
Pattern library for addressable LED strips
Is there any central place that we can get drawing pattern functions for the addressable LED strips like the once based on the WS2812B component?  These are sold on the Adafruit site under the NeoPixel name.  For example I know of a few pattern examples like the Larson Scanner (Cylon), a candle light flicker or a rainbow pattern.  However I could not find a single pattern repository.
I am working on a project for kids learning to program the Arduino and it would be nice to have all the patterns in a single place and to be able to switch between the program examples with a mode switch.
If people send me links I am happy to post a blog of them.

I have never found a single pattern repository, however FunkBoxing has a fantastic sketch with 30 or so patterns well documented. http://funkboxing.com/wordpress/?p=2154
He uses the Fast_SPI (now FastLED) library, which is truly exceptional!
https://plus.google.com/u/0/communities/109127054924227823508

Thake a look at this library.
In this video you can see some of the many animations available.

I like the names you have given each pattern - Sparkle, Bubble etc.


text:
How to reset Arduino from software
As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.
I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?
I use C# to communicate with serial.

OK, I have solved this by sending DSR pulse as seen on code below:
mySerial.DtrEnable = true;
mySerial.Open();
Thread.Sleep(1000);
mySerial.DtrEnable = false;

FYI: The Leonardo's reset is triggered when the Leonardo's virtual (CDC) serial / COM port is opened at 1200 baud and then closed


text:
error: ‘sleep’ was not declared in this scope
I am trying to use the sleep function in lieu of delay(), but when I include sleep(), I get Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope
I read some place, about #include <avr/sleep.h> but that is a fail.
#include <avr/sleep.h>
void setup() {
}

void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  sleep(1);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  sleep(1000);              // wait for a second
}

I was able to locate sleep.h:
$ locate sleep.h | grep avr
/usr/lib/avr/include/avr/sleep.h

So then I started reading avr/sleep.h, and it seems like I'm doing it right, according to the examples. So, why might this be failing?

formating baffles me in these site please help!

"I am trying to use the sleep function in leu of delay()" Why?

delay halts all  other processes, I need to not do that. sample code is sample.

There are no "all other processes", there is only the rest of the code.

"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.
AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).
If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.
Also, vanilla arduino should be using its own packaged avr lib, for example:
arduino/hardware/tools/avr/avr/include/avr/sleep.h

instead of the one located in your usr/lib directory.

The Arduino IDE as packaged by a distro will more than likely use the distro's AVR Libc, of course.


text:
ctc mode on atmega 328
I'm trying to use CTC mode on Arduino 1 but I have the following problem.
I need to generate an interrupt on threshold B and A and I have set the prescaler to 1 since I want to generate interrupt A at 15999 (correspond to 1ms) and interupt B at 15( ie a number small enough from the start of counting).
I'have write a println function in ISR(A and B) to proof the calling of the latter but the program does not print all the characters in the println function and furthermore the counter does not reset at treshold A but stop his work.
How I can resolve the problem?
Here is the program I wrote:
void setup() {
    TCCR1A = 0x00;                // No outputs on compare math, no PWM mode
    TCCR1B = 1 | (1 << WGM12);    // Enable CTC mode up to OCR1A and prescaler /1 -> Start
    //TCCR1B = 0b00001001;
    TCCR1C = 0x00;                // Nothing to set into C register

    OCR1A = 15999;                // Set Threshold A
    OCR1B = 15;                // Set Threshold B
    TCNT1 = 0;                    // Clear Counter

    TIFR1 = (1 << OCIE1A) | (1 << OCIE1B);    // Clear Interrupt flag Match A and B

    TIMSK1 = (1 << OCIE1A) | (1 << OCIE1B);   // Enable Interrapt flag Match A and B

    analogRead(A0);            // Dummy Read to make Arduino setting the AD
    ADCSRA |= (1 << ADIE);     // Enable AD Interrupt on conversion completed
    ADCSRB = 5;                // Select Timer 1 Match B as trigger
    ADCSRA |= 1 << ADATE;      // Enable Auto trigger

    Serial.begin(115200);      // Initialize the USART
    Serial.println("Start");   // Write the welcome message

}

void loop() {
    // Nothing to do
}

ISR(ADC_vect)
{
    Serial.print(TCNT1);
    Serial.print(" - ADC Conversion Completed (");
    Serial.print(ADC);
    Serial.println(")");
}

ISR(TIMER1_COMPA_vect)
{
    TCNT1=0;
    Serial.print(TCNT1);
    Serial.println(" - Interrupt A");
}

ISR(TIMER1_COMPB_vect)
{
    Serial.print(TCNT1);
    Serial.println(" - Interrupt B");
}

In CTC mode TCNT1 is automatically set back to 0 when it reaches OCR1A. So there is no need to do that inside the ISR. In fact TCNT1 might have already increase in value by the time the ISR is called, so the interval would be slightly more that the 1ms you want.

I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port.  That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character.  As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.
Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.

Ok thanks, but why if I increment prescaler setting and threshold the program works?

If you're running the timer slower you're giving it more time between ISR calls to empty out the serial buffer.

serial in an ISR is still bad practice; However, the arduino Serial library detects if interrupts are disabled and will manually run the serial interrupt handlers when necessary so lock up never happens. printing will take a (relatively) long and inconsistent amount of time though.

@BrettAM: Interesting, thanks for the note. This seems to be the case since release 1.5.6 BETA. Interestingly, it appears that, although this behaviour was implemented in April 2013, almost a month before the 1.0.5 release, it didn't make it to 1.0.5, ant not even to 1.0.6, which came eight months after 1.5.6 BETA.


text:
Sending multiple channels with bluetooth
I have ordered my HC-05 BT modules.
My question is this:
Is it possible to send multiple channels over bluetooth. For example, stereo sound has two channels. I think i have seen people do this but i'm not sure.
If it is possible, could you please provide some more information on how its done?
Thanks!

The BT module will connect as a SPP (serial port) device, and then pass the serial data to and from the arduino and whatever you choose to connect to (that supports SPP).
There is only one channel, and in any case only one set of TX and RX wires that will be connected to your arduino, but this does not stop you from sending as much data of as many different types as you want. You are only limited by the BAUD rate and how much time the message will take to send.
For complicated data transfers you will need to write the code for a protocol so both sides can make sense of what the other says. You are free to do whatever you can think of here, although if you need to make a complicated protocol you might get some use out of the answers to this question:
Communication Protocol Best Practices and Patters

To add to BrettM answer, Bluetooth is the RF standard on which many protocols can stack up; each such protocol is called a 'Bluetooth Profile'.
The Bluetooth model you purchased comes only with the Serial Port Profile (SPP) profile implemented in the firmware. This mean that you can use it for establishing serial communication.
As serial protocol will probably be too slow for stereo Audio over Bluetooth, Audio usually use a different profile called Advanced Audio Distribution Profile (A2DP). Unfortunately, the HC-05 does not come with this protocol stack implemented in its firmware. If your primary goal is to send stereo Audio over Bluetooth, consider purchasing a dedicated chip, such as XS3868 or Sparkfun's RN-52. For beginners, it is recommended to get one with a breakout board for easy integration with Arduino projects.
For completeness, there are many other Bluetooth profiles, each is optimized for different task. See Wikipedia for the full list:
http://en.wikipedia.org/wiki/List_of_Bluetooth_profiles


text:
split reading sensors values from stream after it via xbee
I'm trying to make project to monitor my home. I am using some gas sensors and temperature and humidity sensors. I want to do this wirelessly and I think the
best thing to do that is XBee.
I use this code for the transmitter Arduino:
char dataPacket[64];

int gx = 1;
int gy = 321;
int gz = 456;
int ax = 654;
int ay = 789;
int az = 987;
int mx = 147;
int my = 258;
int mz = 369;

void setup(){

 Serial.begin(9600);

}

void loop(){

   sprintf(dataPacket, "X%d" ,gx);
    //  sprintf(dataPacket, "A%dB%dC%dD%dE%dF%dG%dH%dI%d", gx, gy, gz, ax, ay, az, mx,     my, mz);
Serial.println(dataPacket);

    }

gx gy gz .... these are the sensor reading variables
and in the receiving Arduino I use this code
void setup(){
    // Start up our serial port, we configured our XBEE devices for 9600 bps.
    Serial.begin(9600);
}

void loop()
{

    if(Serial.available() > 0)
{
     while(Serial.available() > 0)
 {
        char dataPacket[64];

for (int i = 0; i < 64; i++)
{
  dataPacket[i] = Serial.read();
 Serial.print(dataPacket[0]);

}

String show = Serial.readStringUntil('C') ;
delay(500);

}
}
}

but i can't split the values from the stream and put them into their variables (gx gy ...)
Does anyone have idea how to split it?

Try a communication protocol with a , as a delimiter like:
messageId,data1,data2,data3,....,dataN\n

And use the Messenger library to parse it.
See my answer on comms protocols here:
Communication Protocol Best Practices and Patterns
An how to use the Messenger library here:
Send Processing color data into Arduino

You may be able to use sscanf() which works like a backward sprintf(), to assign the values from the input string into each variable.


text:
Get board.vid and board.pid value in code
I'm working on a custom Arduino core based on the teensy code and want to be able to get the board USB VID/PID from boards.txt, as in .board.vid and .board.pid
From what I can tell, Arduino already does this for the Leonardo and similar since if I change the VID/PID in boards.txt then the sketch will run with those values.
But how do I actually get at them? Right now the code I have has hard coded values, but it would be great to make them dynamic.

The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"
this line in "platform.txt" grabs them and makes build flags for them:
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

the -D* option in the build is equivalent to the following lines being in the code
#define USB_VID /*value of build.vid*/
#define USB_PID /*value of build.pid*/
#define USB_MANUFACTURER /*value of build.usb_manufacturer*/
#define USB_PRODUCT /*value of build.usb_product*/

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.

Weird though... could not get manufacturer and product to work. VID/PID worked fine though.

That is odd. What version of arduino are you using? That came from 1.5.8

No wonder I couldn't find platform.txt... I'm using 1.0.5
I swear there was a reason I hadn't upgraded to the beta yet, but can't remember what that was at the moment... think it was incompatible with something I needed.


text:
Arduino if else code
I have made this If-Then-Else code, but it doesn't work.
First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.
What did I do wrong?
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0.00001;  // variable to

void setup() {
  pinMode(13, OUTPUT);  //LED BORD UIT
  pinMode(12, OUTPUT);  //LED4
  pinMode(11, OUTPUT);  //LED3
  pinMode(10, OUTPUT);  //LED2
  pinMode(9, OUTPUT);   //LED1
  pinMode(8, OUTPUT);   //Elektro Magneet
  pinMode(A0, INPUT);
}

void loop() {
  if (A0 == HIGH) {
     digitalWrite(13, LOW);
     digitalWrite(12, HIGH);   //LED on, magnet off
     digitalWrite(11, HIGH);
     digitalWrite(10, HIGH);
     digitalWrite(9, HIGH);
     digitalWrite(8, LOW);

  } else {
     digitalWrite(13, LOW);
     digitalWrite(12, LOW);   // LED Off, magnet on
     digitalWrite(11, LOW);
     digitalWrite(10, LOW);
     digitalWrite(9, LOW);
     digitalWrite(8, HIGH);
  }
}

Sidenote: Be careful with that electro magnet. Those tend to use quite a bit of current, while the digital pins of the arduino can only source a maximum of 40mA. You don't want to "blow up" you Arduino.

To add to what @Gerben said, you'll want to keep current around and under 20mA on any I/O pin and under 100mA on the MCU. Beyond lighting a few LEDs, you'll have to use transistors, darlingtons and relays.

Replace the line:
  if (A0 == HIGH) {

by this one:
  if (digitalRead(A0) == HIGH) {

If you plan on using the pin back as an analog input, use something like this:
  if (analogRead(A0) > 512) {

The explanation is what Ignacio said: you were comparing the pin "name" A0 directly to HIGH instead of reading from the input named A0. To make it clearer, the two lines are equivalent:
if (A0 == HIGH)
if (0 == HIGH)

Get it?
There's more about what pin names to use with digitalRead() and analogRead() here:

analogRead(0) or analogRead(A0) at EE.SE.

You're comparing the pin variable value with HIGH. If you want to get the value at a digital input then you need to use digitalRead().

You have defined your pin as
int sensorPin = A0;

Which should be replaced with
#define sensorPin = A0

And then in your code, you need to read the value from  the pin in your if statement:
 if (digitalRead(sensorPin) == HIGH) {


text:
How do I activate emulation in the Coddeblocks Arduino IDE
I stumbled upon this question here, so I tried the Codeblocks alternative. After opening an Arduino Project, and leaving all options to default, I ran the Arduino version of the Hello World. A popup opened that requests a serial port to move on. What error did I do?
If more details are needed I'll answer the comments. Thanks in advance!

A serial port seems like a reasonable thing to ask for, are you sure it was in error?

Because it was an emulator rather than an launcher.

I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details.
I just tested it out for the simple program but this looks pretty cool.


text:
20x4 LCD shows alternating blank lines
I just acquired a Arduino learning kit, which includes a 20x4 LCD display. I was going to test it, so I grabbed an example "hello world" program from the Arduino docs, connected the display appropriately, and then "Voila! ... Oh, it didn't work.".
The display lights up both its backlight and characters, however not in any desirable pattern. The first and third lines are full white (display is white-on-blue), while lines 2 and 4 are full blue. See picture:

The below schematic is exactly how I've connected the display, which should be correct.

simulate this circuit – Schematic created using CircuitLab
I triple-checked all wiring for any shorts, adjusted the potentiometer to a good value and quadruple-checked the connections, and wasn't able to find any errors.
The dead-simple example program is following:
#include <LiquidCrystal.h>

// LiquidCrystal display with:
// rs on pin 12
// rw on pin 11
// enable on pin 10
// d4, d5, d6, d7 on pins 5, 4, 3, 2
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
    // Print a message to the LCD.
    lcd.begin(20, 4);
    lcd.print("hello, world!");
}

void loop() {
}

Where is the decoupling for the LCD?

@IgnacioVazquez-Abrams Sorry? I was following this tutorial (in Portuguese) for the connections, it doesn't mention that... http://blog.filipeflop.com/display/controlando-um-lcd-16x2.html

After a quick search, I see that you mean a decoupling capacitor, right? Apparently, the kit I've bought doesn't have a capacitor that I could use for that purpose.

Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.

@Gerben Indeed, after pushing the screen in the direction of the Arduino (as per Q image) and rebooting it, it worked correctly. Would you mind turning this into an answer, and if possible, suggest a better way to connect the display?

Great. Glad you got it working.

I have a similar but different problem. My lcd also hows up as same as in your picture. But I can setCursor on 1 ad 3 lines when printing. But if I print starting from the beginning, it will use the alternate lines only. Got any idea what's causing this? BTW I have the wires soldered.

Just putting the jumper wires in the plated holes, doesn't always give a good connection. Try applying some lateral force, to make sure all of them have proper contact. Wiring looks otherwise fine.
A more permanent solution would be to solder some male headers to the display, so you can properly seat it into the breadboard.

Had the same issue recently, only after soldering my cables to the LCD I was able to avoid tilting them to make effective contact. It's definitely a problem of bad contact. In my LCD the holes turned out to be too big.

I had similar problem and I found that I had wrong contrast/brightness. Communication was working but just the characters were invisible. I spent much time, changed the LCD and in the last minute before went to rubish I got it.

I did check the potentiometer values, and it is on a ok contrast. It's really the characters

It's definitely not the contrast. It hasn't even initialized properly.

First, and third lines is all white, second and fourth lines are all blank. So contrast has been set correctly.

Even though contrast may not be the case in this particular scenario, I can confirm that, for some screens, a poor contrast setting gives these exact symptoms.


text:
Performance of internal vs external resistors
Is there any significant performance trade-off between buttons wired with the internal vs external pull-up/down resistors? I see a lot of tutorials demonstrating the use of external resistors when wiring a simple button, like this and this. But since the Arduino/AVR includes internal pull-up resistors, you can wire a button without any external resistor as demonstrated here.
Is there any good reason to complicate your design with an extra resistor?

If you are using the pin as an input in close proximity to the Arduino there is little reason to use an external pullup.
There are a number of factors to consider.
If the switch is some distance from the chip and/or in a noisy environment it will be more susceptible to interference as the internal pullups are high impedance (20kΩ to 150kΩ depending on model).
If the pin is used as both input & output the pullup can reduce the voltage swing.
In other applications e.g. Raspberry Pi the state of the pin between boot and software initialisation can be significant, but this should not be an issue with Arduino.

I think it depends on the application you're going for.  A simple switch probably doesn't need a resistor, since it doesn't require the chip to provide any specific voltage or current.
If you're trying to run an LED or something that requires a specific amount of current or voltage, then you may be better off supplying the power connection & resistor rather than relying on the chip to provide the proper power to the device.
Another situation may be where you're approaching the maximum power output of the chip that you might change to external pull-up/down resistors.

That's what I thought. I have a simple application that just has a few basic push-button switches, and I didn't understand why I was seeing so many complicated wiring schematics when simply connecting the button to ground and signal was sufficient. I just want to make sure I'm not missing something...

This anwser does not relate to the original question: pullup resistors are used for INPUT exclusively, hence they are not a matter of supplying current or voltage by the MCU. Limiting current on OUTPUT is another matter and can be done by resistors in series (not pure pullup).


text:
Compiling includes with Ino
I'm attempting to compile this simple bounce.ino example with the ino tool, but it's giving me the error:
Bounce2.h: No such file or directory

I've placed it in the same directory as bounce.ino. Why can't it find the header?
Edit: I'm using Ubuntu.

What the is the include code you are using? #include "bounce.h"?

What OS are you using?
If you're in Linux (and some OS X installations) you should note that bounce.h and Bounce.h are two completely different files - you need to make sure you have the capitalization the same in your #include directive as the actual file on disk is.

This wasn't the exact problem, but you were close. I was doing #include <Bounce2.h>, which seems to only look in the library path where it didn't exist. For local includes, I need to do #include "Bounce2.h".

I was going to suggest that, but then changed my mind as in the normal IDE I think it includes the sketch folder as part of the system paths, so <> and "" have no difference. I guess with inotool it does matter.


text:
Add -D option via boards.txt
I'm trying to find a way to set a -D compiler option from within the boards.txt file. Basically set a #define for use in code. There are already some special ones like board.vid but is there a generic way to do it?
Somehow the Teensy add-on adds a little magic that allows the IDE to recognize options like:
.board.define0=-DHELLOWORLD
.board.option0=-DHELLOWORLD
In other words, add the -DHELLOWORD (#define HELLOWORLD) to the command line for GCC.
BUT, I can't get this to work without the Teensy add-on installed.
Is there a way to do this with the stock IDE?

Yes, it is possible in the 1.5.+ IDE. while not possible in the 1.0.+ and earlier.
Hardware-specification refers to both the boards.txt and platform.txt files.
in short the boards.txt file specifies...
uno.build.f_cpu=16000000L

and the platform.txt uses in the compile commands such as ...
 -DF_CPU={build.f_cpu}

You can your own. There is already a "build.extra_flags=" that some of the USB devices use to add their own FLAGs conditionally on the board type.

Ahh, cool. Teensy must modify the IDE somehow to support those things in 1.0.x
Now I just wish I could remember why I didn't want to upgrade to the beta... know there was a reason :P


text:
Data from PROGMEM array mismatches initialisation
The amount of memory needed for my user interface is outrageous. Hence I decided to use flash memory. But after some successful readouts from program space, problems emerge.
Updated:
I have some sort of initialisation files to collect all global arrays which go into flash like this: (intitialisation.cpp)
#ifndef INITIALISATIONDEF
#define INITIALISATIONDEF

#include "initialisation.h" //which includes Arduino libraries and "globals.h"

const uint8_t gl_PsNMenuType[MAXMENUS] PROGMEM = { 0, 0, 0, 0, 0};  // this is, what I intend to read out later.
const uint8_t gl_PsNMenuParent[MAXMENUS] PROGMEM = { MAXMENUS, 0, 0, 0, 0};
const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM] PROGMEM = {
  { 20, 2, MFTS, MFTS, MFTS}, // 0
  {2, 9, 1, MFTS, MFTS}, // 1
  {2, 10, MFTS, MFTS}, //2
  {2, 11, MFTS}, //3
  {2, 12, MFTS} //4

};
#endif

Updated:
while I propagate all global vars via another header (globals.h):
#ifndef GLOBALS
#define GLOBALS
#define SDTXT

#define MAXMENUS 80
#define MAXFIXTEXTSPM 5

#include "initialisation.h"
extern const uint8_t gl_PsNMenuType[MAXMENUS];
extern const uint8_t gl_PsNMenuParent[MAXMENUS];  // referenz auf den übergeordneten MP
extern const uint8_t gl_PsNMenuFixTexts[MAXMENUS][MAXFIXTEXTSPM];  // Liste der festen Menütexte zu jedem MP
#endif

as one can see, I do not initialise my arrays fully, as I'm in a development phase, but the first bytes should be zeroed out correctly AFAIK.
But, when accessing my stored values later in a third file: (uimenu.cpp)
#include "uimenu.h" // which includes globals.h and initialisation.h

// somewhere in the code inside a function, with uint8_t mp=0:
Serial.print(pgm_read_byte(gl_PsNMenuType[mp]));

The last line should print 0, as stated in initialisation, but it prints 12.
So, I think, I'm doing sth. substantially wrong here, but have no clue at the moment. I have several guesses:

I should not use const with PROGMEM. I did this to be informed by the compiler, if I accidentally write to an array stored in flash.
I made some mess with #includes, perhaps with order of occurrence. At the moment I try to sort the order out.
There's something with having global variables or arrays defined and declared in a header and accessed in another source files function. But I cannot imagene, what.
Updated: something wrong with my indices for my arrays? is uint8_t insufficient?

If you need more information or code, I'll edit my question accordingly. Thanks in advance! I appreciate any help.
(all files were edited for brevity before posting them)
Update:
I moved the definitions of the progmem arrays to the source file and all macro constants (#define) to globals.h. The outcome is: different numbers are printed, but they are wrong whatsoever. I poked elsewhere into the progmem array and got other wrong numbers.

Did you try declaring them as PROGMEM in your header so that other code units know how to use them?

The correct way to use pgm_read_xxx is pgm_read_byte(gl_PsNMenuType + mp).

@Gerben: ... or pgm_read_byte(&gl_PsNMenuType[mp]) and mainly switch on warnings. This kind of error should be caught by gcc warnings.

@IgnacioVazquez-Abrams I guess I brought some confusion into this matter by not posting my updates in a new section but changing the code. Actually the first thing I tried was to qefine and initialise it in header file. But I still have a extern declaration in "global.h" which is included by all other headers in my project. IMHO the declaration with extern should suffice for other code to make it linkable, shouldn't it? But I think I have to check gerben's comment as soon as I'm back at the hardware again.

@TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call typesafe?

@TMa: seems to work! I totally missed the necessity of referencing the array element. Thanks a lot. But I did not get any compiler warnings without the reference operator. Why isn't this call type-safe?

The PROGMEM word is an attribute, not a type. It might be type-safe but not attribute-safe (if there is such a thing). See Data in Program Space

Reference
Putting constant data into program memory (PROGMEM)