body:
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);
        }
    }

title: Basic Serial Transmission Protocol

Answers: 2

body:
What you are doing is called "bit-banging" [(wikipedia link)](https://en.wikipedia.org/wiki/Bit_banging) 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:

1. the clock speed of your MCU
2. 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/

body:
<!-- language-all: lang-C++ -->

> 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)`.


body:
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.
[![enter image description here][1]][1]

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?

  [1]: https://i.stack.imgur.com/SEiwb.png

title: Arduino Pro Micro Analog Pinouts

Answers: 1

body: 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.


body:
I have a transmitter(simple [433 MHz transmitter][1]) 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.

  [1]: http://www.ebay.com/itm/433Mhz-RF-transmitter-and-receiver-kit-for-Arduino-ARM-MCU-WL-/261041100836

title: How to fix baud rate when hardware capacity has a low limit?

Answers: 1

body:
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.


body:
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

title: How do you make the arduino go forward,backward and stop using Infrared?

Answers: 2

body:
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.

body:
You need a good IR Library, or tons of low-level knowledge.

Ken Shirriff wrote the best IR library out there! [Here it is][1].

Adafruit writes awesome tutorials too. [Here's one][2].

  [1]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
  [2]: https://learn.adafruit.com/using-an-infrared-library/hardware-needed


body:
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?

title: Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2

Answers: 1

body:
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:

[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/lwFWt.png


body:
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...

title: Detect closed shutter

Answers: 1

body:
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)


body:
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][1]

  [1]: http://pastebin.ca/3177996

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

title: Any chance of repairing Mega 2560?

Answers: 1

body:
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


body: 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.

title: arduino project for c programming language

Answers: 2

body:
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

body:
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!


body: 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

title: how to change variable when a button connected to pin 2 is pressed

Answers: 2

body:
Go [here][1] --> 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][2].

Sounds like you're a beginner, so check out Adafruit's tutorials [here][3].

And lastly, I've compiled links to all my knowledge at the bottom of my article [here][4].

  [1]: https://www.arduino.cc/en/Tutorial/HomePage
  [2]: http://www.electricrcaircraftguy.com/2014/05/ercaguybuttonreader-library-for-arduino.html
  [3]: https://learn.adafruit.com/category/learn-arduino
  [4]: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html

body:
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](http://www.gammon.com.au/switches).


body:
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

title: Arduino "piston" device

Answers: 1

body:
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.


body:
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:
[![enter image description here][1]][1]

And a screenshot of the ATmega328P-PU Datasheet:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/GZBCx.png
  [2]: https://i.stack.imgur.com/Ae11H.png

title: Deviation of power consumption between datasheet and real world?

Answers: 2

body:
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.

body:
<!-- language-all: lang-C++ -->

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:

<!-- language-all: lang-none -->

    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDF
    EFuse = 0xFF
    Lock byte = 0xFF
    Clock calibration = 0x96

---

<!-- language-all: lang-C++ -->

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](http://www.gammon.com.au/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.


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

[As I found][1], 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?

  [1]: https://arduino.stackexchange.com/a/701/6841

title: How to capture good sound with Arduino?

Answers: 2

body:
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

body:
> 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][1] 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][2].

Now an Arduino Due is much more powerful, has much more memory, etc. See [here][3].

  [1]: http://www.atmel.com/images/doc8003.pdf
  [2]: http://apcmag.com/arduino-projects-digital-audio-recorder.htm/
  [3]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer


body: 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.

title: actual use of noTone() in arduino

Answers: 1

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


body:
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);

    }

title: Split RGBW hex String into integers

Answers: 2

body:
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()](https://www.arduino.cc/en/Reference/StringCharAt) 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.

body:
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. :)


body:
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!

title: When the Arduino is in reset mode are the digital pins high impedance?

Answers: 1

body:
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:

1. 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!).

2. 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.

3. 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][1].

  [1]: http://www.atmel.com/images/doc0943.pdf


body:
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.

title: Wireless Communication Between Raspberry Pi 2 and multiple Arduinos

Answers: 3

body:
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](http://google.com/?q=hostapd+raspberry+pi)) 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+](http://google.com/?q=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.

body:
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)

 1. Get range from ultrasonic sensor (every minute)
 2. Send data to the ESP8266 using SoftwareSerial
 3. Send getRequest with WLAN to my php page on the Server
 4. Save Data to MySql Database
 5. 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 :)

body:
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.


body:
I am compiling the sketch found [here][1]. 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.

  [1]: https://github.com/huytd/arduino-flappybird

title: Help with Flappy Bird Sketch

Answers: 1

body:
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 ...


body:
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?

title: Move robot through the waypoints

Answers: 2

body:
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.

body:
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.


body:
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][1] and [Mouser.com][2]

The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score.

  [1]: http://www.pervasivedisplays.com/
  [2]: http://mouser.com

title: Are there any ePaper modules that are bigger than 2.7 inches for arduino

Answers: 1

body:
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][1] is a starting point.

  [1]: http://ugfx.org/platforms


body:
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?
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/st4Or.png

title: Powering arduino and 12V Fan from same supply

Answers: 2

body:
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?

body:
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.


body:
I got the following device

[![enter image description here][1]][1]

(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][2] 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....

  [1]: https://i.stack.imgur.com/HNSIF.png
  [2]: https://www.bosch-sensortec.com/en/homepage/products_3/environmental_sensors_1/bmp180_1/bmp180

title: How can BMP180 measure a temperature too?

Answers: 3

body:
The [BMP085 Barometric Pressure/Temperature/Altitude Sensor- 5V ready](https://www.adafruit.com/products/391) page at adafruit.com says the BMP180 is a drop-in replacement for the BMP085.

The  [BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready](http://www.adafruit.com/products/1603) 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](https://www.bosch-sensortec.com/en/homepage/products_3/environmental_sensors_1/bmp180_1/bmp180) 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.

body:
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.

body:
See, for example, [Adafruit BMP085 library][1] (it's work with BMP180 too), function

    void Adafruit_BMP085_Unified::getTemperature(float *temp)

in file Adafruit_BMP085_u.cpp line 330

  [1]: https://github.com/adafruit/Adafruit_BMP085_Unified


body:
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.

title: Mega pin stuck high after driving optocoupler

Answers: 1

body:
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.)


body:
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!

title: Arduino ethernet need help with game logic!

Answers: 3

body:
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.

body:
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.

body:
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][1]".  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.

  [1]: https://www.arduino.cc/en/Tutorial/Debounce


body:
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

<!-- language: lang-c -->

    #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.

title: Using a state machine

Answers: 2

body:
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.

body:
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:

1. added the circularity to the ring (with variable `currentlyOnLed`)
2. fixed some types (use the `byte` unless you need a bigger type)
3. removed some `constrain`s, which were reduntant
4. `frequency*interval` instead of `frequency/interval` (I guess it was a typo)
5. I prefer summing the step instead of setting `previousMillis` to `currentMillis`, so you will not add error with time passing
6. 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);
    }


body:
Im trying out [this membrane][1] from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?

**UPDATE**

Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on `HIGH`. i used `Serial.println(digitalRead(one));` to verify that and the output was 1.

    int two =  8;
    int one = 9;
    int four = 10;
    int three = 11;

    void setup() {
      pinMode(one, INPUT);
      pinMode(two, INPUT);
      pinMode(three, INPUT);
      pinMode(four, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      if(digitalRead(one) == LOW){
        Serial.println("One");
      }else if(digitalRead(two) == LOW){
        Serial.println("Two");
      }else if(digitalRead(three) == LOW){
        Serial.println("Three");
      }else if(digitalRead(four) == LOW){
        Serial.println("Four");
      }
    }

  [1]: http://www.adafruit.com/products/1332?gclid=CjwKEAjw7aiwBRCPgdu70arX70wSJADK6iDD89H4xAIdw88_bv9K8EcrhdbdzERDU0gKJgrRwAcO2xoClM_w_wcB

title: 1x4 Button membrane help

Answers: 1

body:
>     pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You *must* enable the pullup on the pins (and connect the common to ground) if you want correct operation.

     pinMode(one, INPUT_PULLUP);


body:
I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.

The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.

    duration = pulseIn(echoPin, HIGH);

Any idea on how I can change the pulseIn function with interrupts or something else?

Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

title: Can a ESP8266 and a HC-SR04 be friends?

Answers: 2

body:
`pulseIn()` is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.

Also, I don't know which implementation of the ESP8266 plugin you are using, but [the one I use](https://github.com/esp8266/Arduino) has [pulseIn available](https://github.com/esp8266/Arduino/blob/esp8266/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_wiring_pulse.c).

body:
I had trouble with pulseIn() until the proper initializing code was put in setup().

As follows:

  pinMode(TRIGGER, OUTPUT);

  digitalWrite(TRIGGER, LOW);

  delay(2);

  pinMode(ECHO, INPUT);

TRIGGER and ECHO were initially defined at top of code with other variables as follows:

  #define TRIGGER 13 // Data pin D7

  #define ECHO    12 // Data pin D6

My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.

Project was a 'Tide' reporting system. A work in progress.
Also found HC-SR04 board was  unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.


body:
I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition?
Any implementation ideas are also welcome.

title: Dust sensor for Arduino in open and windy environment

Answers: 2

body:
It depends on how far you want to go.  If you are looking for something cheap, than a GP2Y1010AU0F will only cost you a few pounds.  Or you could step up to £30 GBP or even £1000GBP.

Since you are looking at using an Arduino and not a PC then I'm guessing the GP2Y1010AU0F would be a good idea.  I haven't tried it but this site should steer you the right way: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/

body:
A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.

I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.

I mainly followed this blog's instructions for the code:
http://www.howmuchsnow.com/arduino/airquality/grovedust/

I think I read a few months ago that the next best sensors are in the $200 range.

I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.


body:
I have learned Arduino for a month, and I want to bulid a car with 2 modes,
Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:

    char mode;

    void loop()
    {
        while(serial1.available())
        {
            char control = serial.read();
            if(control == 'r') mode = 'r';     // r stand for Remote Mode
            if(control == 'a') mode = 'a';     // a stand for Auto Mode

            if(mode == 'r') remoteMode(control);

            while(mode = 'a')
            {
                int IR = analogRead(A10);
                float U1cmMsec,U2cmMsec;
                long U1microsec = u1.timing();
                long U2microsec = u2.timing();
                U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
                U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

                robot(U1cmMsec, U2cmMsec,IR);

                /*
                Here is the code to stop while() that I don't know how
                to program.
                I have tried:

                if(serial1.read() != 'a') break;

                But it will stop while(), because it will waits for
                bluetooth send data to arduino board.
                And if I take this line off, it will keeps while() and
                nothing can stop it.
                So, what am I supposed to do?
                */
            }
        }
    }

title: Arduino: how can I stop while() when bluetooth send a data?

Answers: 3

body:
Your problem is with this line:

    while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing `=` (assignment) with `==` (comparison).

You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.

Instead you want:

    while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."

Now you just need to program in some way of changing the value of `mode` within your while loop.

You can read more on while loops here:

* http://hacking.majenko.co.uk/the-while-loop

body:
The `while(serial1.available())` can be turned into an `if`: the loop function is already executed in a loop, as the name hints :-)

And unnest the inner `while`.

here it is at high level, which is probably easier to understand:

`
void loop() {
  static char mode; /*notice the "static"*/
  if (character_available())
    update_mode();
  if (mode == 'r')
    do_one_iteration_in_remote_mode();
  else if (mode == 'a')
    do_one_iteration_in_auto_mode();
}
`

Just make sure that you do not loop inside neither `do_one_iteration_in_remote_mode()` nor `do_one_iteration_in_auto_mode()`.

body:
I have replaced both 'mode' and 'control' (they were identical) with a single variable, `btChar`. At the end of `setup()`, wait for a transmission to be received before entering the main loop.

Once the main loop begins, a while loop executes until the serial receives a new transmission. Once it is received it is read, btChar is updated and the main loop starts again.

    char btChar;

    void setup()
    {
    /* AT THE END OF SETUP() */

    // Wait in setup for first BT transmission

        while (!serial1.available())
        { /* do nothing */ }
        btChar = serial1.read();
    }

    void loop()
    {
        while(!serial1.available())
        {
        // Program will stay in this 'while' loop until
        //    a new BT character is recv'd

            switch(btChar)
            {
                case('a'):
                {
                // do the 'auto' stuff
                    break;
                }
                case('r'):
                {
                // do the 'remote' stuff
                    break;
                }
                default: // this 'block' is not essential
                {
                // you end up here if neither 'a' nor 'r' was received
                }
            }
        }
        btChar = serial1.read();
    }

You can adapt the setup while-loop further to make sure that the main loop doesn't begin until the a correct character is received - change the line to:

    while ((!serial1.available())&&(btChar != 'a')&&(btChar != 'r'))

Using a `switch-case` statement within the main while-loop is not essential, and I included it out of interest more than necessity. You can use `if` statements instead, with one for 'a' and one for 'r'. However, in the event that you have a third or fourth (or more-th) mode then a switch-case statement, in my view, looks easier to read.


body:
Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like `Wire.write("blablabla");` it pass. But when in char is NRF data code crashing when go to "Wire.write".

    /*
    */
    #include <Wire.h>
    #include <SPI.h>
    #include "RF24.h"

    char datar = '';

    //Konfiguracja
    const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
    RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
    //-- Konfiguracja

    void setup() {
      Serial.begin(9600);
      Serial.println("LOL");
      Wire.begin();
      radio.begin();
      radio.setPALevel(RF24_PA_MAX);
      radio.setDataRate(RF24_250KBPS);
      radio.openReadingPipe(1, pipes[0]);
      radio.openWritingPipe(pipes[1]);
      radio.setChannel(78);
      radio.setAutoAck(true);
      radio.startListening();
    }

    void loop() {

      int len;
      if(radio.available())
      {
      len = radio.getDynamicPayloadSize();
      radio.read(&datar, len);
      delay(5);
      Serial.println(datar);
      Wire.beginTransmission(7);
      Wire.write(&datar);
      Wire.endTran345smission();
      radio.printDetails();
      }
      delay(5);

    }

title: Arduino wire can't send char

Answers: 3

body: The  code crash because you pass an memory address to the write function if you look to the arduino doc you pass a variable to the function therefore just writing datar as argument will end your problem

body:
Your problem is here:

    char datar = '';

    ...

     len = radio.getDynamicPayloadSize();
     radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into `datar` more than one byte. This overwrites other parts of memory and the program crashes. You need to make `datar` larger, eg.

    char datar [50];

The exact size would depend on your maximum payload size.

body:
I think the answer is a combination of Nick and Mathieu's answers.

Like Nick said you haven't assigned any memory to datar, so this is probably causing a crash because of buffer overrun.

Now to the call to read.  Mathieu said you are passing a pointer into the function when you probably didn't mean to.  But if you put Nicks change in then you **do** need to pass in a pointer to the character array.  You can do this by `radio.read(datar, len);` because the character array is a character pointer.
You **do not** want to pass a pointer to a character pointer `&datar` because that would mean the function was able to move the memory that you have allocated.

Also, you need to prevent buffer overflows in the "new improved" code by checking that the value of `len` is less than or equal to the value you allocated when you declared the data buffer (i.e. 50).  Because you are using a number in two places you should declare it as a constant at the top of the file.

    const int MaxBufferSize = 50;
    char datar[MaxBufferSize];
    ...
    len = radio.getDynamicPayloadSize();
    if (len > MaxBufferSize)
      len = MaxBufferSize;
    radio.read(datar, len);

Hope that helps.


body:
I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).

Is there a library that supports IR sensors?

A picture of the two possibilities can be seen [here]( http://www.instructables.com/id/How-to-use-IR-Sensor-using-Op-amp-and-Arduino/)

EDIT: This isn't a duplicate of [my previous post](https://arduino.stackexchange.com/questions/16361/a-c-doesnt-detect-ir-codes-sent-from-arduino), it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen [here]( http://www.instructables.com/id/How-to-use-IR-Sensor-using-Op-amp-and-Arduino/)

title: Decoding IR codes with IR sensor rather than IR receiver module

Answers: 3

body:
> I'm looking for a library to decode RAW IR signals from an IR sensor

[AGirs][1] includes a comprehensive library designed to work with raw IR signals. I've used GirsLite in an Arduino and [IrScrutinzer][2] in Windows to do advance IR protocol snooping.

  [1]: https://github.com/bengtmartensson/AGirs
  [2]: https://github.com/bengtmartensson/harctoolboxbundle/tree/master/IrScrutinizer

body:
I had a similar project a few months back and spotted this Arduino Library:

https://github.com/z3t0/Arduino-IRremote

and it is invaluable.

For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.

The wiring is easy and straight forward

> An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3

and the other two Legs of the IR detector/demodulator go to the power source.

body:
IRremote (already recommended) - but to save you some time, use the IRRecvDump example to grab the raw codes you need for `sendRaw()`. They need to be averaged out across 10-20 reads. I log the output to a file, and use a perl script to do it for me, since it is painful to type this into a calculator a million times. The resistor you connect to the sensor affects its sensitivity - I used 330ohm, and have ~10 metres range from a 3V3 remote inside, 4-5 metres outside in sunlight. I would give you the script, but it's on my desktop. Let me know if you need it - or just use python, which is so popular nowadays (indent-or-fail... feh. what about people who don't like setting up the tab-space continuum, and don't have fancy editors...mumblemumble)
Edit: my raw codes absolutely needed to be averaged out, or they were useless. Any negative values in the array can just be made positive, don't fret.


body:
I need to hook up [Bluefruit LE Breakout][1] (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the [library provided][2] is for Arduino.

What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.

Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.

And this is where I need help:

How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).

And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).

Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.

UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

  [1]: https://learn.adafruit.com/downloads/pdf/getting-started-with-the-nrf8001-bluefruit-le-breakout.pdf
  [2]: https://github.com/adafruit/Adafruit_nRF8001/archive/master.zip

title: Running Arduino code for Bluefruit LE on bare ATMega328

Answers: 1

body:
The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.

You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.

You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of `Upload`, choose `Upload using Programmer` (in the `Sketch` menu).


body:
So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.

    *reg = _transmitPortRegister
    _transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D
Continuing...

    #define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

    const uint16_t PROGMEM port_to_output_PGM[] = {
        NOT_A_PORT,
        NOT_A_PORT,
        (uint16_t) &PORTB,
        (uint16_t) &PORTC,
        (uint16_t) &PORTD,
    };

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

Continuing on,

    #define PORTB _SFR_IO8(0x05)
    #define PORTC _SFR_IO8(0x08)
    #define PORTD _SFR_IO8(0x0B)

    #define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
    #define __SFR_OFFSET 0x20

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.

    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);
      b >>= 1;
    }

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte"
and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one?

Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.

title: How to find the deferenced value of a transmit Port Register?

Answers: 2

body:
> My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No.  You're mistaking the operator.  In this context `&` means *the address of*, so it is getting the address of the variable called `PORTD` and casting it to an unsigned 16-bit integer, which it's then storing in the array.

>Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses.  The port register number is (for port D) 0x0B.  Add that to 0x20 and you get 0x2B which is the address of the register in memory.  Then comes the tricky bit:

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Expand that out with 0x2B and you get:

    (*(volatile uint8_t *)(0x2B))

Now, working from the inside out we have:

    (volatile uint8_t *)(0x2B)

That says *this is a pointer to address 0x2B*.

Then that is de-referenced to get the value from that pointer with a `*` operator:

    *(volatile uint8_t *)(0x2B)

So you end up with "The value that is in the address 0x2B"

If we then feed that back into the first part of your question, so:

    PORTD = (*(volatile uint8_t *)(0x2B))

then `&PORTD` would be:

    &(*(volatile uint8_t *)(0x2B))

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:

    (volatile uint8_t *)0x2B

body:
    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);
      b >>= 1;
    }

> In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks,

The comment is: choose **bit**

First, variable `b` is the **byte** that is being set. Now, since async serial sends the least-significant bit first, at the start of the loop of 8 iterations, it takes the low-order bit to see if it is set or not:

      if (b & 1) // choose bit

If set, it sets the output port to HIGH (by ORing in the appropriate mask to the appropriate register), otherwise it sets the port to LOW (by ANDing in the appropriate inverted mask to the appropriate register). The inverted mask would be set to every bit **but** one.

Now look at this:

      b >>= 1;

That shifts the bits right one, throwing away the low-order bit. Now what was previously the second lowest-order bit is now the low-order bit. Then the loop repeats. Now the next bit is sent. And so on for 8 bits.

Imagine we were sending 0x39 (0b00111001). For the 8 iterations of the loop we would see:

    00111001  --> 1 sent, then "b" shifted right one
    00011100  --> 0 sent, then "b" shifted right one
    00001110  --> 0 sent, then "b" shifted right one
    00000111  --> 1 sent, then "b" shifted right one
    00000011  --> 1 sent, then "b" shifted right one
    00000001  --> 1 sent, then "b" shifted right one
    00000000  --> 0 sent, then "b" shifted right one
    00000000  --> 0 sent, then "b" shifted right one

You can see that the right-most bit is sent (the low-order bit) and then `b` is shifted right (introducing zeroes at the left), until all 8 bits are sent.


body:
I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: https://arduino.stackexchange.com/questions/12076/2-8-tft-touchscreen-prohibits-access-to-unused-pins)

However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg==&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)

However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?

Thanks!

title: 2.8" tft screen arduino all pins used

Answers: 1

body:
You're confusing the idea of *using* all the pins to that of *plugging into* all the pins.

Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.

The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.

You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


body:
*Please see the comments section if confused.*
I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V.
I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.

    void setup ()
    {
      pinMode(0,OUTPUT); //IB1
      pinMode(1,OUTPUT); //IA1
    ////  pinMode(2,OUTPUT); //IB2
    ////  pinMode(3,OUTPUT); //IA2
    //  pinMode(4,OUTPUT); //RGB
    //  pinMode(5,OUTPUT); //RGB
    //  pinMode(6,OUTPUT); //RGB
    //  pinMode(A0,INPUT); //lMotor
    ////  pinMode(A1,INPUT); //rMotor
    //  Serial.begin(9600);
    }

    void loop ()
    {
      digitalWrite(0,HIGH);
      delay(1000);
      digitalWrite(0,LOW);
      delay(1000);

    //  int lMotor = analogRead(A0);
    //  Serial.write(lMotor);
    ////  int lMotor = analogRead(A1);
    ////  Serial.write(lMotor);
    //
    //  if (lMotor>10)
    //  {
    //    digitalWrite(4,HIGH);
    //    digitalWrite(5,HIGH);
    //    digitalWrite(6,LOW);
    //  }
    //  else
    //  {
    //    digitalWrite(4,HIGH);
    //    digitalWrite(5,LOW);
    //    digitalWrite(6,HIGH);
    //  }
    }

And here's this:

    void setup ()
    {
      pinMode(0,OUTPUT);
      pinMode(1,OUTPUT);
    }

    void loop ()
    {
      digitalWrite(0,HIGH);
      delay(1000);
      digitalWrite(0,LOW);
      delay(1000);
    }

What do I need to do? Should I use a "while" loop? If so, how?
Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right.
Any help is appreciated, even if it doesn't answer all of my questions.
Thank you.

title: Programming a motor with an RGB

Answers: 1

body:
Try this:

    void setup ()
    {
      pinMode(0,OUTPUT); //IB1
      pinMode(1,OUTPUT); //IA1
    //  pinMode(2,OUTPUT); //IB2
    //  pinMode(3,OUTPUT); //IA2
      pinMode(4,OUTPUT); //RGB red
      pinMode(5,OUTPUT); //RGB green
      pinMode(6,OUTPUT); //RGB blue
      boolean motorOn = false;
    }

    void loop ()
    {
      digitalWrite(0,motorOn);
      if(motorOn) {
        digitalWrite(4,HIGH);  // red on
        digitalWrite(5,LOW);   // green off
        digitalWrite(6,LOW);   // blue off
      }
        digitalWrite(4,LOW);   // red off
        digitalWrite(5,HIGH);  // green on
        digitalWrite(6,LOW);   // blue off
      }
      delay(1000);             // wait
      motorOn = !motorOn;      // toggle the status of the motor.
    }

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:

    void setup ()
    {
      pinMode(0,OUTPUT);   //IB1
      pinMode(1,OUTPUT);   //IA1
    //  pinMode(2,OUTPUT); //IB2
    //  pinMode(3,OUTPUT); //IA2
      pinMode(4,OUTPUT);   //RGB red
      pinMode(5,OUTPUT);   //RGB green
      pinMode(6,OUTPUT);   //RGB blue
      boolean motorOn = false;
    }

    void loop ()
    {
      motorOn = false;
      digitalWrite(0,motorOn);
      updateLEDs();            // update the LED status
      delay(1000);             // wait
      motorOn = true;          // toggle the status of the motor.
      digitalWrite(0,motorOn);
      updateLEDs();            // update the LED status
      delay(750);              // wait a different time
    }

    void updateLEDs(){
      // This routine updates the LEDs based on status of motorOn.
      if(motorOn) {
        digitalWrite(4,HIGH);  // red on
        digitalWrite(5,LOW);   // green off
        digitalWrite(6,LOW);   // blue off
      }
        digitalWrite(4,LOW);   // red off
        digitalWrite(5,HIGH);  // green on
        digitalWrite(6,LOW);   // blue off
      }
    }