text:
Arduino Pro Micro, get data out of Tx pin?
I have a Sparkfun Arduino Pro Micro with an ATmega32u4 on it and a Roving Networks RN32 Bluetooth Module
Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.
Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?
I uploaded this to the Arduino with no hiccups:

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

void loop(){
  Serial.print("HelloWurld");
}

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.
How do I get the Arduino to put out serial data on the Tx pin?

Do you have it powered?

And is the ground on the scope connected to the Arduino's ground?

Yes, it has the +5v in and the scope is on the arduino's gnd pin. How do I push serial data over the TX (digital0) pin? I know it's a code issue

Your code seems fine

Thank you, but we are both wrong then. When I put this code on the arduino and then probe the TX pin (digital 0), I see nothing at all, it's just flat. However, on my serialport program on my windoes machine, I see the helloWurld message. I DO NOT CARE about the serialport program for now. I need to data to come out of the TX pin, NOT the USB. Does that make sense?

Have you tried pin 1?

That is the RX pin, and yes, I have tried every pin to see the outputs. All pins on the board are silent, the pins on the chip are far too small to probe, let alone solder to.

I do not have anything coming out of the TX pin. The scope is set up just fine. I am able to have the TX pin go from +5 to 0 with no problems as a sanity check. It takes about 2ms to switch in the arduino loop call. Here is the code:void setup(){      Serial.begin(9600);     pinMode(5,OUTPUT); } void loop(){     Serial.print("HelloWurld");     analogWrite(0,1);     analogWrite(0,0); } This is just gravy for pulsing the TX pin. By digital header, do you mean the pins on the side of the board, or the pins on the atmega chip itself? Thank you very much for your assistance, i do appreciate it.

Ah, this may be where confusion is coming from. This is NOT a stock UNO, this is a SparkFun board that behaves as one. I am trying to talk to SparkFun for help too. To your comment: Do you mean the ATMEGA chip's TX line then? I am trying to understand how I can have data coming out of the TX pin, not see the 5V swing, and then also have the USB transmit data to my computer. I'm sorry, I really just don't get it. Thank you very much for your help.

 Just wanted to leave full pinout..

You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos.   Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question).
According to the documentation for the official Arduino Pro Micro:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of Serial to Serial1
void setup(){
    Serial1.begin(9600);
}

void loop(){
    Serial1.print("HelloWurld");
}

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers.  If you wish to probe it, that would be the best place to do so.
If you wish to transmit data out of a different pin which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use SoftwareSerial or similar implementation to bit-bang the serial data out of a general purpose I/O pin.
For example (inspired by this example):
SoftwareSerial mySerial(4, 5); // RX, TX

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

void loop(){
    mySerial.print("HelloWurld");
}

Well spotted, Chris! +1

oh my days... as an arduino noob this distinction between ATmeta32u4 and ATmega328 is mind bending... took me three days to figure out... fact that I was trying same code on ATmega328 code on the 32u4 didn't help. A million thanks Chris Stratton.

The bluetooth board uses 3.3V, not 5V according the datasheet.
So you'll need to shift the voltage level between it and the Arduino board (which is 5V). Note that the spec sheet shows how this can easily be done with 2 resistors (R1 and R2 in sheet typical application circuit, page 5).
Also, on the bluetooth module, the RS232 interface has 4 pins:

UART_TX
UART_RX
UART_CTS
UART_RTS

UART_CTS must be 0 to ensure the device reads incoming bytes. Normally this is done by an internal pulldown resistor, but you must ensure you did not connect that pin to +V.
Finally, ensure that the baud rate of the module is properly set to 9600 bauds, the same as in your program.

I am aware of all this, thank you still the same. However, my issue is much more basic. I need to get data out of the TX pin so that I can hook the bluetooth into that. If I can't get data out of a pin on the Arduino board, the bluetooth is useless. How do I get serial data out of the arduino board? The USB pins are sending out serial data just fine, but I cannot get other pins to output data. Do I need to solder to the USB pins in order to get data into the Bluetooth? Thank you very much for any help, I do appreciate it a ton

So I stumbled upon this thread while having similar problem, but with HC-05 module. So because I have too much free time on my hands during finals (no I don't) I decided to create a small github repo that might help someone sometime. https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup
The code is:
//Writen for pro micro
//These proved to be usefull
//http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin
//https://forum.sparkfun.com/viewtopic.php?f=32&t=38889&sid=8178cdb38005ff33cc380a5da34fb583&start=15

void setup()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial1.begin(38400);
}

void loop()
{

  //Serial1 is the physical Serial Connections on TX and RX pins
  if (Serial1.available()) Serial.write(Serial1.read());

  // Serial is from my understanding the virtual connection with computer via USB
  if (Serial.available()) Serial1.write(Serial.read());
}

Nice use of Serial and Serial1.  I posted an edit with your code and diagram.

Just hook up the serial pins from the bluetooth module to the corresponding Pro Micro pins: TX to RX and RX to TX. I hope this can help someone.
Then look for data like this:
void setup(){
   Serial1.begin(9600); // Init Hardware Serial port on pins 0 and 1 - Bluetooth
   Serial.begin(9600); // Init Virtual Serial Port - Machine

   Keyboard.begin(); // Init HID - Keyboard
}

void loop(){
   if (Serial1.available() > 0) {

     char myData = Serial1.read()

     // Send data from Bluetooth/Sensor to the Machine - Virtual Serial Port
     Serial.println(myData);

     // Emulate HID Device - Keyboard
     if ( myData == 0x7F ) { // Detect code of android backspace key
        Keyboard.write(0xB2); //  Convert received code char to PC/Linux ascii keycode for the backspace key. This can change between different OS!
     }

     else {
        Keyboard.write(myData);
     }

   }
}

You also may want to try the "SoftwareSerial" library.  That way you can use almost any pins you want for serial comms.  As a matter of fact, you can have a couple of serial ports.
Please do read up on the SoftwareSerial library though.  It does have some restrictions.

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


text:
Can I load programs through the RS232 pins?
Can I upload new programs onto a MEGA2560 through a serial port connected to pins 2&3?  (through the correct RS232<->TTL level shifters)
I know the 16U2 chip acts as a USB->serial converter and it also asserting the reset which starts the bootloader running on the 2650. Does it do anything else?
As long as I can time the reset correctly, is there anything else preventing reprogramming directly through the RX/TX pins?
And if I do this, will the application program still be able to use the serial channel?

If there are resistors between the 16U2 and the 2560 then likely yes that may give you an opportunity to "overcome" the 16U2's transmit line, though reset timing may be tricky unless you graft in a way to drive that as well.

I'm actually looking at making a clone which wouldn't even have the 16U2.  I'd probably tie serial DTR to a reset circuit like the one the 16U2 is driving.

Then yes, you can just place a header for an FT232 header or similar, as the minimal interfaceless '328 boards do.

The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.
There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in).
Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.
I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6).

Great.  I was thinking of pins 2 and 3 on the 2560 chip - Thanks for pointing  out that's it's D0 and D1 in the Arduino labeling scheme.

source: Stack Exchange

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

sort: votes


text:
Setting up the MMA8452 to trigger interrupt
I am working with the MMA8452q accelerometer by Freescale.  I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the  interrupt that corresponds to it.  I am using Arduino.
I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer).  However, after initializing using the code below, my interrupt due to motion is not getting triggered.
-The datasheet can be found here: http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf
-App note can be found here: http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf
My code is as follows:
void MMA8452::initMMA8452(unsigned char fsr)
{
    //CONFIGURE THE ACCELEROMETER
    MMA8452Standby();  // Must be in standby to change registers

    //Set up the full scale range to 2, 4, or 8g.
    if ((fsr==2)||(fsr==4)||(fsr==8))
        writeRegister(XYZ_DATA_CFG, fsr >> 2);
    else
        writeRegister(XYZ_DATA_CFG, 0);

    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56);  //1.56Hz resolution in both wake and sleep mode (lowest power)
    writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING

    writeRegister(CTRL_REG3, (1 << WAKE_FF_MT));        //ONLY WAKE UP FROM MOTION DETECTION
    writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT));  //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
    writeRegister(ASLP_COUNT, ASLP_TIMEOUT);    //162s TIMEOUT BEFORE SLEEPING

    writeRegister(CTRL_REG5, (1 << INT_CFG_FF_MT) | (1 << INT_CFG_ASLP));  //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452

    //SETUP THE MOTION DETECTION
    writeRegister(FF_MT_CFG, (1 << ELE) | (1 << OAE));      //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME
    writeRegister(FF_MT_THS, MOTION_THRESHOLD);             //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT);      //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
};

I played around more with it, and this code works:
void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
{
    MMA8452Standby();

//Set up the full scale range to 2, 4, or 8g.
if ((fsr==2)||(fsr==4)||(fsr==8))
    writeRegister(XYZ_DATA_CFG, fsr >> 2);
else
    writeRegister(XYZ_DATA_CFG, 0);

writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
if (dr<= 7)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
if (sr<=3)
    writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));

writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
writeRegister(ASLP_COUNT, sc);

// Set up interrupt 1 and 2: 1 = wake ups, 2 = data
writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL));  // Active high, push-pull interrupts, sleep wake up from motion detection
writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) |  (1 << INT_EN_DRDY));  // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT));  // DRDY on INT1, ASLP_WAKE INT2, FF INT2
writeRegister(CTRL_REG5, readRegister(CTRL_REG5));

//SETUP THE MOTION DETECTION
writeRegister(FF_MT_CFG, 0xF8);     /*MOTION DETECTION AND LATCH THE
                                    //RESULT WHEN IT HAPPENS AS OPPOSED
                                    //TO COMBINATIONAL REAL TIME*/
    writeRegister(FF_MT_THS, mt);       //MOTION DETECTION THRESHOLDS
    writeRegister(FF_MT_COUNT, mdc);    //TIME MOTION NEEDS TO BE
                                        //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

    MMA8452Active();
}

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


text:
Reset an Arduino Uno in code
Is it possible to reset an Arduino (i.e., to reboot it) from code (i.e from the sketch itself)? I know that is possible with a special circuit but is there a chance to make it just with code?
Below is my code and the comment //reset is where I want to force a reset.
#include <TrueRandom.h>

int i;
int randSeed;
long randNumber;

void setup(){
  Serial.begin(9600);
  Serial.println("20 pseudo Zufallszahlen:");
  for (i=1;i<=20;i++) Serial.print(random(10));
  Serial.println();
  Serial.println();
  //randomSeed(TrueRandom.random());
  randSeed = analogRead (A0);
  randomSeed(randSeed);
  Serial.print("Der 'seed' Wert: ");
  Serial.println(randSeed);
  Serial.println();
  Serial.println("20 Zufallszahlen mit analogem 'seed' Wert:");
  for (i=1;i<=20;i++) Serial.print(random(10));
  Serial.println();
  Serial.println("---------------------------");
  Serial.println();
  delay(500);
  //reset
}

void loop() {
}

I want to reset the micro-controller at the end of the setup function to show the effect of random numbers with and without a seed.

There three ways to accomplish this. (last is my favorite)
1) Jumper an unused IO to the RESET pin. Leave it as INPUT for normal
    run, As it is externally pulled high. And when desired to reset set
    it as LOW and Output. (bang its rebooting).
setup() {
  ...
  pinMode(PINtoRESET, INPUT);    // Just to be clear, as default is INPUT. Not really needed.
  digitalWrite(PINtoRESET, LOW); // Prime it, but does not actually set output.
  ...                            // Does disable 10K pull Up, but who cares.

then when desired...
...
  pinMode(PINtoRESET, OUTPUT);   // lights out. Assuming it is jumper-ed correctly.
  while(1);                      // never gets here.

2) Jump to beginning of the code.
void(* resetFunc) (void) = 0;  // declare reset fuction at address 0
...
resetFunc(); //call reset

But be careful, this does not perform a true reset, in that all the registers ARE NOT DEFAULTED. Rather they and the IO are left as is. Where somethings from the bootloader and then the heap will be initialized. And reset are not!
3) Use the watchdog. The SoftReset library makes it easy. Although it is not difficult to implement directly. Shown below..
#include <avr/wdt.h>
...
setup() {
  ...
  MCUSR = 0;  // clear out any flags of prior resets.
  ...

then when desired...
...
wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
for(;;) {
  // do nothing and wait for the eventual...
}
...

From everything I've read, the first option is not recommended. Options 2 and 3 are fine.

@sachleen: Please say more about that (opt-1).

Option 1. or a variant can be a clean enough way to do this as long as power on transient conditions are designed for.

@RussellMcMahon - How does one design for the Power on transient conditions?

It should be noted that option 2 does not run the bootloader.

Wouldn't calling resetFunc() not reset the stack? So calling it repeatedly would overflow the stack.

Option 1 is not recommended by the chip designer, Atmel. They do not recommend performing a reset with the chip's pins.

Option 3 works only with bootloaders that have WDT enabled. It puts board into reset loop otherwise.

Option 2 executes the same code that runs when you do a hardware reset or a power-up: the chip always begins at address 0.

Option 2 should be edited to add the fact that not every chip begins at address 0. A pointer to the function to be called should be used instead
void(* resetFunc) (void) = &setup; (in this case setup should be called to begin again, or even main if it makes sense)
I just had the case with stm32 where it begins later in the memory.

Option 2 is a null pointer assignment of a function pointer that actually points to nothing when calling the function. Calling this is illegal, cause a null pointer exception and without exception handling results in a reboot. That is a dirty trick and unreliable to recommend. For all believers, the pointer is a pointer to a VOLATILE memory location, not a program memory (flash) location. @Dardanboy, calling setup() is not a reset and yes all memory start at location 0 however it could be possible not all lower memory is accessible

@Codebeat Nope, this is an actual valid memory address in the program flash, where the embedded program begins.

@DmitryGrigoryev Nope, it is a valid offset you can jump to, not a valid address. Do not confuse these two.

I'm laughing at the comment, "lights out" — thanks. Wish I had a spare I/O pin.

In case you have the original Arduino bootloader which you want to execute as a part of the reset, you can do a SW reset by jumping to the bootloader reset address (0x7800 on ATmega328p boards)
void reset() { asm volatile ("jmp 0x7800"); }

The watchdog reset approach will not work because of a bug in the bootloader. Here's a note from ATmega328P Datasheet page 45:

Note: If the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. If the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the watchdog system reset flag (WDRF) and the WDE control bit in the initialization routine, even if the watchdog is not in use.

This is exactly what will happen after a watchdog reset on a system with Arduino bootloader.

Yes, I have observed the eternal loop of timeouts, while answering the question, "I wonder if the boot loader resets the WDT" Why not just do "jump 0x0" ?

@EricNelson Jumping to 0x0 will not run the bootloader, which is one of the two major use cases for a software reset. The second use case, resetting the system to a known state, is not possible without a bootloader with WD support or connecting the reset pin to a GPIO.

@DmitryGrigoryev For some reason, Visual Studio thinks this is invalid syntax. It underlines the semicolon in red saying it expected a '('. The code will compile, however. I'm guessing it's some sort of discrepancy between Visual Studio and Visual Micro (the arduino plugin for VS).
However, the arduino also gets reset if I leave out the volatile keyword (and that way, Intellisense doesn't complain). Are there any side effects to this?

@Bas volatile prevents the compiler from over-optimizing your code. Technically, the compiler is allowed to eliminate the reset function entirely as it has no side effects visible to the C compiler. Of course, modern compilers are usually smart enough not to do this (e.g. volatile is not necessary with GCC which knows it's forbidden to optimize jmp), but strictly speaking the reset is not guaranteed to happen without volatile on a random compiler.

Thanks @DmitryGrigoryev! Turns out that Intellisense thinking it was invalid syntax was indeed an older version of Intellisense in combination with VMicro. Updating VMicro resolved the issue. Either way, it now works with the volatile keyword as well.

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


text:
Formula / calculation of the function random() / randomSeed()
In which file can I find the calculation that is called with random()? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE.
I found this in the "WMath.cpp" but that is not the final calculation.
void randomSeed(unsigned int seed)
{
  if (seed != 0) {
    srandom(seed);
  }
}

long random(long howbig)
{
  if (howbig == 0) {
    return 0;
  }
  return random() % howbig;
}

long random(long howsmall, long howbig)
{
  if (howsmall >= howbig) {
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

The underlying random() function isn't part of the Arduino code. It's actually part of avr-libc. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).
It's open source though. You can get information about it here:

http://www.nongnu.org/avr-libc

If you look down the page a short way, you'll find the "Source code and documentation" link.
The random() function is under libc/stdlib/random.c. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.

That are 76 lines with copyright, so why not post it?

@kimliv - To be honest, I'd feel discourteous posting a significant piece of someone else's library code without their permission.

But with copyright it is ok an the writer of the library was not the inventor of the algorithm I guess. (What is the main job for me)

Read Peter Bloomfield's answer here: https://arduino.stackexchange.com/a/1482/7727
Then read the following:
For everyone's reference, Arduino's WMath.cpp is found here.
Documentation for AVR-Libc's random() function is here.
Source code for AVR-Libc is found here, as linked-to from here.
I downloaded "avr-libc-2.0.0.tar.bz2.sig    08-Feb-2016" and extracted it. Like Peter said, the source code for "random" is in "avr-libc-2.0.0\libc\stdlib\random.c"
To save you the hassle, here's the source code, with their included copyright and license statement right at the top of it.
/*-
 * Copyright (c) 1990, 1993
 *  The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
 *
 * $Id: random.c 1944 2009-04-01 23:12:20Z arcanum $
 */

/*
 * From:
static char sccsid[] = "@(#)rand.c  8.1 (Berkeley) 6/14/93";
*/

#include <stdlib.h>
#include "sectionname.h"

ATTRIBUTE_CLIB_SECTION
static long
do_random(unsigned long *ctx)
{
    /*
     * Compute x = (7^5 * x) mod (2^31 - 1)
     * wihout overflowing 31 bits:
     *      (2^31 - 1) = 127773 * (7^5) + 2836
     * From "Random number generators: good ones are hard to find",
     * Park and Miller, Communications of the ACM, vol. 31, no. 10,
     * October 1988, p. 1195.
     */
    long hi, lo, x;

    x = *ctx;
    /* Can't be initialized with 0, so use another value. */
    if (x == 0)
        x = 123459876L;
    hi = x / 127773L;
    lo = x % 127773L;
    x = 16807L * lo - 2836L * hi;
    if (x < 0)
        x += 0x7fffffffL;
    return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1));
}

ATTRIBUTE_CLIB_SECTION
long
random_r(unsigned long *ctx)
{
    return do_random(ctx);
}

static unsigned long next = 1;

ATTRIBUTE_CLIB_SECTION
long
random(void)
{
    return do_random(&next);
}

ATTRIBUTE_CLIB_SECTION
void
srandom(unsigned long seed)
{
    next = seed;
}


text:
Allocate object memory statically; intialize it dynamically?
I have an object whose constructor gets passed a parameter. If I know the parameter value at compile time, I can construct the object statically:
static FOOOBJ foo(3);
(I understand that it isn't really done statically, i.e. by the compiler, but is actually done during setup).
But if I don't know the parameter value at compile time, I'd still like to pre-allocate space for the object but construct the object in that space at run time. Can it be done without a separate .initialize() method?

Using an initialize() method to a class is contrary to the principle of a class constructor, i.e. once a class instance has been constructed, it should be "ready to use".
As suggested by Ignacio's answer, C++ placement syntax is much better for your purpose.
However, with Arduino libraries, placement syntax is not supported "out of the box", so you  have to implement it yourself; don't fear, that is quite straightforward:
void* operator new(size_t size, void* ptr)
{
    return ptr;
}

Placement syntax can be a complex beast in C++, but for your specific purpose, its usage can be rather simple:
static char buffer[sizeof FOOOBJ];
static FOOOBJ* foo;

void setup() {
    ...
    foo = new (buffer) FOOOBJ(3);
    ...
}

The difference with your current code is that foo is now a pointer, hence any method call will use -> instead of ..
If you absolutely want to keep using foo as an instance and not a pointer, then you can do it (but I don't advise it as explained later) by using a reference instead:
static char buffer[sizeof FOOOBJ];
static FOOOBJ& foo = *((FOOOBJ*) buffer);

void setup() {
    ...
    new (buffer) FOOOBJ(3);
    ...
}

The problem with this code, is that you cannot know if foo has already been constructed with a real FOOOBJ instance or not; using a pointer, you can always check if it is 0 or not.
Using placement syntax, you must be aware that you cannot delete the foo instance above. If you want to destroy foo (i.e. ensure that its destructor is called), then you have to explicitly call the destructor:
foo->~FOOOBJ();

I wasn't aware of the syntax but that makes total sense! Does the constructor need to be aware of / designed for it? FOOOBJ is a OneWire object, using Jim Studt's library (v2.2). I'm getting the message error: no matching function for call to 'operator new(unsigned int, byte [14])' on the new call. It looks like avr-g++ may not understand the syntax.

Yes, you're right, I'm using Eclipse for my Arduino projects and what I checked it, it seemed to work, except that what worked was Eclipse C++ compilation, not avr-g++! I have edited my answer to show a simple workaround.

Regarding your question on constructor, ther is no specific requirement, but if the constructor itself performs dynamic allocation, then placement new will not prevent it.

I'm also using Eclipse - what C++ compiler is yours configured with? Plus looking at the OneWire constructor, it doesn't new anything, it just initializes some i/o.

I'm using Eclipse with http://eclipse.baeyens.it/ plugin (which uses Arduino IDE tools, ie avr-g++ + Arduino libs); but the C++ compilation occurs on-the-fly with Eclipse C++, and uses avr-g++ only when launching the Arduino build. I had not checked the latter step initially.

This is clearly the right approach. That  my current tools don't support it directly is unfortunate but it points me in the direction I need to go. Thanks for the help.

You can use placement syntax to specify an existing allocation in which to instantiate the class.
FOOOBJ foo(0);

 ...

  FOOOBJ *f = new (foo) FOOOBJ(3);

I'd suggest to replace the declaration of foo with char foo[sizeof FOOOBJ]; so that FOOOBJ constructor does not get called for foo which could be a real problem depending on what the constructor does.


text:
Calculating location with 4 piezo's
i've got the following problem i'd like to get solved and i'm breaking my head, so please help!
I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)
The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D
I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:
A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.
I found a possible solution here: http://mathafou.free.fr/pbg_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.
The thing I do now is:
Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.
I thought Pythagoras could come in handy here. The thing I did was: A*A+B*B=C*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB*BC=AC (We don't know AC but we can square root the outcome of AB*BC)
But then i realised I just know how long the side is and I still don't know where the ball landed :(
The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with
I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.
I'm programming this in Processing 2 : http://processing.org

You'll need to do some trials to see the relationship between sensor value and distance from that corner/edge. Then you can get an equation where, given any sensor value, it will estimate distance.

Although I don't know how well this would work, but I'd try [average of top sensors - average of bottom sensors] to find a Y coordinate, and [average of right sensors - average of left sensors] to find the X coordinates. Note: the center would be the origin. Sample equation: ((A1+B1)/2)-((C1+D1)/2) and ((A1+C1)/2)-((B1+D1)/2). Try that and see how it works. If it works, I'll post an answer explaining some of the mechanics behind it. (The input values are the readings of the sensors.)

You might want to look into how LORAN works, as I believe you can do something similar.
First premise: You want to look for the initial transient caused by the impact propagating to sensors in various places on the periphery.  The signal in the material will end up bouncing around quite a bit before it dies out, but the leading edge of the initial transient should be unambiguous, so use that.
Second premise: You have no idea when the ball actually hits - you can also measure the difference in timing between when various sensors first detect it.
So take any two sensors, measure the time lag between when they detect the ball, and convert that via the speed of sound in your material.  This yields the difference in the distance of the impact point from the two sensors.  If you know the position of the two sensors, and plot the curves of points which satisfy the equation of the measured difference in distance from each of them you can a class of conic section called a hyperbola.
But so far you do not have an answer, but only a pair of curves along which the impact must lie.  So now take at least one new sensor, and repeate the exercise generation a new equation.
Combine the equations and solve to find the intersection of the curves - this is your point of impact.  It is possible to have more than one mathematical solution, but I think you will find that only one possible solution lies in the area between the sensors.
(Unfortunately, the ATmega328p A/D converter probably isn't fast enough to do a good job of this - at 10KSPS each sample is around 34mm in air, and around half a meter in typical solids - so you either need a much faster A/D, or else tune a comparator circuit to detect pulses and measure them with ATmega timer channels.)


text:
Solar Tracker Code - how to limit steppers to max & min angle?
a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev).
We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated.
Cheers
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1);  // declaring horizontal stepper
Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2);  // declaring vertical stepper

int ldr1 = A0;  // right ldr
int ldr2 = A1;  // centre ldr
int ldr3 = A2;  // left ldr
int ldr4 = A3;  // top ldr
int ldr5 = A4;  // bottom ldr

const int threshold = 550;  // limit to stop tracker from moving at night

const int tol = 50;  // tolerance for ldrs // maybe vertical AND horizontal depending on difference?

//int = countv
//int = counth

//const int maxh = ?    // to prevent overturning horizontal (50 steps = 90°)
//const int minh = ?    // combine with count int's // i.e. if counth > 90 - stop
//const int maxv = ?    // to prevent overturning vertical
//const int minv = ?

void setup()
{
  AFMS.begin();
  stepperv->setSpeed(10);
  stepperh->setSpeed(10);
}

void loop()
{
  int right = analogRead(ldr1);
  int centre = analogRead(ldr2);
  int left = analogRead(ldr3);
  int up = analogRead(ldr4);
  int down = analogRead(ldr5);

  //STOP MOVEMENT//
  if ((left < threshold) && (right < threshold) && (up < threshold) && (down < threshold)) {}  // stop any movement if sensor values below threshold
                                                                                // at begining to check after every sensor reading

  //HORIZONTAL MOVEMENT//
  if((right > centre + tol) && (left + tol < centre))   // && (right - ? > tol)
  {
    stepperh->onestep(BACKWARD,DOUBLE);  // add +1 to int counth // if (minh < counth < maxh) - move // else - stop // counth=counth++ , counth=counth--
  }
  else if((left > centre + tol) && (right + tol < centre))  // && (left - ? > tol)
  {
    stepperh->onestep(FORWARD,DOUBLE);
  }
  else {}  // do nothing

  //VERTICAL MOVEMENT//
  if((up > centre + tol) && (down + tol < centre))  // && (up - ? > tol)
  {
    stepperv->onestep(BACKWARD,DOUBLE);
  }
  else if((down + tol > centre) && (up + tol < centre))  // && (down - ? > tol)
  {
    stepperv->onestep(FORWARD,DOUBLE);
  }
  else{}  // do nothing
}

Well first you'll probably need to define your limits. I see you have maxh minh and so on.. how do you know when you've reached the max/min?

Thanks for all the replies. Could i maybe use a magnetic switch or an accelerometer - something like this: Accelerometer? How accurate are these things?

"how do you know when you've reached the max/min?"... You can create a routine of track angles. Check the maximun ammount of energy that the solar pan is getting. At this point, this is the best angle.  At the end, this is the final goal.  Do you have your project concluded?

The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.
At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.

When working with steppers you have to realise that you are not dealing with absolute coordinates. Unlike with, for example servos, which you command to go to particular angle, you command steppers to rotate a particular amount of steps in a particular direction. This creates in your case the problem that you cannot actively check the positions of the steppers without some sensing element.
As a solution I would suggest that you would store the steps the steppers take in some variables, and then with the code limiting, that these variables don't go over a surtain number. With this method, you need to have a way of setting the zero point of the steppers, meaning from where to start the counting. This could for example be done by driving the system against some switch, and then setting the step variable to zero here. This is usually done once in the bootup, meaning that it is excecuted in the setup function.

Stepper motors are nice and all but they actually make less than adequate servos for this purpose. the best way that I can see is with linear actuators that have position sensors in them and feed the Voltage divider outputs from those sensors to the Atmega chip. If you write the code to compare the signals from the light detectors with the voltage from the pos sensors it should be a lot better. Also, limit switches should be used in this arrangement too. They would be as a fail safe. The other benefit is that linear actuators usually hold a lot better without loosing their position due to outside stresses. Steppers can be used for prototyping, but it would still be better to start with small servos with sensors and get the system working first. I myself am trying to get a working system and I am having troubles with the coding also, but I am not good at coding. One other thing, I have looked at a lot of different codes to find something that might help me with my project and I have seen this. Stepper motor systems are written with minimal code which as I see it leaves room for much error. Atmega has plenty of room for code storage and plenty of ports for sensors in this use. Everyone knows that old phrase keep it simple but some times that is not always the best advice. You are working with something that needs to be somewhat complicated, to be less likely to fail. The more engineering you put into something the more likely something is to go wrong but less engineering gives you the same results. So consider all the posibilities and address them. Adding components and sub systems will in the end make your work better.

Although this is useful information, it doesn't really answer the question. Can you add a little bit more (maybe a paragraph) to better answer the question? Thanks!

It's kind of hard to read as a big block of text.


text:
Using multiple laptop battery packs to power everything
I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.
I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.
Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?
Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?
(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)
I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

Doesn't sound off-topic for EE.SE to me...

@IgnacioVazquez-Abrams The question was put on hold, and I deleted it. They said the site was about design of electronics, not usage of electronics.

A power source is electronics.

You mentioned that you have several Arduino for your robot, hence I deduce you probably have several actuator devices (those that need high current), so why not use each battery as a distinct power source? If needed, you'd just have to connect all grounds, but they would not be used in parallel.

@jfpoilpret I could do that, possibly. I've also considered using relays to switch between power packs. Ideally, I want the robot to be "self contained" with a single 220V wall socket connector for charging. The Arduinos are for sensors mostly, Raspberry Pi for logic; it will have a web server, rotating IR radar", two wheels (balancing), speed sensors on the wheels, temperature sensor, whatever I can come up with.

Sometimes I think EE.SE is suffering from overzealous moderating.. I hope Arduino.SE remains as open as it has been.

What's worse, is that when EE.SE flushes sound engineering-principles questions elsewhere, they often get answers of a lower quality.

In case you didn't know it already you can hook any batteries in parallel by adding a diode on every battery to avoid current from any other battery flowing back to it. Like this:
 battery
      |+  diode
+----||--->|---+
|     |        |
|              |
|     |+       |
+----||--->|---+----o V++
|     |
|
_
V GND

The drawback is that you have a small drop of voltage on the diodes and of course a small power loss too. If for example you're drawing 0.5 Amp from the batteries and you're using an 1N4001 diode which has a voltage drop of about 0.7 Volts then expect  0.350 Watts of power loss (0.5A x 0.7V). So choose the diode with the lowest voltage drop that can handle the current you need. There are solutions to lower the power that is wasted but they're more complex.

What happens if I have different voltages on the batteries? A short between the different potentials?

To a first approximation, you only draw significant power from the highest voltage one, until it discharges to match another.

@chris-stratton What you're saying sounds obvious when you say it :)

I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries is a problem.

[multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one will try to charge an old worn battery to its own fresh voltage.

I have two numbers about the packs; voltage at full charge (16.5V for the good packs) and a remaining battery time as reported by the PC; most are around 3 hours. A few are really bad (50 minutes or less battery time left, at full charge).

Since each battery pack has built in over- and undercharge protection, I assume any leakage between the packs will be no problem. One pack at 14.8 volts cannot overcharge another pack to more than 14.8 volts, and I will never connect an empty battery pack together with fully charged battery packs.

@frodeborli I wouldn't assume that with lithiums as the charging cycle is a bit more complex. The protection circuitry stops under and over voltage on the battery cells, but it might expect a constant, high-current source for its input. You will need to find out what that input is as well.


text:
How to make XBee module interrupt/wake arduino
What I am trying to do is, to have arduino in low power mode and waking up only when a packet is received and is available to be read from the buffer.
A scenario : Zigbee XBee module is not receiving anything, arduino is asleep. Once this particular module receives any data from any other module, it makes the arduino wake up and process this packet.
I've looked almost everywhere possible about this, and people say they do not have a 100% working solution.
Does the XBee module produce a particular output on a specific pin when it receives data? If so, can I connect that pin to the interrupt enabled pin on arduino and with that interrupt arduino or wake it up?
do I need arduino mega for that or is the uno a good enough option?

The pin number 9 and 13 on the Xbee are DTR/RTS used for hardware handshaking. You can connect it to the interrupt pins on the Arduino and program the arduino to wake when the pulse changes. Enable the DTR/RTS feature from X-CTU and it should work. Check this for more information.


text:
Adafruit motor shield + Adafruit stepper not working
I have the Adafruit Motor Shield V2 and an Adafruit stepper motor. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected.
As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the website, which is orange-pink-red-blue-yellow.  My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2);

void setup() {
  Serial.begin(9600);
  Serial.println("Stepper test!");

  AFMS.begin();
  myMotor->setSpeed(5);
}

void loop() {
  myMotor->step(100, FORWARD, SINGLE);
}

But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?

You must solder the header pins to the shield.  You can then plug and unplug that from the sockets of the arduino board, but you must solder the pins to the shield board for reliable electrical connection.

You have a lot of extra exposed wire that may cause problems if they touch. You should have little or no bare wire extending out of the screw terminals.

As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: Motorshield V2 assembly

Ok, I'll try this later and see if it works.

Also we removed the vin jumper when we attached an external power source. Cant really see on your pic whether its on or off.


text:
Convert a Bitstring into an integer value
I have got a String filled up with 0 and 1 and would like to get an Integer out of it:
String bitString = "";
int Number;
int tmp;

bitString = "";
  for (i=1;i<=10;i++)
  {
    tmp= analogRead (A0);
    bitString +=  tmp % 2;
    delay(50);
  }
// now bitString contains for example "10100110"
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166

What is the question? What do you expect this code to do and what is it doing? What else have you tried?

@Craig I eddited the question. For example If the bitString contains a "10100110" I want the programm to save it as the decimal 166 in the int variable.

Do you need the string? You could create the integer representation directly.

@Craig i would also like to print out the bitstring

If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value.  Appending integers to strings is a potentially costly operation both in performance and memory usage.
int Number = 0;
int tmp;

for (int i=9;i>=0;i--) {
  tmp = analogRead (A0);
  Number += (tmp % 2) << i;
  delay(50);
}
Serial.print(Number, BIN);

Yes your solution looks more efficient! and does the work

Check out strtoul()
It should work something like this:
unsigned long result = strtoul(bitstring.c_str(), NULL, 2);
Now you have a long variable which can be converted into an int if needed.

@kimliv Did you add .c_str() to the end of bitstring as Peter pointed out above? c_str() should return a const char*.

it is working that way!


text:
How to update a text file dynamically
I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.
Now, I have a text file in my server which updates dynamically for every 5 min - 10 min. I am trying to read that text file contents.
I want my server to be always connected, So It must be in setup() function.
I want update only to my text file which dynamically changes, so it must be loop() function.
How to implement this ? Any Suggestion ?

Does the content change via web interface or with a sensor/other function on the Arduino?

Is the Arduino the server or the client?

I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.

Is your server actually running on an Arduino?

@PeterR.Bloomfield My server is separate. I am just using Arduino to submit the sensor information to my Server database and with other Arduino, I am sending sms to any phone number that request for the server data.

So which part do you need help with then?

I want the server connection in setup() and In loop() I want to updated only current content in the text file. How to update the client.print("GET /current.txt"); dynamically in loop()

It's difficult to answer without details of how your server works.
If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data.  The arduino would only need to serialWrite() data for the server to parse and store.
If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:
http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.
The arduino could also beam data back to your server via IR, or bluetooth, etc.
There's lots of ways to do this.


text:
Use Higher Resistance Than Instructed in a Circuit
I'm following the "Get Started with Arduino" Guidebook, and I'm at the part where pulse width modulation (PWM) is discussed.
The instructions say to create a simple circuit with a breadboard, red LED, arduino (connected at pin 9 and ground) and a 270 ohm resistor. My power source will be the usb connection.
I have a 510 ohm resistor.

May I use it instead?
In general, will using a resistor with a higher resistance than intended in a circuit fry the arduino?

Thanks very much for your help. I'm new to arduino and electronic circuits. I have a Uno R3.

You'll need to show a schematic of the circuit. Not everyone has that book.

Thanks Ignacio, my question was answered below but I'll try to include schematics with my future questions.

The cases where using a higher value resistor will damage a circuit exist, but are a bit less usual than the cases where it may simply produce a weaker result than desired, or a different frequency response than desired.
The primary situations where you do have to watch out come about where "feedback" is used to adjust one thing in relation to something else, and so putting a larger resistor on the "sense" side of the circuit can cause the "output" to be too high.  Examples you might run into would be adjustable voltage regulators (obvious potential for damage with wrong output) and op-amps (higher than desired output, though more often distortion than damage).
It seems quite likely the the role of the resistor in your circuit is to limit the current through the LED - protecting that (and to a more vaguely best-practices degree, the ATmega pin) from damage.
For your needs it could be worth noting that a parallel combination of two 510 ohm resistors will give an effective resistance of half that, or 255 ohms.  This is very close to the design intent, so might be a decent substitution (cheap resistors have a larger tolerance for piece-to-piece variation of value than that anyway).
Normally I would say the desired 270 ohms feels a little small, and that I'd prefer to start with 330 ohms.  But if you do parallel two 510's, the 255 ohms would give just under 20ma of current if connected directaly across a 5v supply.  Given your LED will have some forward voltage drop (varies widely with color), and your Arduino pin a little of its own, the actual voltage and thus current will be less - as a guess the end result is likely to be in the 15ma range, and not unreasonable for many common LEDs.
Resistors would also be a fairly easy component to salvage out of old electronics - the leads will end up short, but other than that you basically just need to read the color code, and perhaps confirm the value after removal with a meter.
Ultimately though it is worth buying an assortment of resistors - the 1/4 watt size are generally preferred for breadboarding as the leads are the best fit.

The question specified a red LED, so the forward voltage drop is likely to be around 1.8V.

If the resistor is in series w the LED, it'll just be about half as bright when you use 510 vs 270 ohms. I=E/R and all -> half the current. Your PWM will still work, but starting from a lesser brightness on down.


text:
Cheapest way to connect android device to arduino wirelessly
I'm building a simple RC car which I want to control using android phone. The phone has bluetooth and Wi-Fi. My questions is what will be the cheapest way to connect the two devices at about 50-120m range? I have thought of the following:

Cheap bluetooth module (like this). Will this fit into my problem? What range I will archieve using this module.
Wi-fi module. I can set the android device to be "wi-fi hotspot", but the wi-fi shields are pretty expensive tho.

Any suggestions will be greatly appreciated.

Solution 1
If you don't want to change the coverage radius, sadly none of them would help you to achieve a coverage of 50m.
But if you are not using a camera feed and just want to control, I think RF transceiver would be best solution for you. But to implement this you mist connect an Arduino Mega ADK to your android device. Serially receive your directions to mega and then transmit the directions over RF transceiver.
Solution 2
If you are willing to change the coverage range to less than 15m, you can use Wi-Fi Module. This will also help you to get live camera feed from your RC car to your phone. Forget about Bluetooth module as they are slow, less range.
You can increase the coverage of Wi-Fi Module if you have a Wi-Fi AP with huge transmit power. As long as the module is able to receive the signal from AP, your car would do great.
P.S. :- Here is a cool tip. Record every turn instruction and the time after which it was given. When the signal from transmitter or AP is absent for more than a particular time, you can program the car to take a U-turn and reverse the directions. Your car will come home without any instruction.

a cool tip indeed :)

@Deamon if I get 2nd arduino board and attach a 443mhz(http://i.imgur.com/GjrvA2Q.png) tranceiver/transmitter, will I archieve my goal? I'm going to power the transmitter with 5V.

looks like its pair of transmitter and receiver. It would better to have a transceiver on both ends. This will help you to have a proper communication and acknowledgement process to implement. But if it satisfies your requirement, go ahead with it. Good luck.


text:
Looking for a protocol, any hints?
I am looking for a multi-purpose wire protocol for Arduino.
Requirements:

Range of at least 500ft (200m)
No shield required
Able to communicate between Arduino and Raspberry Pi
Be able to run "point-to-multipoint"

Are you looking for hardware or software recommendations?

To quote my tag: "Hardware".

What do you mean by "No shield required"? Do you mean no extra electronics on the Arduino?

Yeah, no extra electronics.

So you want hardware, but you don't want electronics?

There is nothing that will work given those constraints.
You only have low power 5V signals on the Arduino which won't handle your distance requirements.
You could look into RS-485 using a shield on the arduino side and a breakout board on the Raspberry Pi.


text:
DC-DC converter with Arduino not working
I've got a program running on the Arduino that is supposed to turn on and off a pump.  currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off.  When I use a multimeter between the port 13 and ground, everything works as expected.
When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?
When the port is turned on: digitalWrite(airPump, HIGH); (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max.  is it ever stable? (pictured below)

So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter.  I tested the converter on a separate bread board just by itself.  I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below)

I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v
Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v.  Any idea why this is happening?

I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help.  I can't get a stable 2.5V output from the converter with the arduino...
UPDATE: Below is a simple wiring diagram:

The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.

Are you connecting the output pin of the Arduino directly to the input of the DC-DC converter? A circuit diagram will help.

I am (through a breadboard) The output pin 13 goes directly to the DC-DC converter voltage in.  Is there a good, free place to do diagrams with components like these?

@Craig Diagram updated.

The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.
You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin.
Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.

Or use a high-side load switch.

Hmm, That's strange, when I read the multimeter it shows it's driving enough voltage, though not consistent.  So I will need to use the arduino just to turn a switch on from a power supply to the pump? I will look into this.  Thank you - I will also look into a high-side load switch.


text:
Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?
So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?
(using arduino mini, LiPo is two cells: 7,4V 150mAh)

Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (INTERNAL). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).

could you suggest a "low-leakage op amp" model? Please?

http://www.ti.com/product/tlv2450

If you are using a single cell, then the Fuel gauge from Sparkfun would be great. Instead of reading analog values manually it sends the battery level via I2C.

"(so using an external battery charge meter IC is cheating :P)" - no can do, sir, also two cells in series.


text:
portd not writing on digital ports 5 and 7
I try to build a function generator (preferably a sine) with an R-2R ladder and a Arduino Leonardo by Borderless Electronics.
For performance reasons one should use portd instead of digitalWrite.
However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on HIGH. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.
Here is the code I use
 int sine[255];

 void setup()
 {
     pinMode(0, OUTPUT);
     pinMode(1, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(3, OUTPUT);
     pinMode(4, OUTPUT);
     pinMode(5, OUTPUT);
     pinMode(6, OUTPUT);
     pinMode(7, OUTPUT);

     float x;
     float y;
     for(int i=0;i<255;i++)
     {
          x=(float)i;
          y=sin((x/255)*2*PI);
          sine[i]=int(y*128)+128;
     }
}

void loop()
{
     for (int i=0;i<255;i++)
     {
          PORTD=sine[i];
          delayMicroseconds(10);
     }
}

I tested this with two Arduinos of the exactly same type.
Question: Why are pins 5 and 7 never on HIGH?
Edit: I have simplified everything down to one statement in the loop: portd = x;
I vary x manually
expected findings:
x  ->  #pin that is on high
0  -> None
1  -> 0
2  -> 1
4  -> 2
8  -> 3
...
128 -> 7
actual findings
x  ->  #pin that is on high
0  ->  None
1  ->  3
2  ->  2
4  ->  0
8  ->  1
16 ->  4
32 ->  None
64 ->  None
128->  6
I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to portd. Furthermore portd = B11111111, according to the manual, is equivalent to portd = 255; and should set all pins on HIGH. But in my case it sets every pin to HIGH, except pins 5 and 7 are on LOW.

How are you testing the signal? Can you give examples of the actual and expected output from all pins?

Hi Peter. Thanks for your comment, i edited the question and hope it is more clear now.

This is because on ATmega 32u4, which is used in Arduino Leonardo,  pins 5 and 7 are not mapped to port D but to port C and E respectively, as you can see in the ATmega 32u4 - Arduino Pin Mapping.

So you will have to:

either find another port where all 8 bits are available as digital outputs (note that I'm not sure one such port exists)
or split each sine[i] in 2 parts because you will have to work with 2 ports at the same time.

As @jfpoilpret points out, Arduino pins are not always mapped to port bits in a straightforward manner, and it’s crucial to understand the mapping for your particular model.
In fact, the Arduino Leonardo is designed in a way that none of the ports has all 8 bits usable as I/O pins. As far as the microcontroller is concerned, ports B and D each have all 8 bits available, but the Arduino Leonardo/Micro design uses one bit on each port for a LED.
I would also recommend that if you’re using a PORTx register directly, instead of going through the Arduino API, that you also use the DDRx register to set pin directions, instead of trying to use pinMode.


text:
How many total digital pin outs does the Arduino Yun have
I have read the details on the products page for Arduino Yun but I have also read, on a Arduino forum, that there are only 18 digital pins because of Tx, and Rx. Is this true? I am not worried about the PWM, or analog capabilities of the pins, just purely digital.

According to the official specification, it has 20 digital IO pins which can be used with digitalRead() and digitalWrite() etc.. As is typical on Arduino boards though, pins 0 and 1 also act as serial Rx and Tx (respectively).
You can program it to use them for either purpose.
The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.
If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.


text:
Detecting ball moving between IR pair and handling ambient light changes
I plan to use the SEN-00241 IR Emitter and Detector pair to detect a ping pong ball moving fast between them.
I understand I could watch for voltage changes to detect this passing object, however how do people generally deal with ambient light changes? From my research it seems that the voltage will change with ambient light, and although I can take steps to create funnel vision between the 2 I'm sure it may still be an issue.
Would you take constant readings and find averages over 10 consecutive readings to allow for changes in ambient light and set a new baseline reading? Then if the voltage changes dramatically and only for a few reads then I know that was the ball and not to change the baseline reading.

this is the same problem that IR remote/television has; how can TV they tell if that high voltage is a direct light or a logic 1 sent by remote? Simply because remote does not send a "HIGH" signal, but a modulated one, tipically at 36KHz. This mean a logic "HIGH" is a train of "HIGH-LOW" at 36KHz (you can see it as PWM at 50%duty cicle and 36KHz frequency)
Ambient light des not have fast variation, and inside light are at 50-60Hz, so they will be "filtered" out.
So, until you see high voltage change at 36KHz, you have your beam fine, if it is not the case, then look at voltage: if fixed at normally low voltage, beam is broken; is fixed at normally high voltage then some light stronger than your emitter is "blinding" the sensor.
note that because 36KHz is a very use frequency on Remote, there a a lot of chip that will emit or read a modulated IR, but expose a normal digital input/output, but still can be done by software, expecially if hardware assistet (like PWM for output), interrupt for input


text:
error: no '' member function declared in class 'SonarSRF08'
Hi, I am a pretty novice coder and I am getting this error consistently with a library I have installed. Here is the code I am trying to run:
#include <Wire.h>
#include <SonarSRF02.h>
#include <SonarSRF08.h>

#define leftAddress ( 0xF2 >> 1)
#define rightAddress ( 0xE0 >> 1)
#define mainAddress ( 0xF8 >> 1)
SonarSRF02 LeftSonar;
SonarSRF02 RightSonar;
SonarSRF08 MainSonar;

char unit = 'c'; // 'i' for inches, 'c' for centimeters, 'm' for micro-seconds

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

    LeftSonar.connect(leftAddress);
    Serial.println("Left SRF02 US-Sensor ");
    Serial.println(LeftSonar.getSoft());

    RightSonar.connect(rightAddress);
    Serial.println("Right SRF02 US-Sensor ");
    Serial.println(RightSonar.getSoft());

    MainSonar.connect(mainAddress);
    Serial.println("Main SRF08 US-Sensor ");
    Serial.println(MainSonar.getSoft());
}

void loop() {
    float sensorReading = 0;

    sensorReading = LeftSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from left: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = RightSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from right: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = MainSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from main: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();
}

My project is using an SRF08 sensor with an Arduino Mega 2560

Please note that I did not try to run your code on my Mega because I don't have SRFs
However, here is what I tried to recreate your error:

I went to the arduino homepage and downloaded the 1.0.5 version.

I downloaded the zipped library from this page SRF08 Ultra Sonic Range Finder

I imported the library into the arduino IDE. For this, I had to unpack the .zip and rename the folder of the library because arduino complained about non-ascii characters. I just called the enclosing folder "arduinoSRFmaster" without dashes. After that it let me import the library the usual way:

After that I copied your code into a new sketch and hit Ctrl + R to compile and verify. It compiled just fine:

(Picture updated for compiling against MEGA)
Please provide more information, like yor OS, Arduino Version, where you got the SRF Library from etc. if that didn't help.

It seems you have compiled for UNO, maybe the problem is specific to Mega?

There should not be anything specific to the UNO in the code, therefore that should not be any issue. I updated my answer anyway.

Sometimes OS might be a problem. When I used BLE library from Redbearlabs. And compile it I got an error message on Ubuntu. But when I did the same procedure with windows I was able to compile my sketch.

I'll try it on Ubuntu and Mac and update my answer


text:
Parallel shift registers
I'm having trouble with using parallel shift registers, I've studied example codes and I've come up with this function to set the pins to on or off. The problem is the first time the function runs all the output pins are set to HIGH regardless of the values in the array.
    void updateRegister(int ClockPin,int DataPin,int LatchPin){
      int pinState;//Holds the state of the data pin
      pinMode(ClockPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(DataPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(LatchPin, OUTPUT);
      digitalWrite(LatchPin, 0);//Turns latch off to prevent bleedover while shifting

      digitalWrite(DataPin, 0);//clear everything
      digitalWrite(ClockPin, 0);//clear everything

      for (int i=1; i<=16; i++){//Repeats 16 times with i increment from 1 to 16
          if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
          else{pinState= 1;}//If it equals false set it to 0, LOW

          digitalWrite(DataPin, pinState);//Sets the data pin depening on the pinstate
          digitalWrite(ClockPin, 1);
          digitalWrite(DataPin, 0);
          digitalWrite(ClockPin, 0);
        }
      digitalWrite(LatchPin, 1);//Turns latch pin back on
    }

I'm storing the boolean values of the each pin in an array called Qout which is defined and all set to false like this
    boolean Qout [17];//Holds the state for each pin
    for (int i = 1; i < 17; i++ ) {Qout[i]=false;}//Sets all output to off

I know I should start at Qout[0] but it just makes it way more confusing.
Can someone help me fix my function so that it actually works.
This is what I based it on ShftOut23

Try bringing ClockPin down before bringing DataPin down and also add some delay before clearing ClockPin(say 1us).

Why not directly use standard Arduino API shiftOut()?

First of all, fix the following part of your code:
if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
else{pinState= 1;}//If it equals false set it to 0, LOW

into:
if (Qout[i])
{
    //Checks the array for the value and if it is true sets the pinstate to 1, HIGH
    pinState = 1;
}
else
{
    //If it equals false set it to 0, LOW
    pinState = 0;
}

Of course, if you always set pinState to 0, it won't work as you expect :-)
Note that you should rather use HIGH and LOW constants (more readable) instead of 1 and 0.
Finally, you could make the code much simpler this way:
pinState = (Qout[i] ? HIGH : LOW);


text:
Why does serial port stop sending data?
I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro.
I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.
One pressure sensor is digital, using the Wire lib, and the other is analog.
My sketch compiles, runs, and works until I try to get the data in Python using pyserial.
If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it.  If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string.  This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE.  Once the serial port stops sending, I have to reset the Leonardo in order to read new data.
I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data.  Another option is that the Wire protocol is getting stuck and halting the program.
Here's my sketch
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate
int PRESSURE_PIN = 1;

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  Wire.requestFrom(ADDRESS, REQUEST);    // request 6 bytes from slave device #2

  Serial.print(analogRead(PRESSURE_PIN));
  Serial.print(',');

  while(Wire.available())    // slave may send less than requested
  {
     Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
     Serial.print(',');
     Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
  }

  delay(10);
}

and here is how I read it from python
import serial

serial_port = '/dev/tty.usbmodem1a1221'
ser = serial.Serial(serial_port, 19200, timeout=0)

vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)]

Welcome to Arduino SE! First of all, try viewing output of the sketch using the Arduino IDE port. If it's not the sketch, I don't know how on-topic this question is.

As far as I can tell, the problem is arduino related, either software or hardware.  I'm hoping it's just a stupid gotcha that I haven't realized

did you work it out?

Yeah.  There is some kind of USB communication problem I'm having with the Leonardo.  I plugged in a Mega and everything works fine.  I did notice that the tty and cu devices for the Leonardo would drop out of /dev when I had this issue.  I don't know enough of the lower layer stuff to adequately explain why this is happening but it's not an issue with a Mega board.

Writing custom clients on a Mac, you may find that you get better results using the /dev/cu.usbmodemXXX devices than the /dev/tty.usbmodemXXX ones.

The leonardo doesn't reset when the serial port is opened.
To check it isn't python, run your Arduino code, then open the terminal and run
screen /dev/tty.usbmodem1a1221 19200

NOTE: to exit the screen session type Ctrl-A Ctrl=\ (see here). If you just close the window it will stay connected and lock up the serial port until you recycle the power on the Arduino.
If the Arduino program spits out just fine to screen, then python is the problem. One thing that can happen is a python/java/whatever program can lock up the serial port driver, but recycling the Arduino power, not restarting the program, is required to reinitialise the driver. So the Arduino is not necessarily problem, as the serial port will stay locked up for ALL programs. So "I would expect future calls to return data" is actually wrong. If I stuff up the serial port code in my java interface programs the same kind of thing happens.
Other ideas:

Make the delay longer than 10ms.
Make sure hardware flow control is off in the python serial
Flash a LED in the Arduino loop to see if it is the main loop locked up or if that is running fine.

The Arduino forums talk the Arduino resetting when the serial port is opened. A solution as stated in the forums is to add a short delay. See if that works.
Source: http://forum.arduino.cc/index.php/topic,18371.0.html

My leonardo isn't resetting when the serial port is opened.  I can close and open it several times in both python or the serial reader and it won't give data until I power cycle the leonardo.  I'm beginning to lean more towards some race case in the wire library

My eventual workaround for the Leonardo was to set up a call-response loop on the Leonardo.  Here's the code:
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  if (Serial.available() > 0) {
    Serial.read();
    Wire.requestFrom(ADDRESS, REQUEST);    // request 4 bytes from slave device at 0x28
    while(Wire.available())    // slave may send less than requested
    {
       Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
       Serial.print(',');
       Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
    }
  }
}

I was able to simplify a little.
There are two things to note:

There is no built in delay and requests made too quickly will result in either an empty response or old data from the sensor.  Have to take into account in requesting program.
The sketch will respond a number of times equal to the number of bits sent.  Use a single ASCII character for one response, 2 characters for 2 responses, etc...  This is important if you use an API similiar to a write() and writeln() as the second sends extra characters.


text:
Significance of the numbers used in the manual
i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.
For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.
Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?
Thanks!

The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).
It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).
However, analogWrite() works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.
That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.
The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for analogWrite().
You can get more information from the online documentation for Arduino:

http://arduino.cc/en/Reference/AnalogRead
http://arduino.cc/en/Reference/AnalogWrite

It's the minimum of the timer capabilities. The 8-bit timers are naturally restricted to 8-bit PWM precision, but even the 16-bit timers are reduced to 8-bit precision for consistency's sake.

To clarify, analogRead() has a 10 bit range due to the arduino's Analog to Digital Converter, or ADC. 10 bits can store 1024 (2^10) different values; counting zero as a value gives the range 0-1023.
In arduino 0 is the reading when a pin is grounded, 1023 is the reading when an analog pin is connected to Vref, or 5v if there is nothing wired to Vref. The sensors provide a voltage somewhere between these values, but not the actual numbers your code gets.
analogWrite() accepts 8 bit numbers. That is 2^8 or 256 different values, called 0-255. It only simulates an analog voltage by pulsing a pin rapidly.
In short, the numbers are not arbitrary, but express the limits of the arduino chip's IO. They look random because they were written in decimal, but in binary they are very simple. If you are interested, you could look into replacing the decimal numbers in the code with hexadecimal numbers, which make their binary representations very obvious by way of 16 being 2^4.

More explanation: binary numbers are different than base 10 as you probably know. The meaning of those numbers is simple.
Start with 1 and double it. Keep doubling. You will soon hit 256 (computers start at 0 not 1,  so you have to take that into account, 0-255 is 256 different values). Keep doubling and you will soon hit 1024 (0-1023).
So these numbers are not arbitrary, they are Base 10 (0-9 like you learned in school) representations of Binary Numbers, more specifically, the high limit a given length of binary digits can represent before having to add another digit.
1111111 is binary for 127, with 0 thats 128 different values those 7 digits can represent. To get to 255, you have to add a digit for 8 total digits, 11111111 = 255. 9 digits or 111111111 = 511 and ten digits or 1111111111 = 1023.


text:
Reading CMPS10 raw values
I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)
i2cBus->beginTransmission(I2C_Address);
i2cBus->write(byte(10));
i2cBus->endTransmission();

i2cBus->requestFrom(I2C_Address, 4);
xMagHighByte = i2cBus->read();
xMagLowByte = i2cBus->read();
yMagHighByte = i2cBus->read();
yMagLowByte = i2cBus->read();

xMag = short(xMagHighByte<<8);
xMag |= xMagLowByte;
yMag = short(yMagHighByte<<8);
yMag |= yMagLowByte;

if(yMag!=0){
  magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
}
else if(xMag>0) magBearing=0.0;
else if(xMag<0) magBearing=180.0;
else magBearing = 1000;
if(magBearing < 0) magBearing+=360;
magBearing=360-magBearing;
return magBearing;

Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.
But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.
To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,
float Scale, Shift, Value;
Scale =  (max-min)/2;
Shift = -(max+min)/2;
Value = float(raw+Shift)/Scale;

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.


text:
Reset fuses on atmega328p using Arduino
I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:
avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

Response:
avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude.exe: Device signature = 0x1e950f
avrdude.exe: reading input file "0x62"
avrdude.exe: writing lfuse (1 bytes):

Writing |  ***failed;
################################################## | 100% 0.06s

avrdude.exe: 1 bytes of lfuse written
avrdude.exe: verifying lfuse memory against 0x62:
avrdude.exe: load data lfuse data from input file 0x62:
avrdude.exe: input file 0x62 contains 1 bytes
avrdude.exe: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude.exe: verifying ...
avrdude.exe: verification error, first mismatch at byte 0x0000
             0x62 != 0x00
avrdude.exe: verification error; content mismatch

avrdude.exe: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n]

You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the lfuse, hfuse, and efuse memory types to read and write the fuse bytes.

If your answer includes information that mine doesn't then you should consider leaving it so that others can learn from it.

It's pretty much the same answer haha