text:
Arduino Due and BNO055 address in i2c mode
I have a project where I need to have several IMUs, the BNO055 shuttle board (I explained my project here), I manage to get the Euler angles from one BNO055 sensor, which have the address 0x29, because I linked the I2C_MODE_ADR_SEL to a HIGH level.
I would like to have another sensor with the address 0x28. As the datasheet says, I must link the I2C_MODE_ADR_SEL to a LOW level (to the GND) the i2c Scanner from the Arduino Playground does not recognize any i2c device.
I don't know how to change my sensor address, can anyone help me with this issue ?

I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.
https://hackaday.io/project/9266-motiosuit
The sensor board and library are open-source and documented in the link, I hope it helps!

You might mention that it uses multiplexing using the TI http://www.ti.com/product/PCA9548A chip and  https://github.com/bqlabs/I2C-multiplexer code.

Wow sorry, I've just seen it. Indeed, it is all explained in the text linked. Just to clarify, that is a fork from https://github.com/alvaroferran/I2C-multiplexer which I actually wrote for that very project :)

Oops.  I missed that you were the author of the interface code. I was looking for BN055 code got distracted by the hackaday project and skipped to google to find the BN055 code.  Thanks for the links.

No worries, glad it was useful :)

According to Table 4-7 on page 90 of the BNO055 datasheet at adafruit.com, the BNO055 supports three I2C addresses: 0x28 or 0x29 in slave mode (selected by COM3 being low or high, respectively), or 0x40 in the HID-I2C configuration.
According to the diagram on page 2 in file BNO055_Shuttleboard_Flyer.pdf (Bosch's description of the BNO055 Shuttle Board), COM3 on pin 17 of the BNO055 (or, PSERCOM3) is wired via 0Ω jumper R106 to the middle pin of J102.
If you plan to get data from five different BNO055's, you may need to use a multiplexer (or several I/O's) to set COM3 on one BNO055 board to a different level than on the other four, to select one of the five boards for access.  For example, you could use a 7438 (eg, an MM74HC138 or DM74LS138).  When you set the 7438's address input to j, line Yⱼ (from among Y₀ to Y₇) will go low while the the other Yᵢ remain high.  The BNO055 with COM3 attached to Yⱼ then would be the only BNO055 that would respond to I2C address 0x28.
For testing, you could set up several BNO055's and use several separate I/O lines to control several COM3 inputs.  Using separate I/O lines takes five I/O lines for five COM3's, vs three I/O lines using a 7438 multiplexer; saving two lines might not be worth the extra effort of obtaining and using a multiplexer.
Another approach is to use two more Arduino (eg Pro Mini or Micro) units to support separate I2C busses for additional BNO055's.  These auxiliary Arduinos could do some data reduction before sending data (via serial or I2C) to the principal Arduino.
Note, it is not clear to me that using more than one or two BNO055's makes sense.  If the assemblage of BNO055's moves through space more or less as a unit, but with attitudes, roll rates, etc differing between BNO055's, then 3/4 or so of the data from different BNO055's will be the same.  Possibly less-general sensors (eg, without magnetometer) with different I2C addresses could be used instead.

The project aim to monitor the movements of the upper limb. For the moment I want to monitor only one arm I just need 3 sensors (One on the arm, one on the forearm and one on the chest), so I don't need a multiplexer. My problem is I can't get the sensor working when I put a low level on the pin that select address. I tried wiring it to the GND, or on a digital pin of the Arduino, that send a low level, and everytime the i2c scanner does not detect the sensor.

I would recheck (with a meter or scope) that pin 6 PS0 and pin 5 PS1 are low, and that pin 17 COM3 goes low or high as you connect or disconnect it from ground, and also would try reading at address 0x28 even if the I2C scanner doesn't see that address.  Which I2C scanner program are you using?

I use this one http://playground.arduino.cc/Main/I2cScanner

I checked with a scope, the PS0 and PS1 are low (0V each), and COM3 is at 3.3V when connected to the source and 0V when connected to the ground. I read that maybe I should use pull up resistors, would i be useful in my case ?

No pullups needed.  See p. 89 of BST_BNO055_DS000_12.pdf, table 4.6 which says COM3 has an internal pullup, typ. 40K.  Note, after table 4.4 it says “It is not allowed to keep the protocol select pins floating” ie the PS pins should be tied high or low.  Have you tried using address 0x28 with only one BNO055 connected up?

Yes, I tried with only one BNO055. I tied the PS pins to the GND everytime. I managed to use two BNO055 at the same time, one on the second I2C input (SDA1, SCL1) and 1,5kOhms pull up resistors (at the address 0x29), and the other one on the regular I2C (PIN 20 and 21). Again, it only works with the address 0x29.

Although this is an older question, I believe there may be people still looking for a solution to this problem. Documentation for the BNO055 Shuttle board is pretty thin. I've added a bit of the schematic below.
BNO055 Com3 (pin 17) is presented on pin 22 of the shuttle board (12C_MODE_ADR_SEL). This pin must be connected through a resistor either to shuttleboard pin 4 (SD0, GND) or to shuttleboard pin 5 (SD1). The datasheet makes mention of 2-position jumper J102 which should accomplish this, but there are versions of the Shuttle board that do not include this jumper or any place to mount it. In the photo of the OP's setup (pasted at bottom in case his link goes away) the jumper header would be installed across the three holes adjacent to pin 3 (GND), and jumping the center pin to the left or right-side pin would set the address to 0x028 or 0x029.
If you don't have the jumper, just connect the pins directly: when I connect pin 17 to pin 4 through a 10K resistor, the Arduino "example" scanner does see it at I2C address 0x28.
Personally I like the Adafruit BNO055 board a lot better than the Shuttle -- it has a voltage regulator and a lot of other additions, and it uses 0x028 as its default I2C address.
For those working in the Arduino code environment and wishing to incorporate more than two BNO055 devices and who do not wish to use a multiplexer, I might suggest looking at the Teensy family of 32-bit ARM cortex CPU boards. These are completely code-compatible with Arduino, but offer more than one I2C bus. In fact the Teensy 3.6 (180 MHz!! with 1M Flash, 256K Ram, 4K eeprom, an FPU) offers four* separate I2C Wire interfaces on different ports, which would permit 8 of the BNO055 devices to be used.
I've personally been very happy with the performance and functionality of the Teensy boards when used with multiple BNO055 devices.


text:
Arduino yun strange uploading error
I'm new to arduino and I'm trying to upload a fairly large (I think) program to a arduino yun which includes a 3 dimensional array. I'm using the bridge features of the yun.
when I upload the first time after unplugging and plugging back in again it runs fine. When I try and upload a second time I get the following error regardless of which code I'm trying to upload (blink example for example)
 avrdude: verification error, first mismatch at byte 0x0000
 0xff != 0x0c avrdude: verification error; content mismatch

In the serial monitor I get the following output:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)...
Unable to connect: retrying (3)...
Unable to connect: retrying (4)...
Unable to connect: is the sketch using the bridge?

I'm currently developing as much as I can in another sketch but it's a pain.
I can provide the code if needed.
Thanks for any help

source: Stack Exchange

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

sort: votes


text:
Use the TCS3200 color sensor without the included LEDs
just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?

The photodiodes in the device itself have filters so it should theoretically be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have two sensitivity peaks and so using it outdoors without an infrared filter is not advised.

So how could I use the sensor without LEDs? I want to operate it using solar power and can't waste any energy. Can I just bridge them? Will I damage anything by doing that? Also is there any DIY infrared filter that I could build use with materials normal people have at home?

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


text:
What are the distances between Arduino Mega connectors?
I am trying to build an Arduino Mega shield. For that, I need to know the exact distances between the different connectors.

Why not start with an EDA file that already contains the connectors?

The pin layout and dimensions of the Mega are as follows:

Dimensions are in thousandths of an inch. Source


text:
Can I use analogReadResolution() on an Uno or Leonardo?
I am trying to get a spectrum analyser up and running. I found the following code on Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer1:
/*
 *
 * Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer
 * https://communities.intel.com/docs/DOC-23406
 *
 *
 * ERROR: analogReadResolution() ???
 *
 */

#include <stdint.h>  //For New Arduino
#include "PCD8544.h"
#define pin_adc 0
#include "fix_fft.h"
char im[128];
char data[128];
int analog_value[128];
int i=0;
PCD8544 nokia = PCD8544(3, 4, 5, 7, 6);
// pin 7 - Serial clock out (SCLK) connects Dig3
// pin 6 - Serial data out (DIN) connects Dig4
// pin 5 - Data/Cmd. selct. (D/C) connects Dig5
// pin 4 - LCD reset (RST) connects Dig6
// pin 3 - LCD chip select (CS) connects Dig7
void setup() {
  nokia.init();
  nokia.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
  nokia.clear();
  analogReadResolution(8);
}

void show_big_bars(char *spektrum) {
    int spek_for_draw;
    nokia.drawline(10, 15, 10, 39, BLACK);
    for (byte i = 1; i < 64; i++){ // Skip 0 Channel
      // Serial.print(spektrum[i],BYTE);
      spek_for_draw = 1.5*(spektrum[i]); // 0/2.5 ~ 255/2.5
      if (spek_for_draw > 39) spek_for_draw = 39;
      nokia.drawline(i+10, 39 - spek_for_draw, i+10, 39, BLACK);
    }
    //nokia.drawstring(5, 5, "0 09 22 36 49");
    nokia.drawstring(5, 5, "0");
    nokia.drawstring(21, 5, "4");
    nokia.drawstring(37, 5, "8");
    nokia.drawstring(48, 5, "12");
    nokia.drawstring(67, 5, "18");
    nokia.drawstring(5, 0, "Spectrum");
    nokia.drawstring(5, 1,"* 0.1KHz");
    nokia.display(); // Update Screen
    nokia.clear(); // Clear Screen for the animation
}
void loop(){
  static long tt;
  int val;
  if (i < 128){
      analog_value[i] = analogRead(pin_adc);
      i++;
   }
   else{
        for (i=0; i< 128;i++){ //Prepare data for FFT
            data[i] = analog_value[i] - 128;
            im[i] = 0;
        }
   //this could be done with the fix_fftr function without the im array.
        fix_fft(data,im,7,0);
   // I am only interessted in the absolute value of the transformation
        for (i=0; i< 64;i++)
             data[i] = sqrt(data[i] * data[i] + im[i] * im[i]);
   //do something with the data values 1..64 and ignore im
        show_big_bars(data);
        i=0;
   }
}

When I attempt to compile the above code, I get the error
Arduino: 1.6.5 (Mac OS X), Board: "Arduino Micro"

fft_galileo.ino: In function 'void setup()':
fft_galileo:31: error: 'analogReadResolution' was not declared in this scope
'analogReadResolution' was not declared in this scope

When I search for the location of analogReadResolution() on Google, I repeatedly get the information that it is only available for the Due and Zero. From Arduino - AnalogReadResolution:

analogReadResolution() is an extension of the Analog API for the
  Arduino Due and Zero.

I was wondering if I needed to add an #include statement but all of the code examples that I found do not have any specific #include for the Analogue library.
Also, thinking maybe it is board specific (as the video Arduino Due error: 'analogReadResolution' was not declared in this scope suggests), I selected the Duemilanove board (as the Due is not on offer in my "Board" menu), but I still get the same error. I have even tried the Arduino NG or older Board menu item, but with the same results.
So, how do I get rid of this compile time error? Or, more poignantly, how can I compile this code for my Uno or Leonardo board.  Should I just comment it out? If I do comment the line out then the code does compile, so does this mean that analogReadResolution() is not required any longer?
If it isn't required, then why does this Uno specific example, How to Use ADC in Arduino Uno?, state:

As default we get the maximum board ADC resolution which is 10bits,
  this resolution can be changed by using instruction
  (“analogReadResolution(bits);”). This resolution change can come in
  handy for some cases.

How can the resolution be changed if the method has, indeed, been deprecated?
Also, why do I not have a "Due" in my Board menu?

1 For completeness fix_fft.h and fix_fft.cpp can be found on TJC's github and here is the PCD8544 Arduino library for Nokia 5510 LCD library. The password for decompressing Intel_Nokia5110.rar file is 406.

It's a Uno, not a UNO. It's not an acronym. Arduino is naming their boards Zero Uno Due Tre - that is Zero One Two Three.

@NickGammon - Thanks for pointing that out. Not sure where, or why, I got the wrong idea. Feel a bit of a fool now. I have made some bad edits in that case :-(

Don't worry about it. Your edits have been good. I've restrained myself from correcting UNO to Uno, because I wanted you to have the credit for making the edit. :)

@NickGammon - I wish you had corrected them though, as I do appear to have sprayed UNO all over the shop. I think that I must have picked up the capitalisation of the Arduino website as they seem to put caps on everything, not sure. BTW, I think that you can make subsequent edits, when reviewing, as many of my edits get revised across SE (I'm not too sure of the procedure). Don't worry about letting me have the credit, I just want to see nice clean posts... ;-) Thx again.

There is no point to having analogReadResolution() on AVR devices since that function only exists to provide/ensure backwards compatibility with the fixed 10-bit ADC that is found in AVR devices. If you want higher or lower resolution then you will need to perform the appropriate actions manually.
You don't have a Due entry because you haven't installed Atmel SAM support in the Board Manager.

Also, why do I not have a "Due" in my Board menu?

See:

Then:

I selected the Duemilanove board (as the Due is not on offer in my "Board" menu) ...

The Duemilanove and the Due are completely different boards, with different processors.


text:
Why is my variable not getting updated?
I have the following snippet of code:
const unsigned long fiveMinutes = 5 * 60 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

The doStuff() routine is getting called on every loop() iteration, because the value of lastCheck isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (doStuff() is defined and works correctly, I'm not posting it here for brevity.)

"unsigned long lastCheck = 0 - fiveMinutes;" Are you sure you meant that?

Yes. It works with that line, the line of concern is lastCheck = now; inside loop(). That line doesn't update the lastCheck variable correctly.

Post the disassembly of loop().

It really would be useful if we could see what doStuff() is doing. Maybe it resets the Arduino and it is constantly rebooting itself. Does the program have the same side effect if doStuff is simplified to just a println()?

I have the following snippet of code: - Unfortunately snippets don't cut it as I try to explain at  Snippets R Us! - you need to post a  Minimal, Complete, and Verifiable example. That is, code that actually demonstrates your point.

I modified your code to produce a working example:
const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

I thought I could update global variables inside subroutines ...

You can.

Are you sure you didn't have:
void loop() {
  unsigned long lastCheck;
...


text:
lcd.print then dataFile.print
My program is a bit large and I'm worried about stability.
I need to print data to both a file and to my LCD. It's like this:
if (hour<10) {
    dataFile.print("0");
}
dataFile.print(hour, DEC);
dataFile.print(":");
if (minute<10) {
    dataFile.print("0");
}
dataFile.print(minute, DEC);
dataFile.print(":");
if (second<10) {
    dataFile.print("0");
}

Then
if (hour<10) {
    lcd.print("0");
}
lcd.print(hour, DEC);
lcd.print(":");
if (minute<10) {
    lcd.print("0");
}
lcd.print(minute, DEC);
lcd.print(":");
if (second<10) {
    lcd.print("0");
}

What is a smart way to make this shorter? Should I write a function to add the leading zero then another that does something like:
void printboth (thing) {
    dataFile.print(thing);
    lcd.print(thing);
}

good idea?

possible duplicate of What will use less memory, an array or if ... else?

You asked an almost identical question here: http://arduino.stackexchange.com/questions/13876/what-will-use-less-memory-an-array-or-if-else where you start: I'm trying to make my sketch smaller.  Please stick to one question for one topic to avoid splitting answers.

Give __attribute__((always_inline)) void printboth (thing) a try and see if it results in a smaller size. PS make sure you are using the latest version of the Arduino IDE.

You could format the data with snprintf:
char timestamp[9];
snprintf(timestamp, 9, "%02d:%02d:%02d", hour, minute, second);
dataFile.print(timestamp);
lcd.print(timestamp);

%02d in the snprintf format means "print at least 2 digits of this value and pad with leading zeros".

While true, note that *printf() will increase code size a lot.

Define "a lot".  I make it an increase of 1046 bytes and the program is far more readable.

I'm making changes with the main goal of making the sketch smaller


text:
Why does this code execute?
After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:
void setup() {
  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));
}

void loop() {
  int timing = 1000;
  delay(timing);
  digitalWrite(13, HIGH);
  delay(timing);
  digitalWrite(13, LOW);
}

I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (Atmel's information on the Atmega328P shows us it only has 2KB of SRAM), the code in void loop() would not be able to run due to lack of memory. As far as my understanding goes, once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable timing and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.
However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by malloc unavailable for use by anything else until free is called on it?

If you add a debugging print you will see what is happening:
void setup() {
  Serial.begin (115200);
  Serial.println ();

  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));

  Serial.print ("data = ");
  Serial.println ((int) data);
}

Output:
data = 0

The malloc failed, it returned NULL, the rest of the program proceeded normally.

once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

malloc does not return with a partial allocation. It either allocates the amount you requested or none at all.

I guess error checking is very important and handy, thank you.


text:
Detect button on a ground line (reverse eng)
I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.
Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons.
Circuit:
Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin
Thanks in advance!
Edit: Circuit Board

Just connect the ground to the ground on the arduino, and the free pin to a IO pin. Enable the pull-up resistor on that pin using pinMode(<nr>, INPUT_PULLUP);. If the button is not pressed, you will read a HIGH. If the button is pressed you will read a LOW.

Exactly what I wanted. Simple explanation! The internal_pullup thing was the thing that bothered me the most but it's all explained now. So thanks! Until I can confirm this I will refrain from accepting this answer :)

That's fine. Good luck on your project.

It sounds like you might have a PCB with debounced switches on them. One such circuit for debouncing switches looks like this:

That circuit and more about switch debouncing can be found here.
A debouncer basically masks the problem of switch "bounce" which is what happens when the contacts get close and the circuit is quickly closed and opened in rapid succession until a firm connection is obtained. Its a natural problem  mechanical switches.
If that's not quite right, maybe you could help us help you better by posting a photo of the board in question.

Well I'll do some research on debouncing... You can see my edit for further analysis on the circuit! Thanks for your concern!

I did some research on the subjects and I came with a solution: I borrowed the code from here and made some modifications to fit my needs.
const int buttonPin = 6;
const int buttonPin1 = 7;

int previousReading = HIGH;
int previousReading1 = HIGH;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(buttonPin1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  int reading = digitalRead(buttonPin);
  int reading1 = digitalRead(buttonPin1);

  if (previousReading == HIGH && reading == LOW) {
     Serial.println(HIGH);
  }

  if (previousReading1 == HIGH && reading1 == LOW) {
     Serial.println(LOW);
  }

  previousReading = reading;
  previousReading1 = reading1;

}


text:
Why do only specific arduinos support the keyboard and mouse libraries?
The Arduino website suggests that only three boards are supported for the Mouse and Keyboard library page:

Leonardo
Micro
Due

What is special about those boards, that the other boards in the Arduino family don't have? I thought they might have the same proceesing chip on them but only two of them do. The CPUs are correspondingly:

ATmega32u4
ATmega32u4
Atmel SAM3X8E ARM Cortex-M3

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?
So my question is: what do those three boards have that lets them support those libraries?

Those chips have hardware support built into them to handle the rather strict timing requirements for interpreting (and responding to) USB sequences. You will notice, for example, that on the Arduino Uno there is a second chip (the Atmega16U2) which also can handle USB. In fact the chips with a "U" in the name generally can do this.

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

You have a couple of options. Some people reflash the USB chip on their Uno (for example), although personally I think that is a bit fiddly.
Alternatively, there is a library called VUSB (virtual USB) which lets you do some USB on the non USB chips. Google vusb arduino.
You need three resistors and two zener diodes to make up the hardware that lets this library do its stuff.

Another option is to use the PS2Keyboard library, a PS2 connector and a PS2-to-USB converter.
You will need only two digital pin of your Arduino and have keyboard solution.

i was actually more interested in simulating a mouse, but this is good to know.

There is also a library called PS2Mouse that enables the possibility to act as a ps2 mouse device (with ps2dev) or receive values from a existing PS2 mouse.


text:
Use TSL2561 and DS1307 RTC together
I want to use a TSL2561 light sensor and a DS1307 RTC and a couple of other sensors like DS18B20, AS3935, ML8511, MQ135, 433 mhz sender together with an Arduino.
However on Adafruit I read this today (Quote from Adafruit)

You may be wondering, how is it OK to connect a 3.3V chip like the
  TSL2561 to 5.0V data pins like the Arduino? Isn't that bad? Well, in
  this specific case its OK. I2c uses pullup lines to the 3.3V power
  pin, so the data is actually being sent at 3.3V. As long as all the
  sensors/device on the i2c bus are running on 3.3V power, we're fine.
  However, don't use a 5.0v powered i2c device (like the DS1307) with
  pullups at the same time as a 3.3V device like the TSL2561! If you
  want to use this sensor with a datalogger that uses the DS1307, remove
  any/all of the pullup resistors from the DS1307 SDA/SCL pins. The
  pullups built into the TSL2561 will then be active and keep the
  voltage at 3.3V which is safe for both the RTC and the sensor.

I don't really understand the meaning of this. What am I supposed to do? It tells me to remove the pullup lines on the RTC, but what are they and where can I find them? Are there any other sensors where I have to do this? If I don't remove the pullup lines, will I damage anything? Can someone clarify those things to me?

You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. What board (if any) are you using for the DS1307?

I am using a normal one you get from ebay for like 2 bucks

There is no "a normal one", as there are multiple version, each having different configurations of pull-up resistors.

I am using this one http://www.ebay.com/itm/2PCS-Arduino-I2C-RTC-DS1307-AT24C32-Real-Time-Clock-Module-For-AVR-ARM-PIC-SMD-/310526222928?hash=item484cce2250

You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. This will not damage the arduino, but could damage chips like the  TSL2561, that can only handle 3.3v.

On the board you indicated you are using, you need to remove R2 and R3
Other 5v sensor breakout might also have pull-ups to 5v. Easiest way to check, is to connect 5v and ground, and then measure the voltage on the SDA and SCL pins. If it's 5v, then it has pull-up resistors that need to be removed.

Thank yoh. How would I remove them? Just desolder them and leave a unconnected gap or bridge them? Also do I need to do this for other chips? How do I figure out if I have to remove resistors and where?

Desolder and leave open. The last two questions I've already answered.


text:
I would like to control 16 motors with a servo shield
Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...
I'm using an Adafruit servo shield.
I can make my servo move. However, I want to stop it at 90 degrees without it returning to 0 degrees each time.
What am I missing?
The code I've used is as follows:
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop()
{
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }
  delay(500);
}

If you don't want it to keep going back to zero, don't have a loop that resets to zero when it reaches 90.

You are right by putting it in the setup the code does only runs once. However my problem is the servo arm sweeps 90deg as coded and returns to where it started (not coded). Putting the code outside Void Loop () or using a count based approach makes no difference. To recap my issue is how do I hold the servo at 90degrees ???

Please post the amended code. You tell it to go to 90 degrees and then you do not tell it to do anything else.

@NickGammon please note that this is in the main loop(), so it will wait half a second and then reset to SERVOMIN.

Andy: do you want it to just go from 0 to 90 one time, or what do you want it to do?

please note that this is in the main loop(), so it will wait half a second and then reset to SERVOMIN - incredibly quickly, yes. The loop executes very quickly so it would go back up to SERVOMAX within a short time. In fact my testing indicates that it executes that loop in 72 ms.

The code in loop is called repeatedly. Thus it does this:

Go from SERVOMIN to SERVOMAX very rapidly (I measured 72 ms)
Pause half a second
Repeat the above

To make it pause at SERVOMAX you need to either not repeat the loop, or put it all in setup, eg.
#include <Adafruit_PWMServoDriver.h>
#include <Wire.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)
void setup()
{
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
  {
    pwm.setPWM(0, 0, pulselen);
  }

}

void loop()
{
}

Thanks Nick, using your code I've added a delay just after. I then noticed when executing the code the servo arm rapidly swings 180 degrees and then it slowly sweeps back the other direction due to the delay as 'pulselen' increases.....

Thanks Nick, using your code I've added a delay just after pwm.setPWM(). I then noticed when executing the code the servo arm rapidly sweeps 180 degrees and then it slowly sweeps back the other direction due to the delay and as 'pulselen' increases..... But what is causing the initial fast sweep as I only need the slow sweep?

Hi nick I noticed if I changed servo max and min to 1500 and 1000 respectively I loose the fast sweep..

Servos differ, and the pulse width for the sweep at max and min positions may well vary. You have it solved then? Good.

The variable pulselen in your code corresponds to the angle you want the servo to turn to. For most servos the pulselen is supposed to be a number from 1000 to 2000, where 1000 corresponds to 0 degrees and 2000 corresponds to 180 degrees, but some servos may be different. It's probably safe to assume that you want a value close to 1500.
Of course the servo takes a while to get to its position, so the best approach usually involves changing pulselen gradually until you get to the desired position.
Once you get to 90 degrees stop changing pulselen. At that point you should still be sending the PWM but keep it at 1500. You'll want to keep sending the PWM signal, or the servo will have no resistance to external forces.


text:
RDM630 RFID Reader on Beaglebone Black?
I have an RFID reader RDM-630 with these specifications: http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf
Could I connect this to a Beaglebone Black?

Yes.  But why ask us?

BBB I believe is off topic for the site: http://arduino.stackexchange.com/help/on-topic

Found what I was looking for and the answer is yes.


text:
Can I use GPS sensors in a country (India) that doesn't have its own GPS Sattelites?
I am living in India. I want to work on Arduino Projects with GPS Modules. But only a few countries like US, Russia, China etc. have their own GPS satellites. India is working on it. So I am hesitating to buy GPS sensors. Can I work normally with GPS modules in my country as shown in Online projects in my country ?

GPS is US only. The Russian version is called GLONASS. The EU version is called Galileo. China version is called BeiDou/COMPASS (this one only works in and around china). PS the 'G' in GPS stands for Global, to indicate it works around the globe/world.

GPS - anyone can use it anywhere that it works. Not so good nearer poles. Best choice for India.
GLONASS - also can be used by anyone. Works best in Nortthern areas- satellites are in very elliptical orbits where they "hand high and slow" over top of northern hemisphere and are "kow and fast"in southern.

Each of the countries listed has their own satnav system. GPS satellites cover the entire world and the US government allows anyone with a GPS receiver to use it, regardless of where on or above the surface they are located.


text:
Sending "Blink" to pin 12 is causing on-board led to blink?
I recently picked up an Uno clone and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.
Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?
Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.
Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.
int ledPin = 12;
int delayPeriod = 100;

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

void loop()
{
  digitalWrite(ledPin, HIGH);
  delay(delayPeriod);
  digitalWrite(ledPin,LOW);
  delay(delayPeriod);
  delayPeriod = delayPeriod + 100;
}

Is there a schematic available anywhere? This behavior is not expected, and certainly not characteristic of an Arduino.

Good question. I'm not sure. I've just emailed the company asking them if a schematic is available. I've also let them know about this unexpected behavior. I'm curious if this has happened to anyone else.

After some digging I came up with this pdf on their website. The second to last page, pg.121, may be it.

Those are the reference schematics, for the 2009 and Uno r1.

Ok, I thought maybe 2009 was AVMicrotech's internal name for their clone. I didn't realize it was an official board. Hopefully they'll get back with me soon.

Try measuring the resistance between the two pins using a multimeter, if you have one. Could be some flux residue or something between the solder joints on the underside, between pins 12 and 13. This residue is slightly conductive.

I checked and yes I was getting a measurement of around 150 ohms checking those two pins. Then again i checked the pairs of 8 and 9, 10 and 11, etc. and most of them read something in the same range. Is that level expected?

See Have I bricked my Arduino Uno? Problems with uploading to board
As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:
 pinMode(13, OUTPUT);
 digitalWrite (13, LOW);

See if that changes the behaviour.

Yes, adding that stopped the blinking.
So what should I do next?

According to this answer. The onboard led might turn on if you leave the pin floating and in input mode.  So you need to leave it in output mode, or make sure it's not floating. A pull-down or pull-up resister may help if you need it in input mode for some reason.

Thanks all for the help. You've given me some insight into the behavior I witnessed as well as more knowledge about this device.
Also, Nick, you're page that you linked to is an excellent resource, that I'm sure I'll refer to again in the future.


text:
Arduino car on bluetooth remote appears to crash when motors started
I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.
When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.
I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.
What is going wrong here? What issue am I encountering?
The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.
Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?

What sort of 9 V battery? One of the ones you put in a smoke detector? Almost certainly it is underpowered. I would also be interested to see the wiring.

It probably is the kind that goes into a smoke detector. It is a Varta Longlife.

Please sketch or photograph the wiring setup.

The wiring is very minimal. The sonic sensors and the bluetooth module are attached to pins on the motor shield. The motors are in the screw in terminals, as is the 9V battery. Here's a photo:https://drive.google.com/file/d/1Ev7B0DkuhxZA6TcpqyLhaMbF5M7nmoaPmQ/view?usp=sharing

Did you cut the "Vin Connect" jumper on the back of the board? I suspect you need to.

In any case you won't drive those motors for long with that 9 V battery.

Cutting that jumper has done the job. Now I'm on to the battery issue. Thanks.

You seem to be using your heavy-duty batteries for the Arduino and the light-duty 9 V battery for the motor. To me this seems backwards. Also the Vin pin to which you have the 9 V battery connected is by default connected to the Arduino as well. This means that if the motors draw a lot of current it will drag the Arduino's voltage down and it will probably reset (thus cutting power to the motors, and then it reboots).
From the Arduino Motor Shield page:

Vin on the screw terminal block, is the input voltage to the motor connected to the shield. An external power supply connected to this pin also provide power to the Arduino board on which is mounted. By cutting the "Vin Connect" jumper you make this a dedicated power line for the motor.

You should cut that jumper so that the Arduino and the motor have dedicated supplies.
Also, arrange better batteries for the motor. You may find you can run the Arduino from the 9 V battery, and then make sure you have enough AA batteries to drive the motors.

it sounds like the motors are pulling down the battery voltage enough to reboot the Arduino; and the USB-port is able to supply enough current without as much voltage drop.
We'd need to see a schematic, but check that the power supplied to your Arduino and power supplied to the motors are completely independent; that the Arduino only supplies current to a switch or a relay in the motors' power circuit but not to the motors themselves.


text:
What will use less memory, an array or if ... else?
I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:
char* ampms[]= {"am", "pm"};

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      dataFile.print(ampms[ampm]);
}

I could do this instead:
void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
}

No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?

avr-size says what?

Sketch uses 25,588 bytes 79% Max is 32,256 Global variables use 1,938 bytes 94%

And the other way?

I appears to be the same.

Then neither is the solution you're looking for. Try putting the constants into flash.

Try looking into PROGMEM. See the 'Arrays of strings' section on the arduino website for example.

As Ignacio says, if the compiled size is the same both ways, look for something else.  (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)
When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the if method, so there are tradeoffs.
You can replace the clunky if statement and its two lcd.prints  with the following:
      lcd.print(hour>12? "am" : "pm");

Note that that line retains the two bugs that your if statement has, but it produces them more compactly. :) [One error is that your if statement prints pm for hours 0 through 12 and am for hours 13 through 23.  Another error is that it prints zeroes instead of twelves for the hours after midnight and noon.  More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.]
Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via
lcd.print(hour>12? F("am") : F("pm"));

saves 6 bytes of RAM.  However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:
lcd.print(hour>12? 'p' : 'a');
lcd.print('m');

The following lines of C can replace much of the code you showed.  However, the printf library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some printf functions.  It replaces the lines from if (hour>12) { hr = hour - 12; } ... to the end with
enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%cm", hour%12, minute, hour>12? 'p' : 'a');
lcd.print(buf);

lcd.print(hour>12? F("am") : F("pm")); will safe 6 more bytes.

@Gerben, but program size increases 74 bytes.  Printing characters (see edited answer) saves the 6 bytes of RAM but increases program size only 12 bytes

didn't thing of checking that. That's very interesting. Having an almost empty sketch with only that line, will make it increase by only 26 bytes on my system.


text:
Arduino Relay Shield
I am wondering if this Arduino Relay Shield design would be good enough to handle 120v 1amp The transistor is a 2n4401. Also The Two capacitors on the other 3 circuits would be going to ground opps its to late for this

You seem to be missing some earth connections: bottom of  C3,C5,C7,

please explain the wiring on the output side, preferably draw in the supply and load.

The relays have 5 pins. Th logical arrangement is the 2 coil pins at ine end and the 3 contact pins together ar the other end. That way there is maximum coil to contacts separation. Some relays (and notably low cost Chinese ones used on premade relay shields) have the contact "common" pin at the coil end between the coil contacts. That means there is a short path from low voltage coil to high voltage contacts. This is gross stipidity but very common.

As already mentioned, everything to the left of the relays is completely irrelevant when it comes to what the system can cope with.  It's purely down to the relays what voltage and current they can deal with.  As far as the circuit goes there's nothing wrong with it that I can see at first glance.
So to go from there to an actual physical shield there are a number of things you do need to consider:

Ensure that the relays have a rating at least as high as the expected maximum voltage and current, ideally derate it by at least 50%.  For CFLs (which present an inductive load as well as a resistive load) you want to dereate it even more.
Ensure that the mains voltage track layout is kept well away from the low voltage digital signals and ground plane.
Ensure that the mains voltage tracks are sized appropriately and kept as short as reasonably possible.  Use a track width calculator to get the right width.
Be sure to use appropriate connectors for the mains power.  They need to be able to cope with as much current and voltage as the relays and at the same time be safe.
Keep all mains voltages away from human contact.  This means no exposed live metal on the upper side of your board where it can be inadvertently touched.  Any components with exposed leads that have mains voltage in them should have their leads insulated.
Be absolutely certain that, since this is a shield, no mains voltages even come close to the Arduino the shield is plugged into.  This is especially critical around such areas as the USB socket where through-hole components (like screw terminal blocks) are likely to short circuit and cause very very nasty things to happen.

Remember: Mains voltages are dangerous, caution and safety should be your first concern over everything else!
One more tip: Do all your mains experimentation as safe as possible.  Either ensure that you have an ELCB and an RCD on your ring main / power outlet (with the former you must ensure that you have your earth wires connected properly), or even better (and what I would certainly recommend above all else), use an Isolation Transformer to separate you from the mains circuit entirely.  With an Isolation Transformer electrocution is only possible if you contact both terminals at once as opposed to just one terminal of the normal mains supply.
Edit: One thing that does puzzle me with your circuit is how you have wired up the common pin of the relays.  That part of the circuit makes no sense to me at all.  You should have 2 connections to each relay - in and out where in connects to the NO and out connects to the common pin¹.  The only way your arrangement could work would be to designate one relay as a master power control and that one has the main power coming in which then feeds through to the common rail to supply the other three relays.  If this is what you want, then you will have to ensure that the relay designated as master (and its connector) has at least three times the capacity of the other three relays and connectors (or all four relays have at least three times the capacity you would otherwise need).

¹ Note: doing it this way around ensures that when the relay is in the off position the NC pin isn't live.  The only pin that would ever be live is the common pin.  Safety first...!

Yes the relays are rated 250v 10amps, They wont be pushing anything to hard, Just A microwave fan, also only two relays can be on at once. As for the common pin it seems that i forgot to add that as the AC in for the relays. It wont be on a trace. I plan on using 22awg wire to make a physical connection

The critical part is the relay.
I'd want relays with rated to switch the load and and handle the cold current that the lamp wants.
I also want to see a good creepage clearance distance between digital side and the relay outputs.  Relays which put the common contact between the coil terminals are probably a bad choice here, relays that instead have the contact terminals at one end and the coil terminals at the other make the PCB layout easier.

The relays are rated 250v 10amps as for the coil clearance i dont quite understand what you mean.

250V 10A sounds suitable for lamps up to 100W or so,  the other bit is  about creepage distance (edit)  you don't want to suddenly find that your arduino is live.


text:
IR frequency difference
I want to create a device that interfaces with the Light Strike Lasertag system using an Arduino Leonardo.
The Light Strike system uses not laser but regular infrared signals. According to a site that I found (http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/) it uses 37.8 khz signals. I only found IR-receivers using 37.9 or 38 khz. Can I use them? How far can the modulation frequency differ?
Is there anything else I need to watch out for when creating an IR-interface?

That's more than close enough. See http://electronics.stackexchange.com/questions/84327/universal-ir-receiver-for-tv-remotes. But note that the frequency being sent may vary from one gun to the next. So your may be different from the one that was tested in that article.

Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?

Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)

I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.


text:
XL335B accelerometer reports false readings
I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.
Code:
const float CYCLE_LENGHT_MILLIS = 1000;

// REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
// => VOLTAGE_STEP 0.0048828125
// MAX_ACC_VOLTAGE 3.3
// => MAX_ACC_VOLTAGE_STEP 675.84
// MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
// => MIN_ACC_VOLTAGE_STEP 337.92
// MAX_ACC_MEASUREMENT 29.43 = 3g

// acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
//This can be simplified to: acceleration = read()*j - k
// => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
// => k = MIN_ACC_VOLTAGE_STEP * j

const float j = 29.43/(675.84-337.92);
const float k = 337.92*j;

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

void loop(){
  Serial.print("(");
  Serial.print(analogRead(0) * j - k);  //X-AXIS
  Serial.print("|");
  Serial.print(analogRead(1) * j - k);  //Y-AXIS
  Serial.print("|");
  Serial.print(analogRead(2) * j - k);  //Z-AXIS
  Serial.println(")");
  delay(CYCLE_LENGHT_MILLIS);
}

Shouldn't it be (analogRead(0) - k) * j?

Not as far as I know. Tested it anyways, it returns (26.53|26.44|21.04).

I've edited my post to add what j and k are. I won't post the reasoning that brought me to acc = read()*j - k here because I would be throwing readability out the window. I'll look into posting it somewhere else in a more organized fashion.

You are assuming here that 3g will result in the maximum voltage of 3.3v. This is not correct. The datasheet says it's 0.3v/g so; 0g-voltage + 3 x 0.3v => 1.65 + 3*0.3 = 2.55volt. Try (analogRead(0)-337.92)/61.44 (337.92 is the 0g voltage in steps; 61.44 is 0.3V is steps)

Now it's returning (-0.06|-0.10|-1.09). What am I missing?

Sorry. That is for g's. So just multiply by 9.81 to get acceleration or whatever that's called. (analogRead(0)-337.92)/61.44*9.81

@Gerben Thanks for your help. If you post your comments as an answer, I'll mark it as the correct one. BTW, is it normal for the IC to be so imprecise? I mean, (-0.63|-0.47|-10.53) when IRL it's (0, 0, -9.81) is not exactly amazing.

You are assuming here that 3g will result in the maximum voltage of 3.3v. This is not correct. The datasheet says it's 0.3v/g so; 0g-voltage + 3 x 0.3v => 1.65 + 3*0.3 = 2.55volt.
To get the g value use (analogRead(0)-337.92)/61.44 (337.92 is the 0g voltage in steps; 61.44 is 0.3V is steps).
To get the acceleration is m/s² just multiply by 9.81; so (analogRead(0)-337.92)/61.44*9.81
Like you stated in the comments, the result isn't that accurate. Just have a look at the datasheet. e.g. Volt per G is typically 300, but can be anything from 270 to 330. Same thing goes for the 0g voltage; 1.35V to 1.65V. So quite a bit of difference can occur between one chip and the next. Even between the 3 axis inside one chip.
So the best thing is to calibrate all 3 axis. For the Z axis; just lay the sensor flat, and get the analogRead value (-1g value). Flip the sensor upside down and get the analogRead value (+1g value). Optionally place the sensor on it's side to get 0g value or just calculate the value in the middle of the above two value. The steps-per-g will be the difference between the two divided by 2 (+1g - -1g = 2g). Put this value and the 0g step-value into the formula. Repeat the procedure for the other 2 axis.

An effective but yet simple calibration is explained in https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-ii-simple-methods/

We need to find the 0G mark and the sensitivity on each axis.  Call them m_x, delta_x, m_y, delta_y, m_z, and delta_z (e.g. m_z is the zero-G mark or the “middle” on the z-axis, delta_z is the sensitivity on the z-axis).  That makes 6 numbers,  so we should expect to need at least 6 measurements.

Check also the more accurate setup: https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-iii-improving-accuracy-with-least-squares-and-the-gauss-newton-method/

Least-Squares
Here is the idea.  We’ve been assuming that there are just six numbers we need to find to get a good calibration: m_x, m_y, m_z, delta_x, delta_y, and delta_z.   Now matter how we place our sensor before we take readings, we assume it is still and is detecting exactly 1G of acceleration in some direction.
So if we read value x on the X-pin, y on the Y-pin, and z on the Z-pin we can look at the acceleration vector
If our measurements have no noise and our parameters are correct, the length of this vector should be exactly 1 no matter which way it is pointing


text:
Count RISING edges of a wave form by using ARDUINO
I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V.
So I have in output a square wave (5V - 0V).
I would like to count how many times I press the button, by using an Arduino MEGA AT2560.
I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times.
For example: I press the button 5 times, but the counter has arrived to 30!
#include <SD.h>
#include <SPI.h>

unsigned int count_hall_f = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, interrFront, RISING); //18
}

void loop(){

}

void interrFront() {
  count_hall_f++;
  Serial.println(count_hall_f);
}

An example of the result is:
1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16

Research a technique called debouncing.

Yeah, I've used a RC filter and it does work. I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

Example schematic:

Results on input pin:

(Maths supporting that figure on the above page).

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.

Simple way to do it: since the first interrupt, wait a pre-determined amount of time (depends on the button you use, could be 100us to few tens of ms) and check again that the value is what triggered the interrupt.
This will kill the effect of the mechanical bounces.
You can even disable interrupts during the delay.
There are much more sophisticated way to do it, but this should be good enough to get you started on the way to debounce your inputs.


text:
Programming "Arduino" code to AT90S8515?
I found (from a previous life) an STK500 and a couple AT90S8515's in the recesses of my basement..  that I would like to put to use.
Is there a way in which I can write "arduino code" for the 8515?  I know that it's basically C/C++.
I also know that the 8515 doesn't have, or support, a bootloader like the Mega series of ICs do..  so I expect that I will need to program it using the STK500.
I downloaded AVR Studio, but I will admit, I became very lost, very quickly.
Thanks for any direction!

Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).

In Atmel Studio 7 you can create a project on Arduino Code.
For instance if you have a code for an Arduino UNO, it will ask for path of the sketch(a.ino file) and ask for device here it will be Atmega 328.
Now you can build the solution and it will generate code for Atmega 328.
Now you can rebuild the same solution by changing the device now select  AT90S8515.
In my case I built the code for a Atmega328. then rebuilt it by changing device to Atmega8. It worked


text:
Is there any problem about calling if (Serial) many times?
I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:
#define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }

That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.
if I change that by this the problem is gone:
#define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
#define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }

I'm using Arduino Pro Micro (Leonardo).
Is there any problem about calling if (Serial) so many times?
Full sketch here

There is no problem, no, but yes it will slow you down.
This is the source code to the boolean operator for the Serial constructor for CDC:
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

As you can see from that all it does is check the value of a variable.  However it also imposes a 10ms delay¹.  Personally I'd have written it as:
Serial_::operator bool() {
    return (_usbLineInfo.lineState > 0);
}

And on top of that I'd have made it inline.
You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².
Edit: I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the delay(10) when it is actually needed rather than at every call to the bool operator regardless of need.

https://github.com/arduino/Arduino/pull/3624

¹ This is done to allow the port to complete opening at the PC end before data is allowed to be sent.  A better system would only perform the delay() at the moment of port opening rather than every call to the operator.
² Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message.  A better system is in the pull request mentioned in the edit to this answer.

However, if the check is false it imposes a 10ms delay. - it always imposes a 10 ms delay.

@NickGammon That's true.  I misread "result = " as "return".  Easily done.

Maybe someone else can come up with a reason for having that delay in there because I sure as hell can't. - I suspect that they expect it to be called once (as per the usual examples of doing it after Serial.begin()) and they found by testing that if it only just became ready you might miss a character or two, so they threw in a delay as well. Or maybe they are trying to not lock up the CPU in a tight loop, in which case an else might have been handy. It's hard to know what they were thinking.

delay() is a tight loop, so that kind of negates your second point.  As for your first I for one am always in the habit (when used in setup) of adding my own delay.  Note that other systems (like chipKIT) don't impose that 10ms delay on you since it really is pointless.

Good point about the delay. :) Yes, it's not like the processor is asleep or anything. It must be my first point then.

There is a comment in the code right before Serial_::operator bool(): “We add a short delay before returning to fix a bug observed by Federico where the port is configured (lineState != 0) but not quite opened.”

@EdgarBonet Then they should be doing it more intelligently - i.e., only impose the delay when the line state transitions from == 0 to > 0 rather than every time the function is called regardless.

@EdgarBonet I have submitted a pull request with a better system for monitoring the line state to the Arduino repository: https://github.com/arduino/Arduino/pull/3624

The real flaw is testing if Serial is available all the time. For one thing, that wouldn't work on a Uno etc. How about something like this?
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); while (!Serial) { } } while (0)
  #define Trace(x)      Serial.print   (x)
  #define Trace2(x,y)   Serial.print   (x,y)
  #define Traceln(x)    Serial.println (x)
  #define Traceln2(x,y) Serial.println (x,y)
  #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

That only does the Serial.begin() once, and the test for waiting for Serial to become available once.
Then, depending on the DEBUG define, the debugging code is executed or not. The fancy ((void) 0) calls get optimized away completely by the compiler if DEBUG is false, thus making them have no effect if debugging is off (which wouldn't apply to your code).

(Edited to add)

As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

Well it wasn't immediately obvious from your code. In that case I suggest you test in the main loop function every second or so, to see if Serial is true. If so, set a flag. Test that flag in your debug function. That way you aren't slowing down every single Serial.print by 10 ms.
Like this amended code:
// make true to debug, false to not
#define DEBUG true

// conditional debugging
#if DEBUG

  #define beginDebug()  do { Serial.begin (115200); } while (0)
  #define Trace(x)      do { if (serialConnected) Serial.print   (x); }     while (0)
  #define Trace2(x,y)   do { if (serialConnected) Serial.print   (x, y); }  while (0)
  #define Traceln(x)    do { if (serialConnected) Serial.println (x); }     while (0)
  #define Traceln2(x,y) do { if (serialConnected) Serial.println (x, y); }  while (0)
  #define TraceFunc()   do { if (serialConnected) { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__);} } while (0)

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

const byte LED = 13;

bool serialConnected;
unsigned long timeSerialLastTested;

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced debugging!"));
  TraceFunc ();  // show current function name

  pinMode (LED, OUTPUT);
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  // every second, see if the Serial port is available
  if (millis () - timeSerialLastTested >= 1000)
    {
    timeSerialLastTested = millis ();
    serialConnected = Serial;
    digitalWrite (LED, !digitalRead (LED));  // blink LED
    }

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

You might have mentioned that. Intentions aren't always obvious from code. See amended reply above.

That helps on the delay but I think it does not work. Maybe Windows 10 reports the port to be open all the time or something. I'll have to put on a led or something to tell me when Serial reports true.

Honestly, I think trying to see if you are connected is not a particularly good idea. If you want to debug some of the time, have a switch you can press if you want to turn it on.


text:
Send numbers to arduino via serial port using python
I have a file with numbers called fginputs.txt. For example it could be something like this:
4958
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4154
4958

I want python to send each number to arduino via serial port. After each number is received, arduino should print back an acknowledgment number, indicating that it got a valid number, and then store that number in a dynamic array, because I could create larger files. When there are no more numbers left, send a '-1' to finish transmission.
Here's my arduino code:
// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);
 //counter for how many numbers I've received starts at 0
 cont = 0;
 //This is true when there are no more numbers to receive, meanwhile false
 inputsReady = false;
 setupInputList();
 }

/* If there's not enough space, resize the array by one unit and store the number
   */
void growAndInsert(int currentSize, int newInt){
    if(currentSize > SIZE)
        inputList = (uint16_t *)realloc(inputList, (currentSize + 1)*sizeof(uint16_t));
    inputList[currentSize] = newInt;
}
/**
  init inputList with 100 blocks
 */
void setupInputList(){
  SIZE = 10;
  inputList = (uint16_t *)malloc(sizeof(uint16_t) * SIZE);
}

void clearBuffer(){
while(Serial.available() > 0)
    Serial.read();
}

/**
Listens in serial port for an integer that represents a new input and returns it.
If it doesn't get anything useful from serial, return 0
*/
  int getNewInputFromSerial(){
   if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

    if(cmd == 4958)
        Serial.write("4");
    else if(cmd == 4154)
        Serial.write("5");
    else
        Serial.write("0");
    return cmd;
   }
  return 0;

}

void loop()
{
     if(!inputsReady){
        int newInput = getNewInputFromSerial();
        if(newInput == 0)
            return;
        if(newInput != -1)
            growAndInsert(cont++, newInput);
        else{
            inputsReady = true;
            //initTimer();
        }
    }

}

and the python script:
global arduino
PORT = '/dev/ttyACM0'
FILENAME = "fginputs.txt"
#Read file with inputs
with open(FILENAME) as f:
        content = f.readlines()
#init serial port
arduino = serial.Serial(PORT, 9600, timeout=1);
time.sleep(2);

#write
for input in content:
    arduino.flush()
    arduino.write(input)
    time.sleep(.1);
    resp = arduino.read();
    print "i got " + resp

#Finish transmission with -1
arduino.flush()
arduino.write("-1")
#done
arduino.close();

The fist time I execute the script I get this:
i got 4
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 5
i got 4

Which is great. But if I run it a second time I get this:
i got 0
i got 4
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0
i got 0

Which is terribly wrong because the file hasn't changed. I don't know what is going on here. If I unplug and plug back in the USB cable, transmission works flawlessly again.

// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);

You are freeing a NULL pointer which is an undefined operation not necessary here, since it was never allocated.

  if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

This is going to just throw data away, I'm not surprised stuff goes missing.
Read this: How to process incoming serial data without blocking - you need to get rid of the delay, and the clearBuffer() for a start.

Example code for reading from Serial without blocking and without using delay:
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

In process_data in my example is where you would call atoi to convert the incoming string into an int (or atol if it is going to be longer).

free(NULL) is ok; per man malloc re  void free(void *ptr),  “If ptr is NULL, no operation is performed.”

Ach, you are right. Still, a pointless thing to do in setup. Post amended.

You could have a look at this.
It's a python program which does record/playback of key-presses, through an UNO.
It already implements:

serial communication with error checking
ACK: each message has its own ID, so you can keep track of what was lost, should anything bad happen
synchronization, in case your Arduino is powered up after the python program is started

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


text:
What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo?
My question is related to this one. My sketch seems to stop responding after some time if I run it with debug enabled and I don't open the serial port/monitor on the computer.
Does the UART buffer fill up and block or something? Or, does it discard the excess data and keep working?
I can't find information about it.

In the avr hardware serial implementation, a write/print command will block until there is room if the buffer is full. My guess is that USB serial would act the same.

In your other thread I suggest a way of testing the Serial port periodically to see if it is available.

As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.
size_t Serial_::write(const uint8_t *buffer, size_t size)
{
    /* only try to send bytes if the high-level CDC connection itself
     is open (not just the pipe) - the OS should set lineState when the port
     is opened and clear lineState when the port is closed.
     bytes sent before the user opens the connection or after
     the connection is closed are lost - just like with a UART. */

    // TODO - ZE - check behavior on different OSes and test what happens if an
    // open connection isn't broken cleanly (cable is yanked out, host dies
    // or locks up, or host virtual serial port hangs)
    if (_usbLineInfo.lineState > 0) {
        int r = USB_Send(CDC_TX,buffer,size);
        if (r > 0) {
            return r;
        } else {
            setWriteError();
            return 0;
        }
    }
    setWriteError();
    return 0;
}

This is the same test as is done in operator bool() without the 10 ms delay.
// This operator is a convenient way for a sketch to check whether the
// port has actually been configured and opened by the host (as opposed
// to just being connected to the host).  It can be used, for example, in
// setup() before printing to ensure that an application on the host is
// actually ready to receive and display the data.
// We add a short delay before returning to fix a bug observed by Federico
// where the port is configured (lineState != 0) but not quite opened.
Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

Judging by the comments above, this may not be the most reliable thing in the world.

The whole CDC/ACM system has a fundamental flaw in that there is no way of knowing if the port has been opened - you can only examine the line states (DTR and RTS) to see if something the other end has asserted those lines.  On some operating systems those lines are asserted by default (though that behaviour can be disabled) and on other operating systems it's left to the whim of the software that opens the port. The whole arrangement is very hit-and-miss, and it's for precisely that reason that FTDI developed their own proprietary protocol instead of using CDC/ACM.

At least on Windows 10 Serial starts to return 'true' when the COM port is open and keeps returning 'true' no matter you open or close it. So if you close it the output buffer may full up and block forever on write calls. I gave it other power source and now I can see disconnecting the USB cable makes Serial to return 'false' and connecting it back and opening the COM port again makes it 'true' again.

@Majenko How can I examine the DTR of Serial on Arduino Pro Micro?

@aalku if (Serial) - that's what it does.  It examines the control line states. But of course it's down to the remote end as to what that actually means.

@Majenko Well, you can't trust it. At least on Windows 10. If DTR is signaled write should not block as far as I know, and it does. That can't happen in a hardware serial port. You write and if the other end can't listen the data is lost.


text:
Power saving of atmega 2560
Is arduino code Consume More power other than "Avr Studio" Code?
Please tell some key points for power saving.
Processor on $ off Methodology.

Processor on $ off Methodology. - not sure what you mean by that.

There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.
Read Power saving techniques for microprocessors for a considerable number of tips about saving power.
Also see related threads about this question such as What are (or how do I use) the power saving options of the Arduino to extend battery life?


text:
What requirements should components have to work with Arduino (UNO in particular)
I am fairly new to the whole concept of Arduino and electronic engineering in general.
Recently I bought myself an Arduino UNO and I'm wondering what "non off the shelf" components will work when I hook them up with the UNO. I have a lot  of old electronic stuff laying around containing pushbuttons, sliders, faders, knobs etc. wich if possible, I'd like to take apart to connect them to the UNO for some fun fuzzin' around.
Many thanks in advance!
PS: this is my fist post ever on stackexchange so excuse me if the question is placed incorrectly or the tags are weird. Please DO correct me where I'm wrong.

When it comes to electronics, hypothetically anything can be connected to anything else. The only real barriers are time, cost, and practicality.
Two major things to look out for though are voltage and current requirements.
Most Arduinos operate at 5 volts, so it's often easiest to connect it to other electronic devices which also operate at 5 volts. That certainly doesn't mean you can't connect an Arduino to something that operates at 3.3 volts (for example). However, it means you may need to add some voltage level conversion circuitry (although it's not always necessary, depending on the context).
Regarding current, a critical issue to look out for is how much current something will draw. For example, a motor will often require more current than an Arduino can safely provide. That means you'd need some kind of external power supply which can be switched by the Arduino.
The most valuable thing to do is to learn to find and read datasheets. These give information about electronic components, specifying things like voltage, current, timing and so on. For situations where there's no datasheet available, you may find it useful to learn how to use a multimeter and an oscilloscope to monitor how equipment behaves.

Dear Peter, thank you so much. I could not wish for a better answer.


text:
Arduino Ethernet Shield Response Process, Time, and Synchronization
I have a ethenet shield. I want to update my server page. Server page have to show current time. The code is given in this link. Code works but there is two problem
1- When i press the stop button in the browser, Arduino stops. After this i press refresh button and there is no response.
2- How can i synchronize the arduino time. From where? without setup another server. Is there any time stamp server that compatible with arduino?

Question 1.
Your code looks odd:
void checkForClient(){

  EthernetClient client = server.available();

  if (client) {
    boolean sentHeader = false;
    while (client.connected()) {
      if (client.available()) {
        if(!sentHeader){
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          sentHeader = true;
        }
        durumBildir(client,50,ID);
      }
    }
  }
  delay(1); // give the web browser time to receive the data

}

void durumBildir(EthernetClient client, int deger,String ID){
  client.print(ID);
  client.print("-");
  client.print(deger);
  client.print("-");
  if (timeStatus()!= timeNotSet) {
    digitalClockDisplay( client);
  }

  client.print("<br>");
}

You never read from client, so it will always be available (and thus you never leave your loop). I just tested it. Why are you sending the time out indefinitely? Even when you disconnect the poor Arduino is still sending the date and time out forever. No wonder you can't connect again.

I don't have an answer for question 1.
For question 2:
You can add a function to implement an NTP (network time protocol) client.  For example, see the UdpNtpClient article on arduino.cc.  In your setup() or loop() code call the function initially or perhaps hourly or daily to set system time via an NTP time server.  The server's IP address can be hardcoded or otherwise as you like.
For lists of public time servers, see www.ntp.org and pool.ntp.org.
Alternately, you could add a DS1302 or similar clock chip board to your hardware.


text:
Can I supply the board's 3.3V directly to the AREF pin?
Short dumb question: can I connect the 3.3V pin and the analog reference pin (AREF) directly?
I've heard mentions of a 32K internal resistor but I'm not willing to risk a short circuit without confirmation. Should I add an external resistor? Won't that create a voltage divider?

In Atmel's doc8271 pdf (with specification details for ATmega48A; ATmega48PA; ATmega88A; ATmega88PA; ATmega168A; ATmega168PA; ATmega328; and ATmega328P), table 29-20 on page 117 shows R_REF (the AREF input resistance) as 32KΩ (typical).  Section 24.5.2 on page 248 suggests that AREF is to be treated as a high-impedance input or output:

... the reference voltage can be made more immune to noise by connecting a capacitor between the
  AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that
  VREF is a high impedance source, and only a capacitive load should be connected in a system.

Also note that there is no reason to connect anything to AREF (pin 21), because on a standard Uno, AVCC (pin 20) is connected to VCC (pin 7), and one can select AVCC as the reference voltage during analog converter setup [as explained below].  Quoting again from section 24.5.2:

VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin.  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC...

Summary: you can connect the 3.3V pin and the analog reference pin (AREF) directly, but on a 3.3V system  there is no reason to do so.
Selecting AVCC as the reference voltage:  Say analogReference(DEFAULT) to select AVCC as the reference voltage.  According to arduino.cc, this will choose “the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)”.

I disagree that "there is no good reason to do so". If you are sampling a signal that is 0-3.3V (or below) then connecting AREF to 3.3V gives you the full resolution over the signal range you are sampling instead of only a portion of the resolution.

That's why I wanted to change the reference. I wish there was a way to do it internally. Since I'm using an UNO, the default is 5V.

@Majenko, I edited that section slightly :)

I don't see any big objection to connecting the 3.3 V pin to AREF, providing you take precautions in your code.
The default for AREF is so-called DEFAULT (heh) as here:
uint8_t analog_reference = DEFAULT;

Once you do an analogRead the analogRead code connects up the desired analog reference:
ADMUX = (analog_reference << 6) | (pin & 0x07);

Then it starts the ADC conversion.
If you change the analog reference voltage then this needs to be done before doing the analogRead. eg.
  analogReference (EXTERNAL);
  analogRead (A0);  // use external reference

The reason they do it this way is so that it is safe to physically connect up the 3.3V pin to the AREF pin, because the initial state of the processor is to read the AREF pin.
Once you do your first analogRead, and with the DEFAULT reference voltage used, you will find 5V at the AREF pin. If you had then connected that to something else like the 3.3V pin, it will short out and damage the board.
Example code:
void setup ()
  {
  pinMode (13, OUTPUT);
  delay (5000);
  digitalWrite (13, HIGH);
  int foo = analogRead (0);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Put your meter on AREF and you will see it jump to 5V after 5 seconds.


text:
What is the Vin Pin for?
I always asumed it was a different option to power the board, but it seems to act more like a 5V supply. What then is the difference between this pin and the 5V pin?

This is a classic example of an X-Y problem. You asked about what the Vin pin was for, and got some good answers, but what you really wanted to do (it turned out) was to trigger your camera shutter without using external components. You would get a faster (and better) answer if you state your real goal, rather than omit your goal, and mention what a possible solution might be (read the link for more info). You could always mention, as part of your question, that you wondered if using the Vin pin would help solve your goal. Just for future reference. :)

The Vin pin serves the same purpose as the barrel jack.  The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.
Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.
If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin.  It's not safe to use that power for anything since you could damage the 5V regulator if you do.
The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).

Thanks for your answer. Can I ask, what is the barrel jack and what is its purpose?

The barrel jack is the big round power connector that you plug your power adapter or battery into.

So is it possible to power the Arduino solely from the Vin pin without the usb or barrel jack?

Yes.  That is one of the normal uses for it.

Thanks. At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short. I have connected the 5V wire from the camera to the Vin pin, and the return wire to a digital out pin. This triggers when the digital out pin goes high. Is this an okay way to trigger the camera, or might I damage something?

No that is not an okay usage of the pin. You risk damaging the 5V regulator like that.  For that system you should have an optocoupler with the optotransistor side of it on the camera (use a DMM to find which pin has the higher potential) and the LED side driven by the Arduino.

To answer this added question:

At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short

I certainly would not be using it as a 5V "virtual ground" - whatever that means. The Vin pin could easily be up around the 10V mark, depending on what you plug into the barrel jack.
I had a project a while ago where I wanted to trigger a camera flash. In the same way as you describe, two pins had to be shorted.
I wasn't sure what voltages would be on them, or if there would be a spike, so I used an opto-coupler like this:

You need to identify by measuring with a meter which pin has the positive voltage on it. That would go to the collector of the transistor in the opto-coupler (pin 5 in this particular case).

(edited to add)

I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

We can probably assume that the current will be low, after all they wouldn't short out the camera's battery through that pin. Put your meter in current mode across the camera's pin and measure the current when the pin is shorted (ie. the meter will short it).
If it is 20 mA or less then the Arduino digital pin can handle that. I imagine it will be a steady flow of current. I just measured my flash shoe with that method, and it seems to use a tiny fraction of current (0.1 mA).
So that should be safe, safer than your method with Vin anyway.

Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires.

Sounds complex. Just make the pin LOW, and make it output to fire it. eg.
In setup:
digitalWrite (cameraPin, LOW);  // default will be INPUT mode

To activate camera:
pinMode (cameraPin, OUTPUT);  // drive low
delay (500);  // or whatever
pinMode (cameraPin, INPUT);   // make high impedance

Make sure you measure the pin and get the correct polarity. You want the positive side to go to the Arduino pin, and the negative side to Ground.
And make sure it isn't higher than 5V. (Use voltage mode on the meter to check that).

Thanks for your suggestion. Unfortunately I cannot add any external components, otherwise an optocoupler would have been perfect. I have been given a suggestion on Electronics stack exchange to connect the camera 5V wire to a digital in pin, and the other camera wire to ground. Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires. I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

See amended post with more details about that.

+1 also for answering the real question.

I like the way someone explained Vin to me. "Whatever power source you connect to the DC Jack is supplied there, be it 12v or lesser"


text:
What's Wrong with this DHT22?
I made a circuit that takes humidity and temperature from DHT22 sensor and displays it on Lcd Screen. Simple enough but i get this error "Failed to read from DHT". That happens because i have this code
 if (isnan(t) || isnan(h)) {
  delay(100);
    Serial.println("Failed to read from DHT");
  } else {
    delay(100);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C");
    //lcd.print("Temp: ") ;
    //lcd.print(t);
    //lcd.setCursor(0, 1);
    //lcd.print("Hum: ") ;
    //lcd.print(h);
  }

So the values are NaN . But 1 minute before it worked fine, and now again it doesnt. Everything is soldered the right way and nothing is false. Lcd is wired ok and it works but i dont get values from DHT22.
Here are some pics to help you out.

In the third Image we see its working. And now its not!
is the DHT sensor broken?
  #include "DHT.h"
#include <LiquidCrystal.h>`

#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHT22 test!");
  lcd.begin(16, 2)
  dht.begin();
}

void loop() {

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(t) || isnan(h)) {
    Serial.println("Failed to read from DHT");
  } else {

    lcd.print("Hum: ");
    lcd.print(h);
    lcd.setCursor(0, 1);

    lcd.print("Temp: ");
    lcd.print(t);

  }
}

Thats my code by the way

What lib are you using? Can you post your setup code also?

#include "DHT.h"
#include <LiquidCrystal.h>
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHT22 test!");
lcd.begin(16, 2)
dht.begin();
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT");
} else {
lcd.print("Hum: ");
lcd.print(h);
lcd.setCursor(0, 1);

lcd.print("Temp: ");
lcd.print(t);

}
}`

Please amend your question to post the code. Putting it in a comment is pretty-much unreadable.

@NickGammon  done

I can't see a resistor in your photo (maybe it is hidden). There should be a 10 k pull-up from pin 2 to 5V (that is, between pin 2 and pin 1). Do you have that?

@NickGammon no and I guess I don't need that.  Lcd works fine

I always use Adafruit_Sensor and DHT - have you tried that?

Two things:

You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so.
Add a 10k resistor between pin 1 and 2 of the DHT.

I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up.

Where should I put resistor

Solder between pin 1 and 2 on DHT. Google image it. It's a very common question.


text:
MCP23017: 16x2 LCD showing black boxes
I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html
and after using the Library LIQUIDTWI2:
(https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing)
for I2C connections, the LCD keeps displaying black boxes on the top row.
I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?
I'm using an Arduino UNO

Have you wired up the contrast adjustment pot? If contrast is wrong you can see black boxes.

No pin 3 is not connected with a POT. I connected pin 3 of the LCD right to the ground and I dont think that it is a problem with the contrast

@NickGammon is contrast is set wrong, either no boxes appear (too low), or boxes appear on both the top and the bottom row (too high).

CrazyBacon did not say specifically that there were no black boxes on the bottom row.

after properly following all steps - photo perhaps?

Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).
So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).
If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.

Thanks. For some reason after resetting the Arduino and attaching a POT to the LCD it started working