text:
Removing CH340g chip from Arduino Nano clone.. any issues?
In trying to figure out how to solve another problem with Arduino Nano clone using CH340 chip, I was just now wondering, would there be any issues if I were to simply remove the CH340 chip? As it stands, I have the slight suspicion that the chip itself might be causing some problems with communicating using only the Tx Rx pins, could this be the case? More importantly, can I just remove the chip with no issues (other than the already lacking ability to use it as USB-Serial bridge)? In a working board, would removing the chip cause any other problems?

If you are not going to use the chip, can't you just ignore it?

@NickGammon, the reason is because I have a feeling it is actually defective and interfering with communication over the TxRx pins. See the linked question for a little background on that.

No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.
Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.
I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.

Looking at the datasheet, I see no problem with removing it.
I'd suggest using a sharp knife and cut all the pins, one at a time, right where they come out of the black epoxy. Make sure you don't accidentally stab into the PCB. Remove the main body of the chip. After that, remove the legs still attached to the PCB, one by one, using a soldering iron.

Once I removed a burned ch340 from a dysfunctional uno, and it didn't brought it back to life, I couldn't program it by other means, because reset remained shorted to ground. It might have other problems, but I still recommend digging more into the problem (eg. Check the diagram for your board)

You could probably get away with just removing 3 legs - Tx, Rx, and DTR. The rest don't anything.
The pins are rather far apart, you could heat them one at a time gently pry/lify up with tweezers too. Better than a knife I would think.


text:
DC Motor Speed Measurement using Rotary Encoder
I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.
boolean check;
boolean start;
unsigned int angle = 5;   //angle moved per encoder tick
unsigned long volatile time1;
unsigned long volatile time_11;
unsigned long interrupt_time;

void setup() {
  Serial.begin(9600);
  while (!Serial) ;
  pinMode(21, INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
  attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
  time1 = 0;
  time_11 = 0;
  interrupt_time = 0;
  check = true;
  start = false;
  time_11 = millis(); //Start Clock
}

void loop() {
  if(time1 == interrupt_time && start) //Both times same , hence bool start.
  {
    if(check)
    {
      Serial.print(millis());  //Time taken to rise to steady speed.
      check = false;
    }
    Serial.println((angle/time1)*1000);   //Display Speed.
  }
  interrupt_time = time1;
  start = false;
  while(!start)
    {}
}

void speed(void) {
  start = true;
  time1 = millis()-time_11;
  time_11 = millis();
}

I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?

I think you'd be better of calculating the speed based on the number of pulses during a certain amount of time, instead of the time of a single pulse. Secondly, you have to use atomic operations on multi-byte variables that are changed by the interrupt-routine. As e.g. during the comparing of time1 in the loop the ISR might be called and the value of time1 would change. The if statement might have compared the first two bytes of the long, but then checks the last two bytes of the new value. I hope this makes sense.

millis() probably won't work for this, unless your motor is slow and your encoder low resolution there would typically be less than a millisecond between encoder events.  If you really want to time individual events, learn to use the hardware timer and wire the inputs accordingly.  Otherwise counting events per period of time is better.  Depending on wiring and details you may be able to count events with the hardware timer's counter mode.

The HW timer counter mode doesn't scale well, though. Taking a time stamp of the even and calculating the delta from the previous allows to use even the PCINT pins.

Serial.println((angle/time1)*1000);   Be careful to not divide by 0.  Also be aware that this is integer division and thus it will truncate (before multiplying by 1000).

How fast do you expect the motor to run?  And how fast do you want to report on the speed?

Just a couple of remarks:

start should be volatile, but you can remove it and simply check
that time1 != 0.
there is no point in calling millis() twice inside the interrupt
service routine:

void speed(void) {
  unsigned long now = millis();
  time1 = now - time_11;
  time_11 = now;
}

Thank you for the feedback!
This is my attempt at calculating speed using the averaging method.
unsigned long volatile encodercount;
unsigned long encodercount_previous;
unsigned long volatile timer;
unsigned int angle;
boolean first;
boolean firstencodertick;
void setup() {
      angle=3;
      encodercount=0;
      encodercount_previous=0;
      Serial.begin(9600);
      while (!Serial);
      pinMode(21,INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
      attachInterrupt(digitalPinToInterrupt(2),speed,FALLING);
      first=true;
      firstecnodertick=true;
        }

  void loop() {
     delay(100);

   if(encodercount==encodercount_previous&&encodercount!=0)
    {
   if(first)
     {
   Serial.println(millis()-timer);  //Steady State Time Taken
   first=false;
     }
  Serial.println((encodercount); //Angle Moved in 0.1second.
    }
  encodercount_previous=encodercount;
  encodercount=0;
   }

  void speed(void)
 {
 if(firstencodertick)
 {
 timer=millis();
 firstencodertick=false;
  }
 encodercount++;
}

source: Stack Exchange

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

sort: votes


text:
How to switch on an AC bulb using arduino as well as regular switch?
I'm trying to build a GSM based AC Power ON/OFF switch using Arduino. I've successfully completed the ON/OFF mechanism using SMS with the help of 240v 100amps relay to control the circuit. Apparently I don't want to disturb the regular on/off switch's operation. I want both of them to be operational. When I'm not at home arduino should be the switch control and the regular one should be preferred while at home. I'm actually a noob in this topic, and want your precious help to solve this issue.

This can be done (to a certain extent) using a SPDT (Single-Pole-Double-Throw) relay and an SPDT switch.
The basic principle is the same as when you have two light switches controlling the same light (such as on a staircase - one switch at the top and one at the bottom).  The two switches alternate between one of two different paths for the current. When both switches are routed to the same path the light is on.

Both the Arduino and the switch can turn the light on and off at will. The only problem, though, is that the Arduino has no clue if the light is on or off. To know if the light is on you will need some kind of feedback mechanism.  That might be a simple LDR that looks to see if it's light or dark, or some kind of current monitoring system (current transformer, hall effect current monitor, etc) which the Arduino can use to see if current is actually flowing through the lamp circuit or not.

You could hook the (or another) switch up to the Arduino, so you have total control over what effect the switch will have. So that switching it on/off twice , fast, will enable disco mode ;p (perhaps you can find a better use, but yeah.)

A safer approach is to optically link the Arduino to an IR remote control light switch.  Such an approach is discussed in this thread. The technical specifications appear to be here for the Lutron light switch remote controls.  From this document one could construct an Arduino IR transmitter to send out these code.

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


text:
calling a random function number
I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.
ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc
and would like to called them randomly in that fashion :
randNumber = random(1,11);
anim[randNumber]();

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that..
I'm sure there must be a way ;)
thanks for your help

What you want is an array of function pointers.
void anim1() {
    // blah blah
}

void anim2() {
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

Then you can use:
anims[animNumber]();

You mean typedef void (*animptr)();.

I didn't know this was possible. But I think I would feel dirty when using it. It just seems wrong to do this.

Why so? Function pointers are one of the most powerful facilities of C. Imagine trying to implement callbacks without being able to use function pointers - and an array of them is just an extension of that. A function is, after all, just a location in memory...

thanks so much Majenko! exactly what i was looking for! :D

I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that  ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!
int randNumber;

void loop(){
randNumber = random(1,14);

if (button is pressed or something){
callAnim(randNumber);
}
}

void callAnim(int randNumber){
if (randNumber==1){
anim1();
}
if (randNumber==2){
anim2();
}
}
// ... etc ...

void anim1() {
// blah blah
}

void anim2() {
// blah blah
}
// ... etc ...


text:
convert String to unsigned long long
i want to convert string for example
"68976543210" to unsigned long long(64 bit) in mega2560,
 do is possible?
String x="68976543210";
unsigned long long y=?;

avr-libc lacks strtoull() that I would normally use for such a conversion. You will have to do it manually.
Fortunately it's quite simple - just start with y=0 and, for each character in the string, multiply y by 10 then add the numeric value of the character in the string:
String x = "68976543210";
unsigned long long y = 0;

for (int i = 0; i < x.length(); i++) {
    char c = x.charAt(i);
   if (c < '0' || c > '9') break;
   y *= 10;
   y += (c - '0');
}

Note that the Arduino Print API has no method for printing a 64-bit integer.


text:
ESP8266 Battery Monitor
Is there a way to monitor the battery that feeds an esp8266 in a portable project?
I have been meaning to implement that feature into my project so that i can be warned when the battery runs low on juice but i don't know if the esp has some kind of onboard sensor to do that.

All ESP8266 have ADC, just not all of them have them "broken out" - in the ESP8266 the ADC can be in one of two modes, one of which allows you to read VCC - so, no external hardware required ... that's the good news, the bad news ... how to set the ADC to read VCC depends on how you are programming the esp

There are two things you need to measure the battery of the system that is doing the measuring of the battery:

An analog-to-digital converter
Some form of fixed voltage reference to compare the battery voltage against.

Some ESP8266 modules have a single analog input available, and some don't. You need to check which module you have and which pins are available on it.
Then you need to use the ADC to measure the fixed known voltage. That could be from a small LDO voltage regulator that is below the voltage of the minimum voltage you will care about from your battery, or something like the forward voltage drop of a silicon diode (~0.7V) - something where you know what the voltage is.
From that reading you can then back-track what the supply voltage must be in order to give you the reading it has given you.  As the battery voltage drops the voltage range the ADC will be measuring will be reduced, and so the fixed voltage will rise within that range giving you higher readings from the ADC.
Here is a snippet of code I use with the 1.1V internal voltage reference of the ATMega328P to calculate the supply voltage:
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

Of course, you need to change that to use the analog input of the ESP8266 instead (probably just using analogRead()). And of course change the ADC-scaled voltage.  The formula is basically:
Vref * ADCmax / ADCreading

So if you have the 1.1V reference as above, and the ADC can read 0-1023, then it's:
1.1 * 1023 / reading

Or, pre-calculate the first half of the sum:
1125.3 / reading

To keep it as integer mathematics work in millivolts instead of volts by multiplying the reference voltage by 1000:
1125300 / reading

And that, as you can see, is what is in the function above.


text:
Pin toggle speed
If I use direct port manipulation, what is the average number of clock cycles it takes to flip a pin on the arduino
ie.
void loop(){
  PORTB |=  0b00010000;
  PORTB &= ~0b00010000;
}

So how fast is this generally?

PINB =  0b00010000; or sbi(PINB, 4); will toggle the pin in a single instruction.

If you compile the code and examine the results you can see how many instructions it will take, and thus how many clock cycles.
It's slightly more complex because of what else happens in main() to call loop, but basically you have:
for (;;) {
loop();
  aa:0e 94 49 00 call 0x92; 0x92 <loop>
if (serialEventRun) serialEventRun();
  ae:20 97       sbi wr28, 0x00; 0
  b0:e1 f3       breq.-8      ; 0xaa <main+0x10>

00000092 <loop>:
  92:2c 9a       sbi0x05, 4; 5
  94:2c 98       cbi0x05, 4; 5
  96:08 95       ret

So you can see there is:
Operation                            Cycles
Call loop()                          4
Check if serialEventRun exists       2
Since it doesn't, got start of loop  2

Then in loop:
Set bit                              2
Clear bit                            2
Return                               4

So in total you have 16 clock cycles. At 16MHz that gives you a frequency of 1MHz - however that won't be a square wave of 50% duty cycle since there is much less time between set and clear than between clear and set.  The full 16 cycles, mapped to the state of the IO pin, would look like this:
             _
 _ _ _ _ _ |   | _ _ _ _ _ _ _ _
| call  |sbi|cbi|  ret  |chk|bra|
 . . . . . . . . . . . . . . . .

You can get a much tighter operation by wrapping the pin manipulation in a while (1) loop:
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    PORTB &= ~0b00010000;
  }
}

That reduces down to just:
00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:2c 98       cbi 0x05, 4; 5
  96:fd cf       rjmp .-6      ; 0x92 <loop>

That's sbi (2) cbi (2) and rjmp (2). A total of 6 clock cycles.  At 16MHz that's 2.667MHz. Again, though, not a 50% duty cycle, since the rjmp takes two extra clock cycles:
     _
 _ |   | _ _
|sbi|cbi|jmp|
 . . . . . .

By inserting a pair of 1-cycle NOP instructions you can even out the duty cycle and make it 50%:
void loop(){
  while(1) {
    PORTB |=  0b00010000;
    asm volatile("nop");
    asm volatile("nop");
    PORTB &= ~0b00010000;
  }
}

00000092 <loop>:
  92:2c 9a       sbi 0x05, 4; 5
  94:00 00       nop
  96:00 00       nop
  98:2c 98       cbi 0x05, 4; 5
  9a:fb cf       rjmp.-10     ; 0x92 <loop>

     _ _ _
 _ |       | _ _
|sbi|n|n|cbi|jmp|
 . . . . . . . .

Now, of course, it's 8 clock cycles, so at 16MHz that's 2MHz output, but with 50% duty cycle.
Incidentally, all these instruction timings are available in the Instruction Set Summary chapter of the ATMega328P data sheet.


text:
Where could I find the "Serial.find()" source code?
As written in the title, could you tell me where to find the source code of the function "Serial.find()"?
I haven' t installed the Arduino IDE, so I'm glad if you could me link a web resource, or if you directly copy the source code here .
Thanks for your time.

It is part of the Stream class which the Serial class inherits from.

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L93

It just calls findUntil() which is a little further down in the same file:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L114

That itself calls findMulti() which is where all the magic happens:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L256

int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
  // any zero length target string automatically matches and would make
  // a mess of the rest of the algorithm.
  for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
    if (t->len <= 0)
      return t - targets;
  }

  while (1) {
    int c = timedRead();
    if (c < 0)
      return -1;

    for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
      // the simple case is if we match, deal with that first.
      if (c == t->str[t->index]) {
        if (++t->index == t->len)
          return t - targets;
        else
          continue;
      }

      // if not we need to walk back and see if we could have matched further
      // down the stream (ie '1112' doesn't match the first position in '11112'
      // but it will match the second position so we can't just reset the current
      // index to 0 when we find a mismatch.
      if (t->index == 0)
        continue;

      int origIndex = t->index;
      do {
        --t->index;
        // first check if current char works against the new current index
        if (c != t->str[t->index])
          continue;

        // if it's the only char then we're good, nothing more to check
        if (t->index == 0) {
          t->index++;
          break;
        }

        // otherwise we need to check the rest of the found string
        int diff = origIndex - t->index;
        size_t i;
        for (i = 0; i < t->index; ++i) {
          if (t->str[i] != t->str[i + diff])
            break;
        }

        // if we successfully got through the previous loop then our current
        // index is good.
        if (i == t->index) {
          t->index++;
          break;
        }

        // otherwise we just try the next index
      } while (t->index);
    }
  }
  // unreachable
  return -1;
}


text:
How is a 41KB char array filling up 256KB of program memory?
I have an array of 41,400 elements of type char, which I am trying to put in program memory on a Mega2560. It should have 256KB of flash memory, but when I try to compile my sketch, it says the size of the array is too large. Each char is one byte, so this array should be 41,400 bytes. I'm at a loss as to how this can be too big.
I have also tried using an array of byte variables (should be the same thing) with no success. This is the only variable going into program memory.
Here is the relevant line:
const char Array[] PROGMEM = {0,19,21,25,27,27,27,29,24, ... };

I have included avr/pgmspace.h
Thanks in advance for any help.

What is the exact error message?

I included <avr/pgmspace.h> (that part of my question didn't display as I expected).

The error message is: error: size of variable 'Array' is too large

It seems AVR GCC limits the size of variables to 32K. Did you try with an array of 32767 chars, I guess it should work. If you try with 32768 chars, then it should show the error message.

I have just proved that in experimentation. 32767 is the limit for a progmem array.

I will try that. I will update when I have done that. It won't be until later today or Monday though. It is a shame they are limited to 32K when there is so much program memory.

00000108 l     O .text 00007fff _ZL5Array

Chances are the AVR architecture is not the right choice for your application.  There are plenty of 32-bit ARM parts with 32-bit ints permitting ordinary data pointers to flash offered at lower prices than an AVR with 256KB of flash.

The limitation here is the data type of the index of the array. That is int, and on an 8-bit system an int can hold a value in the range -32768 to 32767.
That means the biggest index number an array can have is 32767.
That limit cannot be changed. You're stuck with it.
However, there are some tricks you can use to expand it.  One is to use a larger data type than char and pack your data into it.  For instance, using unsigned int as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.
Using unsigned long (32 bits) would double that again.
It is then up to you to work out how to get to the individual bytes. Using the pgm_read_byte_*() function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...

Or an array of arrays. Or an array of structs. There's many ways of skinning this cat. But when it comes to reading it's just seen as a block of raw memory with no inherent type.

Agree, there is many different ways of doing this. Choose the easiest for you :). I gave you +1.

This makes sense. Thanks for the suggestions on workarounds.

You cannot have more than 32767 elements in one array. The reason is explained nicely by Majenko.
Solution for your problem is very simple, because you need only 41400 elements:
class MyArray
{
  static char array1[30000] = {...};
  static char array2[11400] = {...}; // rest

  public:
    char get(long index)
    {
      return index > 30000 ? array2[index - 30000] : array1[index];
    }

    char operator[] (long index)
    {
      return get(index);
    }
};

So you can use two arrays and depending of the index choose which one to use. I think it is faster than using array of ints, because you need to have division (by two, so it can be only shift right by one) and than again shifting to get the char. Also it is easier to use because for ints you need first to pack values (two values in one int).
This is just example code, fit it to your needs.

You're not putting the arrays in PROGMEM. And when they are, you can't access them like that - you need pgm_read_byte_near() etc.


text:
Problems With Fading Through Neopixel Colors
I have a 20x20 matrix of neopixel LED's. I have a certain set of LED's on in different places at different times. Each one is set to mainColor. Right now mainColor is just set to strip.Color(r, g, b) but I would like to have those color fade through the spectrum. I decided the easiest way would just be to do something like this, and simply return strip.Color(r, g, b) to mainColor, then calling it to turn change the colors like so:
strip.setPixelColor(pixelNumber, mainColor(5));

Here is the code for mainColor:
    int r;
    int g;
    int b = 255;
    int _r;
    int _g;
    int _b = 255;
void Color (int FADESPEED)
{
    // fade from blue to violet
    for (_r = 0; _r < 256; _r++) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from violet to red
    for (_b = 255; _b > 0; _b--) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from red to yellow
    for (_g = 0; _g < 256; _g++) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from yellow to green
    for (_r = 255; _r > 0; _r--) {
        r = _r;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from green to teal
    for (_b = 0; _b < 256; _b++) {
        b = _b;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
    // fade from teal to blue
    for (_g = 255; _g > 0; _g--) {
        g = _g;

        mainColor = strip.Color(r, g, b);
        Clock ();

        delay(FADESPEED);
    }
}

This was good but it would only return r, g, b as it was on the last iteration of the last for loop, which obviously isn't what I want. But when I un-comment the Serial.print's the values were perfect. So then I put return strip.Color(r, g, b) into each for loop, however this only returns the first iteration of the first loop, which is also not what I want. Does anyone know how in the world I can return strip.Color(r, g, b) for every iteration of every for loop? Or if not, any alternatives that would work in this situation.
Thanks, Matthew

If you return something, the loop ends. I don't know why you would return something in every iteration. That doesn't make sense. they don't do anything until the for loops are done, which takes forever - well, get rid of the delay calls. In fact, a rewrite is called for. Step back from your code, think of what you want to do, write some pseudo-code on paper, and then code when you are happy you have got a good plan.

@NickGammon That is a good idea, but I need the delay because I want the colors to fade slowly, but I will try some pseudo code...In the mean time, any ideas?

Yes, but you don't have to use delays. See How to do multiple things at once ... like cook bacon and eggs for some ideas.

Thanks @NickGammon, that site is pretty useful, I will see what I can do with that.

There appears to be a number of problems with this code.
The variables only have scope with in this function and are not static.  So they will not survive from call to call.  Every time you call this function it will be like starting over.
Putting returns in the middle of code is not good coding practice.  It is very difficult to follow and hard to debug.  It would be best to arrange your code so that there is only 1 return at the end of the function.
This code (from Adafruit) only controls 1 RGB LED.  If you are to control 40 RGB LEDs all at different stages of color changing you would need 40 copies of this function.  This is not very efficient. Instead use this function to populate one lookup table with R G B data.  Then track 40 variables, one for each RGB LED.  Use the 40 variables to lookup a specific color combination in the lookup table for each of the 40 RGB LEDs.

I have updated the code so the scope is more suitable, though it was designed to not actually matter because the last iteration of the last loop is technically the same as the first iteration of the first loop. I have also removed the extra returns, however it still only is returning the last iteration of the last loop...so back to square one with that. As for the LED's, they are all to be colored the same so it shouldn't really matter, right?

All your LEDs are to be the same color?  I didn't realize that.  So, in the original Adafruit code, a call was made to the function analogWrite() inside each of the different color changing loops.  You are trying, instead, to return that value each time you call your function mainColor().  This is very difficult to do!  I would do what the code on Adafruit's web site does.  Or, as you have already found out, if you print out the values they look correct.  So why not call the function analogWrite() from the same locations as your commented out print statements?

I am building a word clock, so they cannot all be on at the same time, if they were I would just use the rainbow cycle provided with neo pixels code library, that's why I would rather have the one color that I can call for each set of LEDs.

So, some LEDs are on and some are off.   The ones which are on all change their color in unison.  So, continuously call  the change color function.  But from that function call a function that choses which LED to light.  Only from that function make the call to strip.setPixelColor() for the LEDs which are to be lit.

Yes, I'm not home at the moment but I may have an idea. I have a for loop void that takes in an array of pixel id's, the length of that array, and also the color, I do that rather than doing a for loop every time just to make it easier for me. So every group of LEDs call that for loop void, including the color. But I just thought, seeing as though every group uses the same color, I might as well make put that color just in the for loop void, as well as the mainColor loops. I'll give that a go once I'm home, do you think that would make a difference?

Just tried that, no luck...

Changed it back now, still only returning the last value of the last for loop. Is there any alternatives I could try, do you know?

Start over using the Adafruit example code you pointed to.  Instead of calling analogWrite() with the color information like Adafruit did, you call matthewsClock() with the color information created using strip.Color().  In matthewsClock() you pick which world-clock LEDs are to be lit and which to turn off.  Then you send the color information to the ones to be lit and the color black to the ones to be off.

Still nothing, I tried it as a void and as the uint32_t, both are still only coloring the LED's as the last iteration of the last for loop (blue), and when I try to turn on 1 individual LED with strip.setPixelColor(number, r,g,b) it doesn't even turn on until it gets to that last iteration...

Another problem I just noticed is that the for loops are taking forever to iterate through...I have 3 buttons that are meant to change the time (it's a word clock) but they don't do anything until the for loops are done, which takes forever...

Since Stack Exchange Qs & As are supposed to be search-able by others, we shouldn't have long conversations here.  Never the less my advice is to start simple.  Get one feature working.  Do not add anything else until what you have works.  For example, forget about the buttons & the clock for now.  Adapt the Adafruit code to cycle one of your strip LEDs through multiple colors.  Note the Adafruit code "is" this loop() function.  It is not a function you call from a line in the loop() function.  After you get that working do what I outlined in my previous comment.


text:
My Arduino Code isn't workig... and i just couldn't see any problems... thoughts?

There's Latest Update!

So i'm working on a counter just for fun. How it works is when you press BUTTON1 the LED Lights up red, the buzzer beeps and the variable "counter" adds one to itself; After counting, you can press BUTTON2 then it will first show a transition animation then blink&beep while taking away the value of "counter". After the value of "counter" is less than 1, everything will start from the beginning.
But what actually happens is after the transition animation played, the LED and the buzzer just won't do any thing. I'm sure my physical connection is all correct, and the buttons are also pulled to ground with a resistor& a 100nf cap to prevent accidental pressing and vibration.

Note that I'm using a common anode RGB LED, so the anode pin is always HIGH but to light up individual colors i'll have to pull the cathode pins LOW (remember how electrons flow?)

Update
@Tom Carpenter's latest answer still didn't solve the problem. I found the "else" function inside the "if" didn't work at all. So if i put the counter code inside the "else" function, the result would be none. But if i put the counter code in the "if" inside the primary "if", it would, again, count at clock speed, which results blinking forever!
So is there anyway for the code to only count once per press&release cycle without losing?

The latest code:

#define RLED 10
#define GLED 11
#define BLED 12

#define B1 4
#define B2 5

#define BZZ 3

boolean OB1V;

int counter;

void setup() {

  pinMode(RLED, OUTPUT);
  pinMode(GLED, OUTPUT);
  pinMode(BLED, OUTPUT);

  pinMode(B1, INPUT);
  pinMode(B2, INPUT);

  pinMode(BZZ, OUTPUT);

  OB1V = digitalRead(B1);

}

void loop() {

  digitalWrite(RLED, HIGH);
  digitalWrite(GLED, HIGH);
  digitalWrite(BLED, HIGH);

  boolean NB1V = digitalRead(B1);

  if (NB1V != OB1V)
    {
      digitalWrite(RLED, LOW);
      digitalWrite(BZZ, HIGH);
      counter = 0;
    }
  else
    {
      digitalWrite(RLED, HIGH);
      digitalWrite(BZZ, LOW);
      counter = counter +1;
    }

  if ( digitalRead(B2) == HIGH )
    {
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(RLED, LOW);
      delay(300);
      digitalWrite(RLED, HIGH);
      digitalWrite(GLED, LOW);
      delay(300);
      digitalWrite(GLED, HIGH);
      digitalWrite(BLED, LOW);
      delay(100);
      digitalWrite(BLED, HIGH);
      delay(300);

      for ( counter; counter >= 1; counter -- )
        {
          digitalWrite(GLED, LOW);
          digitalWrite(BZZ, HIGH);
          delay(200);
          digitalWrite(GLED, HIGH);
          digitalWrite(BZZ, LOW);
          delay(200);
        }
    }
}

How are your buttons wired?   Typically you would use a pullup resistor and a button switching to ground, so pushed is "low".  Also your non-delay counter case would probably be subject to contact bounce, except for the fact that "counter +1" doesn't actually count as it does not save the result of the add.  Your other path with delays might be somewhat immune to bounce on press, but can suffer it on release unless the user releases the button enough before the end of the sequence of operations there.

I pulled the button to ground so a press event is HIGH.

Also if i change "counter+1" above into "counter = counter+1", the green LED will keep flashing as a result

Go out, walk around some, socialize with people, come home, sleep, and look at it tomorrow.

counter +1; doesn't do anything as Chris says. As a result the value counter is always 0, and so the for loop will never do anything (and will probably be removed as dead code by the compiler). If correcting the line causes something else to break, it means something else in the code is broken.

Try adding Serial.println(counter); inside the if statements to see what the counter value is when buttons are pressed (also add Serial.begin(...) to the setup() if you are adding the print statements.).

So how do i change the value of "counter"? if i change "counter+1" above into "counter = counter+1", the green LED will keep flashing as a result

You change it to counter = counter + 1, which is what it needs to be to change the value of counter. Then you need to find out what is actually causing the green LED to keep flashing - printing debug info to the serial port will help you there.

The green LED is not the indicator on board..it's my user LED and doesn't show any status of the chip. So i think the problem would still be the logic of the program.

What is this doing? for ( counter; counter >= 1; counter -- ) - it makes more sense to initialize counter to something (the first item in the for loop). Eg.  for ( counter = 10; counter >= 1; counter -- )

@Nick Gammon counter already has a value before : - )  Look at the first button listener.

In that case you can write: for ( ; counter >= 1; counter -- ) - just using counter on its own looks like you forgot something

There are a number of problems with your code.  Your code does not deal with releasing the button.  Once you press B1 (assuming pressing B1 causes the input to go high) the counter (if correctly implemented (that is, it should be counter++)) would count up to 32K then start over at zero and count up again. Only stopping when you release B1.  The value of counter could be any number between 0 and 32K.
Working with buttons is difficult.   And the 100nF capacitor will do little to help.  It would be better if you learned how to debounce buttons and treat both the press and the release with equal importance.
There is an Arduino library called Bounce that will do some of this for you.  It will not help with your logical errors.  You still need to treat pressing and releasing the button with equal importance.  But it will help debounce button presses so your results will more closely match your expectation.
added later...
Your altered code will still not work.  You need to keep track of the state of the button in order to increment the counter by one for each button press.  You can call it edge detection code or state machine code.   But the code needs history to decide what to do next.  Here is an example of code which does this.

the cap does help because i've tried to print messgaes on the serial monitor with "caped" buttons--perfectly one result each press. Also to deal with release, i put an "else" function at the end which turns the LED and the buzzer off. So it should trigger counter +1 (or counter ++ if u like) each time i press the button

@user56336 remember that it is in a loop. The whole loop() function will execute thousands of times per second, so unless you release the button in much less than a millisecond, it will repeatedly add 1 to the counter until the button is released. Try adding the print statement I suggested and you will see that.

In most cases when using a button, the software keeps track of 4 states.  1) Button released and action already taken, 2) Button pressed and action not taken yet, 3) Button pressed and action already taken & 4) Button released and action not taken yet.  You need to keep track of these 4 states if you want to count up by one for each button press.

well, what my code does is just add 1 to the "counter" value every time there's a HIGH signal from the button pin untill the second button is pushed, it'll show the results. So i don't think i'll have to listen all four status. The problem now is, after i changed "counter +1;" above into "counter = counter +1;" so that it'll keep the result as mentioned above, the LED keeps flashing when supposed to show the result. So there must be something wrong with adding or minusing.

Perhaps this would be more obvious in a real C code environment instead of in an Arduino environment.  In real C you would have to put your button press inside of an infinite loop.  Because you would want to use your button over an over again.  Not just once.  While inside an infinite loop, you would see that when the button was pressed, the computer would simply be adding 1 to counter over and over again as fast as it could.  Do this, after adding 1 to counter print out the value of counter.  I think you will see, when you press the button, an endless stream of " 1",  " 2", " 3", ...

@ Tom Carpenter i guess ur right. lemme try n figure that out

Your problems come down to the fact that in the first code you are trying to do things on level sensitivity rather than edge sensitivity.
To try and understand the difference, some examples. Level sensitivity is effectively:

Do 'x' while 'y'

In other words, if 'y' is true (for example an input is high), then keep doing 'x' (e.g. adding to a counter). This is what your code is doing at the moment, but not what you want it to be doing.
Edge sensitivity on the other hand is:

Do 'x' when 'y changed'

In other words, when the state of 'y' changes (for example from true to false), then doing 'x' once.
The key difference between the two is the difference between 'while' and 'when'.

So how do you do edge sensitivity in code?
The way you have done it requires that the button be high and then low at exactly the right moment for the code to catch it. What happens if the button goes low at the end of the loop? Your code will miss the edge because at the start of the next loop it is not high, so doesn't get in to the first if statement.
Lets think about what 'changes' means. It means when the current value is different from the previous value. That implies that we need to keep track of what the previous value is in order to compare it to the current value. In fact that is exactly what we do:
boolean oldButtonValue; //It would be better to use a static variable in loop, but for simplicity of the example lets use a global.

void setup() {
    oldButtonValue = digitalRead(buttonPin); //This line is executed once to initialise the variable.
}

void loop() {

    //Each loop we read our current value
    boolean newButtonValue = digitalRead(buttonPin);

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Do something on edge.

    }

    //Update the old button value to match the new one (so we can check it again next loop
    oldButtonValue = newButtonValue;
}

What this does is each loop it compares the current state of the button with the state of it from the previous loop. If the value changes, it does something.

Now the trouble with that code is it executes on any edge. That means that each time you press the button, it will run twice, once on press and again on release. So lets modify it slightly:
    ...

    //Has it changed?
    if (newButtonValue != oldButtonValue) {

        //Was it a rising edge?
        if (newButtonValue) {
            //If the button value is now high, it must have been a rising edge
        } else {
            //Otherwise it was a falling edge

        }
    }

    ...

The extra comparison allows us to determine whether it was a rising edge or a falling edge. So you can now do something either when the button is pressed, or when it is released (or both if you want).

You can have a second boolean variable to keep track of the old state for the second button. Then you use the same approach to do edge sensitivity detection approach for the second button.

i changed my code into this: link Because that the sencond button always works fine, i didn't touch that piece of code. But what happens now is when it is supposed to show the results, it showed nothing! What's wrong now?

@user56336  Try it, and if it works, there you go. It looks basically the same as what I put just with much harder to follow variable names. Except you are missing the bit where you set OB1V = NB1V; at the end of the loop which is a somewhat critical part. And really you should do the same with both buttons, otherwise you will end up with the same problem with the second one - it will execute the code multiple times if you keep the button held down.

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

authors: Ареке Конарбай


text:
Slice byte-stream into bit pieces
I receive byte data from a RS-232 device with Serial.read();. Now I need to slice this down in bit-pieces:

value1: 15bits
value2: 7bits
value3: 9bits
value4: 12bits
and so on

Data from the stream (switch them around for better understanding):

Byte 1: 00101100 => 00110100 (least significant byte first)
Byte 2: 10011011 => 11011001
Byte 3: 00110011 => 11001100
Byte 4: 11101000 => 00010111
Byte 5: 01001100 => 00110010
Byte 6: 01100111 => 11100110

Now the least significant is first.

value1: 00110100.1101100[1] => 6956
Need to cut of the last bit of the second byte
value2: 1.110011[00] => 103
Add the last bit of the second byte and cut off the last two bits of the third byte
value3: 00.0001011[1] => 416
Add the last two bits of the third byte and cut off the last bit of the fourth byte
value4: 1.00110010.111[00110] => 3737
Add the last bit of the fourth byte and cut off the last 5 bits of the fifth byte

Now the question: How do I realize this from programming side. I'm lost.

If the records are byte aligned you could use a struct with bit-fields and let the compiler do the work. http://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

Another alternative is to define a BitStream class that operates on a Stream (Serial). Typical member function would be uint16_t read(uint8_t bits). The class would have to buffer any remaining bits for the next read, etc. http://www.drdobbs.com/bitstream-parsing-in-c/184402014

I'm voting to close this question as off-topic because it's a year old question with no answers.

@LookAlterno But this one has an answer. It is/was edited into the question. I have now put that as an answer.

Note: This is an answer that OP originally edited into his question.

I gather the data into an array of bytes data[125].
Then I gather the relevant bytes per value and stack them together:
long var = (data[4]<<8) + (data[3]);

I shift them so the relevant bytes start first
var=var>>3;

Afterwards I mask them with the RIGHT mask
var=var & 0xFF;

For the example in my question:
long var = (data[1]<<8) + (data[0]); // I need two bytes
var=var>>1; // shift them to the right one bit
var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"

Good work gre_gor!


text:
How to use Arduino as RC Receiver
I want to use Arduino as my RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D. I fetched following image from OpenPilot GCS. The diagram shows to use input 6.

Following is the image of my CC3D. The cable colors does not correspond to each other.

Which input cable should I connect to Arduino?
How should I connect black(ground) and red(5V) cables to Arduino:

EDIT this answer explains how you can put a Arduino between a (1 ppm pin per channel) RC receiver and a RC receptor. This allows for smart features (like autonomous control with RC overrule, or sensor based corrections,..)
It seems it is not the question of op.
What you want is easy but there are some pitfalls.
I can make a long story short by these links
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with.html
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_20.html
http://rcarduino.blogspot.com/2012/04/how-to-read-multiple-rc-channels-draft.html
if you are serious about RC this may be of your interest to
http://rcarduino.blogspot.be/2012/01/how-to-read-rc-receiver-with_25.html
I also converted this info in a library you can find here:
https://github.com/jantje/ArduinoLibraries/tree/master/RCLib
And for stackexchange policy here the hightlights.
If I look at the picture you added you have a 6 channel ppm receiver. Each ppm channel you want to read must be connected to a interrupt enabled pin of your arduino (The drawbacks of software enabled interrupt pin is another discussion).
The high time of the ppm tells how high or low your lever is on the remote control.
You can then have arduino do with this info what you want. For instance use the servo library to generate a ppm signal out to servo's and ppm driven motors.

Your answer addresses a problem opposite of that in the question.  This is not about reading an RC receiver but about creating one.  The PWM(s) are outputs, not inputs.

I was wondering what was actually asked. It just shows the quality of the average question.  My answer is actually RC in RC out. and it is PPM not PWM. The servo library creates PPM

Radio PPM is not servo PWM

@ChrisStratton is right. I want to use Arduino as RC receiver. I will generate PPM signal from Arduino. Then I will send generated signal to my OpenPilot CC3D.

@jantje There are 6 channels. But only 1 of them is used as PPM channel. As shown in the image which I fetched from OpenPilot GCS software, the PPM channel is shown as 8th pin.

@Halil Your question is still not clear to me. As this is a Arduino forum and not a aviation forum I think it would be a good idea to place arduino in the middle and explain what your input is and what the output is you want to achieve.Just my 2 cent. From what I understand now your question is: "How can I -using a arduino- mimic a rc receiver compatible with a openPilot CC3D" (and if that is the question I can't answer it )

@jantje I think you didn't fully read the question. Please review again the last 2 lines which is below the photo. I am not asking how to mimic rc receiver using arduino in this post. I am asking how to connect CC3D controller to Arduino


text:
teensy as a keybooard throws error as keyboard input
I have a program (bash script) I wrote that is for stop motion animation. The script works perfectly, when I use any given keyboard on my laptop, and it works on other computers, as well.  So i wanted to add a controller, using a teensy, and the keyboard library. source here:
The teensy, set up as a keyboard, using one of the example codes, which I modified. The output appears correct: when I press any of the buttons, I get the expected output (asdw). But, the script throws an error, and exits anyhow, which means something else is being sent besides the key presses I desire.
So, WHY?
Here is the keyboard source for the teensy:
 /* Buttons to USB Keyboard Example

   You must select Keyboard from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

#include <Bounce.h>

// Create Bounce objects for each button.  The Bounce object
// automatically deals with contact chatter or "bounce", and
// it makes detecting changes very simple.
Bounce button0 = Bounce(0, 10);
Bounce button1 = Bounce(1, 10);  // 10 = 10 ms debounce time
Bounce button2 = Bounce(2, 10);  // which is appropriate for
Bounce button3 = Bounce(3, 10);  // most mechanical pushbuttons
Bounce button4 = Bounce(4, 10);
Bounce button5 = Bounce(5, 10);  // if a button is too "sensitive"
Bounce button6 = Bounce(6, 10);  // to rapid touch, you can
Bounce button7 = Bounce(7, 10);  // increase this time.
Bounce button8 = Bounce(8, 10);
Bounce button9 = Bounce(9, 10);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(6, INPUT_PULLUP);  // Teensy++ LED, may need 1k resistor pullup
  pinMode(7, INPUT_PULLUP);
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
}

void loop() {
  // Update all the buttons.  There should not be any long
  // delays in loop(), so this runs repetitively at a rate
  // faster than the buttons could be pressed and released.
  button0.update();
  button1.update();
  button2.update();
  button3.update();
  button4.update();
  button5.update();
  button6.update();
  button7.update();
  button8.update();
  button9.update();

  // Check each button for "falling" edge.
  // Type a message on the Keyboard when each button presses
  // Update the Joystick buttons only upon changes.
  // falling = high (not pressed - voltage from pullup resistor)
  //           to low (pressed - button connects pin to ground)
  if (button0.fallingEdge()) {
    Keyboard.println("s");
  }
  if (button1.fallingEdge()) {
    Keyboard.println("d");
  }
  if (button2.fallingEdge()) {
    Keyboard.println("w");
  }
  if (button3.fallingEdge()) {
    Keyboard.println("a");
  }
}

What should I do to just get the key presses (asdw) from the teensy as if it were a plain old keyboard.

You are calling Keyboard.println() which sends the character string followed by a new line.  If you want to emulate a keyboard you should only use Keyboard.print() which only sends the character string with no new line.

Ok I figured it out. The code includes "keyboard.println". I should use "keyboard.print instead", to properly simulate keyboard presses. the newline is what was screwing it up.


text:
Adafruit GPS module with SoftwareSerial affecting servo signals
I'm having a bit of an odd problem here. I'm programming a self-built quadcopter using an Arduino Uno for control. One of the sensor's that I'm using is Adafruit's GPS breakout. The motors are controlled with electronic speed controllers (ESCs) that controlled identically to normal servo motors. Everything is connected together with a custom Arduino shield. The GPS is using SoftwareSerial on pins 3 and 4, and the ESCs are connected on pins 5-8. Most of the GPS code is directly copied from Adafruit's documentation.
What I've found is that even when the throttle is held steady (at any power level), the motors experience quick bursts of power far beyond normal whenever there is communication between the GPS module and the Arduino. For example, the GPS updates on 1Hz intervals and so the motors get a burst of speed about every second. Has anyone else experienced something like this or could someone at least point me in the right direction?
Here's an abbreviated version of the code that I'm currently using:
#include <Servo.h>
#include <Wire.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

Servo ESC1;
Servo ESC2;
Servo ESC3;
Servo ESC4;
const int maxThrottle = 2000;
const int minThrottle = 1000;

SoftwareSerial softwareSerial(4, 3);
Adafruit_GPS GPS(&softwareSerial);
// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
bool usingInterrupt = false;
uint32_t timer = millis();

void setup() {
    ESC1.attach(5);
    ESC2.attach(8);
    ESC3.attach(6);
    ESC4.attach(7);
    setThrottleAll(minThrottle);

    GPS.begin(9600);
    GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
    GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
    GPS.sendCommand(PGCMD_ANTENNA);
    useInterrupt(true);
}
int throttleCommand = 20;
void loop() {
    // Map throttle command percentage to raw throttle values that are sent to the ESCs
    int throttle = map(throttleCommand, 0, 100, minThrottle, maxThrottle);
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}

// GPS interrupt
SIGNAL(TIMER0_COMPA_vect) {
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    #ifdef UDR0
        if (GPSECHO)
            if (c) UDR0 = c;
                // writing direct to UDR0 is much much faster than Serial.print
                // but only one character can be written at a time.
    #endif
}
void useInterrupt(boolean v) {
    if (v) {
        // Timer0 is already used for millis() - we'll just interrupt somewhere
        // in the middle and call the "Compare A" function above
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
    }
    else {
        // do not call the interrupt function COMPA anymore
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
    }
}

void setThrottleAll(int throttle) {
    setThrottle(1, throttle);
    setThrottle(2, throttle);
    setThrottle(3, throttle);
    setThrottle(4, throttle);
}
void setThrottle(int index, int throttle) {
    if (index == 1)
        ESC1.writeMicroseconds(throttle);
    if (index == 2)
        ESC2.writeMicroseconds(throttle);
    if (index == 3)
        ESC3.writeMicroseconds(throttle);
    if (index == 4)
        ESC4.writeMicroseconds(throttle);
}

SoftwareSerial combined with a real time flight controller sounds like a bad idea.  You may also have areas in the message code that can block.  This project requires careful engineering from one end to the other.

@ChrisStratton Is there a different way of communicating with the GPS module that doesn't block? Would the hardware serial pins 0 and 1 be a better choice?

Servo.h uses a timer and will experience glitches if interrupts are disabled frequently/for a long time.

Realistically, an Arduino is not an appropriate platform for a flight controller - pretty much all projects have long abandoned them, and even if you are going to use an ATmega you really need to use only code specifically written for this purpose rather than typical Arduino libraries.  For example, you want to make sure that you are using hardware PWM channels for all outputs and you want to make sure that your control loop cannot under any combination of circumstances get stuck anywhere.  Speaking of loops, a lot more is needed than throttling the motors.

Ah, I understand. The reason I thought it was possible was because of other projects like AeroQuad and BlueCopter. Some people have even gotten quads to fly with a Raspberry Pi as the flight controller (and a totally non-realtime stock Raspbian OS). On the last point, my actual code is much more complex. I just kept the relevant parts because I've narrowed down the issue to the GPS module. The rest is much more than just throttling motors!

Quickly looking at AeroQuad it seems they may not support GPS on anything less than a Mega, moved heavily into 32 bit ARM alternatives to the AVR platform, shipped their own libraries for the key functionality... and don't appear to have touched the code in 3 years.  Which mostly reinforces the sense that while flying something with an ATmega328p is possible, few would bother today, or when using stock libraries that hide many of the critical details to which attention is required.

The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit_GPS), and your program structure is based on the awful Adafruit_GPS example.
The good news is that there are much better alternatives: NeoSWSerial and NeoGPS.  Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos.  It can be an "interesting challenge" or a "beginner's nightmare."
Suggestions:
1) Consider using the HardwareSerial object, Serial, for the GPS interface.  Your excerpt does not show what Serial is currently used for, but if it's debug print statements... don't.  Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC).  This would have a tremendous impact.
2) If you really really can't use Serial for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded SoftwareSerial.  Next best is NeoSWSerial on any pins, including 4&3 that you are using now.  There is absolutely no reason to shoot yourself in the foot with SoftwareSerial.
3) As other's have commented, use HW PWM... let the machine do the work for you.
4) Consider using the faster and smaller NeoGPS library.  And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient.  The Adafruit_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a SoftwareSerial interrupt... that was on for the entire character time of ~1ms.  What a phenomenal waste!
5) Use interrupt-driven GPS parsing.  All three Neo__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters during the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow).  And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete.  This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with strcmp and strchr.  Ugh.  No, I meant to say UGH!
6) NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.
It's definitely a tight squeeze.  Either reallocate your pins and use better libraries, or get a bigger hammer.      :-)

Wow, thank you so much for that thorough answer! I had no idea that there were alternatives to the stock Adafruit libraries for their hardware. I'll definitely take a look at it.


text:
Looking for a wireless soil moisture sensor
I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?

The project is very much possible but it will be easier if you attach the moisture sensor directly to the arduino and add a wifi shield or a bluetooth shield to the arduino itself and make it communicate with computer or phone. You could also program the arduino to directly water the plants if it finds that they dont have much moisture. You will rarely find a sensor that transmits data wirelessly and still be economically feasible. The Sparkfun SEN-13322 moisture sensor is good for the purpose but again connect it to arduino direclty.

so how do I read the moisture in the lawn soil?  I can't put the sensor and arduino in the lawn so not sure what you are suggesting?

@JStorage I cant figure out why you cant put the arduino and the sensor in the lawn. For all such projects that I have seen arduino is encased in a box that protects it from rain etc. and the its connected to the sensor  and kept in the lawn. But also if you want this project to be messy you can actually wire the sensor in the lawn to the arduino inside but that will be a little too messy. Simply keep the arduino in a plastic box and attatch the sensor and keep it in the lawn.


text:
Why is timer0 the fastest timer in the arduino?
In the documentation, it shows that the higher  frequency that can be reached with an Arduino UNO for and 8bits PWM is using timer0  with the pre-scaler  set at 1. That  gives a Fs of 62500 Hz, but why is that so?
I understand the Prescaler is dividing the frequency, but why it does start at 62500 Hz and  timer1 and timer2 have as maximum 31372 Hz.

Timers 1 and 2 are configured by the Arduino core library to run the so
called “phase correct PWM” mode. In this mode, the timers count
forward from 0 to 255, and then they count backwards to zero. Timer 0 is
configured by the same library in “fast PWM” mode, where it counts
from 0 to 255 and then overflows back to zero in a single timer cycle.
You can, if you want, configure timers 1 and 2 in fast PWM mode. For
doing this, you will have to access their I/O registers directly. C.f.
the datasheet of the relevant microcontroller for details.
A couple of links:

the datasheet of the
ATmega328P
microcontroller describes all the possible configurations of the
timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
the source code of the Arduino init()
function
to see how Arduino core configures them.

Where is that function called? is it in the bootloader?

@LuisRamonRamirezRodriguez: No, init() is called by main().


text:
How to connect a phone's camera to an Arduino?
I would like to ask how to connect my phone's camera to an Arduino, just like it is done in this this video. Is anyone familiar with this application they are using?

That video shows a Bluetooth connection between the smartphone and the Arduino.
(A USB connection between the smartphone and the Arduino might be better in some ways).
details
If you want more information after watching a video like this, click the "show more" button underneath the video to see the details.
Those details clearly say "The Nexus S device connects to the IOIO board via Bluetooth, and uses the smartphone's camera in conjunction with OpenCV and the external IR sensors to control the vehicle."
Those details also include a link to
"Android Based Robotics".
The OpenCV image processing software runs on the smartphone. In this autonomous application, the image data never leaves the smartphone. The software on the smartphone reduces the image data to two integers -- the X,Y pixel location of the center of the green ball.
The Arduino and the Bluetooth link can easily handle a few integers at over 200 Hz. Neither one is suitable for handling live video data.
The Arduino could probably act as the controller.
The camera could send the X,Y pixel location of the green ball to the Arduino; while the Arduino collects all the other sensor data; then the Arduino could use that to decide what to do; then send the appropriate control signals to the motor drivers.
However, in this autonomous toy car it appears that the the smart phone acts as a controller.
The Arduino collects all the other sensor data, forwards that data to the smartphone; then software on the smart phone takes that data and the X,Y pixel location of the green ball; then the smartphone decides what motors need to turn; then the smartphone sends the appropriate commands to the Arduino, and the Arduino demultiplexes those commands to the motor drivers.
For even more details on building robots using smartphones and Arduino, see

"Android Based Robotics" ( http://www.socsci.uci.edu/~jkrichma/ABR/ ).
The Tinkernut video
"DIY Smartphone Controlled RC Car" ( https://www.youtube.com/watch?v=xsJ7176fLNw )
goes into more details of how to connect a smartphone to an Arduino via Bluetooth.
Android Based Robotics: ground robot manual
( https://groups.google.com/forum/#!topic/android-based-robotics/_H8Zmvbxx-M )
"Simple RC car for beginners (Android control via Bluetooth)"
( http://solderer.tv/cxemcar/ ) ( via http://english.cxem.net/ ).
Communicate with Your Arduino Through Android (using USB cable)
ArduinoCommander:
"Control your Arduino board from your Android device over Bluetooth, Ethernet or USB"

Normally I would say that the phone is some kind of converting image to serial data and sending it to arduino via serial port. But there is no cables on the phone in the video. It is communicating wirelessly. But I don't think that vehicle is atonoumus?  The phone should be transfering image data via ethernet (wifi) and the user controls it. The reason I don't think that's an atonoumus is because you can't simply process that image stream with an arduino it would be a enormous process for arduino's little chip. They must be processing it on a computer. Either two ways the phone is talking to another processor. Not the arduino. Maybe if you tell what you want to do spesificly I might help you instead of trying to figure out this video :))  EDIT: it could also be a Bluetooth connection :))

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


text:
Interrupt numbering
I'm using an Arduino Mega and four of its interrupts. Each interrupt is only used to start/stop a timer, depending if it's rising or falling, so effectively runs the same function. Does anyone know if theres a way to differentiate between which interrupt has been triggered? This way I can attach them all to the same ISR and just start/stop different timers.
Thanks,
Shaun

The only sure-fire way of knowing which interrupt triggered your ISR is to examine the GPIO pin that the interrupt is associated with.
You need to use CHANGE interrupts so that you can keep track of the state of the pins - both HIGH and LOW.  When you get an interrupt and read all the GPIO pins you have tied to the ISR you can then compare their values to the previously stored values. Any pins that have changed since the last ISR (or a pre-defined initial state) can be processed and handled accordingly.
Yes, it adds a certain amount of overhead to your code, and using digitalRead() may not be the most efficient way of doing it. Instead you may want to use direct port access to read the pin's state directly.

Thanks, I will have to look into direct port access as I haven't done this before.

Assuming that by "Mega" you mean the Mega 2560, see sections 15.2.4 and 15.2.5 of the 2/2014 datasheet referring to the External Interrupt Flags and Pin Change Interrupt flags:

When an edge or logic change on the INT7:0 pin triggers an interrupt
  request, INTF7:0 becomes set (one). If the I-bit in SREG and the
  corresponding interrupt enable bit, INT7:0 in EIMSK, are set (one),
  the MCU will jump to the interrupt vector. The flag is cleared when
  the interrupt routine is executed. Alternatively, the flag can be
  cleared by writing a logical one to it. These flags are always cleared
  when INT7:0 are configured as level interrupt.

It is not clear from the above when specifically "The flag is cleared when the interrupt routine is executed" happens. It wouldn't be much use if it happened on ISR entry so I'll take a guess that it happens on return from interrupt, in which case the flags would be available to read in the ISR. An experiment would be in order, here. These flag registers are known to the compiler as EIFR and PCIFR, respectively.

My reading of the datasheet (see section 7.8) makes me think the flags are cleared at ISR entry. Only the GIE is enabled during RETI (it specifically mentions it) and it reads like it's at the start of the ISR that the flag is cleared: "The first type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag.".

For the RETI it says: "A return from an interrupt handling routine takes five clock cycles. During these five clock cycles, the Program
Counter (three bytes) is popped back from the Stack, the Stack Pointer is incremented by three, and the I-bit in
SREG is set." - So yes, it is very very woolly in its wording, but I would lean towards the interrupt flags not being available to read in the ISR, which is a bit poor really. Personally I prefer the Microchip method where it is up to the user to manually clear the interrupt flag when it is finished with.

Thanks for the response, I'll test this method and post whether or not I can get it to work.

@Majenko: The only reason I hold out any hope at all that they'd be readable within the ISR is that someone designed those registers to be readable, which would be pointless if it is cleared during ISR vectoring (not to say it wasn't done that way!). The program would only ever be able to read zero.

You can read them outside an ISR when the interrupt is disabled. You can use it like a flag that is set by hardware which you can then check as and when you want. You get the notification but you don't have to respond immediately.


text:
can homemade arduino be powered up with battery?
I am new to arduino. It is costly for me to buy an arduino uno board. Therefore I am going to make a Arduino with breadboard at my home. I also want to make my Arduino portable. Arduino Uno boards can be powered up with battery. But can I do so with my homemade Arduino? If it is possible, what things need to be included in my homemade Arduino?

A modern irony is that it can by hard to buy a single processor for less than the cost of a clone board - especially if you want one with the bootloader pre-programmed.  And while the USB-serial chips used on some of the clones can be problematic (as much with the Windows drivers as the hardware), you will need to supply similar functionality when breadboarding, which tends to cost as much as or more than MCU itself.

A breadboard and all components needed will often actually cost more as one of the boards from e-bay.
It should also be very easy to find millions of tutorials on how to make your own Arduino.
For the battery part you will need some kind of regulator. And to be honest, this is also one of the basic "electronic engineering" projects of which millions of articles and blogs can be found. Circuitry and everything can be found most regulators' datasheet.

But can I do so with my homemade arduino? - of course. Why on earth wouldn't you?

First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.
You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.

Linear regulators mean wasted battery capacity.  Unless something in the system needs a consistent voltage, one may not be needed.

That never occurred to me but of course! The programmer, FTDI cable in my case, would have to guarantee clean power during programming (or one could regulate its output). But once built & programmed, it could run off of 4.5v from 3 Alkalines until it fails or until it detects the voltage is too low for the clock frequency. Thanks for the idea!

Yes you can power it from a battery, as long as you add a 5V regulator to your board.  You might get strange behaviour when the battery is running low.
These links all tell you what you need to build the board, good luck.
https://www.arduino.cc/en/Main/Standalone
http://www.instructables.com/id/How-to-make-your-own-Arduino-board/
http://www.instructables.com/id/DIY-Arduino-or-The-DIY-Duino/

You won't get strange behavior if brownout detecting is enabled (which it is by default in Arduino's).

I mostly use two AA batteries to power my 'standalone' ATMega328s. One of the downsides of this, is that you can't run the ATMega at 16Mhz, but only at 8Mhz. I don't mind that, as running at a slower speed reduces the current usage.
You could use 3 AA batteries, or 4 rechargeable AA batteries, instead to get a voltage that is closer to 5V
To get your circuit to run for more than a couple of days, you have to implement ways of reducing the current consumption. One of the first things would be to put the processor into sleep mode.

Indeed, one of the few remaining advantages of the ATmega processor is it's relatively wide voltage range.  As long as you don't exceed the maximum when alkaline cells are new, or drop below the minimum for the chosen clock when NiMH or NiCd are nearing time for recharge, running directly off of them is a possibility with this processor not shared to the same degree by many newer alternatives.

You can use 9 Volt batteries to power most Arduino Boards.  For instance the Mega 2560 has a rated Vin range of 7 to 12 Volts.  A car battery can be used for longer life, although not nearly as portable as a 9 Volt one with a clip.  I'd recommend a common 7809 Positive Voltage Regulator TO-220 between a car battery charged using a car alternator and an Arduino board though, because the Voltage may vary quite a bit above the 12 V maximum.
I've used batteries with microprocessors for years for various embedded applications where access to AC is inconvenient, impractical, or nearly impossible.
The Mega page on the Arduino site explicitly permits battery power 1.
Helpful Guidelines
Here are some important criteria to meet.

The Voltage is within the published range for the Arduino model you are using
The positive of the battery supply connected to Vin (NOT any of the other power pins)
The negative of the battery supply is connected to Gnd
Critical applications don't run under the assumption that the battery will never drop below the minimum of the published supply range
The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

Connection Safety Using Plug and Jack
If you are connecting and disconnecting the Arduino from your battery frequently or you just want .
See the Power section of the pageto make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack 2.  When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.
Battery Use in Robotics and Flight Control
A 9V battery will eventually drop in Voltage below the rated minimum, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 3.
Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU.  The Atmel CPU used by the Arduino Mega 2560 4 has a Brown-Out Detection feature 5.
A simpler approach for critical applications is a resistor divider on an analog input is another related approach.
.....
[1] See the Power section of this page https://www.arduino.cc/en/Main/ArduinoBoardMega
[2] Information about compatible plugs is at http://forum.arduino.cc/index.php?topic=4892.0.
[3] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino.  They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel (See https://electronics.stackexchange.com/questions/177204/will-connecting-two-batteries-in-parallel-increase-current-drawn-in-simple-led-c and http://www.zbattery.com/Connecting-Batteries-in-Series-or-Parallel).
[4] http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
[5] The Atmel CPU for the Due and other boards have under-voltage detection too.

You can also use two 18650 batteries as they have a higher charge capacity
Each battery is about 3.7-4.2 V
That would be perfect for arduino....

Could you please edit your post and remove the "shouting" of all capitals? Also, do you mean 2 x 3.7V (7.4V)? For a homemade Arduino which may not have a voltage regulator that would be too high a voltage.

depends, if you are trying to make a big project

meaning like if you want the Arduino to power up all the components connected

I'm  not sure about homemade arduino

ill check and let u know

https://www.google.com.kw/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=2ahUKEwiW_YvDw9PeAhWuyYUKHTouCmMQwqsBMAF6BAgAEAc&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDMb9Gv8ko6g&usg=AOvVaw2qx2un9CudtgOjJ2pRSDq3

check out this one

https://www.youtube.com/watch?v=DMb9Gv8ko6g


text:
Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature
I'm trying to program an Attiny85 chip using an Arduino Uno as an ISP following this two tutorials: Instructables: Program an ATtiny With Arduino and Programming an ATtiny w/ Arduino 1.6 (or 1.0) but every time I try to upload the sketch I get this error message:
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

I have tried different Arduino boards/changing port and different ATtiny chips but the results are all the same. I have also checked the wiring multiple times and it seems to be correct.
This is the full error message (on verbose mode):
     avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM7
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATtiny85
     Chip Erase delay              : 400000 us
     PAGEL                         : P00
     BS2                           : P00
     RESET disposition             : possible i/o
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
       flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          2    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000 (retrying)

     Reading | ################################################## | 100% 0.05s

     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

     avrdude done.  Thank you.

Downvoted because you stopped answering the questions of the person trying to help you, making this question impossible to answer.

Hint: Start by verifying "Arduino Uno as an ISP". This question assumes that the ISP is working correctly.

@MikaelPatel - I have found that if the ISP is set incorrectly then the error isn't the Yikes!, but is instead either Could not find USBtiny device error or avrdude: stk500_recv(): programmer is not responding

Try connecting the RESET pin of the Attiny85 to GND the second before you hit "program".
In my experience, the Arduino does not always send the RESET signal when it should (or on the pin that you think it would send it).
In these cases, manually resetting the Attiny by connecting the RESET pin to ground makes it programmable.
You can keep RESET low during the whole programming process, but if you keep it low for many minutes before programming the chip, it might not always work. In those cases, set RESET high for a moment before setting it back low, and the Attiny should be good for another round of programming.
And of course, when you want the Attiny to start doing what you have programmed it to do, you have to pull RESET high again.

I tried that and got :
avrdude: stk500_recv(): programmer is not responding
any suggestions?

Have you added the capacitor or pull-up resistor to prevent the Arduino from resetting itself when it tries to reset the Attiny?

Yes I have, a 10uf connected between the GND and RES

The only recurring problem that I've had, that has defied my double and triple checking of ... * the connections, * and remembering to upload the "Arduino as ISP" sketch to the Arduino, * and selecting board, * port, and * "ArduinoISP" in the Arduino IDE, ... has been having to do the reset manually. If none of that helps, then I'm sorry to say I'm out of ideas. Remembering to switch the programmer between AVRISP mkII and ArduinoISP at the appropriate time has tricked me a couple of times, though.

@Voly: Are you trying to program the Attiny in circuit? In other words, are there other components connected to the pins of the Attiny, or is it just the Arduino Uno?

@Voly, another question: Have you "burned the bootloader" to the Attiny85? This doesn't actually burn a bootloader, but it sets the fuses. Does this operation succeed, or does it also fail?

This error (in particular the 0x000000) usually, but not always, means that the ATtiny has the fuses set for an external oscillation, but there is no functioning oscillator:
avrdude: Device signature = 0x000000

You probably need to add an external oscillator, i.e. a 16 MHz crystal, and a couple of 22 pF ceramic capacitors:

However, as this Engbedded Atmel AVR® Fuse Calculator shows, there are a number of permutations that could be set:

So, instead of using a crystal, you may need to provide an external clock:

These schematics come from What's the schematic to share one crystal with two micros?


text:
Split Power supply in voltage and gnd?
I am new to electronics and arduino in general. I need to split a power supply in gnd and voltage. Basically, the power supply has one single wire (with the voltage and the gnd passing through it i think), and I need them to be separated. Sorry if this is a noob question, but I am really new to this whole thing.

Voltage is also called "electric potential DIFFERENCE". There is no such thing as "a wire with a voltage of 5V", but always "a 5V voltage with respect to this ground". Carrying away just the 5V wire is meaningless. And you can't carry both Vcc and ground on the same wire. So.. If you have one wire, there are TWO conductors. If they are coaxial (RGx cables), two wires or coated wires (like in cheap headphones), it doesn't matter. But.. You already have two wires. If you are not sure, post a photo and we'll try to figure out what are the two wires

Do you have a image of this? Logically, and as far as I know, One wire will not carry both GND and Positive.
Are you talking of a DC jack kind of thing?
BTW, I'm starting out here too!

It's exactly a DC jack that i needed! Thanks for the quick answer!

If the cable of the power supply contains voltage and gnd, it's two cables, with a layer between them.

On the inside they look much like coaxial cables, so if you softly cut the outer shell(A) you maye see a mesh of blank wires(B,C,D), they're gnd in most cases.
There also is an inner wire(C) which you have to cut softly, too.
That's the voltage carrying wire(D), in most cases. (If it's approx. less than 10 Volts, check with a LED.)


text:
Can't upload sketch to arduino Uno board
I'm trying to upload a simple sketch to my Uno board but get this error message: avrdude: stk500_recv(): programmer is not responding (full error message at the end).
I have other Uno boards who work fine so I guess it is something to do specifically with this board (which used to work) and not my system or cables (port,drivers,settings etc..).
I did a loop-back test (http://forum.arduino.cc/index.php?topic=73748.0) on  the board and it worked fine.
I read about possible solutions but nothing seems to solve this.
https://stackoverflow.com/questions/19765037/arduino-sketch-upload-issue-avrdude-stk500-recv-programmer-is-not-respondi
I also tried using an Arduino as an AVR ISP but it failed. (https://www.arduino.cc/en/Tutorial/ArduinoISP)
Any help will be appreciated, thanks in advance.
Full error message:
    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd3
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd3

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

In Arduino IDE check that

correct port number is selected in Tools -> Port
correct programmer is selected in Tools -> Programmer (should be AVRISP mkII if you upload the code via USB cable)
correct board is selected in Tools -> Board (Arduino/Genuino Uno)

If above doesn't help, install the latest version of Arduino IDE.

Try the different boards in the menu.  I had that with one of my boards and then it worked fine when I used the Due in the IDE instead.  Something to do with one of the chip revisions I think.


text:
COM+ and COM- to RX and TX
I want to connect a Hokuyo scanning range finder to an Arduino Mega, the outputs are labeled like this:

COM+
COM-
Input
Output
DC12/24
GND

I want to read its serial output with Arduino, please help me in details.
Thanks

Have you looked at the hardware documentation of the device you are trying to connect to, normally this will provide details on how to connect and interface with the COM Ports

Failing @Harvey's suggestion, you will at the very least need to specify the exact model of the device you are trying to interface with. But I suspect this will be off-topic here anyway; Super User is concerned with using computers from a user perspective, not programming or hardware design.

There are many protocols involved in COM programming also, so also a very broad question

You should specify what model of Hokuyo scanning range finder you have.  Some models are USB-interfaced, in which case  COM+ and COM- could possibly correspond to USB D+ and D- leads.
The Hokuyo URG-04LX has both USB and RS-232 interfacing.  The linked page shows the following pinout on CN1:
Pin No.   Signals                                Colors
1         N.C.                                   Red
2         N.C.                                   White
3         OUTPUT(Synchronous output)             Black
4         GND(5th pin of 9-pin, D-sub connector) Purple
5         RxD(3rd pin of 9-pin, D-sub connector) Yellow
6         TxD(2nd pin of 9-pin, D-sub connector) Green
7         0V                                     Blue
8         DC5V                                   Brown

Given that pinout, you would connect pin 5, RxD, to a TXD output on the Mega, and pin 6, TxD, to an RXD input on the Mega.  Note, before making any such connection, measure the output voltage on pin 6.  An ordinary Mega supports 0 V and 5 V levels for serial data, but standard RS-232 levels are lower and higher than that; for example, ±12 V.  If you connect  ±12 V RS-232 levels to your Mega, you will damage it.  The several Hokuyo documents I've looked at don't say whether they use traditional RS-232 levels (±12 V) or TTL levels (0-5 V).


text:
Camera switch with ov7670 to output standard A/V signal - composite
I've got 3 OV7670 cameras and would like to create a switch that outputs one of the cameras video as standard A/V out (I'm not sure the correct naming).
I found docs explaining how to use the cameras on the Arduino platform but I'm not sure how to output video signal - composite.

I think you mean composite video

Three cameras driven by 1 puny Arduino? Video is what you get when you read frames from the camera very quickly (at least 10 frames per second reasonably) and render those frames very quickly on some screen. You can't do either with an Arduino (Uno?) effectively, even if you'll be switching between them. Take a look at this though: https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno

Thanks for comments, I've updated post and now looking at the link.

An arduino uno is way too slow to output composite video. If you want to generate a PAL video signal you can see here the signal specification.
Most important, one line is output in 52us. If the line is 720px long (720x576 is the common resolution), then you will have to generate one pixel in 72ns. This means that

you will need a very fast DAC (a flash one)
you will need a VERY fast microcontroller. If you have a 160MHz uC you will have to send one output byte every 11 clock cycles, which means that you will barely be able to do any more processing.

Result: it is practically unfeasable. I suggest you, if you want to use it, to look for hardware encoders. But... Probably you will need some faster processing units: maybe a raspberry PI, which already have an hardware encoder...


text:
Moisture sensor data will not output data to Serial Monitor?
I am making a Soil Analysis system with an Arduino Uno, but I have run into a problem and was wondering if /r/learnprogramming could help!
The moisture sensor section of my code will not output the data to the Serial Monitor in Arduino 1.7.1 IDE. I am not sure why it's not working. Running the moisture sensor code by itself works, and I just copied and pasted that code into my combined code file since I'll I am running 4 sensors at once with my Arduino Uno.
These are the four values I need to output data on one baud rate:

pH value
EC
DHT temperature reading
Moisture Sensor Value
I am currently missing Moisture Sensor Value when I run Combined1.ino

Here is the Combined1.ino code of the code from four sensors together that's uploaded to the Arduino:
Combined Code Link
Moisture Sensor Link
Any help would be much appreciated!

/r/learnprogramming? Are we Reddit now?

Your second print section will always fail.
You have:
if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator

However, a bit before then you have:
if(millis()-printTime>=printInterval)
{
  printTime=millis();

So millis() - printTime can never be greater than printInterval since you have just set printTime to millis(). So millis() - printTime will always be somewhere between 0 and printInterval - 1.
Consider combining your different printing routines into one single printing routine so you are comparing (and changing) the printTime only once.

I got it to work. There is something happening with the DHT22 section that when the DHT22 is not connected, it fails and ends the loop. I just moved my moisture sensor code above that and it is now working. I will see if I can clean it up using this advice.