text:
Using shiftin() and shiftout() with the same circuit - what to consider?
I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.
This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.
In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with shiftIn() function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the shiftOut() function.
My doubts are: what should I consider in order to do so?

How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in [latch, clock, data], and three for shifting out), right?
Can I use any pin I want? Or is it required to use specific pins?
Is that the "right way" of doing this? Any suggestion or improvement is welcome!

If you can get your head around it, using SPI will let you output to the '595 and input from a shift register (I would avoid CD4k unless you're prepared for its shortcomings) at the same time. And there are a number of GPIO chips that use I2C, which will let you avoid having to deal with shifting altogether.

I'd recommend drawing a schematic of your circuit.  Not only will that make it clear in your own mind, it will aid the folks in the forum to visualize the picture.  Also, once you have the schematic, it will be much easier to construct your physical circuit as you will now have a blue print to follow.

@IgnacioVazquez-Abrams now you got me curious: Since this is the IC used on shiftIn() tutorial, what would these shortcomings be? What other shift register could be used instead? Also, the I2C tip is interesting, are those parts expensive in comparison? How should I search for one, and what would be a good 8 channel "equivalent" to the parts I mentioned?

CD4k parts have the drive strength of a wet noodle and the speed to match. They will work in that specific application, but do not get too used to them until you learn more about electronics and why their differences matter.

As for I2C, there are many options available, some a bit more pricy than others. The basic chip is the MCP23017, which has 16 GPIOs that can be used in any combination of input or output, with optional pullups, pin change interrupt support, etc., and up to 8 can be put on a single bus. It even comes in a SPI variant if you need to access it faster. There are other options such as the TCA6424A, but they come in more exotic packages that you may not be ready for.

@IgnacioVazquez-Abrams thanks very much for your valuable tips. You see, my question was a bit like "is what I am trying to do, and how I'm planning to do it, a good idea, or are there better ways?", so if you care to summon your suggestions as an answer, I would be glad to accept it. I don't know practically anything about I2C or SPI, but the MCP tip sounds like the right way to go, EXCEPT that I wasn't planning to use SMD, but actually through-hole, DIP ICs on a veroboard (or equivalent). Is there a through-hole version of that?

If you follow the link and examine the datasheet you'll see that the MCP23x17 is available in DIL, among other packages.

I found this library from Adafruit for that chip, sounds definitely the way to go: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945
That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).
I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that  Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.
You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.
There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.
See:
http://www.gammon.com.au/i2c
http://www.gammon.com.au/spi

Is there a through-hole version of that?

All the chips I mention here have through-hole versions.

Excellent! I'm new to digital electronics, so finding out all these things has been amazing! One more little question: if I don't need as much as 16 IOs, is there a similar chip with less IOs? I searched for some, and looks like PCAL6408 is a similar, 8-bit one, what do you think? Thank you very much!

As far as I can see the PCAL6408 does not come in a DIP package (through-hole). The MCP23017 seems to be selling on DigiKey for $US1.44 so that seems a reasonable price to me.

You're right, I though I have seen a DIP one, but no... Anyway, I'll look for the MCP, thanks!


text:
Increment in switch statement not working
No matter how I rearrange this, the increment compare always returns false....
I have even taken it out of the if, and put it in its own if:
int buttonFSM(button *ptrButton)
{
    int i;
    i = digitalRead(ptrButton->pin);
    switch(ptrButton->buttonState)
    {
    case SW_UP:
        if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
        {
            ptrButton->buttonState = SW_DOWN;
            ptrButton->debounceTics = 0;
            return SW_TRANS_UD;
        }
        ptrButton->debounceTics = 0;
        return SW_UP;
    case SW_DOWN:
        if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up
        {
            ptrButton->buttonState = SW_UP;
            ptrButton->debounceTics = 0;
            return SW_TRANS_DU;
        }
        ptrButton->debounceTics = 0;
        return SW_DOWN;
    }
}

I get the impression that ++ptrButton->debounceTics needs some bracketing. I fear the compiler is reading it as (++ptrButton)->debTic and you actually mean ++(ptrButton->debTics). You are increasing ptrButton's value, i.e. where it should point to, not the value of what it points to. I would also add some brackets to break up the if statement conditions, although I think that's more my preference than a syntax requirement: if((i==0) && (++(ptrButton->debounceTics) == DBNC_TICS)).

I'd go further and say that side effects like this in the expression statement  should be avoided for example:
ptrButton->debounceTics = ptrButton->debounceTics + 1; if (... expressions ...)

@Kolban The intention of the code is unclear, so it may be a requirement that it's written like this. Short circuit evaluation means that if i!=0 (or 1 in the second if statement), debounceTics will not be incremented.

Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC_TICS is set to, but I'm assuming it's > 1.
ptrButton->debounceTics will never be greater than 1 because you always:
    ptrButton->debounceTics = 0;

-1: the code is clearly a subroutine from loop() (or another function) so you cannot make assumptions on what debounceTics's treatment ought to be inside this function.

Why is this marked down? This is the correct explanation.

@CharlieHanson No assumptions - it's always being set to 0.

The error is due to wrong expectations on operators precedence:
++ and -> have the same precedence, so they are evaluated left to right.
See http://en.cppreference.com/w/c/language/operator_precedence .
Overall, the lack of parenthesis makes the readability poor.
The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period.
Then read the value and decide if it's high or low.
But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling.
Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.

  if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
    {
        ptrButton->buttonState = SW_DOWN;
        ptrButton->debounceTics = 0;
        return SW_TRANS_UD;
    }
    ptrButton->debounceTics = 0;

I'm going to agree with user3877595 but explain why, as his/her answer got a downvote.
DBNC_TICS has to be > 1, right? Otherwise what is the point?
We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero.
If DBNC_TICS is == 1 then this is always true:
++ptrButton->debounceTics == DBNC_TICS

Therefore that test is useless.
If DBNC_TICS > 1 then it will not execute the "if" block and execute this instead:
    ptrButton->debounceTics = 0;

So ptrButton->debounceTics is back to zero, and we are back to square 1.
Therefore the test will always be false.

No matter how I rearrange this, the increment compare always returns false....

As stated in the question.

source: Stack Exchange

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

sort: votes


text:
How does the reset button work on the Arduino?
I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.
I have been using this board for many weeks with no problem and just now I have been getting this error:
avrdude: stk500_getsync()

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.
The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.
When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

If you have anything else plugged into the Arduino then unplug it.
Try powering the Arduino from different power supplies.
If you have another Arduino or an AVR programmer try re-flashing the bootloader.

Thank you. You've confirmed my suspicions. I've been trying to re-flash the bootloader with another Arduino but I keep getting errors for that too. Maybe it's because I didn't unplug everything or maybe because I have bad connections to the ATTINY pins. What sucks is that this Aruduino is part of a robot and I have all pins being used and hot glued into place. I was hoping for a better answer than unplugging everything. :|

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


text:
how does an 8-bit AVR do 10-bit analog read?
I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for analogRead().
https://www.arduino.cc/en/Reference/AnalogRead
I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.
My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?
Shouldn't the analog read be 2^8 or 256?

It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.

...or two bits in the 'low' and 'eight' in the high. You can decide which within your code. The purpose of this is to allow you to easily 'downscale' your 10-bit ADC result to 8-bit : With the eight most-significant-bits in one register you can use one single read command to get your result. This can be useful if you don't need a 10-bit resolution, for example if the input is so noisy that the lowest bits become irrelevant.

@chaaarlie2 Also the left-alignment option gives you in effect a 16-bit value (though with 6 lowest bits static) which is very useful if using standard mathematical algorithms etc that expect a 16-bit value. Means you don't have to do any expensive shifting of each and every sample.


text:
How to store values inside an empty array and get the average integer? [UPDATED QUESTION]
Goodafternoon,
I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.
After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?
I came up with the following:
const int micPin = A0;
int soundArray[10];

void setup() {

  Serial.begin(9600);
  pinMode(micPin, INPUT);

}

void loop() {

  int micValue = analogRead(micPin);
  Serial.println(micValue, DEC);
  //delay(400);

  for (int i = 0; i > 10; i++) {
    soundArray[i] = micValue;
    Serial.println(soundArray[i]);
  }
  delay(1000);
  Serial.println("End of for loop");

}

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.
This is not what I want. I want to get different numbers in the array of that moment.

Hope someone can help me out.
Thanks in advance.

I have a library that does what you want: https://github.com/MajenkoLibraries/Average

Since you do not change micValue, soundArray[i] = micValue is always storing the same number. You probably mean soundArray[i] = analogRead(micPin).

I'm guessing that the code you posted is not copied from your sketch as the for loop will do nothing.  You initialise i to zero then only run the loop whilst i is greater than 10, which it will never be...

The error message is correct. You did not define the size of the array.
You have 3 choices:

Declare it with a constant length
int foo[10];
Declare it and initalize it
int foo[] = {0,1,2,3,4,5,6,7,8,9};
Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)
int foo;
int size = 10;
foo = (int)malloc(size * sizeof(int));
free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array

Ah oke, I understand it. And the third point is to calculate the average?

Add the values together, then divide by the number of values. Simple junior school math.

Maybe I am not asked it right. The values from the analog port will be stored in the array. Then I want to get the number that is repeated most time.. So when I get an array with: (1,2,1,4,5,2,1,3) the number 1 is repeated most type and that one I will store in another variable for example valMost.

Ah, the operation then is called "mode".  My Average library (pointed to above) will do mode() for you.

I will check your code @Majenko. Check also my updated answer so there will be no mistakes!

There are three main sorts of "average" used normally in Maths:

Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
Mode: This is the "most common" value in a set of values.  For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
Median: This is the middle value of a set of values.  If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.

By your comments it sounds like "mode" is what you are after - the most common number in your set of values.
It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.
I have an Average library that can do it for you.  The main part of the mode() function of that library looks like this:
most = _store[0];
mostcount = 1;
for(pos = 0; pos < _count; pos++) {
    current = _store[pos];
    currentcount = 0;
    for(inner = pos + 1; inner < _count; inner++) {
        if(_store[inner] == current) {
            currentcount++;
        }
    }
    if(currentcount > mostcount) {
        most = current;
        mostcount = currentcount;
    }
    // If we have less array slices left than the current
    // maximum count, then there is no room left to find
    // a bigger count.  We have finished early and we can
    // go home.
    if(_count - pos < mostcount) {
        break;
    }
}
return most;

Basically two loops, one inside the other.  The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at).  If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value.  Move on to the next number.
To use the Average library it's quite simple:
const int micPin = A0;

// We want to be able to store 10 int values here.
Average <int>sounds(10);

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

void loop() {
    // Push 10 values into the Average buffer.  Any old values will drop
    // off the bottom.
    for (int i = 0; i < 10; i++) {
        sounds.push(analogRead(micPin));
    }
    Serial.print("Mode value is: ");
    Serial.println(sounds.mode());
    delay(1000);
}


text:
Pinout of Arduino 9 Axes Motion Shield
I bought an Arduino 9 Axes Motion Shield without looking at the pinout. I'm worried it won't work with my Adafruit Motor Shield v1.
It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?
It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.
update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess.

The I2C pins on the V3 shield are just copies of A4 & A5 - so just run a jumper wire some way.
BTW that Motion shield looks like it only uses 1 interrupt pin in addition to I2C, so you may be ok.
The motor board does have a library at https://learn.adafruit.com/adafruit-motor-shield/downloads and you can look at the code to see what it uses.
I personally use the mpu6050 - same kind of thing, I2C one interrupt but only 6DoF (which is plenty).  The 6050 has been superseded with the 9150, 9DoF.  6050 break out boards sell for $6 (or less).  Actually I put all this together on one piece (http://www.spiked3.com/new-products/)


text:
Strange phenomenon when declaring double
Consider this question closed, found my answer through the answers I had
I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

Is someone able to check what is wrong with my code?
float array[30];

struct Formula {
  int LoopTime = 1000;
  int AccelerationLoops = 11;
  float VelocityLoop = 0;
  float VelocityFactor = 0;
  int TotalLoops = 0;
  float DeltaPosition = 0;
  int Setpoint = 0;
  int Iteration = -1;
  float EndOne = 1.25;
}Formula;

float SetPosition = 1404;
float Position = 0;
float Velocity = 36;

void setup() {
  Serial.begin(115200);
  for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    ProgFormula();
    Serial.println(Formula.Iteration);
    if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
  }
  for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
    //Serial.println(array[Formula.Iteration]);
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

void ProgFormula(){
  if(Formula.Iteration == -1) {
    Formula.DeltaPosition = SetPosition - Position;
    Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
    Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
    Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
    Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
  }
  else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
    Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
  }
  else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
    Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
  }
  else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
    Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
  }
  else {
    Formula.Setpoint = Formula.Setpoint;
  }
}

In setup(), array[Formula.Iteration] = Formula.Setpoint yields undefined bahavior when the index is −1.

Bit of a shame that i missed that... Edited my code, what is the reason my double values of the array are just integers with extra zero's?

In avr-gcc, double is the same size as float.

But in what way will that effect my results?

Please be more specific about what the problem is: What behavior do do expect from your code? What behavior do you have instead?

I am trying to make a motion profile for the position (edited my question).

If an answer provides the solution you want you should accept it. Also, writing an "answer found " message at the top is not what's done because the site is trying to build a set of matched questions and answers. So the 'green tick' when you accept serves the same purpose.

OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use printf():
/* Compute position for any acceleration profile. */
void compute_profile(float (*acceleration)(int), int max)
{
    float x = 0, v = 0;

    for (int t = 0; t <= max; t++) {
        v += acceleration(t);
        x += v;
        printf("%d\t%f\n", t, x);
    }
}

/* Your particular acceleration profile. */
float VttgJ(int t)
{
    if (t <  7) return t;
    if (t < 13) return 12 - t;
    if (t < 40) return 0;
    if (t < 46) return 39 - t;
    else        return t - 51;
}

int main(void)
{
    compute_profile(VttgJ, 50);
    return 0;
}

The user inputs the following: Position and Velocity. They both need to be controlled. Because this isn't possible I have build three different formules by integrating the velocity curve. The system is able to measure a position and has a constant looptime. My code is rather complex and can probably a lot shorter. Maybe a modification of your code will be a lot smaller.


text:
Counter using Ultrasonic Sensor (self.arduino)
I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!
example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....
What it is currently doing:
Count:0
Count:0
Count:0
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm, count;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

    // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
// count = 1;

 if (inches > 5)
{
  Serial.print("Count: ");
  Serial.print(count);
  Serial.print('\n');
  delay(1000);
        count++;

}

}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}

Count is a local variable - it gets re-created afresh every time the loop() runs.
Either make it global, or make it static.
These two options look like this:
Global
long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static
void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.

i did int count inside the loop and it still didn't do anything...

You need to place it outside the loop (i.e. global).


text:
How to use Arduino Nano with Arduino Uno
I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?
It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.
Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

Are your Arduinos driving heavy loads or are their outputs only connected to high impedance inputs?

Nothing too heavy. Uno - motor controller (2 tiny motors), 2 servos, push button. Nano - Several LED's (just a few on at one time) and two range finders.

The Nano itself will not draw much current. So, if the sum of your loads is within the Uno's capabilities, it normally should work fine.

Two servos is a really heavy load.

try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.

Be careful not to power any sort of motor directly from an Arduino (or any of it's siblings directly) without a transistor or H-bridge in between, unless you know exactly how much current your motor draws, peak, and how much your arduino can supply on any given pin. The same applies to any other high-draw device too.
If you are using LEDs, make sure you have a resistor in series with the LED - google "LED resistor calculator" to help you figure out which resistor you need.
Also, when you upload the program, it uses two of the pins - rx and tx, should be digital pins 0 & 1 on a Uno (any other, check your docs).

What are you talking about? I didn't ask any of this. I already know all of this. Terrible response.

Maybe it is a very good idea to connect Arduino UNO's only one DIGITAL out point among other digital output pins. This pin can trig Arduino Nano's analog input pins so that you can work your task for further you needed. But you have to seperate your shields or your motors or other things. Like this:

By the way, if you get an upload error, please plug out your shileds or motors or LEDs then try to upload your code again into Arduino UNO.

Connect the GNDs as well.


text:
What is the best way to make a good but simple line follower?
I am new in this site, and like you can see I want to do a line follower, not a clumsy and slow line follower, but a fast and "fancy".
I investigated about the PID method, but can someone explain me in simple words what is it.
Thanks for your answers.

Have you already chosen/built the robot? what kind of hardware do you want to use? BTW, I suspect that PID will only be useful if you have a continuous/fluid way to sense the line and not just 3 infrared sensors like many basic line follow bots have.

The chasis... I have not make it yet, and i have 8 sensors in an array.

This might be a good tutorial for you to look at:
http://letsmakerobots.com/node/39972

Did you check wikipedia, for example?
I doubt it is possible to describe a PID controller in simpler words than those used by the article.
The pseudocode is quite simple and should be also very good for understanding the concept, when applied to a digital system.
See also the limitations of PID controllers.


text:
Velocity from Sensor Data - Best Approach?
I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity.
What is the best approach to get accurate, smooth, and fast data to my control logic?
Would I benefit from combining accelerometer and barometric data? If so, how?

Background:
I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.
Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.
I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.

Thanks!

First off, this is cool. When I first read your question, I was going to say that this is by no means easy, but the fact that you know what a Kalman filter removed any doubts entirely. In any case, I have a few ideas, but questions first! (1) How smooth do you want your data? It looks relatively smooth to me, but I can't say I know the sensitivity of your control system. (2) What was your impetus to use a Kalman filter? (3) How did you implement the filter? (4) Do you have a gyroscope, (5) Could you post your code?

Thanks for the reply! I am not too familiar with the Kalman filter, but I do have an aerospace engineering background.

For example, in this case, the rocket's velocity should only be affected by air drag and gravity. There should be no spikes down or especially up like in the data I tested against. I would like to see a curve similar to the grey line, but it seems to lead rather than follow the as the Kalman filter is causing.
I have read about it being used in similar control systems such as robotics (which I consider this very similar to).
It is a very simple implementation.....

...I wanted to initially just filter the sensor data versus model the system (which the Kalman filter can do) so I opted for the simplest approach.
4) I do have a gyroscope (L3GD20H) and accelerometer/compass (LSM303) from the Adafruit 10DOF.
5) I do not currently have the filtering implemented in my code, I tweaked the parameters and tested it using my data output and excel (and in the case of the screenshot, previous rocket flight data from another altimeter). My steady state parameters...

... from the Kalman filter implementation I posted are as follows:
P: 27.92 or 22.92 (depending upon where in the code)
K: 0.1791
R: 128
Q: 5
@Mlagma The reason I haven't moved onto using a matrix implementation of the Kalman filter yet, is that I am worried it may still produce significant lag and I wanted to know if there was a better filtering technique for what I am doing.

I just wanted to thank you for making this post. I had a similar question.

Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).
The first few things to address are in regard to the barometer:
(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data before passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.
(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there.  (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."
Just one more thing before we get into the filter...
It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.
Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.
One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between [-1, 1]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.
Regardless, here's some insight that may be useful:
The Kalman filter is very much dependent on how you model your system.
To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):
Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.
We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:

The filter works fairly well.
But what if our model happened to be off - that is, it doesn't reflect what's really happening?
In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.
This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.
There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag",  you need to use what is known as an extended Kalman filter - which basically linearizes your data.
Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.
In any case, I hope this helped. Feel free to ask any questions.
(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).

Thanks for the awesome info! I want to get into the Kalman filter modeling for the actual rocket launch, but I don't have any unfiltered data. The Raven already filters its data and I can't test against that.
I have been messing around with combining the low pass filter with the 1DKalman I was using before, it certainly gives better results for less lag time!
Would I be best off (unless I can get real sensor data) to implement some sensor fusion? I was thinking by combining accelerometer data with the baro, I can smooth it out, but I am not quite sure how to do that yet.

I am starting to feel like this is going well past the scope of my original question. I have been doing some research and it may sound like to get good data I may need to implement a full IMU system. Do you have any reading suggestions for books or otherwise? I frankly don't know where to start.

@ZNaught Sensor fusion will certainly give you better data, and this is where the Kalman filter excels. However, it can quickly become hairy because you'll automatically be using a 2-D filter. An IMU is probably the best sensor you can use for this application - some already do the filtering for you. If you're going to be using an accelerometer, you'll need to process its data with a gyroscope in order to retrieve accurate data. In regards to books, are you looking for references on filtering, control systems, both, or other?

Also, I know you said your background is in aerospace engineering (degreed, student?), but what's your mathematical background? I'm not sure what math courses aerospace engineers take.

The IMU I am currently using is the Adafruit 10DOF which does absolutely no filtering (except the sensors themselves which you can select resolutions and such). It has a gyro, compass, accelerometer, and barometer (with temp). As for books, I could use background on both of those subjects for sure. My math background is up to differential equations and I have a year left until I graduate with my BSE.
I did find this awesome resource, it seems to be what I am trying to do: http://home.earthlink.net/~david.schultz/rnd/2004/KalmanApogeeII.pdf He has a bunch of info on his website too

Sounds good. The article you linked is probably one of the best I've seen as an introduction to Kalman filtering. I know at my University the aerospace department has a course on linear systems. Now my background is primarily applied math and signal processing, so the course I took on linear systems may be slightly different. The books I used, Signals and Systems by Oppenheimer, is a great place to start. Its dense, but I don't think you'd have an issue getting through it. The reason I mention it is that it gives you a solid basis to branch off into control systems and filtering.

I'll also try to recall the name of one of the  controls books I have. In regards to filtering, I'd start with the book I mentioned. The complexity and the amount of math required for signal processing can grow fairly quickly. A solid understanding of linear algebra and probability is extremely helpful. Sheldon Ross has a good book on probability theory, and Applied Linear Algebra by Oliver and Shakiban is a nice, self-contained reference. I'll also try to post some PDFs later.

Thanks! Do these cover the Extended Kalman Filter? That is definitely what I need to implement.

I don't believe they cover the EKF. I don't really know of any textbooks that cover it. Typically, if I need to implement one of these filters or read up on them, I'll pull up a research paper or lecture such as this: http://www.cs.cmu.edu/~motionplanning/papers/sbp_papers/kalman/ekf_lecture_notes.pdf They tend to be pretty thorough.

Hey thanks! I will see what kind of progress I can make

You can use Excel to smooth out data and do graphs if you need to. That's what I use myself. Easiest way is to create a table and type formula to make average from range of numbers, smoother data needs a bigger range of numbers.


text:
How to read/write variables persistenly on Arduino Due (no EEPROM/shield)?
I am relatively new to Arduino and I am currently writing some code to control a relay board. The on/off times are provided by the user at run-time and should be stored persistently (EEPROM or flash) in case of power-down.
On my Uno I worked with the EEPROMex library and that worked well. Now I have a Due which doesnt have any EEPROM and I am struggling how to store variables persistently. Specifically, I dont know how to access whatever I wrote to the flash memory previously. In the example below the content of test[] is obviously overwritten on every restart.
PROGMEM int test[] = {1, 2, 3, 123, 23};

void test()
{
  Serial.println((long)test);
  for (int i = 0; i < 5; i++)
  {
    Serial.println(test[i]++);
  }
}

I noticed that the address does not change during re-starts, so I I tried reading/writing beyond index 4. This out-of-bounds read/write worked, I guess since I am anyway not storing anything else. Interestingly even this memory which is out of the array is overwritten on power-up.
So: How do I store on unser input data (variables) persistenly on an Arduino due without using any shields?

You don't need a whole shield for EEPROM. Just 4 or 5 wires and an EEPROM DIP-chip.

I really hope that somebody knows differently, but I'm fairly sure that the answer is that you can't directly save runtime data back to the Arduino Due board.  I've looked into this myself and have only found answers saying "wire up an external EEPROM" or similar.  Whilst it seems that it should be technically possible to write into unused (or pre-reserved) areas of the program memory, I suspect that the CPU has to be put into a special mode to do this, which is very probably only possible from the bootloader when flashing a new program to it.
I've chosen to go with FRAM chips for data storage. Link to mine.  They are difficult to wire up - the only ones I found were in surface mount packages (although some hobby retailers sell them mounted to little boards with header pins), but they are very cheap, very durable (you can write to them a great number of times before they wear out), operate at high speeds and you can read/write single bytes from/to them.  Other storage chips often require you to write whole "pages" of data at a time which can mean reading in the existing data, modifying it, then writing it back.
Additional comments:
In your original question, you state that the contents of your PROGMEM located array must be restored on restarts.  I don't think this is the case.  That would suggest that the contents are stored elsewhere and code is in place to overwrite them, however it could be the case that they are copied into working RAM, which would mean that the PROGMEM macro is not actually doing anything on the Due - which may well be the case.
Modify your code to change one of the values of the array (within the bounds of the array!) and then print its value out again after changing it.  If the value printed has changed then this means that PROGMEM is not actually doing what it is supposed to do on the Due, which would be a real shame.

Adafruit sells FRAM on a breakout board which is a lot easier to deal with when everything else is thru-hole. Plus FRAM are crazy fast compared to EEPROM.

The SAM3X8E has also backup domain (several backed up registers, RTC), but its power supply is shorted to the main 3V3 rail on DUE board, so there is no easy way to add battery.

This library called DueFlashStorage was created by Sebnil and is in the Arduino Library Database Tool!
It basically takes the EEPROM functionality and applies it to the Flash storage on the DUE. The only drawback is that the flash memory gets erased every time you upload a new (or new version of a) sketch.
For my application that works but for other applications that might not be what you want!
Click here to go to the GitHub for it called DueFlashStorage

Without an external device you won't be able to store data permanently. So it might not be a full shield, but you'll have to add SOMETHING. Depending on how much data you need you might use components that have EEPROM as a side feature. For instance, as explained here, the DS1337 RTC module has 56 spare bytes of EEPROM^H^H^H^H^H^H Non-Volatile RAM available. I know, it sure isn't much, BUT it might be enough for your needs, depending on how much you need to store.
And of course it provides you with DateTime capabilities, wich could come in handy.
Aside from this, there are EEPROM chips mounted on a small board, with DIP switches to set the I2C address, which would be very discrete, and could store a large amount of data. See this one for instance.

Technically the DS1337 memory is not called EEPROM, but battery backed RAM. You can abuse the alarm sections to get an additional 7 bytes :-). I used this trick on the DS3231 which doesn't have any 'free memory'.

You're right. The datasheet says "56-byte, battery-backed, nonvolatile (NV) RAM for data storage". Neat trick you did abusing the alarm section ;-)

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


text:
Why is this returning the wrong answer?
Why does this print output -3? xpos can be any value.
void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);

}

What types are your variables declared as? (int, float, etc)

xPos and yPos are ints and pwm is currently float i tried int aswell, and its outputting 0 not -3 sorry, (xPos*255)/1023 outputs -3.

@user10936 Could you edit your question to include the setup() loop and the declarations of xPos, yPos, and pwm. There could be something there that you're overlooking.

Just swap the priority of the operations. So use pwm = xPos*255/1023; instead.

The problem is that (255/1023) is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:
pwm = xPos*(255.0f/1023.0f);

Is the f designator necessary? Without it does the compiler treat the calculation as doubles and then re-cast it to float or something? Also, is it not sufficient to add the decimal point to just the numerator or denominator? I know it works in 'regular C++ on a computer', but in an embedded environment would it bloat the program memory?

@chaaarlie2 Without the f designator, a C++ compiler would treat it as double during the calculation, which normally requires slightly more resources. Most Arduinos treat float and double the same though so it wouldn't necessarily make a practical difference. It's not usually a good idea to rely on platform quirks like that though.

@chaaarlie2 I would always put the f designator on both values, simply for consistency. The chances are that the compiler would be smart enough to convert the integer to floating-point at compile-time (rather than run-time), so it probably doesn't matter from a technical point-of-view.

I prefer the format pwm = xPos *  val1 / (float) val2; which works equally for hardcoded values, constants and variables.

The previous answer correctly suggested writing
pwm = xPos*(255.0f/1023.0f);

in place of the original form pwm = xPos*(255/1023);.  But because 255/1023 - 1/4 = -1/1364 which is fairly small (ie it differs by 1 part in 1364), just saying
pwm = xPos/4;

will usually give the correct result or nearly so.
Note, the following python program shows that this result is exact 514 times as xPos ranges from 0 to 1023, and is one too large 510 times, which for many processes being controlled by PWM signals is close enough.
#!/usr/bin/env python
c = [0]*8
for i in range(1024):
    vf = int(i*255.0/1023.0)
    vi = i/4
    d = vi-vf
    c[d+3] += 1
    #print '{:5} {:5} {:5} {:5}'.format(i, d, vi, vf)
print c


text:
Serial3.available loop issue
I am trying to read information coming from an Atlas Scientific FLO30 chip.
The following code works fine in an individual sketch:
String inputstring = "";                                                       //a string to hold incoming data from the PC
String sensorstring = "";                                                      //a string to hold the data from the Atlas Scientific product
String LPM="";
float LPM_INT;

boolean input_stringcomplete = false;                                          //have we received all the data from the PC
boolean sensor_stringcomplete = false;                                         //have we received all the data from the Atlas Scientific product
#define CIRC_PUMP_PIN 10 // circulation pump pin - high when on, low when off

unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change :
const long interval = 1000;

  void setup(){                                                                //set up the hardware
     Serial.begin(9600);                                                       //set baud rate for the hardware serial port_0 to 9600
     Serial3.begin(38400);                                                      //set baud rate for software serial port_3 to 9600
     inputstring.reserve(5);                                                   //set aside some bytes for receiving data from the PC
     sensorstring.reserve(30);                                                 //set aside some bytes for receiving data from Atlas Scientific product
     pinMode(CIRC_PUMP_PIN,OUTPUT);
     digitalWrite(CIRC_PUMP_PIN,HIGH);

void loop(){

unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

            if(Serial3.available()>0){
              while(sensor_stringcomplete==false){
        char inchar = (char)Serial3.read();                              //get the char we just received
              sensorstring += inchar;                                          //add it to the inputString
              Serial.println("adding to string");
            if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
             }
            }

 if (sensor_stringcomplete){                                                   //if a string from the Atlas Scientific product has been received in its entierty
      Serial.println(sensorstring);                                            //send that string to to the PC's serial monitor
      byte n = sensorstring.length();
      LPM = sensorstring.substring(n-8,n);
      Serial.print("This is the extracted part ");
      Serial.println(LPM);
      LPM_INT=LPM.toFloat();
      Serial.print("Now in float ");
      Serial.println(LPM_INT);
      LPM="";
      sensorstring = "";                                                       //clear the string:
      sensor_stringcomplete = false;                                           //reset the flag used to tell if we have received a completed string from the Atlas Scientific product
      }

      if(sensor_stringcomplete==false){
       Serial.println("Skipping");

      }
  }

      }

however when I try to integrate the code with another master sketch, the Arduino seems to jam or lockup when it enters the following part of the code, which is called periodically from the main void loop():
    if(Serial3.available()>0){
      while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read();                              //get the char we just received
      sensorstring += inchar;                                          //add it to the inputString
      Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
     }
        }

All the code is the same and I do not understand why the Arduino locks up. I intially thought it was a problem with memory as the master code is singificantly bigger but the line  "sensorstring = "";  " and "sensorstring.reserve(30) " should take care of this? Besides it cannot even get one reading from the sensor.
Can anyone give insight as to why this might be?

Firstly, don't use String.  It's wasteful of memory and the dynamic aspects of it don't sit well on a tiny resource-starved 8-bit microcontroller.
Secondly, your method of reading from the serial is flawed right from the start.
if(Serial3.available()>0){

... If there is at least 1 character available ...
while(sensor_stringcomplete==false){
    char inchar = (char)Serial3.read(); //get the char we just received
    sensorstring += inchar;     //add it to the inputString
    Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}

... read characters until I get the end of string character regardless of if those characters are even available.
In order to read the data from the serial port you have to ensure that the data is actually available.  Just waiting for the first character to arrive and then reading (much faster than the serial is able to receive) other characters is doomed to failure.
I have discussed this at great length in a blog article, including how to perform non-blocking string reads that will not interfere with the rest of your program: http://hacking.majenko.co.uk/reading-serial-on-the-arduino
It even mentions your specific situation since it is something that is so commonly done wrong.

Thanks Majenko, interesting stuff. I thought it could be a problem like this. I have integrated this readline function into my master code and have placed: "  static char buffer[80];
if (readline(Serial3.read(), buffer, 80) > 0) {
Serial.print("You entered: >");
Serial.print(buffer);
Serial.println("<");
} " But now the there is nothing being printed on the Serial monitor, again the code works in solitary!

If the code works by itself, but doesn't work when integrated with your sketch, then there must be something else in your sketch that is stopping it.  Can you post your entire non-working sketch?

its too long for comments so Ill post it under the original!

Its too long to add!

Ok, so put it somewhere like PasteBin and provide a link.

MASTER Code:  http://pastebin.com/iiansA2n

Hmm, there is quite a lot there, isn't there?  I'd suggest commenting out everything in loop() except my serial code, then see if it works.  If it does then gradually uncomment each entry in loop() until it stops working.  Also you can reduce the 80 down to 30 in both the buffer and readline call.


text:
A question about the possible limits of an Arduino Uno
I've searched the web but could not find a straightforward answer to my query.
I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.
Anyway, I have a single Arduino. It is operating the following:
An LCD display,
a 4 button operation panel I made using an LS148 ic,
an L293 operating 2 small motors,
a servo,
a dark sensor,
a temperature sensor,
and it also does serial communication.
Everything is working great, but slow (or so it appears to me).
If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.
When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?
I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.
I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.
Thanks for your advice.

Did you mean a "74LS148"?

Yes I did. xxxx

A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.
For instance, take the LCD code.  Commands have to be sent at the right speed with the proper delays in there for things to happen.  LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.
Nothing else can happen while there's a delay() running.
Many other things will introduce their own delays.  Put them all together and you have a slow system.
No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.
There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.
For a start there is the millis() function which tells you the time.  Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.
It's like boiling an egg.  Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?
It's the same with Arduino programming.  Note the time, then check that time against the current time to see if the required time has passed.
Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.
There are also hardware timers.  These allow you to run small snippets of code at regular periods.  Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.
There are two key phrases to take away here:

Non-blocking.  That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.
Asynchronous programming.  This is using things like timers to make things happen "outside" your main loop.

So you are saying that the list of components and circuits have no effect and my problem most likely is in the code?

More than likely, yes.  External components don't affect the speed of the chip, only how you program it can do that.

The problem with most of the Arduino libraries is that they are sort of ok at doing one task, but they do it inefficiently and monopolize the whole device.
So when one tries to do a real system, problems like this one are quite common.
One solution is to use more units, each with a specific purpose. After all they are fairly cheap. Alternatively, get rid of the Arduino code base and just treat it as normal AVR, using for example FreeRTOS.

Another good choice would be to work with Cosa as the core instead of Arduino.  If you switch to UECIDE instead of the Arduino IDE you can switch between Arduino and Cosa as the core at will.


text:
Beginner here, trying to start learning arduino, which starter kit should I buy?
I'm really interested in arduino but I don't know much about it. I want to buy a starter kit to play with, but when I searched it on amazon, there are couple unofficial starter kit and a more expensive official one. So, can some one tell me the major difference between the unofficial starter kit and official starter kit? And which one would you recommend me to buy? Thank you!
Sorry, bonus question: why is the start kit($89) in arduino website is much cheaper than the official starter kit in amazon($120)?

I can answer the bonus question for you right now:  They're not that much different.  Look at the units.  The "more expensive" one is in Canadian dollars, the cheaper in US dollars. Do the conversion, and there's not that much difference.

You could do worse than a cheap 37-in-1 Sensor Kit from eBay and any Arduino board of your choice.
Also some Dupont Jumpers are essential.  Get a selection of M/M, M/F and F/F.

I got the 1st one, and It's of decent quality. I only wish it came with an SD breakout for logging metrics.

I tend to recommend the oomlout ARDX starter kit to students at the university I work at as it is relatively low cost, widely available, and doesn't have too much cheap filler components that you don't use...


text:
Can I use an Arduino Due as a flash drive?
More specifically, can I use an Arduino Due to have an interface that can plug in/out of a USB port on a computer, connect it to an SD card or similar via a sd card logging shield, and have it present itself as a flash drive to the computer?
Why do I want this as opposed to a normal flash drive? I would like the Arduino to also have access to the contents of the sd card when the computer interface is not plugged in (or rather controllable via the Arduino which device has access to the card, the Arduino or the computer), without the need to remove/disconnect the cable

Possibly - you would have to implement USB mass storage mode.  And then you would have to implement a FAT filesystem when you want to access the card from a program on the due.   That is probably possible, but if you are willing to install a custom program on the PC there are simpler ways.

@ChrisStratton no easy way to pass the card access directly to the PC? (and thus let the PC format the file system as it would a flash drive)?

That's what USB mass storage does.  But you need filesystem code yourself if you want to access the contents of the result from the due.


text:
Sensing horizontal tilt
I'm building a digital gear shift knob, which would display current gear (1-5, R) and based on readings from OBD-II change color when gear shifting is required, to save on fuel consumption.
I need a way to detect the current gear - PID 0D (current gear) is not availiable in this car. I was thinking about doing it based on the horizontal tilt of the gear stick, since there are 6 positions plus a neutral gear:
    1   3   5
     \  |  /
      --0--
    /   |  \
   2    4   R

Is there a sensor I could use? Or perhaps it'd be possible to build one, e.g. using 6 of these ball switches: https://www.adafruit.com/products/173
There is however a space constraint since everything needs to fit inside a gear knob, therefore I'd prefer a nice single package.

My first thought was accelerometer, but you'd have a hell of a job filtering out the acceleration/deceleration/turning g-force and the general vibration of the car.  Maybe a gyroscope may work.  Tough one this...

That's funny. I had the same thought too, use an accelerometer. I think you could do it with just a three axis accelerometer , but like Majenko said, you'd have to filter out the noise. However, my thought is that shifting gears has a distinct motion pattern, so you might be able to implement a state machine. Otherwise, you can "beef" up your accelerometer and go for an IMU. This would allow you to create internal frame of reference for tracking the position of the shift knob.

You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.

Many vehicles with manual transmission use two push rods or cables to transmit gear selection to the gearbox. It may be easier to detect the position of those rods/cables than to attempt to filter out the g-forces involved in a moving vehicle.
Alternatively, you could use the ratio of vehicle speed to engine revs (if you can retrieve these from OBDII in your vehicle). Given that these two are directly related when a specific gear is selected and the clutch is engaged, a simple division should give you a ratio you could use to decide which gear is selected.

Your stick goes into the chassis at some point.
Why not detect the position down there?
But to be sure to save fuel, you'd need to know the rpm/speed and especially the load of the engine. If you are going at a high gear and low speed you won't save fuel either, so the knob is not the right place to detect the gear in question.
Go for OBD, get the ratio of speed and rpm and get the load or injection quantities. If you go up the hill and select too high a gear, you won't be happy either.


text:
Remove Bootloader on Arduinos
I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?
Thanks.

You don't "remove" the bootloader, you just ignore it.  When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.

If you actually need to.  Just because a program is written bare-metal without use of the Arduino runtime libraries down't mean an Arduino/optiboot/whatever bootloader may not still be a convenient way to get it onto the chip.  It's really only necessary to remove the booloader if you need to speedup the start of the application after reset, remove any chance of it not starting based on serial input that looks like programming commands, or reclaim that small amount of flash space.

I think you need to change the fuses, to set the correct Boot Start Address (or that flash memory isn't available for your program).

Isn't that naturally part of you writing your program? Setting the right fuses for your program?


text:
LED too dim when connected to digital output pin
I am making an attempt to put LED headlights in an RC car I am building. I want the headlights to turn on when I click circle on a PlayStation 4 Dual Shock controller.  I currently have it working except the LED is very dim and not near as bright as if I just power it from the 5v pin on the arduino board.  Since I want it to only turn on when circle is pressed I have it connected to digital pin 7.  Here is my code.  Any help would be much appreciated!
/*
 Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
 For more information visit my blog: http://blog.tkjelectronics.dk/ or
 send me an e-mail:  kristianl@tkjelectronics.com
 */

#include <PS4BT.h>
#include <usbhub.h>
#include <Servo.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;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
Servo servo1;
Servo servo2;

/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
PS4BT PS4(&Btd, PAIR);

// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);

const int headlights = 7;
bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

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\nPS4 Bluetooth Library Started"));

  pinMode (3, OUTPUT);
  pinMode (5, OUTPUT);
  servo1.attach (3);
  servo2.attach (5);
}
void loop()
{
  Usb.Task();

  if (PS4.connected())
  {
    servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
    servo2.write(map(PS4.getAnalogButton(R2), 0, 255, 90, 0));
  }
  else
  {
    servo1.write (25);
    servo2.write (90);
  }

  if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117)
  {
      Serial.print(F("\r\nLeftHatX: "));
      Serial.print(PS4.getAnalogHat(LeftHatX));
      Serial.print(F("\tLeftHatY: "));
      Serial.print(PS4.getAnalogHat(LeftHatY));
      Serial.print(F("\tRightHatX: "));
      Serial.print(PS4.getAnalogHat(RightHatX));
      Serial.print(F("\tRightHatY: "));
      Serial.print(PS4.getAnalogHat(RightHatY));
  }

    if (PS4.getButtonClick(PS)) {
      Serial.print(F("\r\nPS"));
      PS4.disconnect();
    }

    else {
        if (PS4.getButtonClick(CIRCLE)) {
        Serial.print(F("\r\nCircle"));
        digitalWrite(headlights, HIGH);
        }

      if (PS4.getButtonClick(CROSS)) {
        Serial.print(F("\r\nCross"));
        digitalWrite(headlights, LOW);
      }

      if (PS4.getButtonClick(TRIANGLE)) {
        Serial.print(F("\r\nTraingle"));
        PS4.setRumbleOn(RumbleLow);
      }

      if (PS4.getButtonClick(SQUARE)) {
        Serial.print(F("\r\nSquare"));
        PS4.setLedFlash(0, 0); // Turn off blinking
      }

      if (PS4.getButtonClick(UP)) {
        Serial.print(F("\r\nUp"));
        PS4.setLed(Red);
      } if (PS4.getButtonClick(RIGHT)) {
        Serial.print(F("\r\nRight"));
        PS4.setLed(Blue);
      } if (PS4.getButtonClick(DOWN)) {
        Serial.print(F("\r\nDown"));
        PS4.setLed(Yellow);
      } if (PS4.getButtonClick(LEFT)) {
        Serial.print(F("\r\nLeft"));
        PS4.setLed(Green);
      }

      if (PS4.getButtonClick(L1))
        Serial.print(F("\r\nL1"));
      if (PS4.getButtonClick(L3))
        Serial.print(F("\r\nL3"));
      if (PS4.getButtonClick(R1))
        Serial.print(F("\r\nR1"));
      if (PS4.getButtonClick(R3))
        Serial.print(F("\r\nR3"));

      if (PS4.getButtonClick(SHARE))
        Serial.print(F("\r\nShare"));
      if (PS4.getButtonClick(OPTIONS)) {
        Serial.print(F("\r\nOptions"));
        printAngle = !printAngle;
      }
      if (PS4.getButtonClick(TOUCHPAD)) {
        Serial.print(F("\r\nTouchpad"));
        printTouch = !printTouch;
      }
     }
    }

You forgot to set headlights as an output, meaning that you're attempting to power the LED through the 20k-50kohm input pullup.


text:
avrdude: stk500v2_getsync(): timeout communicating with programmer error
When I try to upload I get this error. I cannot upload the program into my Arduino Mega ADK board. I tried putting the drivers agiain too, but it does not work.
avrdude: stk500v2_getsync(): timeout communicating with programmer

Is it the problem with the hardware or the system?
Please help me. Thank you :)

See Have I bricked my Arduino Uno? Problems with uploading to board and What happens when code is uploaded using the bootloader?. I'm going to close this question. Thanks for your understanding and cooperation!

I get this problem sometimes with some of my boards. I usually solve the problem following these steps:

Set the compiler on debug/verbose mode to see what's happening
Launch compilation/upload
When the compile phase is done, and the upload process is about to start, press the reset button on the board

Usually that takes care of the problem.

What @dda says in his answer are good points.
Removing the board USB for a few seconds, then re-plugging and re-selecting the COM port in the IDE usually fixes it.  Sometimes when you un-plug and re-plug the board it changes COM ports.
Also if you have a short-circuit wired to your arduino sometimes it becomes non-responsive in this manner.


text:
Attiny45 wake by Software Serial
I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0_vect routine, I get an error "multiple definition of `__vector_2'" so it looks like Software Serial already uses "ISR (PCINT0_vect)" and pin change interrupt.
So my question is, will incomming communication wake Attiny from sleep?
Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.
I was thinking of something like this:
void loop() {
 if (SWSerial.available()>0) {
   noInterrupts ();
   CLKPR = bit (CLKPCE);
   CLKPR = clock_div_1;
   interrupts ();
 }
//other code here
}

I don't mind loosing some bytes, but I need to low Idle current as much as possible.
Thank you.

Have you tried it? What were your results?

Any reason why you don't use the USI on pin 5 to read your serial data? Hardware support for reading in the bits and also ability to wake when a start condition is detected.

I haven't received my attiny yet. I didn't know there is such possibility, I have pin 5 unconnected. But I can modify it.

Question #1: Can a change on pin 7 wake from sleep?
Yes. The lowest power mode for this chip is Power-down, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.
Depending on what compiler/libraries you are using, something like this...
include <avr/sleep.h>

...

set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();
//We will only reach this line after an interrupt has occured

...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.
If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.
For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.
Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?
Yes. You can change the prescaler any time, but note that...

The clock is not running at all during power-down mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.

Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.

The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be extremely power efficient, but it can take work to take advantage of it.

I don't need low power consumption during communication.

Chip will be conncted to 20Ah battery and it will comunicate only during charging. I  haven't decided whether I will use power down or only slow down the chip. Thank you for your answer. :-)


text:
Digital pin input stays high after receiving a high signal
I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
int thermPin = A5;
int relayPin = 9;
int upButton = 10;
int downButton = 11;
int rawVoltage;
float mv;
float desiredTemp = 20.5;
float currentTemp = 20;
long newSetTime = millis();
long oldSetTime = newSetTime;
long newUpPushTime = millis();
long newDownPushTime = millis();
long oldUpPushTime = millis();
long oldDownPushTime = millis();
int mainDelay = 600;
int flashDelay = 600;
boolean isSetting = true;

void drawCurrentTemp(){
  lcd.setCursor(0, 1);
  lcd.print(currentTemp);
}

void drawDesiredTemp(){
  lcd.setCursor(12, 1);
  lcd.print(desiredTemp);
}

void drawMainScreen(){
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("TEMP");
  lcd.setCursor(12, 0);
  lcd.print("SET");
  drawCurrentTemp();
  drawDesiredTemp();
}
String setString = "SET";
void flashSet(){
  if(newSetTime - oldSetTime > flashDelay) {
    if(setString == "SET"){
      setString = "   ";
    }else{
      setString = "SET";
    }
    lcd.setCursor(12, 0);
    lcd.print(setString);
    oldSetTime = millis();
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(relayPin, OUTPUT);
  pinMode(upButton, INPUT);
  pinMode(downButton, INPUT);
  drawMainScreen();
}

void checkInput(){
  if(digitalRead(upButton) == HIGH){
    newUpPushTime = millis();
  } else {
    oldUpPushTime = millis();
  }
  if(digitalRead(downButton) == HIGH){
    newDownPushTime = millis();
  } else {
    oldDownPushTime = millis();
  }
  long upButtonTimePushed = newUpPushTime - oldUpPushTime;
  long downButtonTimePushed = newDownPushTime - oldDownPushTime;
  if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
    oldDownPushTime = millis();
    oldUpPushTime = millis();
    if(!isSetting){
      isSetting = true;
    } else {
      isSetting = false;
      drawMainScreen();
    }
  }
  if(isSetting){
    if(digitalRead(upButton) == HIGH) {
      desiredTemp +=0.5;
    } else if(digitalRead(downButton) == HIGH) {
      desiredTemp -=0.5;
    }
    drawDesiredTemp();
  }
}

void loop() {
  newSetTime = millis();
  if(isSetting) {
    flashSet();
  }
  checkInput();
  Serial.println(digitalRead(upButton));
}

Could it be because you don't have a pulldown / pullup resistor to force the input into a known state when there is no "signal"...?  Show your circuit.

yes :) I just found out about the pullup resistors and how exactly the INPUT works its all fixed now thanks :) i just made them pinMode(pin, INPUT_PULLUP);

I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.
When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.
So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.
As you mentioned using the code:
pinMode(PIN, INPUT_PULLUP);

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:
pinMode(PIN, INPUT);
digitalWrite(PIN, HIGH);

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.
Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

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

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.

Comment by Glen Cashen turned into an answer:
I just found out about the pullup resistors and how exactly the INPUT works it's all fixed now thanks :)
I just made them:
 pinMode(pin, INPUT_PULLUP);


text:
How do I turn a number of pins to high and then off after 5 seconds based on a serial command
I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).
In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.

Have you tried the delay() function? Try putting this in the loop() function for pin 3.
digitalWrite(3, HIGH);
delay(1000); // time in milliseconds as parameter
digitalWrite(3, LOW);

You can use the Timer library to achieve this:
#include "Timer.h"
[...]
digitalWrite(3, HIGH);
int afterEvent = t.after(5000, doAfter);
[...]
void doAfter() {
  digitalWrite(3, LOW);
}

As you can see, you cannot pass a parameter to the timer, just a callback. I suggest that you implement either a bunch of doAfter functions, from doAfter3 to doAfter9` for instance, and call the right one in the callback.
There are probably other timer libraries, but this one is simple and complete enough for your needs.


text:
Scroll LCD display connected to an Arduino Uno
I want to make some characters scroll left without affecting the first positions in each row of my LCD 16x2 screen. I have this code inside the loop so far:
lcd .clear();
lcd.setCursor(17, 0);
for (int i = 15; i > 0; i--) {
  lcd.print("x");
  lcd.scrollDisplayLeft();
  if (digitalRead(switchPin) == HIGH) {
    lcd.setCursor(0, 0);
    lcd.write(5);
  } else {
    lcd.setCursor(0, 1);
    lcd.write(5);
  };
  lcd.setCursor(17, 0);
  delay(500);
}
lcd.noAutoscroll();

I think it should work, but the character x just moves left by one position, whereas the character in the first position, either in the first or second row doesn't appear at all.

There is an example that does just this shipped with the arduino IDE and the LCD library. Check it out

I would do the following (beware - not tested):
lcd.clear();
lcd.setCursor(15, 0);
lcd.print("x");
for (int i = 0; i < 15; i++) {
    lcd.setCursor(0, digitalRead(switchPin) == LOW);
    lcd.print("5");
    delay(500);
    lcd.scrollDisplayLeft();
}


text:
Use a PIR Sensor to detect the movements of a paper
I need to detect when a paper comes out from a laser printer and count the number of printed papers. For that I hope to use a PIR sensor to detect the movement of the paper from the printer. Is it possible to detect the movement of a paper using a PIR sensor? Please be kind enough to help me.

If the paper is hot when it comes out of the printer, possibly.  Could be unreliable though.
Better would be to place a photo-interrupter (or IR LED and IR Photodiode) in the path of the paper to detect a break in an infra-red beam.

The solution from the OP with the photo-interruptor is probably the most standard one.
However it might be worth checking if you can get away with a light sensor: assuming that the paper is mostly of different colour than the background, the paper should change the current passing through the photodiode.
Alternatively, you could use a proximity sensor, aimed at a location on the path of the paper, where there is typically nothing.
These 2 solutions are trying to avoid having to place something on both sides of the paper. If that doesn't bother you, then I'd recommend the OP's solution.

A "light sensor" that relies on ambient light may be rather subject to changes in external conditions.  If using anything open to the environment it's really best to provide your own light source that is modulated and look for that pattern in the receiver, at least with an op-amp filter, and possibly with something as discriminating as a lock-in amplifier (which is fairly easy in software - it ends up a lot like a single point fourier transform)


text:
What maximum length of wire can I use to connect a push button to an Arduino?
I am trying to get 8 stop buttons to cause an Arduino UNO to activate a single relay!
The stop buttons have been placed 30' to 250' away from the Arduino uno board.
Q: How far can you go with 5v and still get signal back?
Q: Is there a way to boost the signal?

Are the buttons all on the same pair of wires? Or on 8 separate pars?

Q: how far can you go with 5v and still get signal back?

That depends on two main factors:

The gauge of the wire
The noise in the environment

Assuming a low-noise (where noise is negligible) environment, we will first look at the wire.
All wire has an inherent resistance to it.  The thicker the wire, the lower the resistance.  This table has good information about the resistance of different gauges of wire: http://www.powerstream.com/Wire_Size.htm
Given a typical arrangement where the internal pullup resistor of the Arduino's IO pin is used to create an "active low" arrangement (pinMode(x, INPUT_PULLUP) the equivalent circuit can be seen as this:

Given that the "Input Logic Low" (VIL) level of an input pin (according to the ATMega328P Datasheet (Table 30-1) is 0.3Vcc, and Vcc is 5V, the input low level would therefore be 1.5V.  The voltage present at the IO pin has to be below 1.5V in order for the input to be seen as a LOW.
The circuit, when the button is pressed, can be simplified to this:

That is a simple voltage divider.  The formula for calculating Vout is (R2/(R1+R2))*Vin.  We know that the Vout limit is 1.5, and Vin is 5V.  Also that R1 is approximately 50KΩ (very approximately).  So we can rearrange the formula to:
R2 = R1(1/((Vin/Vout)-1))
Substituting our known values we have:
R2 = 50,000 × ( 1 / ((5 / 1.5) - 1)) = 21428.57Ω
So the total resistance of the wire permissible is around 20KΩ assuming the internal pullup resistor is 50KΩ (note: it could be as low as 10KΩ or as much as 70KΩ).
Divide that value by 2, since the wire has to run twice the distance (once there and once back again) and you get a total resistance of around 10KΩ for one leg of the journey.
Now assume a wire gauge of 24AWG.  That has a resistance of 84.1976Ω/km.  So we can work out that 10,000 / 84.1976 = 118.77km.
So with 24AWG wire you could theoretically have your button about 100km away from the Arduino and just about have it still register properly.
But of course that's with no noise, and there will be noise - especially over that kind of distance.
The noise will basically make the voltage seen at the input vary randomly around the theoretical value.  Those wires act like great big antennae, and they pick up all sorts of stray EMI.  The longer the wires the more noise there will be, and consequently the lower the voltage you will need to aim for (or higher voltage if using a pull-down arrangement - just turn the whole thing upside down) to keep the logic level below (or above) the right threshold value.

Q: is their away to boost the signal?

Yes, you can use a higher voltage.  There is nothing to say that you have to interface your button directly with the Arduino.  There are many ways of having your button switch a higher voltage on and off and use that to trigger the Arduino.  The simplest (and also the safest) may be to use an opto-coupler.  Use your button(s) to switch a 12V power supply on and off, and that then passes through a suitable resistor to power the LED in the opto-coupler.  That then switches on the built-in transistor to turn on the IO pin.

Another option may be to use a reliable communication bus with a small microcontroller at each stop-button point (maybe something like RS-485), though that may be overkill for this kind of application.

I agree with Majenko. The noise over any sort of moderate length is likely to swamp the 5V in the wire. However as he suggested you could use an opto-coupler (like MIDI does). The opto-coupler is activated by current not voltage, and whilst mains and other sources may introduce quite high voltages they are unlikely to introduce high currents. The opto-coupler also lets you use a higher voltage, thus overcoming wire resistance. Its third benefit is isolating the input pins from any high voltages that might appear in the wire.

While the galvanic protection may have some advantages, note that you can make what is basically a current-mode input by using a smaller pullup resistor.  Many practical systems also use differential receivers.  There are also transmission line effects like reflections to consider, though a system with a mechanical switch will already need debouncing for that which may deal with the line reflections too, until the distance gets to be huge.

Majenko's answer is probably the safest option. There is, however,
something simpler that you can try:

Use a strong pull-up (or pull-down). Something around 1 kΩ will
make it quite difficult for the noise to pull your signal low, at the
cost of increased current consumption.
Connect each push button to the Arduino using a twisted pair of copper
wires. This will minimize the inductive pickup effect.

PS the increased power consumption is only while the button is being pressed.