text:
GET the first result in HTTP request
I have a String content="" and if I put an HTTP request like this:
client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();

the output I get is:
 [{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"},{"action_id":41,"action_type":"up","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:14","updated_at":"2015-08-16 20:50:14"},{"action_id":42,"action_type":"down","parking_id":39,"user_id":17,"ramp":"entry","created_at":"2015-08-16 20:50:21","updated_at":"2015-08-16 20:50:21"},{"action_id":43,"action_type":"down","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-08-16 20:50:22","updated_at":"2015-08-16 20:50:22"}]

The little parser I created is this:
while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

Is it possible to store only the first action in JSON output, because the actions are updated, and if the number of chars extends 256 than I get errors while working with the String content?

if (c == ',') {       break;      } (i.e. break on the first comma, instead of the first closing bracket)

Your question is not clear to me. First of all does your parser get the whole response? And second by first action do you mean "action_id":35"?
If both are true then your solution is simple.
First you separate every comma ", " and put in a string array then you further split each index by ":" so the first part is the name "action_id" and the second is the value "35". I hope that helps . You can look up the split function, it's easy.
But if the above is not what you needed then I am afraid you cannot get only the first response, because that has to do with the server itself.
Here is a solution, do try it.
I found an easier solution. Follow the example and replace the content and fields with your response content and you will be done in minutes.

Yes, the parser gets the whole response. I need only the first one stored in String content which in this example is :
[{"action_id":35,"action_type":"up","parking_id":39,"user_id":17,"ramp":"exit","created_at":"2015-07-10 18:02:40","updated_at":"2015-07-10 18:02:40"}

Darkclaude X, please edit your answer and adjust the unconventional, hard-to-read capitalization.  Capitalize the first word of each sentence; capitalize proper nouns and the pronoun I; don't capitalize other words.  Also, please spellcheck  “Seperate”.

thx Jwpat, FunKction check the library above

Your question is not clear to me. Getting clarification on questions belongs in the comments, not in an answer. Please adjust your answer and comment accordingly.

Unfortunately i cant comment on his Post i need 50 points


text:
Unexpected behaviour of blinking LED code
I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :
 void setup(){
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
}

void loop(){
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}

The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly.
int LEDpin = 13;
void setup(){
pinMode(LEDpin, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 8;
  }
}

Also, when I just typed the if statement without the else part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the else part?

The problem with your code is that:
you have not initialised all the LED pins as output. Only pin 13 is initialised as output.
So, initialise all the pins to output. A correct code would look like this:
int LEDpin = 13;
void setup(){
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 12;
  }
}

LEDpin needs to be assigned to 12 in both the initial declaration and in the else statement (and not 13 and 8 respectively). Otherwise, the first loop will try to write to pin 13 which is not initialised as an OUTPUT in setup(), and finally will only write to pin 8, instead of continuing to cycle from 12 to 8...

I see that you have (correctly) edited your answer for the else statement, however, the initial declaration of LEDpin is still set to 13, when it should be 12. So, the first line should be int LEDpin = 12; What will happen the first time the loop() is executed?

As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.
Let's say you have led's connected from pin 2 to 8.
int pin = 2;
void setup()
{
   for (Pin = 2; Pin < 8; Pin++)
   {
     pinMode(Pin, OUTPUT);
   }
}
void loop()
{
   for (int Pin = 2; Pin < 8; Pin++)
   {
     digitalWrite(Pin, HIGH);
     delay(1000);
     digitalWrite(Pin, LOW);
     delay(1000);
    }
}

As Abhishek Jain explained, the pin's need to be initialised for OUTPUT.
However there is another error.
The code in loop() counts down to 8, once, flashing the LEDs, but then only lights an LED on pin 8 because it always goes through the else which maintains LEDpin's value as 8. LEDpin needs to be reset to 12, after it passes 8.
Better code might be
int LEDpin = 12;
void setup(){
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
}

void loop(){
  digitalWrite(LEDpin, HIGH);
  delay(1000);
  digitalWrite(LEDpin,LOW);
  delay(1000);
  if(LEDpin >= 8){
    LEDpin--;
  } else {
    LEDpin = 12;   // <---- start with the first LED again
  }
}

For what its worth, I wouldn't do the code this way. I would write something using for loops, like:
const int firstLED = 8;
const int lastLED = 12;
int LEDpin;

void setup() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
     pinMode(LEDpin, OUTPUT);
  }
}

void loop() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
    digitalWrite(LEDpin, HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    delay(1000);
  }
}

Initializing all the pins to OUTPUT solved my problem. Thank you!

@ayerhs7 - Initializing all the pins to OUTPUT is necessary, but not sufficient. If you want all of the LEDs to blink repeatedy, and not just once when the Arduino is reset, LEDpin must be reset to 13, which is missing from the answer that you have accepted. IMHO, for clarity, you should either update your answer to reflect the fact that you only need the LED on pin 8 to blink, or comment that the answer you have accepted does not solve the problem, or maybe explain why you accepted it.

source: Stack Exchange

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

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

sort: votes


text:
How do nested for loops work?
In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true?
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

A for statement repeats everything between { and }, (or just the next line if there is no { and } a certain number of times.  It's not as simple as you might at first think, but it makes more sense if you write it out as a while loop explicitly.
For instance, for (a; b; c) { ... } could be re-written as:
a;
while (b) {
    c;
}

So if you had:
for (int i = 0; i < 100; i++) {
    Serial.println(i);
}

it could be re-written as:
int i = 0;
while (i < 100) {
    Serial.println(i);
    i++;
}

The two mean exactly the same thing.  A for has the three elements - initializer, comparison and iterator.  The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.
To re-write your specific example:
for(int r = 0; r < 8; r++){
    for(int c = 0; c < 8; c++){
        lc.setLed(0, r, c, HIGH);
    }
}

You would end up with:
int r = 0;
while (r < 8) {
    int c = 0;
    while (c < 8) {
        lc.setLed(0, r, c, HIGH);
        c++;
    }
    r++;
}

Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like?  Well, let's start with the inner c loop.  That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing c each time would end up with:
int r = 0;
while (r < 8) {
    lc.setLed(0, r, 0, HIGH);
    lc.setLed(0, r, 1, HIGH);
    lc.setLed(0, r, 2, HIGH);
    lc.setLed(0, r, 3, HIGH);
    lc.setLed(0, r, 4, HIGH);
    lc.setLed(0, r, 5, HIGH);
    lc.setLed(0, r, 6, HIGH);
    lc.setLed(0, r, 7, HIGH);
    r++;
}

We could take it a step further and unroll the outer r loop.  A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):
lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);

There would, of course, be 8 × 8 = 64 entries in there.
for loops can be used in lots of other fun ways too.  It's not just a simple "run this X number of times".  For instance, you can loop through a C string until you reach the NULL character at the end of the string:
for (char *p = str; *p != 0; p++) {
    ... do something with *p
}

You can iterate through the entries in a linked list:
for (struct mylist *scan = myListHead; scan; scan = scan->next) {
    ... do something to scan->whatever ...
}

You can even embed functions in there:
for (char c = 0; c != '\n'; c = Serial.read()) {
    ... Do something with character `c` until `c` is a line feed ...
}

As you can see for is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit while.

This was incredibly useful. Expressing it in terms of while made it easier to understand. Thank you.

Mr. Majenko, I'm a teacher trying to teach junior high kids programming using Arduino. I can do the basic "if," "else," etc. The kids wanted to learn how to program a game, I'm using this code http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/ I've tried to figure out the code with great success but I still have a few questions. Where is good place to ask them? Your answer was very useful but I often feel intimidated asking questions in this "forum." Thank you for your time.

@GabeRuiz Don't be intimidated.  We're here to help. It's only when people ask "Tell me how to do this project" and things like that we get a bit shirty with them. Questions like yours, along the lines of "How does this work" or "I don't understand this bit, can you explain it" are bread and butter for this site.  Feel free to ask away.

The preferable approach is to make an attempt on your own, and if it doesn't quite do what you want, post your code, describe what happened, and compare it to what your expectations were. Or if it does work, you might ask if there is a better way of doing it.

What you have there is a nested loop. The first for statement runs 8 times, incrementing r from 0 to 7. For each of those 8 iterations the second for statement runs, incrementing c from 0 to 7. Thus the setLed statement is executed 64 times.

Will it continue to run till both statements are true?

Yes. Unless you have a break or return statement somewhere in the part of the code you haven't shown.
Strictly-speaking, a statement does not become true. They will run while the test inside the for remains true (both tests).
This is standard C++ or C programming. You may wish to consult a C tutorial if you find this sort of thing puzzling.

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


text:
Arduino coding of producing frequency
Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

Sound a lot like an IR carrier wave.

The code below generates 38 kHz and modulates its duty cycle.
// Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
// Author: Nick Gammon
// Date: 24 September 2012

const byte POTENTIOMETER = A0;
const byte LED = 10;  // Timer 1 "B" output: OC1B

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()
 {
  pinMode (LED, OUTPUT);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  }  // end of setup

void loop()
  {
  // alter Timer 1 duty cycle in accordance with pot reading
  OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

  // do other stuff here
  }

Just to add; this code works for pin 10, and pin 10 alone.

I connected the output to the ultrasonic transmitter but its not working. here is the transmitter specification that i used (http://www.farnell.com/datasheets/1498178.pdf) and the circuit diagram (https://www.google.com.ph/search?q=ultrasonic+circuit&espv=2&biw=1366&bih=643&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjoivap6-fJAhUK-2MKHdFeAFwQ_AUIBigB#tbm=isch&q=ultrasonic+transmitter+circuit+diagram&imgrc=fLTfT6_BQfBMyM%3A)

Not working? How do you know? Are you getting 38 kHz out of the Arduino or not? You would need an oscilloscope to check.

use the 'tone' function:
arduino tone function
example:
//tone(pinNumber, FrequencyInHertz);
tone(6, 35000); //generate a 35kHz tone on pin 6
delay(10);
tone(6, 43000); //generate a 43kHz tone on pin 6

Could you elaborate a bit? This is basically a link-only answer which would not be helpful if the link went down.

I wanted to generate a set of high frequency at the range of 25k-60k Hz using the arduino uno. Please help me. What function do i use? I'm a newbie on coding and if anyone would share some code it would be a great help. Im very thankful.

@user13535 You now say 25k-60kHz, but your question says 38k-43kHz. Which is it?

The 25k-60k Hz. I change the range.

This is meant to be a comment, but I can't put (pseudo) code in a comment.
A 40 kHz square wave? Simple:
for(;;){
   wait ( 1 / 2 * 40.000 );
   make pin high;
   wait ( 1 / 2 * 40.000 );
   make pin low;
}


text:
Basic Serial Transmission Protocol
I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a startbit to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if startbit is being received. If startbit is not being received, then it prints out whatever was transmitted. If startbit is received, then it doesn't print the startbit, just the nibble all in one line.
My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?
#include <Arduino.h>
#include <WirelessComm.h>

int tx_pin;
int rx_pin;
WirelessComm::WirelessComm(int rxPin, int txPin)
{
    pinMode(rxPin, INPUT);
    tx_pin = txPin;
    rx_pin = rxPin;
}

int countDigit(long n)
{
    int count = 0;
    while (n > 0)
    {
        n /= 10;
        count++;
    }
    return count;
}

void getDigit(bool *data, long num)
{
    int cd = countDigit(num);
    long shift = 1;
    for (int i = 0; i < cd; i++)
    {
        data[i] = (num / shift) % 10;
        shift *= 10;
    }
}

int WirelessComm::writeTx(long nibble)
{
    int i;
    bool data[11]; // warning: I didn't check for buffer overrun!
    int32_t startBit = 110101L; // larger than 32767, so cannot be in int
    if(nibble != 0)
    {
        int sbLen = countDigit(startBit);
        for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
            data[i] = 0;
        getDigit(data, startBit);
        getDigit(data + sbLen, nibble);
    }
    else
        return -1;

    for(i = 0; i < 10; i++)
    {
        if(data[i] == 1)
        {
            digitalWrite(tx_pin, HIGH);
        }
        else
        {
            digitalWrite(tx_pin, LOW);
        }

    }
    return 1;
}

int WirelessComm::readRx(long nibble)
{
    bool first = 0;
    bool second = 2; //initially set to some random value
    bool third = 2;
    bool fourth = 2;
    bool fifth = 2;
    bool sixth = 2;
    bool counter = 0;
    bool val = 0;
    while(true)
    {
        first = digitalRead(rx_pin);
        if(first == 1);
        {
            second = digitalRead(rx_pin);
            if(second == 1)
            {
                third = digitalRead(rx_pin);
                if(third == 0)
                {
                    fourth = digitalRead(rx_pin);
                    if(fourth == 1)
                    {
                        fifth = digitalRead(rx_pin);
                        if(fifth == 0)
                        {
                            sixth = digitalRead(rx_pin);
                            if(sixth == 1)
                            {
                                while(counter < 4)
                                {
                                    val = digitalRead(rx_pin);
                                    Serial.print(val);
                                    counter++;
                                }
                                Serial.println();

                            }
                            else
                                Serial.println(first);
                                first = digitalRead(rx_pin);
                        }
                        else
                            Serial.println(first);
                            first = digitalRead(rx_pin);
                    }
                    else
                        Serial.println(first);
                        first = digitalRead(rx_pin);
                }
                else
                    Serial.println(first);
                    first = digitalRead(rx_pin);
            }
            else
                Serial.println(first);
                first = digitalRead(rx_pin);
        }
        else
            Serial.println(first);
            first = digitalRead(rx_pin);
    }
}

"Hope to run on Arduino" — so it doesn't actually run? In another version of this question on Code Review (now deleted), a concern was raised over the correctness of if(third = 0).

Does this code actually work with whatever device you want to talk to? This is not the way to perform serial IO.

@user5402 The write function is ok, and it works. However, this is my attempt at serial communication. Can you please tell me what things I am doing wrong so I can perform a more correct serial IO.

Does your readRx function work?

Not exactly the way I want it to. Some of the bits are lost. I think it's because of the interval time of the data. I'm guessing it would actually pick up the signal correctly if the clock was right. However, I am not doing synchronous communication. Just asynchronous. THerefore, I am sending a clock signal.

I don't see a clock signal in your code.

Sorry, typo. I meant, therefore, I am NOT sending a clock signal. (since it's asynchronous).

[codereview.se] has a policy that the code in questions must be working correctly to be on-topic. However, [arduino.se] doesn't have that strict requirement, so I am migrating the question.

if(fourth = 1) - that, and all your similar tests, are wrong. That is assigning and then testing. So the if will always be true in this case.

If you want to bit-bang, I suggest you look at how SoftwareSerial does it.

Hey @NickGammon that if statement was a typo. And I initially used SoftwareSerial to do all my hardware tests. However, I'm trying to make my own library without the extra fluff. I had a very very hard time trying to understand what is happening in SoftwareSerial's code.

So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

What you are doing is called "bit-banging" (wikipedia link) but you have no guarantees about the timing of your bits.
In your writeTx routine you are changing tx_pin at some rate which depends on:

the clock speed of your MCU
the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.
The same applies to your read routine.
The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware
is very versatile and capable of a lot of different functions.
In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.
This article can give you an idea of what the USART in an Atmel processor is capable of:
http://maxembedded.com/2013/09/the-usart-of-the-avr/

But the thing is, I don't want to do synchronous communication. I actually want to do asynchronous and then implement different ways of synchronizing the clock such as NRZ.

Also, i was told that if i know the interval of data, i can implement that and not worry about the clock signal. How should I approach that? What exactly does the interval of data* mean?

You still want hardware to do this for you. "knowing the interval of data" just means that you have set a specific baud rate - i.e. so many bits per second. The USART can handle asynchronous comms, and it can monitor the receive pin and respond to changes a lot faster than you can in code.

OO! i see what you are saying. ok ok. And so, should I just restart the code I'm trying to make? I've tried to create a buadrate function before, but I had very bad luck with it. One big problem was, when i tested how many times my receiver transmitter a bit in 1 second, it was 1000. So it wouldn't really be any use if I set the baud rate to be 1200 or something. Cause if the maximum it sent (since the pin was on high for the whole second) was 1000 transmissions, that's max hardware capability. right?

What you do is start learning how to program the USART of the AVR. Using the USART you can reliably handle 1Mbit per second. The article I mention in the answer is a good start. Start with getting standard RS-232 working. Get two Arduinos talking to each other over RS-232. The USART has a lot of registers you can configure - it takes a while to fully understand what can be done with it. And an upvote would be nice if you've found any of what I've said to be helpful.

Thank you very much! I have upvoted it. As soon as I reach 15 rep points, you will see the change! thank you so much!

Cause if the maximum it sent (since the pin was on high for the whole second) was 1000 transmissions, that's max hardware capability. right?  - if you read the datasheet, you will see that at 16 MHz clock the maximum baud rate is 2 Mbps. That's a lot more than your 1000 bits per second.

So to clarify, SoftwareSerial uses bit-bang? How are you able to tell?

By reading the code. For example, this is how it reads 8 bits. It does a delay (which you don't) for the exact amount of time, and then reads the pin, and "ors" it into the variable which is the assembled byte.
// Read each of the 8 bits
for (uint8_t i=0x1; i; i <<= 1)
{
  tunedDelay(_rx_delay_intrabit);
  DebugPulse(_DEBUG_PIN2, 1);
  uint8_t noti = ~i;
  if (rx_pin_read())
    d |= i;
  else // else clause added to ensure function timing is ~balanced
    d &= noti;
}

And to write the 8 bits:
// Write each of the 8 bits
for (byte mask = 0x01; mask; mask <<= 1)
{
  if (b & mask) // choose bit
    tx_pin_write(HIGH); // send 1
  else
    tx_pin_write(LOW); // send 0

  tunedDelay(_tx_delay);
}

Your rather elaborate nested if just seems complete overkill, when you see how SoftwareSerial does it in half a dozen lines.

Another typo:
if(first == 1);

You don't want that semicolon.

Second, is there a way to make my code more efficient?

Use loops, like SoftwareSerial does.

Also, is my code legible or very convoluted?

Very convoluted.

Where can I clean it up?

I suggest you browse through the SoftwareSerial library for ideas.
Meanwhile, HardwareSerial is available, so you don't need to write any of this. For that matter, SoftwareSerial is available too. If you are just doing it to learn, well and good.

You really should read about loops. Whenever I have to do something 8 times I have a loop of 8 (or even for "x" times, a loop of "x"). Unrolling into 8 different variables is just confusing and prone to errors. As you had, before you fixed it, doing if(fourth = 1) instead of if(fourth == 1).

Thank you very much for that explanation. I will do what you suggested as well.

Hey, the actual software serial library, frmo the installation files looks much different from the snippets you posted. Can you please show me where you are pulling your code from? Thank you so much!

I got that from IDE 1.0.6. It looks like they changed it a bit in 1.6.5, however conceptually it is similar. The changes look like efficiency tweaks to me. Fundamentally it is the same. They are reading/writing bits with a carefully calculated delay between each one.


text:
Arduino Pro Micro Analog Pinouts
I have the Arduino Pro Micro and I would like to use all the analog pins that I can on it.
It currently looks like it has a total of 9 Analog pins that can be used.

A0, A1, A2, A3, A6, A7, A8, A9 and A10.
However, I am unsure how to call these pins since all of those are also digital pins.
Would A0-A3 be defined as:
#define analog1 A0;
#define analog2 A1;
#define analog3 A2;
#define analog4 A3;

While the other pins would be this?:
#define analog5 4;
#define analog6 6;
#define analog7 8;
#define analog8 9;
#define analog9 10;

Then just call:
analogRead(analog1);
analogRead(analog2);
.....
analogRead(analog8);
analogRead(analog10);

Would that be the correct way of defining the 9 analog pins?

Assuming you have the Pro Micro core, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.

So you're saying its = A0, = A1, = A2, etc... or are you saying its just = 0, = 1, = 2, etc?

Analog pins in the Arduino libraries are prefixed with "A".


text:
How to fix baud rate when hardware capacity has a low limit?
I have a transmitter(simple 433 MHz transmitter) connected via digital pins on the Arduino. The receiver is connected to another arduino.
Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones.
But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc.
So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.
I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two.
So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec?
Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.

Yes, please clarify. I have no idea what you're asking.

I made an edit.

Perhaps it would help if you mentioned what sort of "transmitter" you're talking about.

I suspect this is related to the OP's other post about serial transmission. it can only transmit 1000 ones - how do you get that? If it is high for a second, you could argue it has transmitted a billion ones. So when you specify a baud rate of 1200, is it useless? - no. You might want to read my post about how serial works.

Hey Gammon, I'm looking at your forum rn. Thank you! I'll really look into this.

I have a transmitter(simple 433 MHz transmitter) - please specify the model of the transmitter (part number). Also are you transmitting to another Arduino, or some other device which has a known protocol?

The transmitter you're using is very basic, and only transmits "on" and "off". As such it is protocol-agnostic. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.
One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.
The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via Serial on non-USB-native Arduinos as well as Serial1, Serial2, and Serial3 on Arduinos where they are present.
Additionally, SoftwareSerial can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.

Hello Gammon, I'm looking into all the things you just talked about. I also have a request. I don't have enough rep points to do so, but I would like to create a new tag called Voice Over IP (VOIP). It's a very common topic in the wireless communication world, and stackoverflow doesn't have that tag yet. So may you please create it? Thank you!


text:
How do you make the arduino go forward,backward and stop using Infrared?
Please give me a code and diagram use makeblock i.r sensor V2.1 and makeblock remote. It should be connected to a d.c motor that works with a h-bridge.It also has to be a dual motor which combines these two codes:
1:This one for the movement
const int controlPin1 = 2; // connected to pin 7 on the H-bridge
const int controlPin2 = 3; // connected to pin 2 on the H-bridge
const int enablePin = 9; // connected to pin 1 on the H-bridge
const int directionSwitchPin = 4; // connected to the switch for direction
const int onOffSwitchStateSwitchPin = 5; // connected to the switch for turning the motor on and off
const int potPin = A0; // connected to the potentiometer's output

// create some variables to hold values from your inputs
int onOffSwitchState = 0; // current state of the On/Off switch
int previousOnOffSwitchState = 0; // previous position of the on/off switch
int directionSwitchState = 0; // current state of the direction switch
int previousDirectionSwitchState = 0; // previous state of the direction switch

int motorEnabled = 0; // Turns the motor on/off
int motorSpeed = 0; // speed of the motor
int motorDirection = 1; // current direction of the motor

void setup()
{
    // intialize the inputs and outputs
    pinMode(directionSwitchPin, INPUT);
    pinMode(onOffSwitchStateSwitchPin, INPUT);
    pinMode(controlPin1, OUTPUT);
    pinMode(controlPin2, OUTPUT);
    pinMode(enablePin, OUTPUT);

    // pull the enable pin LOW to start
    digitalWrite(enablePin, LOW);
}

void loop()
{
    // read the value of the on/off switch
    onOffSwitchState = digitalRead(onOffSwitchStateSwitchPin);
    delay(1);

    // read the value of the direction switch
    directionSwitchState = digitalRead(directionSwitchPin);

    // read the value of the pot and divide by 4 to get
    // a value that can be used for PWM
    motorSpeed = analogRead(potPin) / 4;

    // if the on/off button changed state since the last loop()
    if (onOffSwitchState != previousOnOffSwitchState)
    {
        // change the value of motorEnabled if pressed
        if (onOffSwitchState == HIGH)
        {
            motorEnabled = !motorEnabled;
        }
    }

    // if the direction button changed state since the last loop()
    if (directionSwitchState != previousDirectionSwitchState)
    {
        // change the value of motorDirection if pressed
        if (directionSwitchState == HIGH)
        {
            motorDirection = !motorDirection;
        }
    }

    // change the direction the motor spins by talking
    // to the control pins on the H-Bridge
    if (motorDirection == 1)
    {
        digitalWrite(controlPin1, HIGH);
        digitalWrite(controlPin2, LOW);
    }
    else
    {
        digitalWrite(controlPin1, LOW);
        digitalWrite(controlPin2, HIGH);
    }

    // if the motor is supposed to be on
    if (motorEnabled == 1)
    {
        // PWM the enable pin to vary the speed
        analogWrite(enablePin, motorSpeed);
    }
    else
    { // if the motor is not supposed to be on
        //turn the motor off
        analogWrite(enablePin, 0);
    }
    // save the current On/Offswitch state as the previous
    previousDirectionSwitchState = directionSwitchState;
    // save the current switch state as the previous
    previousOnOffSwitchState = onOffSwitchState;
}

2: This one for the IR:
#include "IRremote.h"  //-----( Import needed libraries )-----
int receiver = 11; // ----- DAT pin of IR receiver to Arduino digital pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);           // create instance of 'irrecv'
decode_results results;            // create instance of 'decode_results'

void setup()    /*----( SETUP: RUNS ONCE )----*/
{
    Serial.begin(9600);  // Begin serial communication
    Serial.println("IR Receiver Raw Data + Button Decode Test");
    irrecv.enableIRIn(); // Start the receiver
}               /*--(end setup )---*/

void loop()     /*----( LOOP: RUNS CONSTANTLY )----*/
{
    if (irrecv.decode(&results)) // have we received an IR signal?
    {
        //    Serial.println(results.value);  // Uncomment to print raw decimal values
        translateIR(); // run function "translateIR"
        irrecv.resume(); // receive the next value
    }
}               /* --(end main loop )-- */

/*-----( Declare User-written Functions )-----*/
void translateIR()  // translate Makeblock remote raw values to keys
{
    switch (results.value)
    {
        case 4219133059:      Serial.println(" A ");     break;
        case 667718909:       Serial.println(" B ");     break;
        case 3478241646:      Serial.println(" C ");     break;
        case 1322193145:      Serial.println(" D ");     break;
        case 3689098103:      Serial.println(" ^ ");     break;
        // case 3478241646:      Serial.println(" E ");     break;
        case 1776008254:      Serial.println(" < ");     break;
        case 1803700378:      Serial.println(" * ");     break;
        case 3495019267:      Serial.println(" > ");     break;
        case 1943112141:      Serial.println(" 0 ");     break;

        case 3444686410:      Serial.println(" v ");     break;
        case 2806989789:      Serial.println(" F ");     break;
        case 3689098101:      Serial.println(" 1 ");     break;
        // case 3689098103:      Serial.println(" 2 ");     break;
        case 1943112142:      Serial.println(" 3 ");     break;
        case 3689098102:      Serial.println(" 4 ");     break;
        // case 3689098102:      Serial.println(" 5 ");     break;
        case 2181502997:      Serial.println(" 6 ");     break;
        case 650941290:       Serial.println(" 7 ");     break;
        case 402038415:       Serial.println(" 8 ");     break;
        case 945450753:       Serial.println(" 9 ");     break;
        default:     Serial.println(" other button   ");
    }

    delay(250);
} //END translateIR

Please provide a bit more information on what you're using, and what research you've done so far.

You should be able to search on Google and get a library to interface with the sensor.  Then you will need some motors, a motor controller, and a library to control that.  Then you will need to stick it all together using your code.
What you need to do is:

Search for your IR library and a tutorial.
Search for a Stepper motor tutorial and library.
Then post a question when you are stuck with that.

You need a good IR Library, or tons of low-level knowledge.
Ken Shirriff wrote the best IR library out there! Here it is.
Adafruit writes awesome tutorials too. Here's one.


text:
Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2
I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode.
So I created a setup code like this:
void setup() {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL); // use AREF for reference voltage
}

I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:
LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope

But when I change the board to Arduino Uno in Tools option, the program in compiling fine.
This means that Intel Galileo Gen 2 does not support external analog voltage reference?

There is no such thing as an external analog reference on the Galileo.  If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:

So no, it won't support the EXTERNAL analog reference function.


text:
Detect closed shutter
I want to controll some ambient lights in my living room.
Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.
The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.
Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.
A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.
Edit:
What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...

Is there some cord or something you could attach a magnet to, which you could detect, being in the closed position?

Not without getting ugly =(

What is this mythical shutter? How does it operate? What is it made of? Does it slide like a blind, or close like a door? Roll? Solid? Made of pressed geranium leaves? Please, we need some actual information.

It's a roller shutter. It rolls up in a box inside the wall, above the window. Aside the window there is a cord which i pull to let the shutter down.

I'd use a magnet in place of the tinfoil and a (latching) hall-effect-sensor/reed-switch instead of the photo-reflector you were planning to use.

Nice idea. I could simply drill a little hole in the lowest shutter-bar and glue in an magnet. Simple. But these sensors are surprisingly expensive, what are they made of, pure gold? I mean, IR sensors cost about 10-20% of that price o.O

Maybe you're looking for the wrong things.  Think household security - reed switch / magnet pairs for doors. Very cheap.

To avoid doing anything to the shutter itself you could use an ultrasonic sensor. These also have a benefit of working over a longer range than door/window magnet-and-reed-switch setups, thus the shutter doesn't need to close all the way to activate the lights. You can set the threshold in code.

I have a cat which walks on the windows sill now and then. Ultrasonic is usually a good idea, but doesn't fit the situation.

I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1).  There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm.
(If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)


text:
Any chance of repairing Mega 2560?
So I decided it would be a good idea to flash a firmware onto my mega 2560 for a project. I ended up flashing the wrong side of the ICSP header (one near the usb plug/ M16U2) and killed my arduino for the most part. I'm a newb for the most part when it comes to this. I plug it in and the 'L' light is on with the 'ON' light as well. Wont show up in device manager, can't load sketches and can't get into DFU mode.(REV3 has DFU right?)
I have both a usbasp and USBtinyisp programmer and have tried 5 - 10 firmwares on both sides of the headers in hopes I can get it to work again.Literally almost tried everything I could find to get it to flash back. One guide I did find that got me somewhere was this though:
http://forum.arduino.cc/index.php?topic=96706.0
It appears to flash correctly with whatever firmware I use, but cannot pull the firmware off it to check or do the rest of what it says.My guess is that 1 or 2 of the firmware's are gone. Have erased the firmware/relfashed and tried to flash in the IDE with no luck in it working.
I did use this command to read the firmware(or lack of) on both sides of the header to get a better idea of what might be going on:
M16U2/M2560
I don't know if I'm supposed to flash one side first then the other or flashing one will be able to do both at the same time. Here is an example of how I would flash from avrdude:
avrdude -C avrdude.conf -P usb -p m16u2 -b 1200 -c usbasp flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

With each side I would set the correct the fuses from what that file pulled up. So if anyone knows what I'm doing wrong for why it is not working I'd appreciate the help. Just don't know if I can save this or it's gonna end up in the garbage.Thanks

this https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex is the one you'd need for the 16u2. For the 2560 you'd need https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex . First do the 16u2. After that you should see something in the device manager.

I tried it but didn't have any luck getting to work once plugging it back in to the laptop. Maybe i'm doing the wrong lock fuse or something. To me though it looks like it is flashing.  http://pastebin.ca/3178364

I got a board with the symptoms you described. I ended up removing the 16u2 as I found out it was faulty, the board works now (without any USB of course) so if you can make sure the mega2560 chip works and the 16u2 doesn't and you are not bothered by the lack of USB connection then you can do the same.

I think i could possibly live without it but i just can't seem to get a firmware to  stay on either one of them. Starting to wonder if there are certain steps to flashing that i'm missing besides what i have been doing.(erasing/unlocking/flashing/locking of the firmware) When i look over everything, it seems like it should all be good. Gonna keep trying and see if i can get a firmware to stick.

This looks interesting even though it's to repair a Mega ADK:   http://altlab.org/d/m/jpralves/recover_atmega2560/  Maybe i do have to unlock/flash/lock the firmwares to keep them in. Will see how it goes.

It looks like it's back to working :) I flashed both side's with the firmware 'Gerben' mentioned using the guide in the link above.(* Setup Fuses unlocking bootloader * Burn the bootloader * Setup Fuses locking bootloader) From what it looks like it was because i didn't unlock/lock in the firmwares correctly and or the right firmware. For whatever reason i'm on COM4 instead of COM3 now but i can upload sketches and seems to have no issues. Hopefully someone else will be able to use this if they end up messing up there firmware to fix it. Appreciate all the help.

http://altlab.org/d/m/jpralves/recover_atmega2560/
Change fuses/firmware depending on which side you are flashing (M2560/M16U2)
Firmwares: Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex / stk500boot_v2_mega2560.hex
1st command:
avrdude -C avrdude.conf -P usb -p m16U2 -b 57600 -c usbtiny -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m

2nd command:
avrdude -c usbtiny -p m16U2 -P usb -b 115200 -V -U flash:w:Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex

3rd command:
avrdude -c usbtiny -p m16U2 -P usb -b 115200 -U lock:w:0x0F:m

http://pastebin.ca/3178420


text:
arduino project for c programming language
i am a student from 2nd semester BCA (Bachelor in Computer Application). My group need some project for presentation from c programming language so i thought of using #ARDUINO project for our presentation . i really don't have any idea in this project so any ideas, answer, guides will be helpful to us.

Great idea - choose something you know nothing about and then beg others for help.  At least start with having a clue what you want to achieve, then we may be able to help you achieve it. Until then you're on your own.

I must say. Kind of a silly question. It indicates you've done virtually no reasearch on your own. Kind of like saying, I have a pencil and paper. I need some guidance as to what types of marks I can make on the paper with the pencil. :) Here's something that may give you some insight: see the latter 3 links that I posted in my answer here: http://arduino.stackexchange.com/questions/16413/how-to-change-variable-when-a-button-connected-to-pin-2-is-pressed.

Good luck with this! Arduino is awesome. I really enjoy using it. You may find this at least a little insightful: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html.
Arduino is a small computer. It can do essentially whatever you want it to do: drive robots, fly airplanes, control motors, turn on or off TVs, get on the internet, make a home alarm, buzz a speaker, make a touch lamp, fade LEDs, play music (even with no music chip; just using a skillfully-written library), control HollyWood action cameras, talk to your smartphone, read your heartbeat, make a bike speedometer or odometer, read a GPS receiver, etc. Cool stuff!

I am not going to list example-projects as the possibilities with an arduino are endless. If you are looking for inspiration: take a look at websites like www.instructables.com and www.hackaday.io. Those are websites with mostly starter arduino projects that contain step-by-step guides on how they are created. I would suggest that you browse through those projects and look for something that peaks your interest and then think of your own similar project. You should however think of a project with a certain complexity as it is for your bachelor's. Most projects on instrucables lack the challenge. For getting parts: take a look at ebay. Ebay has some webshops that sell arduino's and arduino extension modules really cheap.
Good luck

Instructables is the worst site. Please rethink your answer.

I do agree with you that instructables is not a website for someone looking for a project with a challenge of some sort. Instructables contains examples of easy to follow and replicatable projects. It also has tutorials like "how to upload blink to an arduino" or "How to install the arduino IDE and the UNO drivers". And those tutorials come with step by step instructions and pictures. That's exactly what a total beginner needs. So I stand with by my answer. Your comment however is short and lacks any form of explanation. Maybe you are the one that has some rethinking to do.


text:
how to change variable when a button connected to pin 2 is pressed
Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.
Those 3 are key.
Also, I wrote a buttonReader (debouncing) library here.
Sounds like you're a beginner, so check out Adafruit's tutorials here.
And lastly, I've compiled links to all my knowledge at the bottom of my article here.

You might want to make your answer a little bit more substantive than simply including links to sites that may or may not exist by the time someone else looks at the question.

What you need is to detect a transition. That is, either:

It was closed and is now open.

Or:

It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
bool toggle;

void setup ()
  {
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    toggle = !toggle;   // toggle the variable
    delay (10);         // debounce
    }  // end of state change

  // other code here ...

  }  // end of loop

For more information see my post about switches.


text:
Arduino "piston" device
Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed.
The ideal size would be something within the 1-2 inch length range

Could you elaborate a bit on "piston-like devices" that can "apply pressure safely various parts of the head"? Do you have an image or some sort of link to what you are talking about?

Do you need a particular pressure/force to be applied? I ask because it would be possible to use servo or other motor driven mechanisms, but force control would be more complicated with these. I thought of small Lego Technics pistons but some air source and valves would be needed.

Is this really an Arduino question yet? I think this should be migrated to EE (and modified to change title from "Arduino" to something less MCU-specific).

@CharlieHanson, I think the question is off-topic here and in electronics.stackexchange as well.  Possibly on topic in robotics.stackexchange, probably on topic in engineering.stackexchange

It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino.
I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.
If that is right then I think what you are looking for is a Linear Actuator.  There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V.  This means you would require a Darlington transistor or relay to control them from an Arduino.
If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel.  This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

Can you provide more details on what you want to move?
List item
Is it heavy? Do you need lots of Torque?
Are you pushing straight or do you need to push in an arc (i.e. a door)?
What voltage supplies do you have available?
How fast do you want it to move?
Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.


text:
Deviation of power consumption between datasheet and real world?
According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

void setup () {}
   void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?
EDIT:
I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.
Now that I think about it..  Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."
Is it possible that the oscillator needs that extra 5mA?
EDIT2:
Here is a screenshot of my schematic:

And a screenshot of the ATmega328P-PU Datasheet:

Perhaps if you show your schematic. I have got consistent results from my tests.

Thank you!
I added a schematic and screenshot of the datasheet.
By consistent you mean that the results of your measurements were as one yould expect after reading the datasheet?

What kind of meter are you using. Also, try adding a bypass cap to the VCC line (unlikely to help, but still good practice). Do you have any other ATMega328 chips around, or just this one? Did you set the correct fuses?

Set all your IO pins to outputs and set them LOW.  Then disable all timers and interrupts.  What results do you get then?

According to the datasheet:

All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

That was the critical point. Trying this sketch:
int main ()
  {
  for (int i = 0; i < 20; i++)
    pinMode (i, INPUT_PULLUP);
  }  // end of setup

Note that timers are not running (your sketch would have timer 0 running):
With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.
Fuses:
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDF
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96

If we turn pull-ups off:
int main ()
  {
  }  // end of setup

Now it consumes 14.4 mA, closer to what you measured.

And with your actual test sketch:
void setup () {}
void loop () {}

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the init function). It is also close to what I had on my page about power - 15.15 mA.

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.
I did mention further down in my page the importance of configuring the pins:

Testing in SLEEP_MODE_PWR_DOWN:

All pins as outputs, and LOW: 0.35 µA (same as before).
All pins as outputs, and HIGH: 1.86 µA.
All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.

Thank you so far! I have to wait until my new chip arrives and I can test this.

Probably Atmel measured the chip consumption without any code. An empty sketch has some code in it (believe it or not).
Another possibility is the remaining components like voltage regulator, usb chip are also consuming some current.
Try to test in a bare minimum configuration.

Thank you for your reply!
I forgot to mention.. I didn't use it with the arduino uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it.. Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source." Is it possible that the oscillator needs that extra 5mA?

@elperro, now that you've added the info from those two comments to question, feel free to delete the comments.

authors: พี่ โน๊ต. นอนน้อย


text:
How to capture good sound with Arduino?
Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.
As I found, maximal sample rate, achievable with built-in ADC is 9kHz, which is to low.
So, I require to use some external hardware. But wave shields I saw are to expensive (comparable by price with Arduino itself), probably, because of excess functions (including not only ADC but also DAC and so on).
Simultaneously, there are ICs, providing ADC functionality and even MP3 encoding functionality for relatively low price. But here a schematic design required.
So, how to find appropriate solution here?

I would use something with considerably more grunt than a baby Arduino - something with an I2S interface built in. Maybe a Due, but the best one that I use regularly would be a PIC32MZ based system, like the chipKIT WiFire.

Yes but you want something much faster then the Arduino, normally it is in the 96k~48k bps range.  Try this link, they make a lot of great parts and the bulk of what you have to do is control software.  You can let the chip do the grunt work (analog) and transfer thee data to where ever you want.  Some of the chips will record for 300 seconds plus.
http://www.aplusinc.com.tw/exec/product.php?lg=E&mod=show&cid=43&pid=aPR33A3
I have used there parts they work great.
Have fun,
Gil

Is it possible to capture good sound with Aduino? I need to record street / birds / nature sounds.

The answer is "no" for AVR based Arduino boards. They have simply too low sampling rate, ADC resolution, limited buffering memory and processing speed.
The ADC sample rate is at most 9 K samples per second (112 us per sample) at highest resolution (10 bits). The resolution can be improved (e.g. 12 bits) by using oversampling but this is at the cost of sampling frequency.
The Arduino Uno has only 2K byte memory. Using all that for buffering would give at most 1 K samples. That is little over a second sound data. A SD file could be used but requires a lot of smart programming to not drop samples at max sampling rate.
Low quality, 8-bit samples, then "yes". See here.
Now an Arduino Due is much more powerful, has much more memory, etc. See here.

Is it possible to capture sound with Due?

Added some results from google. See new links above.

This about playing audio, but how about recording? How fast is DAC in Due?


text:
actual use of noTone() in arduino
What is the use of noTone() function as the duration for which the note must be played can be specified using the third argument of note() function.

So that you can terminate the output prematurely, e.g. during an interrupt.


text:
Split RGBW hex String into integers
I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm.
Whats the best/easiest way to do this?
Example:
void incomingMessage(const MyMessage &message) {

    // h = hex value
    // message = e.g. (h) #112233AB
    redval = ?; // h11 => 17
    greenval = ?; // h22 => 34
    blueval = ?; // h33 = 51
    whiteval = ?; //AB = 171

    analogWrite(RED_PIN, redval);
    analogWrite(GREEN_PIN, greenval);
    analogWrite(BLUE_PIN, blueval);
    analogWrite(WHITE_PIN, whiteval);

}

I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:
byte fromhex (const char * str)
  {
  char c = str [0] - '0';
  if (c > 9)
    c -= 7;
  int result = c;
  c = str [1] - '0';
  if (c > 9)
    c -= 7;
  return (result << 4) | c;
  }

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

  const char * test = "#112233AB";

  byte redval   = fromhex (& test [1]);
  byte greenval = fromhex (& test [3]);
  byte blueval  = fromhex (& test [5]);
  byte whiteval = fromhex (& test [7]);

  Serial.println ((int) redval);
  Serial.println ((int) greenval);
  Serial.println ((int) blueval);
  Serial.println ((int) whiteval);

  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

Output:
17
34
51
171

That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)

So you basically want to convert a pair of hexadecimal digits into a numeric value.  You also want to extract those values from a string.
The latter can be done using the String.charAt() method.  That allows you to extract individual characters from your string.
Then you need to convert those into a number.  There's a number of ways that could be done.
strtol()
The strtol() function takes three parameters - the first is a C string (NULL-terminated char array) which contains the number you want to convert, the second you can ignore, and the third is the base to convert from.  So you could use something like:
char temp[3] = { char1, char2, NULL };
int val = strtol(temp, NULL, 16);

Discrete functions
It's simple enough to write a function that converts a single hex digit into a value 0-15:
unsigned char h2d(unsigned char hex)
{
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

It's then simple enough to use that to make a function that takes two hex digits and converts them into a number:
unsigned char h2d2(unsigned char h1, unsigned char h2)
{
    return (h2d(h1)<<4) | h2d(h2);
}

There's as many ways of doing it as there are of skinning a cat (as the saying goes).  Every way has benefits and drawbacks though.  Of the two I have shown, to compare them:

The first is "safer" as it has more error checking and can cope with other things besides hex values
The second results in much smaller code but results with values other than hex digits are undefined.


text:
When the Arduino is in reset mode are the digital pins high impedance?
I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.
I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.
All Arduinos involved are Uno Rev 3s.
Any help would be appreciated, thanks!

I'd suggest adding some resistors between the arduino outputs, and the FRAM IC. So that in the case that Arduino A is not reset (broken connection e.g.) you don't get any shorts (i.e. one arduino outputs a HIGH, while the other outputs a LOW).

From the ATMEGAxx8 datasheet...

11.1 Resetting the AVR
... The I/O ports of the AVR are immediately reset to their initial state
when a reset source goes active. This does not require any clock
source to be running.

(bold added)
Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of 0, corresponding to high impedance input.
...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the RESET pin goes low.
Caveats:

The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).

Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.

The MISO pin can inadvertently become an output while RESET is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in App Note AVR910.

Thank you for explaining the whole reasoning path from datasheet to initial values of the registers. That helps a bunch!

But note that holding a AVR in reset also means that it will be listening for programming signals on some of its pins.

My reading of this is that there is you must hold the RESET pin low during power up to enter serial downloading mode. - no, when I am programming using ICSP, you can enter ICSP programming from any reset, not just power-on reset.

Above commentors are correct! Despite what the data sheet says, the MISO line does become an output if RESET is asserted and then the programming enable command is sent! Answer updated to reflect. Great catch for a very obscure corner case.


text:
Wireless Communication Between Raspberry Pi 2 and multiple Arduinos
I have about 10 Arduinos that have sensors attached, which report information back around my house. I would like to have a RPi 2, because they have nice screen and GUI options, to collect the information and display it accordingly.
I am looking for success stories on what wireless parts you used to get these two working. The the wireless must be able to penetrate a brick wall about 120ft away.
Thanks for replying, I edited the response above.

The range requirement is going to be your main challenge.  If for some reason you end up with a radio technology that does not integrate readily with the pi, you can always use another arduino/atmega on USB-serial  or logic level serial as a gateway between the master radio and the pi.

Please check http://arduino.stackexchange.com/search?q=raspberry+multiple+arduino there might be a question that greatly resembles yours, read them first, dealing with the same project they can have other/better approaches or the same difficulties.

There's many options you could use.
The simplest, though most expensive, would be to equip all your Arduinos with WiFi shields and connect a USB WiFi dongle to the Pi.  The Pi could run in AP mode (investigate hostapd) so you don't have to connect them all to your internet router.
A cheaper option, though harder to work with on the Pi, would be to use the incredibly cheap but popular nRF24L01+ modules.  There are libraries aplenty for the Arduino, but I am not aware of code for the Pi (though there probably is somewhere if you google for it).
And then there are options in between which vary in price and complexity.
Of course, you haven't mentioned range, only a brick wall.  The right choice could well be affected by the range of communication you need - do you go for the bare nRF28L01+ with a range of maybe 10m, or the one with the power amplifier and SMA antenna with a range of many hundreds of meters? Is WiFi going to be long enough range? Would a 433mHz module be a better choice?  All these questions and more need to be answered, and the best way is for you to describe your setup in detail, including what the longest range is you need to deal with, what amount of data you will be sending, do you need ultra low power to save batteries, etc.

I only saw 3 Google results after clicking your nrf28l01 link.

That was a typo - should have been nRF24L01

Thanks. Those look like neat units. Have you ever seen anything that uses the 433 or 315 spectrum that has similar range-boosting features (the amplifier and SMA connection)?

@Jerry I can't say as I have, no.

That seems strange to me, since the lower frequencies should be able to go through obstacles better, and since they don't interfere with the noisy 2.4/5.8 GHz spectrum. I'm guessing maybe the FCC and other groups regulate it.

@Jerry They may well exist - I just have never seen or used them, but then I have never looked.

I use the ESP8266 to get the data from my arduino to my webserver using wlan. You could easy install a webserver on your pi and connect it to your wifi, or just use a server online.
So you can install on all places where you get WLAN. Also you could use a repeater if your wlan is not strong enough.
Thats how my projekt works (Water level messure)

Get range from ultrasonic sensor (every minute)
Send data to the ESP8266 using SoftwareSerial
Send getRequest with WLAN to my php page on the Server
Save Data to MySql Database
Show the Data Online with php and a javascript graph lib

My example is one way Arduino to Server, but you could easy communicate back to each of your arduinos.
good luck :)

You could use an xBee.
I have 2 of these and they are really easy to set up. Here is a link to the data sheet: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf
Link to site:
https://www.digi.com/lp/xbee
These I believe can interface to the GPIO of the pi - as i seem to recall doing that myself. Either I did that or used an arduio to get the readings and had the arduino feed the readings to the pi GPIO pins - either way the modules make sending data wireless super easy.


text:
Help with Flappy Bird Sketch
I am compiling the sketch found here. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.
In file included from flappyDuino.ino:7:0:
Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 };

                                                 ^
In file included from flappyDuino.ino:7:0:
Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 };

                                                 ^
Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E };

                                         ^
Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
 static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF };

                                      ^
variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

I'd appreciate any help.

What it says... make those variables const.

This is embarrassing. . . But how?

By adding the word const after the word static.

Thank you. I had const on the back of my head but wasn't sure where to put it.

The arrays need to be tagged with the keyword const.  It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the const keyword whereas the author's doesn't.
Basically any arrays that are PROGMEM need the word const adding to them.  For instance, lines that start:
static unsigned char PROGMEM ...

need changing to:
static const unsigned char PROGMEM ...

Thank you for answering why the sketch would not contain the necessary const. BTW Does the ! symbol mean not throughout the Arduino IDE, so that the statement "if (!player.isDead()) means if isDead is not true then. . .

Yes, ! is logical negation - true becomes false, false becomes true.  So !player.isDead() would logically be the same as (if the function existed) player.isAlive().


text:
Move robot through the waypoints
My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..
My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.
Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?

What have you tried so far? Can you get the robot to drive around (e.g. forward a while, turn left, back a while, turn right)? Can you talk over bluetooth from the PC to the robot?

Yes I can control robot movements using keyboard as a joystick. And I can talk over Bluetooth from the PC to the robot

With the arrangement you have described I would say it's very very hard to do what you want.

You know where the robot is
You know where the robot has to get to
You can easily calculate the direction the robot has to go in (simple trigonometry from school)

But:
You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.
So either you need some kind of calibration procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.
The latter is probably the easiest.  Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape.  What that shape is can be up to you, but there is one big constraint: It must have a clear direction to it (i.e., it must have no rotational symmetry.  Triangles are good since they only need 3 LEDs.  An equilateral triangle though wouldn't work since in three different rotations it would look the same.  However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.
You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.
Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.

Other option: use 2 LEDs of different colour, like RED and GREEN. That will simplify the calculation, as it only requires calculating the line passing through 2 points.
For supporting multiple robots: use blinking patterns, each robot could encode its unique ID, as long as it's not too fast for the camera.

@IgorStoppa I assumed the use of IR LEDs was specifically stipulated because it was easier for the camera to isolate from the backround image. Using visible LEDs would require considerably more complex processing.

It should be a matter of running a 1-pass filter on the image.
Should be piece of cake for OpenCV.

If IR leds is a requirement, you might still get away with having two LEDs, and have one on continuously, the other strobing; depending on the camera, either the strobing one will be dimmer (ideally), or will be there sometimes, not there the rest of the time.

This depends if you want the hypothetical best solution, or if good enough is good enough.
If good enough is good enough, I'd take the following approach:
Work out the distance from your robot to the first waypoint; move forward. Work out how fast you're moving towards (away from) the goal. Turn left a bit, go forwards again; did things improve (less away from/more towards)? If not, turn slightly right. Keep turning this way (left or right), and going forward a bit; whenever your speed towards to the goal gets worse, change your turning direction.
This should get you to where you are going.
Then, start making improvements.
If you are moving away from the goal (distance is increasing), your rotates can be quite sharp; as your approach speed to the goal increases, make the rotates smaller.
You could also try rotating while driving - if you are driving forward, and want to turn slightly left, run your left wheel at 90% of the speed of the right.
With a bit of trial and error, you should be able to end up with a table - work out your approach speed, look up in a table (or formula) how fast your slower wheel should go - from 0% (or even 100% reverse!) if moving away from your goal, to 100% if you are going at your driving speed towards your goal. Remember that if you are turning, you will approach it more slowly than if you are going straight. And if you start to turn and things get worse, then you are turning the wrong way.


text:
Are there any ePaper modules that are bigger than 2.7 inches for arduino
I am looking for a large ePaper Display for the Arduino. The issue is is that I cannot seem to find one any larger than 4.5 inches in size. That will be compatible with arduino. Even with a controller board.
Are there any companies that sell controller boards for these displays? Is there anyone who can manufacture these epd displays upon request?
I am looking to take this project to a pcb board after I prototype it so do I need to build my own controller? If what parts would you need? Is it easy for a designer with intermediate capability?
I can find all kinds of display like at pervasivedisplays.com and Mouser.com
The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score.

I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.
Here is a starting point.


text:
Powering arduino and 12V Fan from same supply
I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.
Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?
If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below?

Sounds fine.
You can connect the two fans in parallel, as long as they don't use more than 5A combined, as that is the maximum of the TIP120. Though you definitely need to attach a heatsink to the TIP120, if you are using a largish amount of current. Though in that case, I'd suggest using a MOSFET instead of a Darlington Transistor (TIP120), as MOSFETs don't heat up that much.
The diode is not needed if you use the TIP120, as there is already a diode inside the package.
Since you are using 12V as a power supply, the voltage regulator has to convert 7v into heat. Depending on the amount of current you use, this could result in the voltage regulator getting very hot. If you are only powering the ATMega328 and maybe some LEDs from the 5v line, you'll be fine. Just don't connect something like a 5v fan.

I see, thank you. Out of curiosity, if I would want to connect some 5v fan, how would I go about protecting the built in regulator from overheating? Should I but some resistors on the RAW pin to make the 12v line go down to 5v before entering the arduino? I guess that would make the much cheaper resistors handle dissipation?

Just bypass the onboard 5v regulator, and use an external voltage regulator in e.g. a TO-220. Depending on the load, you can easily add a heatsink to this TO-220 package. Connect the 5v output of the external regulator, to the 5v pin on the arduino board.

The board will take 12V, but the regulator will have to dissipate (as in heat) the excess power.
However, how much do you trust your power supply to not exceed the 12V?
The same applies to the other loads.
About max current, you should do the math for both typical case and peak case. Ex: the fan will draw much more current if for any reason it is stopped.
If you use only 1 transistor, you will get both fans to behave in the same way, because you will be using only 1 control line. Is this what you want?

I think I trust the supply, I'm a trusty person :).
I don't need to control the fans separately, in fact the PCR PID system I'm building would benefit from both fans being in sync. I guess that having only one transistor the fans would get max 6V and thus run at half capacity?
Since the Arduino itself really doesnt need the 12V, should I put a resistor on the RAW pin to limit power supply voltage?

Why would the fan get 6V?

Yes, you can put a resistor. You could also put a zener, to clip just the extra voltage.

I was thinking that I had to connect the fans in serial and that it would mean they got half the voltage each. but I guess I could just connect them both to the Collector of the transistor?
But would I need to put a resistor/zener to protect the Arduino, or will it work without it, is it considered good practice?

Why wouldn't you trust a 12v switching power supply? Maximum voltage of the mic5205 is 16Volt (absolute maximum 20Volt). Using a zener is a very crude way to make a voltage regulator. If anything, I'd just add one or two diodes. Those will drop the voltage by around 0.6Volt each. Added bonus is, that it will protect your board in case you accidentally connect the powersupply the wrong way around.

I see. So I would put two diodes in serial on the RAW pin?

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


text:
How can BMP180 measure a temperature too?
I got the following device

(sorry for imperfect focus)
and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.
Simultaneously, on Bosch site for BMP180 I can't find any notes it can measure temperature, only pressure.
How can it be?
1) Bosch's BMP180 has undocumented feature to measure a temperature
2) The device on picture has additional component to measure temperature
3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.
4) Something else....

If you read the data sheet (on the site you point to) you see plenty of references to temperature:

The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C
  bus. The pressure and temperature data has to be compensated by the calibration data of the
  E 2 PROM of the BMP180.

and

The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and temperature. The E 2 PROM has stored 176 bit of individual calibration data. This is used to
  compensate offset, temperature dependence and other parameters of the sensor.

And many many more.

The BMP085 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180 is a drop-in replacement for the BMP085.
The  BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180  is completely identical to the BMP085 in terms of firmware/software/interfacing.
In addition, while Bosch's web page for the BMP085 doesn't mention temperature, the data sheet itself – the final reference, typically, for a device like this – says “Temperature measurement included” on page 2, and on page 14 refers to measuring temperature in steps of 0.1°C, and on other pages shows temperature register numbers, etc.  To get the data sheet, click the Documents & Drivers tab, then the BST-BMP180-DS000-12 Datasheet link.

See, for example, Adafruit BMP085 library (it's work with BMP180 too), function
void Adafruit_BMP085_Unified::getTemperature(float *temp)

in file Adafruit_BMP085_u.cpp line 330


text:
Mega pin stuck high after driving optocoupler
I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.
void setup() {
  pinMode(42, OUTPUT);
  digitalWrite(42, LOW);
}

void loop() {
  digitalWrite(42, LOW);
}

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.

Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)
Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current.  If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working).  Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.
(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)

Thanks, I'll probably increase the resistor up to 500ohms even.


text:
Arduino ethernet need help with game logic!
I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.
Example image: https://i.stack.imgur.com/gtnUm.png
I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.
Code that switches LED:
led = random(1, 4);
switch(led) {
  case 1:
    ledLeftState = HIGH;
    break;
  case 2:
    ledMiddleState = HIGH;
    break;
  case 3:
    ledRightState = HIGH;
    break;
}

Code that checks if the wrong button is pressed:
 if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
    static unsigned long lastTime = 0;
    if(millis() - lastTime > 400) {
      Serial.println("Ouch, minus ten miliseconds!");
      hurt += 10;
      lastTime = millis();
    }
  }

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.
Thanks for your time!

I'm not too good at making up code in my head and then solving any problems with it. ;) Please post a Minimal, Complete, and Verifiable example of what you are talking about.

The line
if(millis() - lastTime > 400)

is supposed to test that the button press does not come right after the
LED switches. This means the line
lastTime = millis();

should be right when you change the displayed LED.

First: Your buttons are not wired up properly according to the diagram.  They seem to be only connected to 5V.
On Arduino buttons can be wired both active-high and active-low.  Active-high means then when the button is pressed you get a HIGH signal, and LOW otherwise.  Obviously active-low is the opposite.  The code below assumes active-high.
You might want to go do some reading on "button de-bouncing".  I've included some rudimentary code to help, but it's not perfect.  A 0.1 micro-farad capacitor across the button terminals will help with this too.
So ... onto the code.
It's really the game-loop that needs some work.
I'll assume your random LED-lighting code is in a function called newRandomLED(), and variables ledLeftState, hurt, etc. are globals.
The new_pattern_time variable should probably also be set in newRandomLED() since they always are called together.  But I'm trying to help, not re-write ;)
const int debounce_time  =  30; // milliseconds
const int max_push_time  = 400; // milliseconds - How long is a turn

// Draw the first LED pattern
newRandomLED();

// the time the latest LED pattern was re-drawn
unsigned long new_pattern_time = millis();

// Reset the score
hurt = 0;

while (true) // TODO: insert some game-length decision
{
    // Has the time to press a button expired?
    if (millis() - new_pattern_time > max_push_time)
    {
        // TODO: sound the buzzer for *fail*

        // Time is up, penalise the user
        hurt += 10;

        // Time for a new pattern
        newRandomLED();
        new_pattern_time = millis();
    }

    // Perform the initial-read of the buttons
    int butt_left  = digitalRead(BUTTON_LEFT);
    int butt_mid   = digitalRead(BUTTON_MIDDLE);
    int butt_right = digitalRead(BUTTON_RIGHT);

    // de-bounce the button presses
    delay(debounce_time);
    if (butt_left == HIGH)
        butt_left = digitalRead(BUTTON_LEFT);
    if (butt_mid  == HIGH)
        butt_mid = digitalRead(BUTTON_MIDDLE);
    if (butt_right == HIGH)
        butt_right = digitalRead(BUTTON_RIGHT);

    // So now we have the state of the three buttons, de-bounced too.
    // Was there any input from the user?
    if (butt_left == HIGH || butt_mid == HIGH || butt_right == HIGH)
    {
        // So one (or more) buttons have been pressed
        // Check that for each LED that is on, that the button is pressed too
        boolean success = true;
        if (ledLeftState != butt_left)
            success = false;
        if (ledMiddleState != butt_middle)
            success = false;
        if (ledRightState != butt_right)
            success = false;

        // Was the user correct?
        if (success == true)
        {
            // TODO: sound the buzzer for *WIN*
            hurt -= 10;

            // And we need to show the next pattern
            newRandomLED();
            new_pattern_time = millis();
        }
    }
}

So essentially you're looping around checking to see if the player pressed anything.  Most of the time, there will be no input from the user, and this loop will spin thousands of times without any input.
On each loop the code checks to see if the time is up, or some buttons were pushed.  In both cases, it's time for a new pattern.  A side effect of this code is that it allows for simultaneous button pushes, so at higher difficulty levels you could illuminate more than 1 LED.
Note: this code is a quick response to the question.  It may not be 100% correct, nor have flawless C-textbook syntax.

Off the top of my head and without a compiler would something like this work?
int BasePin = 3;
int BaseButton = 7;

int led = random (1, 4); // Are you sure its 4??
digitalWrite(BasePin+led, HIGH);

if (digitalRead(BaseButton+led))
{
  // Success
}
else if (millis() - lastTime > 400))
{
  // Out of time
}
else if (  digitalRead(BaseButton+1)
        || digitalRead(BaseButton+2)
        || digitalRead(BaseButton+3)
{
  // Wrong button
  // (The right one will have been handled by the earlier clause)
}

OK the last clause is a bit of a hack, but it should give you a starting point to tidy up.
You are probably going to get issues unless you debounce the switches.


text:
Using a state machine
I'm trying to get a strip of Neopixels to circle through its length, one LED at a time, I want it to do it faster as the value received from the sensor increases
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure,
    barometricToRGB,
    frequency       = 0,
    high            = 0,
    low             = 600,
    interval        = 50;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN,INPUT);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  airPressure = analogRead(SENSOR_PIN);
  autoTune();

  unsigned long currentMillis = millis();
  Serial.print("frequency ");
  Serial.println(frequency);
  Serial.print("Time to beat ");
  Serial.println(frequency*interval);
  Serial.print("Last Called ");
  Serial.println(currentMillis - previousMillis);

  if(currentMillis - previousMillis > (frequency/interval)) {
    previousMillis = currentMillis;

    for (int i=0; i<NUM_LEDS; i++) {
          leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
          FastLED.show();
        }
  }
}

void autoTune() {
  if (airPressure < low) {
    low = airPressure;
  }
  if (airPressure > high) {
    high = airPressure;
  }
  barometricToRGB = map(airPressure, low, high, 1, 255);
  barometricToRGB = constrain(barometricToRGB, 1, 255);
  frequency = map(airPressure, low, high, 1, 100);
  frequency = constrain(frequency, 1, 100);

}

While I had managed to cause the color to change based on the sensor, I can't seem to understand how to control how fast it will go, every how long.

Can you copy and paste the code into the question please? It isn't long.

Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?
If so, you did not write any "select this led" code, so it can't work.
I fixed a couple of things in your code. Mainly:

added the circularity to the ring (with variable currentlyOnLed)
fixed some types (use the byte unless you need a bigger type)
removed some constrains, which were reduntant
frequency*interval instead of frequency/interval (I guess it was a typo)
I prefer summing the step instead of setting previousMillis to currentMillis, so you will not add error with time passing
moved FastLED.show() outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.

So, here is the fixed code. Let us know if it works for you
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure;
int high  = 0;
int low   = 600;
byte barometricToRGB;
int frequency = 0;
byte interval = 50;
byte currentlyOnLed;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(115200);
    pinMode(SENSOR_PIN,INPUT);
    FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    currentlyOnLed = 0;
}

void loop() {
    airPressure = analogRead(SENSOR_PIN);
    autoTune();

    unsigned long currentMillis = millis();
    Serial.print("frequency ");
    Serial.println(frequency);
    Serial.print("Time to beat ");
    Serial.println(frequency*interval);
    Serial.print("Last Called ");
    Serial.println(currentMillis - previousMillis);

    if(currentMillis - previousMillis > (frequency*interval)) {
        previousMillis += (frequency*interval);

        //Set next on led
        if (currentlyOnLed >= NUM_LEDS - 1)
            currentlyOnLed = 0;
        else
            currentlyOnLed++;

        for (byte i=0; i<NUM_LEDS; i++) {
            if (i == currentlyOnLed)
                leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
            else
                leds[i] = CRGB::Black;
        }
        FastLED.show();
    }
}

void autoTune() {
    airPressure = constrain(airPressure, low, high);
    barometricToRGB = map(airPressure, low, high, 1, 255);
    frequency = map(airPressure, low, high, 1, 100);
}

That's amazing! This is very thorough, and thoughtful. Thank you so much

You are welcome ;) and... I don't know if it is you or someone else who needs to accept the edits in the original post. I just added the code (so it was cleaner and, moreover, links can break)

Are these reversed?
high            = 0,
low             = 600,

It looks like high and low both get set to airPressure on the first pass through autoTune(). If the pressure drops after this, for example, low will track airPressure and high will stay the same.
Also, with frequency 1 to 100 and interval 50 the largest time difference is 2 milliseconds and the smallest is 0.  Your loop could be taking 2 ms without the if statement.