text:
How to write data in RAM memory using Arduino Uno or Arduino Due?
I know that it is possible to write data in ROM(Read Only Memory).
But what about if I want to write data in RAM(Random Access Memory)?
Can I do it using "Arduino Uno R3"?
RAM is normally associated with volatile types of memory.
There are several examples about writing data in EEPROM as in a (Read Only Memory) which may have 8 pins.
In order to store values read from analog input 0 into the EEPROM we need to use the "EEPROM.write()" function.
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
ROM is a Non-volatile type memory.
SD card is also Non-volatile type of memory.
We know that there are few SD card shields for "Arduino Uno" and it is possible create your own shields.
But what about volatile types of memory?
what about if I want to write data in RAM like a "DDR SDRAM" or in a DDR3 memory which may have 240 pins instead of 8 pins?
So my question is is it possible to write data in "DDR SDRAM" using "Arduiono Uno R3"?
How? Where should I connect those 240 pins?

What is your eventual goal? What do you want to do with DDR3 that you couldn't accomplish with SRAM? Or with an SD card if you need a large storage?

I think the OP wants to write to external memory (not the onboard RAM). @IremadzeArchil19910311 - please specify what sort of RAM you have in mind (part number). 240 pins? I hope you are joking. There are not 240 I/O ports on the Arduino. These are designed to plug into a PC or Mac. You can however get SPI or I2C RAM modules.

"So can any kind of SDRAM Shield help me to solve this problem?" You've only asked about a solution - DRAM - and haven't yet explained the problem you're trying to solve. If you could have DRAM, what would you do with it? Must it be DRAM or can you accept alternate ways to accomplish your goal?

Even in the rare situations where external RAM could be remotely sensible, you are probably better off using SRAM than any flavor of DRAM like DDR, SDRAM, etc, as you are unlikely to use enough of it for the greater complexity of dynamic RAM over static RAM to be justified by the lower cost-per-bit.  But really, for anything requiring this scale of memory, you should move beyond the Arduino to a more appropriate platform first.

i too have similar question, its useful in case you have uno refreshing page running of arduino uno, so if you tick the check box on auto refreshing page it we be unchecked on page reload, so best is to store the state on RAM , which would also ensure vale is reset in case we reboot uno .

just hit my mind, can't pointers be handy to access a memory location and store and retrieve data there ?

DRAM of any kind requires a memory controller which is not present in any AVR device. Larger AVR devices such as the ATmega64A and ATmega128A do have an external memory bus that can be used for SRAM and MMIO.

So can any kind of SDRAM Shield help me to solve this problem? Do SDRAM Shields have this memory controller?

The Uno R3 does not have an external memory bus regardless. And performing MMIO to access paged DRAM will be painful at best.

In short, the Uno (or rather, the ATmega328) simply isn't designed for that kind of application. The new Zero might, with it's Cortex M0+ processor. Don't quote me on that, though...

The memory controller wouldn't be integrated into the core, so it would depend on which specific chip or family it uses. The SAM-D21 (Zero) doesn't have an external memory bus. The SAM3X8E (Due) has an external memory bus but no memory controller and doesn't seem to expose the entire bus via headers. The Sitara 335X (Tre) does have a memory controller, but it is only connected to the on-board DRAM.

OK! But what about "Arduino Mega"? Or what about "Arduino Due" which is an ARM device?

Your program is already using the on board RAM:
int a = 5; // This is RAM. Where did you think it goes? (This might go to a CPU Reg)
int a[5000]; // This is RAM

DDR3 RAMs require (typically) 1633 MHz clocks, and store gigabytes of data, not something you use with Arduino, which has a 16 MHz CPU.
If you need EXTRA (emphasis on extra) RAM, my first advice would be to refactor your project, and reduce processing on Arduino.
However, if must have more RAM, get SRAM. In most cases, DDR3 trade high maintenance for cost. Have a look here.

int a = 5; is in RAM only if declared at global scope. If it's a local variable, it is almost certainly assigned to CPU registers. There are exceptions though: if you take the address of the variable, or if there are not enough available registers, it will end in RAM, but this is uncommon.

How about recursion. This will almost certainly use stack, in memory.

Even with recursion, the variable is likely to be assigned to a register while “live”, and saved on the stack only for the duration of the recursive call. This may depend on how much use the variable has though, so you should disassemble if you want to know for sure for some particular recursive function.

The easiest way to read and write DDR SRAM would be to install it in a PC and write a serial server that allowed the Arduino to access the data by requesting it over the serial port.
Now although that is possible to do, the performance probably won't be great.  So it might be worth looking into memory that interfaces over SPI or IIC, there are several ICs that you could use.  Most of them would have libraries already available and you would be looking at about £1 per 256kbits.
But like it has been said above if you are looking at storing multi-GBs of data then you probably want SD cards.  If the write speed is going to be a problem then look at multiplexing the data over many SD cards.


text:
Aduino 7 segment dice project
I am struggling with the code that I should write for my project. I finished my breadboard but I have never learnt programming before so I cannot write the program for the dice.
My project is to make the dice output random numbers when the button is pressed.
This is what I have completed already. I just want to know how to complete the program to make it work for my arduino.

This is the code so far:
int leda = 2;
int ledb = 3;
int ledc = 4;
int ledd = 5;
int lede = 6;
int ledf = 7;
int ledg = 8;
int ledh = 9;
int leda1 = A0;
int ledb1 = A1;
int ledc1 = A2;
int ledd1 = A3;
int lede1 = A4;
int ledf1 = A5;
int ledg1 = A6;
int ledh1 = A7;

void setup()
{
    Serial.begin(9600);
    pinMode(leda, OUTPUT);
    pinMode(ledb, OUTPUT);
    pinMode(ledc, OUTPUT);
    pinMode(ledd, OUTPUT);
    pinMode(lede, OUTPUT);
    pinMode(ledf, OUTPUT);
    pinMode(ledg, OUTPUT);
    pinMode(ledh, OUTPUT);
    pinMode(leda1, OUTPUT);
    pinMode(ledb1, OUTPUT);
    pinMode(ledc1, OUTPUT);
    pinMode(ledd1, OUTPUT);
    pinMode(lede1, OUTPUT);
    pinMode(ledf1, OUTPUT);
    pinMode(ledg1, OUTPUT);
    pinMode(ledh1, OUTPUT);

    pinMode(12, INPUT);

    digitalWrite(12, HIGH);
}

if (number == 1)
{
    digitalWrite(2, HIGH);
    digitalWrite(7, HIGH);
}

else if (number == 2)
{
    digitalWrite(3, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(9, HIGH);
    digitalWrite(8, HIGH);
    delay(200);
}
else if (number == 3)
{
    digitalWrite(3,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(200);
}

else if (number == 4)
{
    // do number 4
}

else if (number == 5)
{
    // do number 5
}

// ... etc
// Additional 'numbers' have been removed for brevity

Proper formatting, come on! It's a pain to add four spaces to the front of each line (I'm not being sarcastic, it really is!) but nobody likes reading it when it's like this. I'll edit it this time...

This looks horribly repetitive. See Controlling 7 segment LED display from Arduino for an example program that does work, and my comment to the same post for a more compact way of writing all this.

@chaaarlie2 It's not a pain - just highlight it and press the { } button above the editor.

Don't forget you need to turn off the segments you no longer need on when you change from one number to another...

@Majenko: I didn't know that (or, rather, I think I forgot it); I'm horribly embarrassed.

@chaaarlie2 To be fair, the icon's not exactly very meaningful - easy to overlook it.

@Majenko ALL THOSE HOURS OF SPACEBAR-PRESSING I'LL NEVER GET BACK.

About random numbers
What you are trying to achieve is actually not that easy. An Arduino is
basically a computer, and as any computer, it is designed to execute
instructions in a very deterministic fashion. Computers are not good
at randomness and, unless fitted with dedicated hardware, they cannot
generate random numbers. Given this, you are left with two options:

pseudo-random number generators
entropy gathering

The first is the easiest:
int first_dice  = random(1, 7);  // 1 (inclusive) to 7 (exclusive)
int second_dice = random(1, 7);

and voilà! You have two random-looking numbers. They are random-looking
in the sense that you will find no obvious pattern in any sequence of
numbers you draw. However, if you reset your Arduino, either with the
reset button or by power-cycling it, it will give you the exact same
sequence as in the first run. Thus, pseudo-randomness in useless unless
you commit to never unpower your circuit. It is a good starting point,
however, if your main goal is to get started with Arduino programming.
Entropy gathering means getting some randomness from outside the
Arduino: you would connect it to some source of randomness and perform
some measurement that has unpredictable outcome. A human being is a good
source of randomness: if you require the user to press a button before
displaying the dice value, the timing of the button press is a good
random source. The micros() function can be used to get the current
time with 4 µs resolution, which is more than enough for this
purpose. Entropy gathering is usually used in tandem with pseudo-random
number generators, as a way to seed them, like this:
wait_for_the_user_to_press_a_button();
randomSeed(micros());
int first_dice =  random(1, 7);
int second_dice = random(1, 7);

If you cannot have human interaction, you could try to get some
electromagnetic noise by performing an analogRead() on a floating pin.
Ideally you would connect that pin to an analog noise source. See the
first comment to this answer for more information on this option.
About arrays and loops
You should definitely try to find a good tutorial about arrays and
loops. Whenever you find yourself writing tons of almost-identical lines
of code, you should wonder whether you can replace that repetition with
a loop. For example, for displaying the digit 1, you may write:
if (number == 1) {
    digitalWrite(leda,  LOW);
    digitalWrite(ledb, HIGH);
    digitalWrite(ledc, HIGH);
    digitalWrite(ledd,  LOW);
    digitalWrite(lede,  LOW);
    digitalWrite(ledf,  LOW);
    digitalWrite(ledg,  LOW);
}

(I am using the "canonical" A–G letter assignments, and yes, you should
also take care of setting to LOW the segments you want to be off).
This code is an obvious candidate for being replaced by a loop:
if (number == 1) {
    for (int segment = 0; segment < 7; segment++)
        digitalWrite(leds[segment], digit1[segment]);
}

This requires that you first define the following arrays:
//                A     B     C     D     E     F     G
int leds[]   = {  2,    3,    4,    5,    6,    7,    8 };
int digit1[] = { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW};

This logic can be pushed one level further by using a two-dimensional
array (an array of arrays): instead of defining six arrays digit1,
digit2... digit6, you create an array of arrays like this:
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         ...
};

and you use digits[number] instead of digit1, etc. This way you get
rid of the whole if () ... else if () chain, replaced by:
for (int segment = 0; segment < 7; segment++)
    digitalWrite(leds[segment], digits[number-1][segment]);

Take care though that in C++ arrays are indexed from zero, which is why
you need to use number-1 as the index in digits. If you have more
than one die (which is your case), you can also put their pin
assignments in a two-dimensional array. Then all the dice updating code
would be wrapped inside a loop indexed by the die number. Putting all
this together you end up with something like this:
// Pin assignments.
int leds[][7] = {
   /*                A     B     C     D     E     F     G  */
   /* 1st die */  {  2,    3,    4,    5,    6,    7,    8 },
   /* 2nd die */  { A0,   A1,   A2,   A3,   A4,   A5,   A6 }
};

// 7-segment "font".
int digits[][7] = {
         /*          A     B     C     D     E     F     G  */
         /* 1 */  { LOW, HIGH, HIGH,  LOW,  LOW,  LOW,  LOW},
         /* 2 */  {HIGH, HIGH,  LOW, HIGH, HIGH,  LOW, HIGH},
         /* 3 */  {HIGH, HIGH, HIGH, HIGH,  LOW,  LOW, HIGH},
         /* 4 */  { LOW, HIGH, HIGH,  LOW,  LOW, HIGH, HIGH},
         /* 5 */  {HIGH,  LOW, HIGH, HIGH,  LOW, HIGH, HIGH},
         /* 6 */  {HIGH,  LOW, HIGH, HIGH, HIGH, HIGH, HIGH}
};

void setup()
{
    for (int die = 0; die < 2; die++) {
        for (int segment = 0; segment < 7; segment++) {
            pinMode(leds[die][segment], OUTPUT);
        }
    }
}

void loop() {
    for (int die = 0; die < 2; die++) {
        int number = random(1, 7);
        for (int segment = 0; segment < 7; segment++)
            digitalWrite(leds[die][segment], digits[number][segment]);
    }
    delay(200);
}

This is still lacking the entropy gathering phase discussed above.

Connecting the analogue input to the collector of a run-of-the-mill transistor, with the emitter grounded and base open helps to make a noisy input. There's actually plenty of information about random noise generation techniques for this purpose on the internet.

I made it so at least it compiles. It should loop through the numbers.
As for the circuit; you really should add a resistor to every segment, instead of just one the the common cathode. Otherwise the brightness will be different if more segments are on.
int number = 1;
int number1 = 1;

int leda = 2;
int ledb = 3;
int ledc = 4;
int ledd = 5;
int lede = 6;
int ledf = 7;
int ledg = 8;
int ledh = 9;

int leda1 = A0;
int ledb1 = A1;
int ledc1 = A2;
int ledd1 = A3;
int lede1 = A4;
int ledf1 = A5;
int ledg1 = A6;
int ledh1 = A7;

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

    pinMode(leda, OUTPUT);
    pinMode(ledb, OUTPUT);
    pinMode(ledc, OUTPUT);
    pinMode(ledd, OUTPUT);
    pinMode(lede, OUTPUT);
    pinMode(ledf, OUTPUT);
    pinMode(ledg, OUTPUT);
    pinMode(ledh, OUTPUT);

    pinMode(leda1, OUTPUT);
    pinMode(ledb1, OUTPUT);
    pinMode(ledc1, OUTPUT);
    pinMode(ledd1, OUTPUT);
    pinMode(lede1, OUTPUT);
    pinMode(ledf1, OUTPUT);
    pinMode(ledg1, OUTPUT);
    pinMode(ledh1, OUTPUT);

    pinMode(12, INPUT);
    digitalWrite(12, HIGH);
}
void loop() {

    // turn off all leds
    digitalWrite(leda, LOW);
    digitalWrite(ledb, LOW);
    digitalWrite(ledc, LOW);
    digitalWrite(ledd, LOW);
    digitalWrite(lede, LOW);
    digitalWrite(ledf, LOW);
    digitalWrite(ledg, LOW);
    digitalWrite(ledh, LOW);

    digitalWrite(leda1, LOW);
    digitalWrite(ledb1, LOW);
    digitalWrite(ledc1, LOW);
    digitalWrite(ledd1, LOW);
    digitalWrite(lede1, LOW);
    digitalWrite(ledf1, LOW);
    digitalWrite(ledg1, LOW);
    digitalWrite(ledh1, LOW);

    if (number == 1)
    {
        digitalWrite(leda, HIGH);
        digitalWrite(ledf, HIGH);
        delay(200);
    }
    else if (number == 2)
    {
        digitalWrite(ledb, HIGH);
        digitalWrite(leda, HIGH);
        digitalWrite(ledd, HIGH);
        digitalWrite(ledh, HIGH);
        digitalWrite(ledg, HIGH);
        delay(200);
    }
    else if (number == 3)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(leda,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        delay(200);
    }
    else if (number == 4)
    {
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(leda,HIGH);
        digitalWrite(ledf,HIGH);
        delay(200);
    }
    else if (number == 5)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        delay(200);
    }
    else if (number == 6)
    {
        digitalWrite(ledb,HIGH);
        digitalWrite(ledc,HIGH);
        digitalWrite(ledd,HIGH);
        digitalWrite(ledf,HIGH);
        digitalWrite(ledg,HIGH);
        digitalWrite(ledh,HIGH);
        delay(200);
    }

    if (number1 == 1)
    {
        digitalWrite(A4, HIGH);
        digitalWrite(A1, HIGH);
        delay(200);
    }
    else if (number1 == 2)
    {
        digitalWrite(A5, HIGH);
        digitalWrite(A4, HIGH);
        digitalWrite(A7, HIGH);
        digitalWrite(A0, HIGH);
        digitalWrite(A2, HIGH);
        delay(200);
    }
    else if (number1 == 3)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A4,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 4)
    {
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A4,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 5)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }
    else if (number1 == 6)
    {
        digitalWrite(A5,HIGH);
        digitalWrite(A6,HIGH);
        digitalWrite(A7,HIGH);
        digitalWrite(A0,HIGH);
        digitalWrite(A1,HIGH);
        digitalWrite(A2,HIGH);
        delay(200);
    }

    number = (number%6) + 1;//show next number the next loop
}

source: Stack Exchange

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

sort: votes


text:
What's wrong with my Arduino board?
When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?

Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.
When you disconnect the board, the fuse will reset.
So either the board is faulty of the connection you made to it are.

thx for the explaination,and help.

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


text:
Arduino Protothreads by Example
I am trying to get Arduino working with Protothreads and wanted to confirm I have the basic setup correct. If I have understood the API correctly, then the following code should be what I need to start 2 concurrent threads from inside an Arduino program:
#include <pt.h>

static struct pt t1, t2;

void setup() {
    PT_INIT(&t1);
    PT_INIT(&t2);
}

void loop() {
    doSomething(&t1, 500);
    doSomethingElse(&t2, 500);
}

static int doSomething(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(100);
    PT_END(pt);
}

static int doSomethingElse(struct pt *pt, int interval) {
    PT_BEGIN(pt);
    sleep(250);
    PT_END(pt);
}

Does anyone see anything that jumps out at them as missing or wrong?

What is sleep() ?

Check this example: rather than sleep(), it uses PT_WAIT_UNTIL
  while(1) {
      PT_WAIT_UNTIL(pt, millis() - timestamp > interval );
      timestamp = millis();
      doSomething();
  }

That should be the proto-thread way of waiting: PT_WAIT_UNTIL will make sure that your thread sleeps in a way that allows other threads to run.
The rest looks fine, but I have not tried to run the code.

Just to add to the understanding (or confusion), PT_WAIT_UNTIL blocks the execution or "yield" to the other threads. You can see its difference from sleep which blocks everyone. The while(1) "re-arms" the thread again, once dosomething() finishes. Here is some C switch-while hackery going on. (see http://dunkels.com/adam/pt/expansion.html)

Why reinvent the wheel? There are libraries that can do just that for you.
For example
ArduinoThread. I tried it out and did not need to keep looking further. There are also Wiring and SoftTimer but I did not try those.

authors: Артём Типикин

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


text:
Graphic fail when rebooting the micro controller and OLED! (NOT when uploading the code??!!)
Im using Spark fun´s Pro micro: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro
And Digole OLED 1.8" hooked up with UART: http://www.digole.com/index.php?productID=859
As the head line reads, got code that work just fine when I upload it to the Pro Micro. But when I restart the pro micro (after successful upload it starts to show these weird characters and tokens. I can still se the "working code" but with a lot of additional crap?!
EDIT: This is installed in a car, and I´ve notice its just screwing around when I turn the car ON.. The cars electric is probably somehow interfering with the data-signal to the oled. Maybe I need a resistor of some kind?
What is this, why is it happening, and what can I do to get rid of the problem?!?
Help´s very appreciated!! Thanks!! /Rasmus

Try adding a 1000ms delay to the start of your code before you do any serial work.

@Majenko, ok will try that today! I´ll be back with the result! Thanks!

Tried with a delay but the problem´s still there.. Thanks anyway for the suggestion @Majenko

It would have been nice to know the rather important fact you just now mention in your edit... running from a car and it only happens when you start the engine...  Starting the engine is very noisy. You need lots of filtering to get rid of the massive spikes, and lots of capacitance to absorb the deep brownouts you get.

@Majenko, Yeah, and not only during startup, of course also during idle and driving. Do you know what I could use?

This may help you: http://electronics.stackexchange.com/a/73921/4245


text:
analogRead-ing Potentiometer Values in void setup()
I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button [indicating the beginning of the loop()], and the speedometer would begin measuring and displaying his or her speed.
This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.
Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.
Thanks!

You presumably know that:  The easiest and usual way to read a potentiometer is to connect the "track" between V_pot (often = Vcc) and ground and to connect the pot "wiper" to an analog input pin. You then use analogRead(Ax) to read the pot value in the range 0-255.
The use of analogRead() is valid in setup.
However a more "real" method would be to have a "flag" variable that indicates that the speedo initialisation code has or hasn't been run.
Set this flag to false in setup, detect and action it in loop and then set the flag to true so that the code is not repeatedly actioned.

eg
void setup()
{
...
boolean initialised = false ;
...
}
void loop()
{
if (initialised == false) {
// initialise speedo
//  ....
   initialised = true;
}
...
} // end of loop()
}

If you really want to use this feature in the setup() then you can do like this:
#define BUTTON 2
boolean not_done = true;

void stopDiameterSetup() {
    // some button debounche code
    ...
    // we are done with setting up the diameter.
    not_done = false;
}
void setup() {
    ...

    // POT reading
    interrupts();
    attachInterrupt();
    while(not_done) {
       attachInterrupt(BUTTON, stopDiameterSetup, CHANGE);
    }
}
void loop(){
// your loop code
}

If you can't or afraid to use interrupts then just check for a button pressed inside the while loop.


text:
Light sensor acting up when used with other code
I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:
const int lightSensorPin = A0;
int lightSensorValue = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);
}

Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000.
Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:
int trigPin1 = 5;
int echoPin1 = 6;
int blue1 =  7;
int green1 = 8;

int trigPin2 = A3;
int echoPin2 = A4;
int blue2 =  A2;
int green2 = A1;

int redLED = 10;
int greenLED = 3;
int yellowLED = 9;
int blueLED = 4;

const int lightSensorPin = A0;
int lightSensorValue = 0;

int securityLength1 = 28;
int securityLength2 = 28;

int frontEyes(11);
int backEyes(12);

const char* front = "front";
const char* back = "back";

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

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(blue1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(green2, OUTPUT);

  pinMode(frontEyes, OUTPUT);
  pinMode(backEyes, OUTPUT);

  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(yellowLED, OUTPUT);

}//end setup

void loop(){

  digitalWrite(redLED, HIGH);
  digitalWrite(greenLED, HIGH);
  digitalWrite(yellowLED, HIGH);
  digitalWrite(blueLED, HIGH);

eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front);
eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back);

  lightSensorValue = analogRead(lightSensorPin);
  delay(100);
  Serial.println(lightSensorValue);

}//end loop

void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  long distance = (duration/2) / 29.1;

  Serial.println(distance);

 if (distance >= securityLength || distance <= 0) {
  digitalWrite(green,HIGH);
  digitalWrite(blue,LOW);
  if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);
  }//end else
  }//end if

  else if(distance < securityLength) {
  digitalWrite(blue,HIGH);
  digitalWrite(green,LOW);

  if (frontOrBack == "front") {
    digitalWrite(frontEyes, HIGH);
  }//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, HIGH);
  }//end else

 }//end else if

}//end function

It wouldn't be something as simple as the light sensor "seeing" all those LED's, could it? :)

No, they aren't bright enough. And even covering it with my hand it results in totally random numbers.

I see two things to try: 1) lightSensorPin's i/O direction hasn't been set; 2) There's a lot of I/O going on immediately before you call analogRead(). Try delaying for a couple of milliseconds before that read to let any transients settle out.

@JRobert I've actually already tried doing both of those things. Set the pin to INPUT then put half a second delays on both ends. Seems like it reads the light better when my hand is over it but still get's a lot of random super high numbers like something is interfering.

0 - 3000? I missed that. You're seeing bigger numbers than the A/D can deliver (0 - 1023). Can something be over-writing lightSensorValue? Have you tried making  lightSensorValue local to the loop() function? That would move it far away from the other globals (though it wouldn't live between calls to loop(). Also, Serial.println(analogRead(lightSensorPin)); should directly print the return from analogRead() (though the compiler may have already done that for you).

Ok I moved the variable to the loop with same results. I tried process of elimination and found that when I delete the function outside of the loop it works perfectly fine. Here is what bad results kind of look like:
7
632
6
6
634
6
6
630
6
7
630
6
7
634
6
6
632 - It gets a good value then throws it a few bad ones in between.

Let us continue this discussion in chat.

@MichaelRader I've just read your solution. Thank you for cheering me up. And as far as embarassing mistakes go, welcome to the club.

I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had Serial.println(distance); in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings.

There's no pinMode(lightSensorPin, INPUT); in either of your codes. In the original code this probably doesn't matter because you set no other pins to In or Out.
As a side note, instead of declaring all your pin number as int then defining them, make use of preprocessor directives:
#define trigPin1  5;
#define echoPin1  6;
#define blue1     7;
#define green1    8;

When you hit Verify or Upload the preprocessor sweeps through your code and replaces all instances of a defined term with whatever comes immediately after it in the definition. You can't use it for variables of course, but it's perfect for designating pins.
This will cut down on unnecessary memory usage. Not a huge saving in your case, but I don't see why people don't do it more often.

Thanks for the tip on the preprocessor directive. Do those go in the setup? Also, we already discussed that the pinMode(lightSensorPin, INPUT); does nothing different. It doesn't solve the problem.

Also how do you specify INPUT or OUTPUT with the preprocessor directive?

#define goes at the top of the program, along with things like #include <A_LIBRARY>. That said, you can put #define at the bottom, or in the middle, but code before it that relies on the definition will not compile. You can't specify if a pin is input or output with #define - think of it as a 'find-and-replace' command. Change the first block of code to what I put in my answer above, in exactly the same place it is in currently, and you won't have to change a single bit of the remaining code from void setup() and beyond.


text:
Connecting battery and LED to Arduino Due
I am brand new to Arduino/robotics and am trying to take baby steps. First I'd like to just power an Arduino and an LED from a 9V battery like so:

No programming, just simple circuitry. The battery powers the Due, and the Due in turn powers the LED.
A few concerns here:

Will the 9V battery fry the Due, which I believe is expecting 3.3V? If so, what can I do to reduce the voltage/amps?
Will the 9V battery fry the resistor and/or LED?
As you can see by my question marks, I'm not real sure where to connect the battery to the Due (both positive & negative terminals) as well as the where to connect the breadboard to the Due (again, both terminals).

Any ideas?

You can connect the battery to VIN. That way the onboard regulators will bring it down to 5v and 3.3v. If you want to connect the led to the 9v battery directly, you might have to use a bigger resistor value.

What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield):

My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one.  You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).
It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.
In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do.  I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.
In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.
As a next step, you could load the sample sketch Examples->01Basic->Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).
Edit (to specifically address your concerns):

The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.
The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.
Only connect the battery through the power socket.  If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended.  Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.

Additional edit:
You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket.  Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.

The only thing I'd add to this thorough answer is, if you connect a barrel plug to your 9v battery (b/c I don't see one in your - OP's - photo) make sure to connect 9v + to the center-pin and 9v - to the outer shell.

Thanks @Mick Waites (+1) - one quick followup question: please see Gerben's comment under my question. Gerben alludes that there is something called Vin which handles non-5V external power supplies. Sure enough, on the Due's website (under Power) they define Vin as: "The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source)." Can you confirm that I could use Vin to power my board directly from the 9V battery? Thanks again!

@smeeb - Gerben is completely right.  I have never used the Vin pin as I use a stable 5V supply for my board in my projects.  The voltage limits for the Vin pin are 6-16V, but 7-12V is recommended.  This saves you having to get a connector for your battery to fit the power socket.  You would connect the + pole of the battery to Vin, and the - pole to Gnd.  You would then connect your black LED/resistor wire to another Gnd pin (it would be difficult to plug 2 wires into the same pin socket, but it would work if you could manage it) and the red LED/resistor wire to a 3.3V or 5V pin.


text:
Will writing to serial when no serial is available cause problems?
I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?

What will happen is the data will dribble out of the unconnected port and drip onto the floor.  Data stains can be a real pain to get out of carpet, so put some newspaper down first.

No, that will not cause any problem.
What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected and the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.
This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.

It's not left dangling. The RX and TX are connected to the ATMega16u2 that does the USB-to-Serial conversion.

ok. Actually there is a way to disable the USB to serial converter. If you short its reset pin, like in the procedure required to update its firmware with dfu utils, it should do in high impedance mode (I think).

I seem to recall the Arduino core or bootloader code activating an internal pullup on the serial input line anyway.


text:
How to count the number of times a changing variable reaches a peak value
I am recording a varying distance with an Ultrasonic sensor and Arduino but my problem is I want to display the number of times this variable reaches peak (at an instance the value will be increasing and the next instance decreasing in that order) on an LCD.
So far this is my code:
//Libraries
#include <Ultrasonic.h>
#include <LiquidCrystal.h>

//Setup connection with LCD and HC-SR04
LiquidCrystal lcd(12, 10, 5, 4, 3, 2);
Ultrasonic ultrasonic(A0,A1);

void setup() {
  //Lcd init
  lcd.begin(16, 2); //16 rows, 2 columns
}

void loop()
{
  lcd.clear();
  lcd.print("  Ardumotive ;)  "); // You can change this message.
  lcd.setCursor(0, 1);
  lcd.print("Distance: ");
  lcd.print(ultrasonic.Ranging(CM));
  lcd.print("cm");

  delay(300); // 1sec delay
}

So far this just looks like a copy-paste code from an example for the Ultrasonic sensor. You need to show us that you've thought about how you're going to achieve your goal.

The counting portion of what you want to achieve is simple - you just increment a variable.  The hard part is knowing when to count.
You need to remember what your value has been doing in the past in order to know if you have had a peak or not.  Also you have to define exactly what a peak is.
The simplest method (I'm not going to spoon feed you code, just help you understand the concepts) is to set a couple of thresholds, and maintain a flag.
You decide upon a value "above which the value enters the peak zone", and another "below which the value leaves the peak zone".  They could be the same value, but don't need to be.
You then have a flag which remembers if you are in the peak zone or not.
If you're not currently in the peak zone and the new value is above the peak zone entry threshold then you have entered the peak zone.  Set the flag to remember that fact.
If you are currently in the peak zone and the new value is below the peak zone leaving threshold then you have just left the peak zone.  Clear the flag to remember the fact that you're not in the peak zone and increment your peak counter now you have left the peak.

It can be very good to have the leaving threshold lower than the entering threshold so that the value has to drop significantly out of the peak zone before it will register another peak.  This is known as hysteresis and is great for getting rid of the noise you may get if the value is hovering around the peak zone entry threshold.

If ((current distance - previous distance) < 0)
Max = previous distance;
Current distance = previous distance;


text:
Coding Debugging
This program is supposed to act as a Decimal To Binary Converter, the LeD's acting as output.
The problem is that this function returns Garbage Value

const int LED1 =1, LED2 =3, LED3 =5;
void setup()
{
  Serial.begin(9600);
  pinMode (LED1, OUTPUT);
  pinMode (LED2, OUTPUT);
  pinMode (LED3, OUTPUT);
}
void loop()
{
  int x = 0;
  x = Serial.read();
  x = x-48;
  switch(x){
    case 0:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
    case 1:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, LOW);
      break;
      case 2:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 3:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, LOW);
      break;
      case 4:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 5:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, LOW);
      digitalWrite (LED3, HIGH);
      break;
      case 6:
      digitalWrite (LED1, LOW);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
      case 7:
      digitalWrite (LED1, HIGH);
      digitalWrite (LED2, HIGH);
      digitalWrite (LED3, HIGH);
      break;
  }
 Serial.write(x);
}

If you want some help, you should at least put some effort in writing a decent question: What are you trying to achieve? What have you done so far? What do you expect your program to do? What is it doing instead?

That massive program can be compressed into just a handful of lines:
const int LED1 = 1,
          LED2 = 3,
          LED3 = 5;

void setup() {
    Serial.begin(9600);
    pinMode (LED1, OUTPUT);
    pinMode (LED2, OUTPUT);
    pinMode (LED3, OUTPUT);
}

void loop() {
    if (Serial.available()) {
        int x = Serial.read();
        x = x - '0';
        digitalWrite(LED1, x & 0x01);
        digitalWrite(LED2, x & 0x02);
        digitalWrite(LED3, x & 0x04);
        Serial.print(x);
    }
}

Note the use of Serial.print() not Serial.write().  If you use Serial.write() then it prints the ASCII character associated with the number you feed it - in your case characters 0 to 7 (none of which are printable).
Also, unless you check for there actually being something available for you to read from the serial you'll only get a brief flicker of something meaningful (too fast for the eye to see) and then it will just return -1, which with 48 subtracted from it would be -49, which would be "complete garbage".

How does x & 0x01 works?

It's called a bitwise operation. I returns just the first bit of x, so 0 or 1.  With 0x02 it returns the second bit, so 0 or 2. 0x04 returns the third bit, so 0 or 4.  0 is LOW, anything above 0 is HIGH.

why do we use 0X04 and not use 0X03 if we want the third bit?

Because 0x03 is the first two bits combined. 1+2=3. Binary.

So we are moving according to according to numbers that are 2^(something) ??

That is what binary is, Yes.

There are a couple of issues:

The function loop() doesn't return anything, by definition. Functions that do return a value return it with a statement like `return(someValue); Did you mean to say that it prints garbage on the terminal?
If you want to print a value on the terminal, you need to use the the Serial.print(someValue) function; Serial.write() sends a binary value and that is probably not what you wanted. The binary values 0 - 9 represent non-printing characters so I'm not surprised that the terminal printed some odd graphic characters.

-


text:
Leonardo Serial1 enable internal pull-up for removable Bluetooth module
I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.
My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.
I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.
I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?

Yes, what you have done is good.
It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs.  When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.
As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.
UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter.  By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.
The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART.  If that happens then you want to add an external stronger (lower resistance) pull up.
Another thing to think about with your disconnected pins is to protect them from ESD.  You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.


text:
Controlling 2WD car chassis with PS3 controller
I'm having trouble with controlling my car with the PS3 joystick, and there hasn't been any example codes out there. I'm using;

PS3USB library from USB_Host_shield_2.0 library
Freetronics H Bridge shield http://www.freetronics.com.au/collections/shields/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.VXMqXUJJmgM

This is my code;
include <PS3USB.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nPS3 USB Library Started"));
  pinMode(motora1, OUTPUT);
  pinMode(motora2, OUTPUT);
  pinMode(motoraspeed, OUTPUT);
  pinMode(motorb1, OUTPUT);
  pinMode(motorb2, OUTPUT);
  pinMode(motorbspeed, OUTPUT);
  delay(5000);
}

void loop() {
  Usb.Task();

  if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

    //go forward
     if (PS3.getAnalogHat(LeftHatY) == 0) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
         digitalWrite(motora1, HIGH);
          digitalWrite(motora2, LOW);
          digitalWrite(motoraspeed, 255);
        digitalWrite(motorb1, HIGH);
        digitalWrite(motorb2, LOW);
        digitalWrite(motorbspeed, 255);
}

//go backward
if (PS3.getAnalogHat(LeftHatY) == 255) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
           digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 255);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 255);
}

//turn left
if (PS3.getAnalogHat(RightHatX) == 0) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
           digitalWrite(motora1, HIGH);
  digitalWrite(motora2, LOW);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 200);
}

   //turn right
   if (PS3.getAnalogHat(RightHatX) == 255) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
          digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, HIGH);
  digitalWrite(motorb2, LOW);
  digitalWrite(motorbspeed, 200);
}

As of now, when I look at my code in the serial monitor, I get the following;
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127

The numbers adjust as I'm moving the joystick around but just keeps going even though I'm not moving the joystick around. Any help would be appreciated, thanks

I found three issues:

You don't have a # before the include on line 1.
There is no } at the end of the void loop().
You forgot to include an if statement for when the joystick is idle.

Try this code:
#include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
                  //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
    Serial.begin(115200);
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
    }
    Serial.print(F("\r\nPS3 USB Library Started"));
    pinMode(motora1, OUTPUT);
    pinMode(motora2, OUTPUT);
    pinMode(motoraspeed, OUTPUT);
    pinMode(motorb1, OUTPUT);
    pinMode(motorb2, OUTPUT);
    pinMode(motorbspeed, OUTPUT);
    delay(5000);
}

void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
        } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 255);
        } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 200);
        } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 200);
        } else { //stop moving
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 0);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 0);
        }
    }
}


text:
How to communicate with arduino uno when arduino motor shield connected to arduino uno?
I'm using this Dual Motor Shield

when I plug Arduino Dual Motor Shield into Aruino uno can't seen any way to communicate with Adruino uno.how can I communicate with uno ?

What "communication" are you talking about? Do you mean "plug wires into D0-D13, A0-A5 pins of the Arduino UNO (in this case that would not be called communication) or USB communication to your PC, or ICSP communication with a programmer?

plug wires into D0-D13

Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and  D1)
If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.

i need to plug wires into D0-D13

authors: สาโรจน์ เกตุสมบัติ


text:
Is there such a thing as an "Always" loop?
I seem to remember somewhere somebody making an "Always" loop between Setup() and Loop().
But I can't find any documentation on it. Does such a thing exist, or am I imagining it?

There's nothing officially called an "always" loops as such. However, you can make a loop which goes on forever like this:
while (true)
{
    // this bit repeats forever
}

A while loop checks the condition before every iteration of the main body. If it detects that the condition equals boolean false then it will stop the loop and move on to the next bit of code.
Normally, the condition would be some kind of expression, like (x < 10). However, in the example above, the condition is hard-coded as true, meaning it will never be false so it will never stop.

Another variant - with exactly the same result - is for(;;){ ... }, which appeals to me for the simple reason that it reads almost like the word "forever". (Or maybe I just have an overactive imagination.... :-)

You might be thinking of the Serial Event system.
This is a specially defined function which runs whenever loop() finishes if there is anything to read from the serial port.

http://www.arduino.cc/en/Reference/SerialEvent

Basically it is implemented as a function call after loop() in the main() function, which looks like this:
setup();

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

As you can see there is only setup(), loop() and the serial event system.

serialEventRun is a weak reference. If some code file (typically an included library) defines a function by that name, it is called. It really does not check for serial data, but that is what it could be used for. The name only hints at a purpose, but nothing really ties it to serial data ready (despite misleading documentation).

@Spiked3 I beg to differ.  Yes, it is defined as weak, but there is a default one provided in HardwareSerial.cpp:190 which checks for serial data availability.  Yes, you can override it with your own, but if you don't (and few would) then it acts exactly as I described.

Interesting. We must have different code, as I am looking and the line you mention is at 63, not 190, but it is preceded with a note '// this next line disables the entire HardwareSerial.cpp,
// this is so I can support Attiny series and any other chip without a uart". In any case, in context of this question, not important, your answer stands as correct.


text:
Arduino IDE / Teensy 3 on Ipad
Does anyone know a good IDE for Ipad to write Arduino code and compile it for teensy 3 ?
Answers with different alternatives would be appreciated

I don't know of any way to compile it on an iPad, but Textastic should do the trick for writing the code if you set the syntax highlighting to C++.


text:
Non line of sight radio and arduino uno
I've been using a pair of arduino uno and nrf24l01 and found it wasn't really suitable due to low range when it comes to obstacles.
Essentially I'd like to use it in country areas where it would ideally transmit through dense trees and over hills at around 500 meters.
I've spotted the SI4432 and the sx1272 (which seems ideal but it doesn't seem popular despite it's high NLOS range capabilities?)
I was just wondering if anyone had any recommendations on which would be the best radio module to try? Any help would be really appreciated. Many thanks in advance.

Which country are you in, oduffy?

Hi  chaaarlie2, I'm in England

Then check out www.rfsolutions.co.uk, and their BRAVO transceiver modules.

@chaaarlie2 thanks I'll check them out

General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.
The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.

Not sure I would agree with the proposed frequency vs. range rule.  It is true that the ionosphere is more often reflective at lower frequencies (it's most basic characterization model being a "maximum usable frequency") but that will be more a source or interference than propagation here.  And there are bands where vegetation and atmospheric moisture absorb more.  But generally I'd look at trying to build a digital repeater or mesh network around one of the already digital-packet-oriented chipsets, even at 2.4 GHz.

@ChrisStratton Frequency vs Range is proved in the Friis equation (too complex to add in comments!) but is observerd by playing around with an online calculator such as http://www.random-science-tools.com/electronics/friis.htm .

@chaaarlie2 - that has essentially no application in terrestrial settings, such as this question.

@ChrisStratton on what grounds?

Here on earth, the grounds are curved, bumpy, and prickly with stuff - those facts dominate.

Since you already have the uno+nrf24 working, it might be worth trying a better nrf24 module before trashing the work you've already done. You can buy nrf24 modules with an integrated LNA, PA, and external antenna port. Just do a search for NRF24L01+LNA+PA. You can find them on amazon for < $10 and usually come with an external antenna.

Thanks Curtis, I do have one of the NRF24L01 with an aerials (http://goo.gl/nGfDDw). However, am I right in thinking that one doesn't have the LNA and PA circuits on?

@oduffy yes, some nrf24's have an external antenna but no LNA/PA.

Great, thanks, I'll buy a pair and see how I get on.

@oduffy Come back and add your results when you're done. This is a common topic and others would be interested. A quick search brings up some comparisons other people have done between different nrf24 modules... Like this. https://hallard.me/nrf24l01-real-life-range-test/

I will do, I'll write something up once I've done some tests


text:
Programming an Arduino BT-V06 using an UNO using ICSP
I have an Arduino BT-V06 laying around which I can't program over bluetooth for some reason. To be honest I don't understand the exact problem, but the problem is described in the question https://electronics.stackexchange.com/questions/7843/arduino-bt-upload-problem.
To solve the problem of programming the board I'm trying to program the BT-V06 using an Arduino Uno. I wired it all up using the description at https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader. The UNO seems fine, but the BT-V06 has the BATT-LOW led burning.
I've programmed the Arduino UNO using the Arduino ISP sketch. I've set the Arduino IDE to the COM port of the UNO, the target board to Arduino BT and the programmer to "Arduino as ISP". When trying to program the blink sketch I get the following error:
Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 28,672 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: verification error, first mismatch at byte 0x0002
         0x40 != 0x5c
avrdude: verification error; content mismatch

Could it be that the power requirements are too high to be powered through the UNO?

The sparkfun tutorial doesn't seems to mention the capacitor needed on the reset pin of the Arduino as ISP. On the Arduino Uno, you'll need to connect a 10 uF capacitor between reset and ground (source)

I'll have to buy the capacitor to try it out. Can you explain why it is needed?

When the IDE start to upload the code, it opens a serial connection. By design the Arduino Uno board resets when a new connection is opened. Because of this reset, the PC is communicating with the bootloader code, instead of the ISP sketch. They suggest you can also use a 120 ohm resistor between reset and 5v. Looking at the schematic, you can probably also directly connect it.


text:
Use of Resistor in PinWheel Exercise
I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.
Here is the schematic:

(if img not showing: https://goo.gl/tqZmKD)
My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?
Thank you!
EDIT**: Additional help from the arduino forums:
The resistor is needed so when the switch is closed you don't short the supply
to ground.  Switch open the resistor pulls the signal to ground and no current
flows, when the switch is closed it forms a resistive divider with the 10k
(switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling
the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.
Replace the 10k with a wire and you'd simply overload the supply completely and
perhaps weld the switch contacts shut.
Arduino Forums

It's a pull-down resistor.
A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).
With the switch open and no resistor present, the Arduino pin is neither high nor low. It will probably read as low if you tried digitalRead(), but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.
However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) until you press the switch, at which point the Arduino pin switches state.
If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?
Think about it...
One side of the switch connected to Vdd.
The other side is connected to the Arduino and GND.
Close the switch, I dare you.
Vdd is now connected to GND

Apologies - I didn't understand that. The switch controls whether or not voltage will continue to the green wire and thus, the digital input (in this case, pin 2). If switch is closed, voltage will continue to pin 2 and it will read HIGH. If switch is open, no voltage will pass through and the pin will read LOW. Is this not correct? And thank you for your time!

@ZAR: There is no situation of "no voltage" here; there is either Vdd or there is GND.

Hmm, so how is there voltage if the switch is open and thus not completing the circuit? I thought there would only be current when the switch is pressed, closing the circuit... Clearly I am missing some fundamental knowledge ;)

@ZAR 'no voltage' and zero-volts ARE NOT THE SAME. No voltage is no connection to anything, Zero Volts is connection to ground.

...and a digital pin that is not connected to anything is called floating. Any floating digital input could be either high or low, and you can't guarantee which (unless you read it of course). Floating digital inputs are thus highly inadvised. The same doesn't apply for unused pins - they can be left unconnected.

Aha, I did not know this. So we want to have 'Zero Volts' in order for the pin to read LOW, correct? But why do we need the resistor? Can't we just connect this straight to GND and achieve the same thing?

NO !! Read my answer again, starting at "Think about it..." Then read it again, and again, until you understand the very last sentence. Although you are correct with "[...] we want to have 'Zero Volts' in order for the pin to read LOW [...]"

You've explained well that we need to have a connection to GND so that we can pull the input to either Vdd or GND (and not allow it to float). Got it. You've also explained that the switch will, when closed, connect the Vdd with GND. Got it. Here's what I have from you: a) We must connect to GND. b) the switch will connect the vdd to GND. You've asked my question "What if I removed the resistor" and then said think about it. Perhaps there will be too much voltage headed toward the arduino? We can connect to GND without the resistor.. The Vdd will still connect to GND, so what here is missing?


text:
w5100 and nrf24l01 - SoftSPI - Radio not starting
I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.
The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time
The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.
What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.
Code here. http://pastebin.com/SMWC9x4F it errors at 146. Which I assume is the radio never starting since the:
radio.printDetails();

does nothing.
I'm using manicbug's library.
I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.
Pinouts:
CSN -> 10
CE   ->  9
MISO -> 12
MOSI -> 11
SCK   -> 13
VCC   ->  Separate 3.3 source, not the arduino
GND  -> GND
My guess is this is because both are using SPI.
Tried the softspi method http://pastebin.com/4mv612B7 .
Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..
EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago.  I can get details now. still having communication issues.  Will post more debugging information in a bit.

The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.

Issue one:  .printDetails(); uses printh.  If you don't have that included you won't get the information.
Issue two:  The ide gets confused when you have two libraries with the same file.  I compiled my receiver with the softspi file. Once I put the right library in it works.


text:
How is the diode here effective?
I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.
Here is the schematic:

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.
According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?
If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.
If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.
So how is this diode working?
Thanks!

Think about what the diode would do if it was just the diode and the motor, and you turned the motor in the opposite direction to normal (generated "back EMF").  It's just the same whether the rest of the circuit is there or not.

Thanks for the response. I'm still not understanding this. What happens if we just take the diode away here. Where is the back-voltage going? To the battery?

+1 Excellent question. Something puzzling that seemed not to make sene -> major lesson learned. (Hopefully :-) )

Please note that only fast diodes are effective there, as most H-Bridges that require external diodes will specify on their data sheets. If you are using a transistor like in your circuit, it's always a good idea to go for the fast version of a diode. For example, don't use a 1N4007, but an UF4007 (Ultra Fast) instead.

Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.
During a "back EMF" event (the collapsing of the magnetic field) a large voltage of the opposite potential is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.
That is very bad for anything connected to the - pin of the inductive load.
With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become forward biased and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.
Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.
The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.

This makes sense. Thank you. I have the same question to you as I do with the above answer. Can you check my question in the comments to that answer? After that, I should be good to go. Thank you!

See my edit.  It should cover it for you.

Flywheel Diode.
When the transistor shuts off, the stopping of the motor generates back EMF (ElectroMotive Force) . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.

This makes sense. I now get that the diode is trying to conduct the extra charge back to the positive rail. Still, won't some of that extra (harmful) voltage still reach the transistor through the greenwire? Or can that simply not happen because of the presence of the diode?


text:
How to interface arduino nano with sim900A?
I have arduino nano and sim900a modem.

Rx(pin30) and Tx(pin31) pins of arduino shows 3.8VDC respectively and Rx and Tx of SIM900a shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?
Thanks..

Given that it has a 9-pin D-sub and is not suspected of being differential, one would ordinarily expect RS232 voltage levels which would destroy your Arduino, and are also inverted in polarity.  However, it's not clear where the level shifting to that from the likely low-voltage signals of the SM900A itself is happening.  Can you show the back side of the board?   Do not rely on voltmeter measurements  for serial lines.

Thanks for the reply Chris. Are you asking SIM900A  back side?

No, the circuit board.  The Sim900 is only the little rectangular metal can.

@ChrisStratton i've posted the image.

The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.
It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.
However, a quick look at the SIM900A docs I could find suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!
Essentially, you have two problems:

You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter.  It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.
You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it.  You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's  data sheet and finding the enable pin, or merely desoldering it.

Another option would be to make your Arduino talk at RS232 levels using its own shifter board.
Finally, there's a sort of hackish option:  Connect the transmit data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 receive pin.

Hi Chris. I've designed a simple voltage divider circuit for arduino tx to modem rx. Now its working.


text:
PID control for Motor Speed control
I was trying to apply PI controller to a motor using Arduino. I have somewhat achieved the task but the problem is that it oscillates too much. Also i couldn't figure out what to do when pwm signal are calculated as negative
  int counter = 0;
  double end_time=0;
  double ini_time=0;
  double rpm=0;
  double my_time=0;
  double temp = 0;
  int pid_speed=0;
  float kp=2.25;
  float ki=.01;
  float kd=0.005;
  int prev_error=0;
  double pwm_sig=0;
  int integrator  = 0;
  int motor_sig_pin= 5;
  int error=0;
  int absolute = 0;
  float desired_rpm=1000; //my desired RPM value
  double zero_time=0;
  double i_time=0;
  double f_time=0;
  int rpm_tacho=0;
  int previous_error=0;
  int derivative=0;

  void setup() {
    pinMode(2,INPUT);
    digitalWrite(2,HIGH);
    pinMode(motor_sig_pin,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(10,OUTPUT);
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW );
    attachInterrupt (0,Count,RISING);
    ini_time = micros();
    i_time=micros();
    Serial.begin(115200);
  }

   void Count(){ //calculating time for one round using encoder

      counter++;
      if (counter>=100){
        end_time=micros()-ini_time;

        ini_time=micros();
        counter=0;
      }
   }
  void loop() {
      rpm = ((1000000*60)/(end_time));
      rpm = abs(rpm);
      rpm_tacho = ((1000000*60)/(zero_time));
      if (rpm <10 || rpm>5000){
        rpm=0;
      }
      error=desired_rpm-rpm;

      integrator += error;
      pid_speed = kp*error; + ki*integrator;

      pid_speed=(int)pid_speed;

      Serial.print(pid_speed);
      Serial.print("       ");

      if (pid_speed> 0){
        if (pid_speed>255)
          analogWrite(motor_sig_pin,255);
        else
          analogWrite(motor_sig_pin,pid_speed);
      }
      if(pid_speed<0){
        if(pid_speed<-255)
        {
            analogWrite(motor_sig_pin,0);
        }
        else
       {
          pid_speed=abs(pid_speed);
          analogWrite(motor_sig_pin,255-pid_speed);
       }
      }
      Serial.print ("      ");
      Serial.println(rpm);
  }

Just a few comments: 1) end_time is used both in normal context and in interrupt context, it should therefore be qualified as volatile. 2) In loop, as end_time is more than one byte, you should copy it to a local variable while blocking interrupts. 3) You are not using kd. 4) There is a ; before + ki*integrator, which means that the computation of the integral term is a no-op.

@EdgarBonet what do you mean by blocking the interrupt.

noInterrupts(); double end_time_copy = end_time; interrupts();, then use the copy instead of the original. Otherwise Count() may update end_time while you are in the process of reading it.

ini_time and end_time should be unsigned long or uint32_t, otherwise the tachometer will return garbage when micros() rolls-over to zero. 6) Then there is no point in abs(rpm), as rpm cannot be negative. 7) rpm_tacho is unused, and computed by dividing by zero. 8) You should properly indent your code before posting it.

You should also remove all the variables that you never use. 10) There is no point in casting an int to int. 11) Your set of if...else looks too complicated, why not just constrain(pid_speed, 0, 255)? 12) You should not Serial.print() on every loop iteration as it is too much to read and it slows down loop(). 13) But then you should control the update rate or your PID.

pid calculations also spit out negative values, what should i do for that?? @EdgarBonet

constrain(). Or better yet, use a ready-made PID library.

float kp=2.25;; I don't think the proportional part should be more than 1.0, but I might be mistaken here.

@Gerben: The kp can be larger than 1.  It should be whatever it takes to convert the measured input error to the process output.  If the input was radians per second instead of rpm, kp should be 2pi60=376 times larger than the kP would be for a sensor measuring in RPM.

Instead of thinking of the PID output as pid_speed, think of it as motor_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.
You are probably getting oscillation because of integral windup.  If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust.   For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec  If the integrator is faster than the system, it can easily cause overshoot.  You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmErrorseconds/100, rpmErrorseconds/10, or rpmError*seconds into output power.
To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.

I do not know if this question still exists or you managed to solve it. Regardless, I was (still am) working on a self balancing robot where I also faced such an issue and I came to this forum. The way I tackled it was to set PID outputs (assuming you are using Arduino 's PID library) 0 - 255 instead of -255 to 255. Now for my project I needed to change direction of the motor depending upon the inclination angle of the robot. So, each time I need to change the motor rotation direction, I do the following

I first reset the Iterm (or make it zero).
Change the direction of rotation.
Begin PID computation again.

Earlier I was also trying to achieve this by -255 to 255, but it was very jerky and I was not sure if that was the correct way to do it. With my current approach, I have managed to solve my problem.


text:
Need help with uploading to arduino ng or older with atmega8
I am a newbie in arduino. I successfully installed driver for arduino atmega 8l, which were provided by the company i bought arduino from. The driver is PL2303 by prolific. The reason i m mentioning this is because at first i had some problems in installing them.
Now after i have made a blink program. I thought of uploading it. Whenever I try to upload i get this error:
avrdude: arduino_read_sig_bytes(): (a) protocol error, expect=0x14, resp=0x75
avrdude: error reading signature data for part "ATMEGA8", rc=-2
avrdude: error reading signature data, rc=-1
My computer: Windows 7 32-bit
I tried pressing the reset button before uploading, i get the same message.
I tried it in another computer of mine. There the driver is showing a code 37 error so basically my other computer is not reading the arduino.(also my board comes with bootloader already innstalled). Thank You

You have to select the correct board from the Tools->Boards menu.

@Gerben i have selected the correct board as well as the serial port. I have select arduino ng or older with atmega 8 and serial port com25 in my case, the board info was given by the manufacturer of arduino

I thing 0x75 is for a ATMega16, not an 8. Please look at the main chip on your board. The type should be written on it.

@Gerben I already have checked the chip. Its is an atmega 8, I know how to program in 8 languages but electronics was new and i do want to try it, so i just ordered a new board, but would like to see this running too though and thanks for helping me out


text:
What is the diffrence between following arduino boards and which should i buy?
Arduino UNO R3 Compatible Board ATmega328P ATmega16U2
http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH_DefaultDomain_203&hash=item2ee26a3860
Arduino UNO R3 ATmega328P USB Development Board CH340G
http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH_DefaultDomain_203&hash=item463beed1f0
I will be working on a windows 7 32 bit pc.

The first is an unofficial clone of an R3 using the same schematic as the real R3.  The second is a rough copy using a cheaper USB serial interface chip.
Neither of them are real Arduino boards.  The first one is closer to the real UNO and should do the same things that a real UNO should do (assuming it works at all).  The second one - well, who knows?  You certainly can't do any of the fancy things to the USB interface that you can with a real UNO R3.
Which should you buy? Well, really, you shouldn't buy either of them - but if you must go for one I'd pick the first one.  Better to buy a real UNO from Arduino though, at least then you know what it is you're getting, and you expect it to work.  With these cheap Chinese clones (Chinduinos) you may just get a bunch of counterfeit chips selotaped to a piece of cardboard.

You can't say 'selotape' anymore. The politically correct term is "sticky tape and promises".


text:
MPU6050 causing arduino not to run sketch
I have a mpu6050(which I got from here http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html) and I have connected it to special ports on a sensor shield made for the mpu6050(http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem.
This is my code
#include <Wire.h>
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <I2Cdev.h>
#include <MPU6050.h>

MPU6050 accelgyro;
int16_t ax, ay, az;
int16_t gx, gy, gz;

#define Gry_offset 0
#define Gyr_Gain 0.00763358
#define Angle_offset 4
#define RMotor_offset 20
#define LMotor_offset 20
#define pi 3.14159

long data;
int x, y;
float kp, ki, kd;
float r_angle, omega;
float f_angle;
float Turn_Speed = 0, Turn_Speed_K = 0;
float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0;
float LOutput,ROutput;

unsigned long preTime = 0;
float SampleTime = 0.08;
unsigned long lastTime;
float Input, Output;
float errSum, dErr, error, lastErr;
int timeChange;

int TN1=3;
int TN2=4;
int ENA=9;

int TN3=5;
int TN4=6;
int ENB=10;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  pinMode(TN1,OUTPUT);
  pinMode(TN2,OUTPUT);
  pinMode(TN3,OUTPUT);
  pinMode(TN4,OUTPUT);
  pinMode(ENA,OUTPUT);
  pinMode(ENB,OUTPUT);

  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.payload = sizeof(long);
  Mirf.config();
  Serial.begin(115200);
  Serial.print("Hello");
}

void loop() {
  Recive();
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  r_angle = (atan2(ay, az) * 180 / pi + Angle_offset);
  omega =  Gyr_Gain * (gx +  Gry_offset);
  //Serial.print("  omega="); Serial.print(omega);
  if (abs(r_angle)<45){
    myPID();
    PWMControl();
  }
  else{
    analogWrite(ENA, 0);
    analogWrite(ENB, 0);
  }
}

void Recive(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Mirf.getData((byte *)&data);
    Mirf.rxFifoEmpty();

    y = data >> 16;
    x = data & 0x0000ffff;
    //Serial.print("  x="); Serial.print(x);
    //Serial.print("  y="); Serial.println(y);
    if(x >= 520){
      Run_Speed_K = map(x, 520, 1023, 0, 100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else if(x <= 480){
      Run_Speed_K = map(x, 480, 0, 0, -100);
      Run_Speed_K = Run_Speed_K / 50;
      Run_Speed = Run_Speed + Run_Speed_K;
    }
    else{
      Run_Speed_K = 0;
    }
    if(y >= 520){
      Turn_Speed = map(y, 520, 1023, 0, 20);
    }
    else if(y <= 480){
      Turn_Speed = map(y,480,0,0,-20);
    }
    else{
      Turn_Speed = 0;
    }
  }
  else{
    x = y = 500;
  }
}

void myPID(){
  kp = analogRead(A0)*0.1;
  //kp=17;
  Serial.print("  kp=");Serial.print(kp);
  kd = analogRead(A2)*1.0;
  //kd=840;
  Serial.print("  kd=");Serial.print(kd);
  //ki = analogRead(A3)*0.001;  Serial.print("  ki=");Serial.print(ki);

  //kp = 0;  Serial.print("  kp=");Serial.print(kp);
  //kd = 0;  Serial.print("  kd=");Serial.print(kd);
  ki = 0.08;
  Serial.print("  ki=");Serial.print(ki);

  unsigned long now = millis();
  float dt = (now - preTime) / 1000.0;
  preTime = now;
  float K = 0.8;
  float A = K / (K + dt);
  f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle;

  Serial.print("  f_angle=");Serial.print(f_angle);

  timeChange = (now - lastTime);
  if(timeChange >= SampleTime){
    Input = f_angle;
    error = Input;
    errSum += error * timeChange;
    dErr = (error - lastErr) / timeChange;
    Output = kp * error + ki * errSum + kd * dErr;
    LOutput = Output + Run_Speed + Turn_Speed;  Serial.print("  LOutput=");Serial.print(LOutput);
    ROutput = Output + Run_Speed - Turn_Speed;  Serial.print("  ROutput=");Serial.println(ROutput);
    lastErr = error;
    lastTime = now;
  }
}

void PWMControl(){
  if(LOutput > 0){
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, LOW);
  }
  else if(LOutput < 0){
    digitalWrite(TN1, LOW);
    digitalWrite(TN2, HIGH);
  }
  else{
    digitalWrite(TN1, HIGH);
    digitalWrite(TN2, HIGH);
  }
  if(ROutput > 0){
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, LOW);
  }
  else if(ROutput < 0){
    digitalWrite(TN3, LOW);
    digitalWrite(TN4, HIGH);
  }
  else{
    digitalWrite(TN3, HIGH);
    digitalWrite(TN4, HIGH);
  }
    analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset));
    analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset));
}

and this is a picture of the mpu6050 on the sensor shield

Please post your code and, if not included in the above links, the schematic.

The shield you linked to is no longer sold.
The current version is

But it has no special connection for an MPU6050 breakout (and BTW that same 6050 board is $6 about everywhere else).  A shield serves no purpose for just the 6050 really.
If you connected the 6050 to the I2C lines (aka A4 & A5), Then you also need to connect an additional interrupt line.  If you are using unmodified example code, it depends on the interrupt being connected.
Here is a post made a while back using the 6050
http://www.spiked3.com/very-cool-imu-demo/
It is possible to use the 6050 without interrupts but you would have to (understand and) modify the standard example code.
Update: I knew you had a different board, and it had a connector for the 6050, the comment was that the link you provided, since it was 'no longer available', did not link to any documentation. Without a schematic it can not be known how it is hooked up beyond simple I2C. As you are using other devices I am not familiar with, I would expect some sort of conflict on the i2C bus maybe. Are all i2c bus devices using the same reference voltage? It does not matter if they are all 5v or all 3.3V as long as they are all the same.
Since you say 'nothing is printed' and your second line of setup is 'initialize' gyro, odds are good it is not getting past that. Simple (archaic) debugging, put a print (and a small delay) before and after the call to initialize.
My code uses the following for Wire.begin
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
    TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif

I dont know if your Arduino is different and if it would make any difference.
I have a line after initialize
mpu.testConnection();

That may or may not help you.
FYI PI is already defined, as is DEG_TO_RAD and RAD_TO_DEG
if (abs(RAD_TO_DEG * headingDelta) > .1F)
    poseChanged = true;

Update: I just looked quickly at the code, and the only thing initialize does is write to i2c, it never waits really. And that means writing to I2C is hanging.  I ran into this once when I had an unpowered device on the bus. I thought it would not harm, but I was wrong.  Does the power light on the mpu come on? (is it really getting power?)  I have run them at 3.3v and 5V so I do not think that would be a problem, but  if you can, switch it to 3.3V to be sure. Getting down to the nitty gritty, you could check if the default pullup resistors are still on the board and did not get accidentally knocked off. Even better would be to try it with a known good MPU.  I have about 10 of them within reach :P (spiked3.com)

I do not fully get you, on the shield I have on one of the sides there are eight holes where a mpu6050 goes, as it says mupu6050 beside them. I have added my code along with a picture of the sensor on my shield

Yes it is not getting past the accelgyro.initialize();

Sorry to say but at this point I learned how to (buy and) use a saleae logic analyzer.  Start a new sketch with nothing but the MPU code. If that works, then its a conflict with the 24l01 maybe?

I tried a mpu6050 example and that did not work either

The light does not come always as the mpu6050 is not stuck to the pins, however when I press the mup6050 against the pins to make the light light up the arduino gives me this error "programmer is not responding
avrdude: stk500_getsync() attempt 1 of 1: not in sync: resp=0x00"

Sounds like you need to make better connections. Sparkfun (and others) have pins that connect well without soldering so you can change your mind later. I have used them with success on the MPU breakout board before. The error you are getting is almost always an Arduino in a not happy state, caused by some electrical problem. https://www.sparkfun.com/products/10527


text:
Which Arduino Board should I start with?
I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.
My questions are:

Which Arduino Board should I start with?
Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?

Start, exactly as your question tag says, with an Uno.

And I don't know of any Arduino simulators that don't cost less than the price of 50 Unos.

@chaaarlie2 Okay that is fine, any recommendations or points I must consider to get started well?

As @rslite says, get a starter kit. But before you get anything, buy a book. It will be more educational in the first chapter alone than any answer here will be.

My advice:
 - get a model with USB port (some do not have one)
 - the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up
 - you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC
 - same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.
I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.

Well, thanks for the idea. I have a good programming back ground: C, VB, Java, PHP,HTML and JavaScript. As of now I am specializing with Java, C and C++, however, I lack an electronics background. I visited Ebay and found too many boards that have the same tug as one I am looking for. If please you can point for me one that I can start with from this list

this is what I would recommend:
http://www.ebay.com/itm/Hot-Sale-ATmega328P-CH340G-UNO-R3-Board-Free-USB-Cable-for-Arduino-DIY-DJNG-/351337582344?pt=LH_DefaultDomain_0&hash=item51cd5a0f08

this is a bread board (but there are many other types):
http://www.ebay.com/itm/Prototyping-Prototype-Shield-ProtoShield-Mini-Breadboard-for-Arduino-UNO-R3-Mega-/360919191173?pt=LH_DefaultDomain_77&hash=item540875ce85

this is a variant I have never used:
http://www.ebay.com/itm/UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-NEW-/281685195762?pt=LH_DefaultDomain_0&hash=item4195befbf2

this is an example of cables, i advice buying male/male male/female female/female:
http://www.ebay.com/itm/40PCS-Dupont-Wire-Color-Jumper-Cable-2-54mm-1P-1P-Male-to-Female-20cm-WC-/221480820368?pt=LH_DefaultDomain_0&hash=item3391491e90

some rgb led:
http://www.ebay.com/itm/50pcs-Ultra-Bright-5mm-4-pin-RGB-Diffused-Common-Anode-LED-light-Red-Green-Blue-/281487760818?pt=LH_DefaultDomain_0&hash=item4189fa5db2
And don't forget the resistors (see the LED page).

Thanks very much for the ideas, I will settle for what you have recommended.

If you find the answer useful, please remember to upvote it :-)

Depending on your budget you could start with an Arduino Uno starter kit that will include the Arduino, breadboard and wires plus different sensors (like this one - but there are others with less peripherals and cheaper).
If you have a lower budget you can still buy the arduino and many separate sensors/LEDs etc from eBay.
By googling you'll find a lot of tutorials about getting started with the hardware that you bought.


text:
Can we control an Arduino with voice commands?
I'm looking for some method to control an Arduino with voice commands.
Could this work on this platform?

"Google Now" is a proprietary process that requires the Android operating system. You can't run Android on an Arduino, at least not if you're having to ask. However, controlling an Arduino by your voice IS possible, maybe.

Yes possible on some of the high end Arduinos, but I know of no example where it has been done. The quality of recognition will be proportional to the processing power provided. In the case of an Arduino, probably not at an acceptable level.
You would be much better off looking at the multitudes of PC solutions, and using the Arduino as an interface to what ever it is you plan on controlling.
FYI: https://www.sparkfun.com/products/13316