message:
avrdude: stk500_recv(): programmer is not responding - OSX10.11

I'm getting the following error with a genuine Arduino Uno on Mac OSX10.11 El Capitan when uploading to it (the green light is on, the orange light flashes intermittently while attempting to upload). Here's the error:

    avrdude: stk500_recv(): programmer is not responding

I've tried all the solutions I can find. I've selected the correct port and board. I've tried pressing the `reset button` before uploading. I've tried different USB cables. I've tried unplugging and replugging everything. I've read this: `http://arduino.cc/en/Guide/Howto` .

I tried all these solutions here: https://stackoverflow.com/questions/23993111/mac-uno-avrdude-stk500-recv-programmer-is-not-responding

I tried the FTDI fix, (but not sure if was actually able to disable the mac drivers, or which drivers are now running, the example I tried is for for OSX 10.10 [Here](http://www.mommosoft.com/blog/2014/10/24/ftdi-chip-and-os-x-10-10/)). I ran into the following issue in the Terminal:

    Mac-Pro:~ m$ cd /System/Library/Extensions/IOUSBFamily.kext/Contents/PlugIns
    Mac-Pro:PlugIns m$ sudo mv AppleUSBFTDI.kext AppleUSBFTDI.disabled
    mv: rename AppleUSBFTDI.kext to AppleUSBFTDI.disabled: No such file or directory

I don't get why it says `No such file or directory` because `AppleUSBFTDI.kext` definitely exists as a package in the Extensions folder, but I guess it's talking about another file named that in the plugins folder? Confusing ... Was this moved in OSX 10.11 and should I rename this package in the Extensions folder?

I did download and install the old FTDI drivers, but I don't know if they're actually the ones working right now? How do I clarify that?

  [1]: http://www.mommosoft.com/blog/2014/10/24/ftdi-chip-and-os-x-10-10/ "Here"

Any ideas how to get this working?

I also tried on an old Mac Laptop 10.6.8 - Snow Leopard, and had the same issue :(

body:
Has this ever worked?
Can you use avrdude and hit the target?
There is a terminal mode in avrdude you can also use.  At least this would help you determine what is working.

Sounds like a configuration issue.  If you have the ability to 'follow the tail' (tail -f <logfile>) I'm assuming that you have 'like' tools we have in Linux like lsusb to assist?

You can ensure yourself that if it says it isn't found, it's not finding it, so it's not wherever it's looking. :)


sender: user

sender: assistant

body: I had this problem for some time and what I did was I deleted the Arduino IDE and reinstalled it again and it worked. Thanks!


body: Nothing I tried could get it to work. I took it back on the hunch it was a bad one, that something was just not working right on it. And got a new one directly from the Arduino people. The new one works just fine! Problem solved :D


message:
How to set up a long press with something other than a button?

I wrote a program for a night light. There are 4 modes:

 - on,
 - adjustable brightness,
 - timer,
 - off.

For input, instead of using a button, I am using a distance sensor. Once a certain distance is read (eg. when passing your hand over the distance sensor) it changes to the next mode.

For the adjustable brightness mode it reads the distance sensor and is mapped to a PWM. The output pin is connected to a MOSFET which is switching a 12 volt LED.

This seems a slow way to cycle thru the system. I would like instead, if the user waved their hand over the sensor, it would turn on or off. However, if the user waited for 3 seconds with their hand over the sensor it would enable a dimmable mode. I'm not concerned about the timer function anymore and will be removing it.

All the code is already there except I need help writing a function that will keep track of how long its been reading a certain distance. Let's say for instance if the sensor reads a distance between 1 inch to 3 inches for 3 seconds it will then go into the dimmable mode. If it's under that then it will only toggle on/off. If the hand remains longer then 3 seconds it will also trigger the dimmable mode.

    //----------------------------------------------------------
    // USING A DISTANCE SENSOR TO CYCLE THRU DIFFERENT MODE
    // FOR AN LED NIGHT LIGHT
    // vonderasche
    //----------------------------------------------------------

    // declares library for distance sensor
    #include <NewPing.h>
    // constants
    #define TRIGGER_PIN  12
    #define ECHO_PIN     13
    #define MAX_DISTANCE 200
    const unsigned long onTime = 5000;
    const unsigned long onTimer = 1200000;

    int state = 1;

    // declares NewPing object
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

    void loop() {
     delay(50);
     // take distances reading
     int distance = sonar.ping_in();
     static enum { ON, ADJUST, TIMER } state;

     // if distance range is between certain values switch the state
     if (distance > 1 && distance < 3) {
      switch(state) {
      case ON:
        {
       // turns LEDs on
       Serial.println("ON");
       analogWrite(3, 255);
       analogWrite(5, 255);
       state = ADJUST;
       delay(1000);
              }
              break;
      case ADJUST:
              {
       // allows user to set brightness based on hand distance to sensor
       Serial.println("Adjusting Brightness");
       int distance2 = 0;
       int mappedBrightness = 0;
       unsigned long previousMillis = millis();
       unsigned long currentMillis = millis();

       // timer for setting brightness
       while ((currentMillis - previousMillis) < onTime) {
        int distance2 = sonar.ping_in();
        if (distance2 >= 1 && distance2 <= 6) {
         mappedBrightness = map(distance2, 0, 6, 13, 255);
         analogWrite(3, mappedBrightness);
         analogWrite(5, mappedBrightness);
        }
        currentMillis = millis();
       }
       Serial.print("Mapped Brightness = ");
       Serial.println(mappedBrightness);
       delay(1000);
       state = TIMER;
              }
              break;

      case TIMER:
              {
       Serial.println("TIMER - 20 MINS");
       // variable declaration
       unsigned long ontime = 50;
       unsigned long previousMillis = millis();
       unsigned long currentMillis = millis();

       // dims leds to 25 percent
       analogWrite(3, 64);
       analogWrite(5, 64);
       delay(1000);
       // timer for leds
       while ((currentMillis - previousMillis) < onTimer) {
        int distance2 = sonar.ping_in();
        //breaks timer if hand swipe
        if (distance2 >= 1 && distance2 <= 4) {
         break;
        }
        currentMillis = millis();
       }
       // turn off leds - either hand swipe happened or timer is up
       Serial.println("Turn off LEDs.");
       analogWrite(3, 0);
       analogWrite(5, 0);
       delay(1000);
       state = ON;
              }
              break;
      }
     }
    }

body:
This is not too different from the long press of a button. Lets consider the code to detect a long button press of greater than 3 seconds.

    buttonState = digitalRead(PIN1);

    if (buttonstate == HIGH)
    {
        if ((currentMillis - previousMillis) > THREE_SECONDS)
        {
            // Put your code here
        }
    }
    else  // ie. buttonState == LOW
    {
        previousMillis = currentMillis;
    }

OK, so the code could be optimized. However, it shows the code for a long button press and hopefully its easy to understand for any newbies out there. The code above reads the button state and if it is HIGH (ie. pressed), it will then check to see if the timer has run for more than 3 seconds. However, if the button is released, the timer resets.

Now lets consider the code for a distance sensor:

    int distance = sonar.ping_in();

    if (distance >= 1 && distance <= 3)
    {
        if ((currentMillis - previousMillis) > THREE_SECONDS)
        {
            // Put your code here
        }
    }
    else  // ie. outside of the range
    {
        previousMillis = currentMillis;
    }

You will notice that only the first two lines change. I hope this helps!!


message:
List of connected clients to server

I have a server on my arduino (WiFi) and want to save the clients that connect, so that I can send to them (to each separately) data later.

Is the best data structure a _linked list_? How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles? How can I detect when they disconnect in order to delete them?

Of course, I read the [ref][1]; but I cannot find the answers there.
Here is my minimal example (The maximum number of simultaneous connections is 5):

**EDIT** Keep in mind, that I just want to have a simple connection using the WiFiClient/ WiFiServer class and not a HTTP-Webserver

    #include <WiFi.h>

    WiFiServer server(23);
    void setup() {
      server.begin();
    }

    void loop() {
      WiFiClient client = server.available();

      if (client) {
        //if not seen yet, add to a linked list (?)
      }
    }

  [1]: https://www.arduino.cc/en/Reference/WiFi

body:
The [WiFiClient.h header][1] and [WifiClient.cpp source][2] files are useful for reference.
> Is the best data structure a linked list?

Probably not here.  [Possibly not ever][3].  It's a load of effort to implement, and won't give you any benefit.  Just create an array of them:

    WiFiClient clients[5];

Then perhaps something like

    WiFiClient newClient = server.available();
    if (newClient) {
        // TODO: Check whether we have an existing connection from this IP
        // TODO: Get the first 'free' array index
        clients[firstFree] = newClient;
    }

> How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles?

Get the remote IP address of the new client

    IPAddress = newClient.remoteIP();

Do the same with all the connected clients in your array* and compare them.  If you find a match, drop the connection

    newClient.disconnect();

and, probably, don't put it in the array.

> How can I detect when they disconnect in order to delete them?

    if (client[i].connected())

Lastly, how do we keep track of which items in our array are current active connections, and which aren't (either not yet used, or already disconnected).  You could do this several ways.  One would be to iterate through the array, checking whether the item is valid and connected:

    // Returns -1 if no free slots
    int firstFree() {
        for(int i=0 ; i<5 ; ++i) {
            if(!clients[i] || !clients[i].connected()) return i;
        }
        return -1;
    }

All code untested so you may find typos, but I believe it's basically correct.

  [1]: https://github.com/codebendercc/arduino-library-files/blob/master/libraries/WiFi/WiFiClient.h
  [2]: https://github.com/codebendercc/arduino-library-files/blob/master/libraries/WiFi/WiFiClient.cpp
  [3]: https://www.youtube.com/watch?v=YQs6IC-vgmo


body:
> I have a server on my arduino (WiFi) and want to save the clients that connect, so that I can send to them (to each separately) data later.

The question (and some of the answers) seem to misunderstand how HTTP works. I know how it works (at least to an extent) as I have written server scripts in Lua, as well as C++ for the Arduino.

As I mention in [my page about an Arduino HTTP server](http://www.gammon.com.au/forum/?id=12942) when the client initiates a request it sends an HTTP header along these lines:

    POST /forum/showpost.php?id=12345&page=2 HTTP/1.1
    User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0)
    Host: www.example.com
    Cookie: foo=bar;
    Accept-Language: en, mi

    action=save&user_id=1234

Breaking those parts down you get this:

[![HTTP message structure][1]][1]

Once the client has sent the request it awaits (on the same connection) for the server to respond. The response may look something like this:

<!-- language: lang-html -->

    HTTP/1.1 200 OK
    Content-Type: text/html
    Connection: close
    Server: HTTPserver/1.0.0 (Arduino)

    <!DOCTYPE html>
    <html>

    <head>
    <title>Arduino test</title>
    </head>

    <body>
    <h1> My heading </h1>
    <p>Some text
    </body>
    </html>

Notice the blank line between the HTTP header and the actual file data (the HTML data).

---

Under HTTP 1.1 the server can request that the connection keep open the connection by replacing:

    Connection: close

by:

    Connection: keep-alive

All this means is that the client is still connected and can now request other stuff (for example an image from an `<img>` tag). It does that by sending **another** HTTP header and then getting another response. It doesn't keep the connection open just so that the server can randomly send other stuff in the future.

*Note:* - the **default** under HTTP 1.1 is for the connections to be persistent.

---

>  ... so that I can send to them (to each separately) data later.

You don't "send data later", that's not how it works. The client may **request** data later.

---

The standard way of keeping track of clients which are doing stuff (like filling in a series of forms) is to use **cookies** - that is what they are for. The server sends a cookie, the client remembers it, and sends it back with the next request. The cookie identifiers that it is the same client as before, and what it was doing. For example, a cookie might contain a token to indicate that you have logged in.

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


message:
Floating pins: digitalRead returns always high or always low

I was trying to see whether my board operates as expected with random readings on floating pins. Oddly it does not. The following code produces all HIGH readings:

    #define PIN_MISO 12

    void setup() {
      pinMode(PIN_MISO, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      uint16_t data = 0;
      Serial.print("MISO digitalRead: ");
      data = digitalRead(PIN_MISO);
      Serial.println(data, BIN);
      delay(300);
    }

    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1
    MISO digitalRead: 1

I tried grounding pin 12 and after a few seconds the readings all came back LOW as expected. However leaving it floating produces all HIGH instead of random readings.

I tried the same program for pins 3 and then A3 with more weird output: all LOW.

What am I missing here?

body:
Floating means it would generate any value. This could be a result of innumerable factors and it is HIGH in this case! you cannot expect anything other than a HIGH or LOW.

Think of it this way-
It's fluctuating in a range of about 900-1000 but the range is still very close to 1023 hence it results in a HIGH.

Some other time it may be near the lower values then it would show LOW.


message:
Do I need a transistor if my relay has an optocoupler?

I'm looking to use this [relay]  with my arduino. It has an optocoupler and correct me if I'm wrong but this should prevent any back EMF from affecting my arduino. Do I still need to use a transistor?

  [relay]: http://www.ebay.com/itm/5V-1-2-4-8-Channel-Relay-Board-Module-Optocoupler-LED-for-Arduino-PiC-ARM-AVRC-/311672067486

body:
That isn't just a relay you are linking to. That's an entire board that, among others, contains a relay (blue box). This board already has a transistor to drive the coil inside the relay. It also has a diode to handle back EMF.

It even has a opto-coupler, thought that isn't that useful as in most cases both sides of the opto-coupler are powered by the same 5V coming from the arduino.


body:
Gerben is right. That is a complete board, not a relay. I have used some of these and they do not require a transistor to drive them (although you could use one if power output from the ports are a concern).
I beg to differ from Gerben, as the optocoupler isolates the pin from the driving circuit (even if it does not isolate the regulator) it still retains much of its safety characteristics.


message:
Having Arduino read a video game screen

I want to connect my Arduino to my tv screen while playing a playstation/XBox game. When a certain screen comes up (like say when you die the same screen pops up) then I want Arduino to catch that and then trigger another device on and off. How might I be able to trigger something by having arduino read the screen then trigger something on and off?

body:
Most Arduino platforms contain a very low power embedded processor.  As such it is very unlikely such a device will decode an NTSC or PAL signal let alone modern digitally compressed video.

Instead consider using a light sensor attached to your monitor.  This is more in line with what, for instance, the Arduino Uno is capable of.  If you can identify a spot on the monitor that will only change to a certain brightness at the conclusion of a game, you could look for that brightness level using a light sensor attached to the monitor and connected to an Arduino.

[Here is a tutorial][1] about using a light sensor with an Arduino.  Most of the circuit is for the display of which you need not bother with.

  [1]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-arduino-lesson-9-sensing-light.pdf


message:
Multiple tones with one piezo buzzer

I have figured out how to make a piezo buzzer play two tones at once with `analogWrite()` and `tone()` but how would I make an actual song by playing both bass and treble, such as [this one][1]. Here is the circuit I had to do it:

[![Circuit][2]][2]

and here is the code I had to do it:

    int buzzer1 = 9;
    int buzzer2 = 10;

    void setup() {
      pinMode(buzzer1, OUTPUT);
      pinMode(buzzer2, OUTPUT);
    }

    void loop() {
      analogWrite(buzzer1, 100);
      tone(buzzer2, 262);
    }

  [1]: http://makingmusicfun.net/images/thumbs/twinkle-twinkle-little-star-piano-solo.jpg
  [2]: https://i.stack.imgur.com/H2Q1R.png

body:
First of all - You can drain max 20mA via pin, when one of the pins is HIGH and the other LOW, there is 5V between them, so there should be at least 250 Ohm resistor placed there, if you do not want damage your Arduino. I sugest add, to each of the red wires, at least a 200 Ohm resistor (to be safe).

For playing melody you have to save it somewhere, probabely easiest way is in arrays, and then play it note by note at regular intervals.

something like this (but insert your notes and set the length correctly):

    int num_tones=6;
    int tones1[] = {100,200,400,200,100,50};
    int tones2[] = {262,131,131,262,131,524};

    void loop() {
      for (int i=0;i<num_tones;i++){
        analogWrite(buzzer1, tones1[i]);
        tone(buzzer2,tones2[i]);
        delay(250);
      }
    }


body:
I completed the following project https://github.com/linhartr22/count

Plays PWM files on Arduino through piezo speaker.

Most of the results came from the following page:

http://highlowtech.org/?p=1963

I'm using the https://github.com/damellis/PCM/zipball/master library mentioned there. count.ino is my sample sketch. As the web site mentions the audio comes out on Digital I/O pin 11. I've tested with both a piezo buzzer and a 4 ohm speaker. I'm really impressed. It does mess with some of the PWM timers so this may not be suitable for all applications.

I used Audacity to convert the sample wave files I was provided into PWM. The .h files are included in this repo.

The number of notes you can hold on the Arduino will depend on the size of the wave samples. If you need more notes, it might be possible to extend this with an SD card reader or other form of memory. It wasn't required for my project.


message:
Get pixel data with OV7670 (w/o FIFO) and Arduino Uno

I have read a great deal today about interfacing the OV7670 with the Arduino Uno. I decided to jump in and start tinkering with this thing. I wired it up according to this schematic:
[![Wiring Diagram][1]][1]

And I copied and pasted the sketch I found here (http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/step3/Upload-sketch-to-Arduino/):

    // Source code for application to transmit image from ov7670 to PC via USB
    // By Siarhei Charkes in 2015
    // http://privateblog.info
    //

    #include <stdint.h>
    #include <avr/io.h>
    #include <util/twi.h>
    #include <util/delay.h>
    #include <avr/pgmspace.h>

    #define F_CPU 16000000UL
    #define vga   0
    #define qvga  1
    #define qqvga   2
    #define yuv422  0
    #define rgb565  1
    #define bayerRGB  2
    #define camAddr_WR  0x42
    #define camAddr_RD  0x43

    /* Registers */
    #define REG_GAIN    0x00  /* Gain lower 8 bits (rest in vref) */
    #define REG_BLUE    0x01  /* blue gain */
    #define REG_RED       0x02  /* red gain */
    #define REG_VREF    0x03  /* Pieces of GAIN, VSTART, VSTOP */
    #define REG_COM1    0x04  /* Control 1 */
    #define COM1_CCIR656  0x40    /* CCIR656 enable */

    #define REG_BAVE    0x05  /* U/B Average level */
    #define REG_GbAVE   0x06  /* Y/Gb Average level */
    #define REG_AECHH   0x07  /* AEC MS 5 bits */
    #define REG_RAVE    0x08  /* V/R Average level */
    #define REG_COM2    0x09  /* Control 2 */
    #define COM2_SSLEEP         0x10  /* Soft sleep mode */
    #define REG_PID           0x0a  /* Product ID MSB */
    #define REG_VER           0x0b  /* Product ID LSB */
    #define REG_COM3    0x0c  /* Control 3 */
    #define COM3_SWAP         0x40  /* Byte swap */
    #define COM3_SCALEEN          0x08  /* Enable scaling */
    #define COM3_DCWEN          0x04  /* Enable downsamp/crop/window */
    #define REG_COM4    0x0d  /* Control 4 */
    #define REG_COM5    0x0e  /* All "reserved" */
    #define REG_COM6    0x0f  /* Control 6 */
    #define REG_AECH    0x10  /* More bits of AEC value */
    #define REG_CLKRC   0x11  /* Clocl control */
    #define CLK_EXT           0x40  /* Use external clock directly */
    #define CLK_SCALE   0x3f  /* Mask for internal clock scale */
    #define REG_COM7    0x12  /* Control 7 */ //REG mean address.
    #define COM7_RESET          0x80  /* Register reset */
    #define COM7_FMT_MASK         0x38
    #define COM7_FMT_VGA          0x00
    #define COM7_FMT_CIF          0x20  /* CIF format */
    #define COM7_FMT_QVGA         0x10  /* QVGA format */
    #define COM7_FMT_QCIF         0x08  /* QCIF format */
    #define COM7_RGB          0x04  /* bits 0 and 2 - RGB format */
    #define COM7_YUV          0x00  /* YUV */
    #define COM7_BAYER          0x01  /* Bayer format */
    #define COM7_PBAYER         0x05  /* "Processed bayer" */
    #define REG_COM8    0x13  /* Control 8 */
    #define COM8_FASTAEC          0x80  /* Enable fast AGC/AEC */
    #define COM8_AECSTEP          0x40  /* Unlimited AEC step size */
    #define COM8_BFILT    0x20  /* Band filter enable */
    #define COM8_AGC    0x04  /* Auto gain enable */
    #define COM8_AWB    0x02  /* White balance enable */
    #define COM8_AEC    0x01  /* Auto exposure enable */
    #define REG_COM9    0x14  /* Control 9- gain ceiling */
    #define REG_COM10   0x15  /* Control 10 */
    #define COM10_HSYNC         0x40  /* HSYNC instead of HREF */
    #define COM10_PCLK_HB         0x20  /* Suppress PCLK on horiz blank */
    #define COM10_HREF_REV          0x08  /* Reverse HREF */
    #define COM10_VS_LEAD         0x04  /* VSYNC on clock leading edge */
    #define COM10_VS_NEG          0x02  /* VSYNC negative */
    #define COM10_HS_NEG          0x01  /* HSYNC negative */
    #define REG_HSTART    0x17  /* Horiz start high bits */
    #define REG_HSTOP   0x18  /* Horiz stop high bits */
    #define REG_VSTART    0x19  /* Vert start high bits */
    #define REG_VSTOP   0x1a  /* Vert stop high bits */
    #define REG_PSHFT   0x1b  /* Pixel delay after HREF */
    #define REG_MIDH    0x1c  /* Manuf. ID high */
    #define REG_MIDL    0x1d  /* Manuf. ID low */
    #define REG_MVFP    0x1e  /* Mirror / vflip */
    #define MVFP_MIRROR         0x20  /* Mirror image */
    #define MVFP_FLIP   0x10  /* Vertical flip */

    #define REG_AEW           0x24  /* AGC upper limit */
    #define REG_AEB           0x25    /* AGC lower limit */
    #define REG_VPT           0x26  /* AGC/AEC fast mode op region */
    #define REG_HSYST   0x30  /* HSYNC rising edge delay */
    #define REG_HSYEN   0x31  /* HSYNC falling edge delay */
    #define REG_HREF    0x32  /* HREF pieces */
    #define REG_TSLB    0x3a  /* lots of stuff */
    #define TSLB_YLAST    0x04  /* UYVY or VYUY - see com13 */
    #define REG_COM11   0x3b  /* Control 11 */
    #define COM11_NIGHT         0x80  /* NIght mode enable */
    #define COM11_NMFR          0x60  /* Two bit NM frame rate */
    #define COM11_HZAUTO          0x10  /* Auto detect 50/60 Hz */
    #define COM11_50HZ          0x08  /* Manual 50Hz select */
    #define COM11_EXP   0x02
    #define REG_COM12   0x3c  /* Control 12 */
    #define COM12_HREF          0x80  /* HREF always */
    #define REG_COM13   0x3d  /* Control 13 */
    #define COM13_GAMMA         0x80  /* Gamma enable */
    #define COM13_UVSAT         0x40  /* UV saturation auto adjustment */
    #define COM13_UVSWAP          0x01  /* V before U - w/TSLB */
    #define REG_COM14   0x3e  /* Control 14 */
    #define COM14_DCWEN         0x10  /* DCW/PCLK-scale enable */
    #define REG_EDGE    0x3f  /* Edge enhancement factor */
    #define REG_COM15   0x40  /* Control 15 */
    #define COM15_R10F0         0x00  /* Data range 10 to F0 */
    #define COM15_R01FE         0x80  /*      01 to FE */
    #define COM15_R00FF         0xc0  /*      00 to FF */
    #define COM15_RGB565          0x10  /* RGB565 output */
    #define COM15_RGB555          0x30  /* RGB555 output */
    #define REG_COM16   0x41  /* Control 16 */
    #define COM16_AWBGAIN         0x08  /* AWB gain enable */
    #define REG_COM17   0x42  /* Control 17 */
    #define COM17_AECWIN          0xc0  /* AEC window - must match COM4 */
    #define COM17_CBAR          0x08  /* DSP Color bar */
    /*
    * This matrix defines how the colors are generated, must be
    * tweaked to adjust hue and saturation.
    *
    * Order: v-red, v-green, v-blue, u-red, u-green, u-blue
    * They are nine-bit signed quantities, with the sign bit
    * stored in0x58.Sign for v-red is bit 0, and up from there.
    */
    #define REG_CMATRIX_BASE  0x4f
    #define CMATRIX_LEN           6
    #define REG_CMATRIX_SIGN  0x58
    #define REG_BRIGHT    0x55  /* Brightness */
    #define REG_CONTRAS         0x56  /* Contrast control */
    #define REG_GFIX    0x69  /* Fix gain control */
    #define REG_REG76   0x76  /* OV's name */
    #define R76_BLKPCOR         0x80  /* Black pixel correction enable */
    #define R76_WHTPCOR         0x40  /* White pixel correction enable */
    #define REG_RGB444          0x8c  /* RGB 444 control */
    #define R444_ENABLE         0x02  /* Turn on RGB444, overrides 5x5 */
    #define R444_RGBX   0x01  /* Empty nibble at end */
    #define REG_HAECC1    0x9f  /* Hist AEC/AGC control 1 */
    #define REG_HAECC2    0xa0  /* Hist AEC/AGC control 2 */
    #define REG_BD50MAX         0xa5  /* 50hz banding step limit */
    #define REG_HAECC3    0xa6  /* Hist AEC/AGC control 3 */
    #define REG_HAECC4    0xa7  /* Hist AEC/AGC control 4 */
    #define REG_HAECC5    0xa8  /* Hist AEC/AGC control 5 */
    #define REG_HAECC6    0xa9  /* Hist AEC/AGC control 6 */
    #define REG_HAECC7    0xaa  /* Hist AEC/AGC control 7 */
    #define REG_BD60MAX         0xab  /* 60hz banding step limit */
    #define REG_GAIN    0x00  /* Gain lower 8 bits (rest in vref) */
    #define REG_BLUE    0x01  /* blue gain */
    #define REG_RED           0x02  /* red gain */
    #define REG_VREF    0x03  /* Pieces of GAIN, VSTART, VSTOP */
    #define REG_COM1    0x04  /* Control 1 */
    #define COM1_CCIR656          0x40  /* CCIR656 enable */
    #define REG_BAVE    0x05  /* U/B Average level */
    #define REG_GbAVE   0x06  /* Y/Gb Average level */
    #define REG_AECHH   0x07  /* AEC MS 5 bits */
    #define REG_RAVE    0x08  /* V/R Average level */
    #define REG_COM2    0x09  /* Control 2 */
    #define COM2_SSLEEP         0x10  /* Soft sleep mode */
    #define REG_PID           0x0a  /* Product ID MSB */
    #define REG_VER           0x0b  /* Product ID LSB */
    #define REG_COM3    0x0c  /* Control 3 */
    #define COM3_SWAP         0x40  /* Byte swap */
    #define COM3_SCALEEN          0x08  /* Enable scaling */
    #define COM3_DCWEN          0x04  /* Enable downsamp/crop/window */
    #define REG_COM4    0x0d  /* Control 4 */
    #define REG_COM5    0x0e  /* All "reserved" */
    #define REG_COM6    0x0f  /* Control 6 */
    #define REG_AECH    0x10  /* More bits of AEC value */
    #define REG_CLKRC   0x11  /* Clocl control */
    #define CLK_EXT           0x40  /* Use external clock directly */
    #define CLK_SCALE   0x3f  /* Mask for internal clock scale */
    #define REG_COM7    0x12  /* Control 7 */
    #define COM7_RESET          0x80  /* Register reset */
    #define COM7_FMT_MASK         0x38
    #define COM7_FMT_VGA          0x00
    #define COM7_FMT_CIF          0x20  /* CIF format */
    #define COM7_FMT_QVGA         0x10  /* QVGA format */
    #define COM7_FMT_QCIF         0x08  /* QCIF format */
    #define COM7_RGB    0x04  /* bits 0 and 2 - RGB format */
    #define COM7_YUV    0x00  /* YUV */
    #define COM7_BAYER          0x01  /* Bayer format */
    #define COM7_PBAYER         0x05  /* "Processed bayer" */
    #define REG_COM8    0x13  /* Control 8 */
    #define COM8_FASTAEC          0x80  /* Enable fast AGC/AEC */
    #define COM8_AECSTEP          0x40  /* Unlimited AEC step size */
    #define COM8_BFILT    0x20  /* Band filter enable */
    #define COM8_AGC    0x04  /* Auto gain enable */
    #define COM8_AWB    0x02  /* White balance enable */
    #define COM8_AEC    0x01  /* Auto exposure enable */
    #define REG_COM9    0x14  /* Control 9- gain ceiling */
    #define REG_COM10   0x15  /* Control 10 */
    #define COM10_HSYNC         0x40  /* HSYNC instead of HREF */
    #define COM10_PCLK_HB         0x20  /* Suppress PCLK on horiz blank */
    #define COM10_HREF_REV          0x08  /* Reverse HREF */
    #define COM10_VS_LEAD           0x04  /* VSYNC on clock leading edge */
    #define COM10_VS_NEG          0x02  /* VSYNC negative */
    #define COM10_HS_NEG          0x01  /* HSYNC negative */
    #define REG_HSTART    0x17  /* Horiz start high bits */
    #define REG_HSTOP   0x18  /* Horiz stop high bits */
    #define REG_VSTART    0x19  /* Vert start high bits */
    #define REG_VSTOP   0x1a  /* Vert stop high bits */
    #define REG_PSHFT   0x1b  /* Pixel delay after HREF */
    #define REG_MIDH    0x1c  /* Manuf. ID high */
    #define REG_MIDL    0x1d  /* Manuf. ID low */
    #define REG_MVFP    0x1e  /* Mirror / vflip */
    #define MVFP_MIRROR         0x20  /* Mirror image */
    #define MVFP_FLIP   0x10  /* Vertical flip */
    #define REG_AEW           0x24  /* AGC upper limit */
    #define REG_AEB           0x25  /* AGC lower limit */
    #define REG_VPT           0x26  /* AGC/AEC fast mode op region */
    #define REG_HSYST   0x30  /* HSYNC rising edge delay */
    #define REG_HSYEN   0x31  /* HSYNC falling edge delay */
    #define REG_HREF    0x32  /* HREF pieces */
    #define REG_TSLB    0x3a  /* lots of stuff */
    #define TSLB_YLAST    0x04  /* UYVY or VYUY - see com13 */
    #define REG_COM11   0x3b  /* Control 11 */
    #define COM11_NIGHT         0x80  /* NIght mode enable */
    #define COM11_NMFR          0x60  /* Two bit NM frame rate */
    #define COM11_HZAUTO          0x10  /* Auto detect 50/60 Hz */
    #define COM11_50HZ          0x08  /* Manual 50Hz select */
    #define COM11_EXP   0x02
    #define REG_COM12   0x3c  /* Control 12 */
    #define COM12_HREF          0x80  /* HREF always */
    #define REG_COM13   0x3d  /* Control 13 */
    #define COM13_GAMMA         0x80  /* Gamma enable */
    #define COM13_UVSAT         0x40  /* UV saturation auto adjustment */
    #define COM13_UVSWAP          0x01  /* V before U - w/TSLB */
    #define REG_COM14   0x3e  /* Control 14 */
    #define COM14_DCWEN         0x10  /* DCW/PCLK-scale enable */
    #define REG_EDGE    0x3f  /* Edge enhancement factor */
    #define REG_COM15   0x40  /* Control 15 */
    #define COM15_R10F0         0x00  /* Data range 10 to F0 */
    #define COM15_R01FE         0x80  /*      01 to FE */
    #define COM15_R00FF         0xc0  /*      00 to FF */
    #define COM15_RGB565          0x10  /* RGB565 output */
    #define COM15_RGB555          0x30  /* RGB555 output */
    #define REG_COM16   0x41  /* Control 16 */
    #define COM16_AWBGAIN         0x08  /* AWB gain enable */
    #define REG_COM17   0x42  /* Control 17 */
    #define COM17_AECWIN          0xc0  /* AEC window - must match COM4 */
    #define COM17_CBAR          0x08  /* DSP Color bar */

    #define CMATRIX_LEN             6
    #define REG_BRIGHT    0x55  /* Brightness */
    #define REG_REG76   0x76  /* OV's name */
    #define R76_BLKPCOR         0x80  /* Black pixel correction enable */
    #define R76_WHTPCOR         0x40  /* White pixel correction enable */
    #define REG_RGB444          0x8c  /* RGB 444 control */
    #define R444_ENABLE         0x02  /* Turn on RGB444, overrides 5x5 */
    #define R444_RGBX   0x01  /* Empty nibble at end */
    #define REG_HAECC1    0x9f  /* Hist AEC/AGC control 1 */
    #define REG_HAECC2    0xa0  /* Hist AEC/AGC control 2 */
    #define REG_BD50MAX         0xa5  /* 50hz banding step limit */
    #define REG_HAECC3    0xa6  /* Hist AEC/AGC control 3 */
    #define REG_HAECC4    0xa7  /* Hist AEC/AGC control 4 */
    #define REG_HAECC5    0xa8  /* Hist AEC/AGC control 5 */
    #define REG_HAECC6    0xa9  /* Hist AEC/AGC control 6 */
    #define REG_HAECC7    0xaa  /* Hist AEC/AGC control 7 */
    #define REG_BD60MAX         0xab  /* 60hz banding step limit */
    #define MTX1            0x4f  /* Matrix Coefficient 1 */
    #define MTX2            0x50  /* Matrix Coefficient 2 */
    #define MTX3            0x51  /* Matrix Coefficient 3 */
    #define MTX4            0x52  /* Matrix Coefficient 4 */
    #define MTX5            0x53  /* Matrix Coefficient 5 */
    #define MTX6            0x54  /* Matrix Coefficient 6 */
    #define REG_CONTRAS         0x56  /* Contrast control */
    #define MTXS            0x58  /* Matrix Coefficient Sign */
    #define AWBC7           0x59  /* AWB Control 7 */
    #define AWBC8           0x5a  /* AWB Control 8 */
    #define AWBC9           0x5b  /* AWB Control 9 */
    #define AWBC10            0x5c  /* AWB Control 10 */
    #define AWBC11            0x5d  /* AWB Control 11 */
    #define AWBC12            0x5e  /* AWB Control 12 */
    #define REG_GFI           0x69  /* Fix gain control */
    #define GGAIN           0x6a  /* G Channel AWB Gain */
    #define DBLV            0x6b
    #define AWBCTR3           0x6c  /* AWB Control 3 */
    #define AWBCTR2           0x6d  /* AWB Control 2 */
    #define AWBCTR1           0x6e  /* AWB Control 1 */
    #define AWBCTR0           0x6f  /* AWB Control 0 */

    struct regval_list{
      uint8_t reg_num;
      uint16_t value;
    };

    const struct regval_list qvga_ov7670[] PROGMEM = {
      { REG_COM14, 0x19 },
      { 0x72, 0x11 },
      { 0x73, 0xf1 },

      { REG_HSTART, 0x16 },
      { REG_HSTOP, 0x04 },
      { REG_HREF, 0xa4 },
      { REG_VSTART, 0x02 },
      { REG_VSTOP, 0x7a },
      { REG_VREF, 0x0a },

    /*  { REG_HSTART, 0x16 },
      { REG_HSTOP, 0x04 },
      { REG_HREF, 0x24 },
      { REG_VSTART, 0x02 },
      { REG_VSTOP, 0x7a },
      { REG_VREF, 0x0a },*/
      { 0xff, 0xff }, /* END MARKER */
    };

    const struct regval_list yuv422_ov7670[] PROGMEM = {
      { REG_COM7, 0x0 },  /* Selects YUV mode */
      { REG_RGB444, 0 },  /* No RGB444 please */
      { REG_COM1, 0 },
      { REG_COM15, COM15_R00FF },
      { REG_COM9, 0x6A }, /* 128x gain ceiling; 0x8 is reserved bit */
      { 0x4f, 0x80 },   /* "matrix coefficient 1" */
      { 0x50, 0x80 },   /* "matrix coefficient 2" */
      { 0x51, 0 },    /* vb */
      { 0x52, 0x22 },   /* "matrix coefficient 4" */
      { 0x53, 0x5e },   /* "matrix coefficient 5" */
      { 0x54, 0x80 },   /* "matrix coefficient 6" */
      { REG_COM13, COM13_UVSAT },
      { 0xff, 0xff },   /* END MARKER */
    };

    const struct regval_list ov7670_default_regs[] PROGMEM = {//from the linux driver
      { REG_COM7, COM7_RESET },
      { REG_TSLB, 0x04 }, /* OV */
      { REG_COM7, 0 },  /* VGA */
      /*
      * Set the hardware window.  These values from OV don't entirely
      * make sense - hstop is less than hstart.  But they work...
      */
      { REG_HSTART, 0x13 }, { REG_HSTOP, 0x01 },
      { REG_HREF, 0xb6 }, { REG_VSTART, 0x02 },
      { REG_VSTOP, 0x7a }, { REG_VREF, 0x0a },

      { REG_COM3, 0 }, { REG_COM14, 0 },
      /* Mystery scaling numbers */
      { 0x70, 0x3a }, { 0x71, 0x35 },
      { 0x72, 0x11 }, { 0x73, 0xf0 },
      { 0xa2,/* 0x02 changed to 1*/1 }, { REG_COM10, 0x0 },
      /* Gamma curve values */
      { 0x7a, 0x20 }, { 0x7b, 0x10 },
      { 0x7c, 0x1e }, { 0x7d, 0x35 },
      { 0x7e, 0x5a }, { 0x7f, 0x69 },
      { 0x80, 0x76 }, { 0x81, 0x80 },
      { 0x82, 0x88 }, { 0x83, 0x8f },
      { 0x84, 0x96 }, { 0x85, 0xa3 },
      { 0x86, 0xaf }, { 0x87, 0xc4 },
      { 0x88, 0xd7 }, { 0x89, 0xe8 },
      /* AGC and AEC parameters.  Note we start by disabling those features,
      then turn them only after tweaking the values. */
      { REG_COM8, COM8_FASTAEC | COM8_AECSTEP },
      { REG_GAIN, 0 }, { REG_AECH, 0 },
      { REG_COM4, 0x40 }, /* magic reserved bit */
      { REG_COM9, 0x18 }, /* 4x gain + magic rsvd bit */
      { REG_BD50MAX, 0x05 }, { REG_BD60MAX, 0x07 },
      { REG_AEW, 0x95 }, { REG_AEB, 0x33 },
      { REG_VPT, 0xe3 }, { REG_HAECC1, 0x78 },
      { REG_HAECC2, 0x68 }, { 0xa1, 0x03 }, /* magic */
      { REG_HAECC3, 0xd8 }, { REG_HAECC4, 0xd8 },
      { REG_HAECC5, 0xf0 }, { REG_HAECC6, 0x90 },
      { REG_HAECC7, 0x94 },
      { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC },
      { 0x30, 0 }, { 0x31, 0 },//disable some delays
      /* Almost all of these are magic "reserved" values.  */
      { REG_COM5, 0x61 }, { REG_COM6, 0x4b },
      { 0x16, 0x02 }, { REG_MVFP, 0x07 },
      { 0x21, 0x02 }, { 0x22, 0x91 },
      { 0x29, 0x07 }, { 0x33, 0x0b },
      { 0x35, 0x0b }, { 0x37, 0x1d },
      { 0x38, 0x71 }, { 0x39, 0x2a },
      { REG_COM12, 0x78 }, { 0x4d, 0x40 },
      { 0x4e, 0x20 }, { REG_GFIX, 0 },
      /*{0x6b, 0x4a},*/{ 0x74, 0x10 },
      { 0x8d, 0x4f }, { 0x8e, 0 },
      { 0x8f, 0 }, { 0x90, 0 },
      { 0x91, 0 }, { 0x96, 0 },
      { 0x9a, 0 }, { 0xb0, 0x84 },
      { 0xb1, 0x0c }, { 0xb2, 0x0e },
      { 0xb3, 0x82 }, { 0xb8, 0x0a },

      /* More reserved magic, some of which tweaks white balance */
      { 0x43, 0x0a }, { 0x44, 0xf0 },
      { 0x45, 0x34 }, { 0x46, 0x58 },
      { 0x47, 0x28 }, { 0x48, 0x3a },
      { 0x59, 0x88 }, { 0x5a, 0x88 },
      { 0x5b, 0x44 }, { 0x5c, 0x67 },
      { 0x5d, 0x49 }, { 0x5e, 0x0e },
      { 0x6c, 0x0a }, { 0x6d, 0x55 },
      { 0x6e, 0x11 }, { 0x6f, 0x9e }, /* it was 0x9F "9e for advance AWB" */
      { 0x6a, 0x40 }, { REG_BLUE, 0x40 },
      { REG_RED, 0x60 },
      { REG_COM8, COM8_FASTAEC | COM8_AECSTEP | COM8_AGC | COM8_AEC | COM8_AWB },

      /* Matrix coefficients */
      { 0x4f, 0x80 }, { 0x50, 0x80 },
      { 0x51, 0 },    { 0x52, 0x22 },
      { 0x53, 0x5e }, { 0x54, 0x80 },
      { 0x58, 0x9e },

      { REG_COM16, COM16_AWBGAIN }, { REG_EDGE, 0 },
      { 0x75, 0x05 }, { REG_REG76, 0xe1 },
      { 0x4c, 0 },     { 0x77, 0x01 },
      { REG_COM13, /*0xc3*/0x48 }, { 0x4b, 0x09 },
      { 0xc9, 0x60 },   /*{REG_COM16, 0x38},*/
      { 0x56, 0x40 },

      { 0x34, 0x11 }, { REG_COM11, COM11_EXP | COM11_HZAUTO },
      { 0xa4, 0x82/*Was 0x88*/ }, { 0x96, 0 },
      { 0x97, 0x30 }, { 0x98, 0x20 },
      { 0x99, 0x30 }, { 0x9a, 0x84 },
      { 0x9b, 0x29 }, { 0x9c, 0x03 },
      { 0x9d, 0x4c }, { 0x9e, 0x3f },
      { 0x78, 0x04 },

      /* Extra-weird stuff.  Some sort of multiplexor register */
      { 0x79, 0x01 }, { 0xc8, 0xf0 },
      { 0x79, 0x0f }, { 0xc8, 0x00 },
      { 0x79, 0x10 }, { 0xc8, 0x7e },
      { 0x79, 0x0a }, { 0xc8, 0x80 },
      { 0x79, 0x0b }, { 0xc8, 0x01 },
      { 0x79, 0x0c }, { 0xc8, 0x0f },
      { 0x79, 0x0d }, { 0xc8, 0x20 },
      { 0x79, 0x09 }, { 0xc8, 0x80 },
      { 0x79, 0x02 }, { 0xc8, 0xc0 },
      { 0x79, 0x03 }, { 0xc8, 0x40 },
      { 0x79, 0x05 }, { 0xc8, 0x30 },
      { 0x79, 0x26 },
      { 0xff, 0xff }, /* END MARKER */
    };

    void error_led(void){
      DDRB |= 32;//make sure led is output
      while (1){//wait for reset
        PORTB ^= 32;// toggle led
        _delay_ms(100);
      }
    }

    void twiStart(void){
      TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN);//send start
      while (!(TWCR & (1 << TWINT)));//wait for start to be transmitted
      if ((TWSR & 0xF8) != TW_START)
        error_led();
    }

    void twiWriteByte(uint8_t DATA, uint8_t type){
      TWDR = DATA;
      TWCR = _BV(TWINT) | _BV(TWEN);
      while (!(TWCR & (1 << TWINT))) {}
      if ((TWSR & 0xF8) != type)
        error_led();
    }

    void twiAddr(uint8_t addr, uint8_t typeTWI){
      TWDR = addr;//send address
      TWCR = _BV(TWINT) | _BV(TWEN);    /* clear interrupt to start transmission */
      while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
      if ((TWSR & 0xF8) != typeTWI)
        error_led();
    }

    void wrReg(uint8_t reg, uint8_t dat){
      //send start condition
      twiStart();
      twiAddr(camAddr_WR, TW_MT_SLA_ACK);
      twiWriteByte(reg, TW_MT_DATA_ACK);
      twiWriteByte(dat, TW_MT_DATA_ACK);
      TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
      _delay_ms(1);
    }

    static uint8_t twiRd(uint8_t nack){
      if (nack){
        TWCR = _BV(TWINT) | _BV(TWEN);
        while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
        if ((TWSR & 0xF8) != TW_MR_DATA_NACK)
          error_led();
        return TWDR;
      }
      else{
        TWCR = _BV(TWINT) | _BV(TWEN) | _BV(TWEA);
        while ((TWCR & _BV(TWINT)) == 0); /* wait for transmission */
        if ((TWSR & 0xF8) != TW_MR_DATA_ACK)
          error_led();
        return TWDR;
      }
    }

    uint8_t rdReg(uint8_t reg){
      uint8_t dat;
      twiStart();
      twiAddr(camAddr_WR, TW_MT_SLA_ACK);
      twiWriteByte(reg, TW_MT_DATA_ACK);
      TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
      _delay_ms(1);
      twiStart();
      twiAddr(camAddr_RD, TW_MR_SLA_ACK);
      dat = twiRd(1);
      TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);//send stop
      _delay_ms(1);
      return dat;
    }

    void wrSensorRegs8_8(const struct regval_list reglist[]){
      uint8_t reg_addr, reg_val;
      const struct regval_list *next = reglist;
      while ((reg_addr != 0xff) | (reg_val != 0xff)){
        reg_addr = pgm_read_byte(&next->reg_num);
        reg_val = pgm_read_byte(&next->value);
        wrReg(reg_addr, reg_val);
        next++;
      }
    }

    void setColor(void){
      wrSensorRegs8_8(yuv422_ov7670);
    }

    void setRes(void){
      wrReg(REG_COM3, 4); // REG_COM3 enable scaling
      wrSensorRegs8_8(qvga_ov7670);
    }

    void camInit(void){
      wrReg(0x12, 0x80);
      _delay_ms(100);
      wrSensorRegs8_8(ov7670_default_regs);
      wrReg(REG_COM10, 32);//PCLK does not toggle on HBLANK.
    }

    void arduinoUnoInut(void) {
      cli();//disable interrupts

        /* Setup the 8mhz PWM clock
      * This will be on pin 11*/
      DDRB |= (1 << 3);//pin 11
      ASSR &= ~(_BV(EXCLK) | _BV(AS2));
      TCCR2A = (1 << COM2A0) | (1 << WGM21) | (1 << WGM20);
      TCCR2B = (1 << WGM22) | (1 << CS20);
      OCR2A = 0;//(F_CPU)/(2*(X+1))
      DDRC &= ~15;//low d0-d3 camera
      DDRD &= ~252;//d7-d4 and interrupt pins
      _delay_ms(3000);

        //set up twi for 100khz
      TWSR &= ~3;//disable prescaler for TWI
      TWBR = 72;//set to 100khz

        //enable serial
      UBRR0H = 0;
      UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate.
      UCSR0A |= 2;//double speed aysnc
      UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter
      UCSR0C = 6;//async 1 stop bit 8bit char no parity bits
    }

    void StringPgm(const char * str){
      do{
          while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
          UDR0 = pgm_read_byte_near(str);
          while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
      } while (pgm_read_byte_near(++str));
    }

    static void captureImg(uint16_t wg, uint16_t hg){
      uint16_t y, x;

      StringPgm(PSTR("*RDY*"));

      while (!(PIND & 8));//wait for high
      while ((PIND & 8));//wait for low

        y = hg;
      while (y--){
            x = wg;
          //while (!(PIND & 256));//wait for high
        while (x--){
          while ((PIND & 4));//wait for low
                UDR0 = (PINC & 15) | (PIND & 240);
              while (!(UCSR0A & (1 << UDRE0)));//wait for byte to transmit
          while (!(PIND & 4));//wait for high
          while ((PIND & 4));//wait for low
          while (!(PIND & 4));//wait for high
        }
        //  while ((PIND & 256));//wait for low
      }
        _delay_ms(100);
    }

    void setup(){
      arduinoUnoInut();
      camInit();
      setRes();
      setColor();
      wrReg(0x11, 11); //Earlier it had the value: wrReg(0x11, 12); New version works better for me :) !!!!
    }

    void loop(){
      captureImg(320, 240);
    }

The sketch has way too many `#define`s, and isn't exactly straightforward, but at least it loads, although there is one warning:

    /Users/charles/Documents/Arduino/cameraTest2/cameraTest2.ino:13:0: warning: "F_CPU" redefined
     #define F_CPU 16000000UL
     ^
    <command-line>:0:0: note: this is the location of the previous definition

To validate that this does anything, I tried playing around with [ComputerNerd's SimpleFrameGrabber][2], but I'm on a mac and I ran into problems when trying to `./build`:

    main.c:26:10: fatal error: 'SDL/SDL.h' file not found
    #include <SDL/SDL.h>

I then tried opening up the Arduino IDE Serial Monitor, and am not seeing anything. Should I be seeing anything? I was expecting I would at least see gibberish..

Ideally, I would like to find some simple example code that would setup the camera (the defaults might even be just fine), and allow me to get RGB pixel data for a 320x240 or 640x480 image. If I could just print that to the Serial Output, I could then write a simple python script to save it as a jpg or a png or something.

I just need to get to a sanity state with this thing. Or find another inexpensive camera module that's easier to work with.

  [1]: https://i.stack.imgur.com/w8xPu.png
  [2]: https://github.com/ComputerNerd/simpleFrameGrabber

body:
    //enable serial
    UBRR0H = 0;
    UBRR0L = 1;//0 = 2M baud rate. 1 = 1M baud. 3 = 0.5M. 7 = 250k 207 is 9600 baud rate.
    UCSR0A |= 2;//double speed aysnc
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);//Enable receiver and transmitter
    UCSR0C = 6;//async 1 stop bit 8bit char no parity bits

This bit enables Serial (Rx=0, Tx=1) at 1M baud. Is the Serial Monitor set to the right baud rate?


message:
Are these components connected correctly?

I intend to use two ultrasonic sensors as input and a vibration motor as its output, is this connected correctly?

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

As part of my project, I intend to use an ultrasonic sensor to feed in distance data and react through vibration motor. I have to confirm this arrangement will work but I don't own an Arduino.

  [1]: https://i.stack.imgur.com/7g6iZ.jpg

body:
in short: Definitely Not.

1 : you do really need to connect the trigger pins of the ultrassonic sensors, or else you will not be able to "trigger" them.
Read the ultrassound library examples, they may help you.

2 : I am pretty sure an analog (or digital for that matter) pin in arduino nano cannot sink the current needed to make the motor spin. You are going to fry that pin/port or even brick the entire arduino.
Read on power mosfets for the solution of that.

Moreover, i don't think the 5v out of the arduino feeding the motor is a good idea as well, as the current given by its internal regulator may not be enough for the motor as well.


message:
Win10 PCs won't see ATtiny boards

I bought some ATtiny boards on ebay but I can't get my computers to see them.  When I plug them in I get the USB connected sound then a couple of seconds later it gives the USB unplugged sound.

The power light stays on and the LED blinks, I assume it has the blink sketch already loaded.

I have added the drivers to the IDE but I reckon the problem is before that, something to do with the Win10 PC even seeing it.  I have two versions of the board, one with a USB socket and one with a USB plug, neither work.  *[UPDATE] Should have mentioned that the board doesn't show up as being connected to a port*

I've looked around for solutions with no joy, I have tried everything I can think of.

Does anyone have a suggestion on where to start troubleshooting this?

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

  [1]: https://i.stack.imgur.com/4sjJg.jpg

body:
There were a couple of comments that both led to the solution.

For me the most important was Nick's that *the board pretends to have a USB interface for a couple of seconds, and then runs the sketch*.  It stopped me tearing my hair out over why the board didn't show up as a port.

Ignacio suggested using Micronucleus.  I did this having installed the Digistump drivers and selecting them.

After compiling I was prompted to plug in the board, *voila*, it uploaded.

Thanks Stack Exchange!


message:
How to save a hex file into Arduino Flash to send it via Serial?

I have a text file with hex values formatted in the following style:

    A0 3F 55 01 00 C7 55 01 00 C7 AA 29 71 11 00 0B
    00 C7 AA 29 71 1F AA 29 71 11 55 01 A0 3F 55 DC
    ...

How can I save this data into my Arduino's Flash (to save RAM)? What libraries are needed? Is there any tool that can automatically create code for this purpose?

After I save this data into the Arduino's Flash, I want to send the data via Serial. I have to send it as binary.

A solution without saving it into the Flash would be also OK.

I am using an Arduino Due.

body:
If I understand your question correctly, you need to integrate this data into a `.ino` script.  Probably as a byte array. Then the script can read the array and `Serial.write` its content.

You could write a small tool in Python or else on your computer, that takes the text file and converts it into a `.h` header. Include that into your `.ino` script. Or use your favorite text editor to format the data into C++ code, and copy/paste that into your script.


message:
Wait for serial input otherwise start with preconfigured options

I need to input config parameters from serial input. After a period (1 min) with no input I would like the program to start with preconfigured parameters.

Currently in the `loop()` section I use `Serial.available`, which stops until it receives new data.

How can I implement that?

    void loop() {
      // read serial input
      if (Serial.available() > 0) {
        inChar = (char)Serial.read();
        inputString += inChar;

body:
The Serial.available function does NOT block execution. If you want to try, upload this

    unsigned long lastTime;
    #define LED1 5
    #define LED2 13

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

    void loop() {
      if (Serial.available() > 0)
      {
        Serial.read();
        digitalWrite(LED1, !digitalRead(LED1));
      }
      if ((millis() - lastTime) > 500)
      {
        lastTime = millis();
        digitalWrite(LED2, !digitalRead(LED2));
      }
    }

You will see led on pin 13 to turn on and off even if the serial port buffer is empty.

Maybe your problem is somewhere else. Anyway what you want can be solved this way:

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

     // Wait for one minute - millis is started at 0, so there's no
     // need to store the initial value of the waiting time
     boolean receivedConfiguration = false;
     while ((!receivedConfiguration) && (millis() < 60000))
     {
      if (Serial.available() > 0)
      {
       // There's some data; parse it

       if (__receivedDataIsComplete)
       {
        __myConfiguration = __configurationFromSerial;

        receivedConfiguration = true;
       }
      }
     }
     if (!receivedConfiguration)
     {
      __myConfiguration = __defaultConfiguration;
     }
    }

In this setup function, the microcontroller waits for one minute. If it receives the data it ends the waiting time and uses that configuration, otherwise restores the default one and goes on. In your loop you can then use the configuration.

Please note that the variables starting with a double underscore (`__`) are false variables, you will have to fill with the proper code and/or variables


message:
Using Arduino libraries for adding more functionalities to a bootloader

I have a short question to ask before putting time for research.

I have an Arduino Leonardo with the LUFA mass storage bootloader flashed. Now what I need to do is to add more functionalities to the bootloader. Because in the final product, the Leonardo board will be connected to a fitness machine (permanently connected) and the machine has Windows OS. Then the Leonardo should be able to read an RFID card (I need to add an RFID reader to the board, each user has his own RFID card) and then mount a remote server directory to the local USB Host based on the selected user.

I will have to use a wifi shield too. My question is this: is it theoretically possible to add all these functionalities to the LUFA mass storage bootloader? Because it's not possible to use the Arduino IDE for this purpose, since I'm not uploading any sketch on top of the bootloader, rather than editing the existing mass storage bootloader with the required functionalities and re-flash the chip. Am I correct? (This is what I understood after some research. And I'm a noob :D).

Could you please elaborate what would be the first step for solving this issue?

body:
From your brief description of what you want to do I think you want to:

1. Mount a Windows share on your Leonardo
2. Make said share available through USB MSD

Well, sorry to break it to you, but that is not possible. No, it's not because the Leonardo isn't up to the task, but you are trying to mix two completely different concepts.

A Windows share (*CIFS*) is a file-centric system. That is, you access files within the share and request bytes at offsets within the files. The client has no concept of the underlying filesystem, it just works on files.

A USB MSD device, in contrast, has no concept of files, directories, etc. Instead all it knows about is blocks. Raw fixed size blocks of data. The computer that it is attached to is what knows what a filesystem is. It requests blocks of data from the MSD and interprets them as a filesystem, allowing you to access the files within it.

You can see the problem you would now face? MSD responding to requests for raw blocks of data from a computer which then wants to get the contents of files from a server - how do they fit together? Simply: they don't.

So you are going to have to re-think your basic idea.

One possible idea would be to use some client-server block based system, such as iSCSI, which gives you block devices on a network (a single file which is an image of a virtual disk), though only the device which is attached to that block device through the network can see the content of it.


body:
@Majenko: I think, that the task IS possible, but it is really hard (and Leonardo may need more memory for that eventually and some shields too and so ...) but if I understand the problem, than the Leonardo should pretends to be mass storage device for that application, and pretend it have some folders and files on it, depending which RFID is used to activate it.

The application probabelly is NOT going to format the MSD because it would lose all the user data on it.

So Leonardo can do following:

 - pretend it is already formatted and have some known filesystem on it (vfat is easy enought and probabelly usable as many USB flash sticks came with it)
 - when the machine detects inserted USB, it ask for type - so it get MSD
 - then it will read partition table - Leonardo can emulate it easily, having "just one partition of given size and type" the partition can even be stored as a file on that fileserver to save Leonardo's memory.
 - next goes reading FAT table and root directory
 - - knowing  the user from RFID it is possible to select the right directory on file server,
-  then enumerate lengths of all files inside (and directories)
-  make table with the names and "offset"
- send back the FAT as if those files were ordered on the "disk" so each entry points to the following sector, until the last marks EOF
- root directory begins after FAT and contains names of the files, their lenghts, dates and starting sectors (and some very basic right like read-only, system and such)
- then follows files and directories

 - each time the machine asks for a "sector", it is possible to compute, in which file the sector is placed, read the portion of a file (potentially fill it with zeroes to "sector lenght" and return it as requested "sector"
 - if the sector is in directory instead, return the part of directory (that means filenames and such)
 - if the sector is outside it all (should not happen), return just zeroes.

On the other direction:

 - if you get something outside structure, put it to temp. file along with address of such stray "sector"
 - if you get something in a file, just replace the file content on given offset
 - if you get something in directory, you need to compare it with previous version and "rename file", "create file" or "delete file" acordingly.

 - it would probabely need two directories on the server for each user - one for actual files, other for "lost sectors" and "deleted files" which could be "reconected", "undeleted" or "attached later" to the files/directories. The second directory can be emptied after "removing USB MSD" when user with given RFID logouts.

It is lot of work, but basically it could be done. It also needs a lot of accounting on the Leonardo and lot of communication with the fileserver, but it is possible to do.

It suppose, that the files on fileserver would not be modified by somebody else while "mounted" and that the Windows machine would not "format" the USB to some kind of filesystem, the Leonardo does not understand (how to translate to the real files on server).

But for the supposed use I think those two conditions could be reasonable. The MSD probabelly just holds the "user profile" so the machine can put in records of hir/her activiti, some stats and so on, probabely it would be just a few growing files maybe even just in root directory.

Anyway I would not like to write such system, as it is terrifying lot of work and a lot of things could go wrong, if there is a bug (or bad connection).

Also the size of required memory for Leonardo is large - probabelly larger, than the Leonardo actually have, but it could be offloaded to the filesystem too (in "hidden directory" not shown to the machine) - which would be slow and hard to manage - or expanded by HW RAM, which would be a lot faster, but needs nontrivial settings.

(Remebers me, how I wrote resident program for DOS, which had just 130 bytes, which swaped in two 16KB widows of EMS where the rest of program (actually interpret of some pseudocode) was placed (it was like 4 or 6 such 16KB pages, but was able to swap itself acordingly) while the remaining two EMS pages was reserverd for data (like 300-400KB total of pseudocode and data) which was also swapped as needed to access everything. From DOS point of view it was just the 130B resident API, from the view of program, which was using it, it was 400KB engine running FORTH-like program and containing database. The result was like 3x faster processing of 2.000+ employes wages.)

Here are the memory restrictions even more tight, but I thing, that it is possible to do such thing, only it is extremely hard to make it work reliably.


message:
bridge messes up serial.print

**EDIT**
I am using an Genuino Uno & Yun Shield

I am a complete arduino noob

I am creating something where I need a process to execute a command on my yun shield but when I use `Bridge.begin();` It scrambles all text to something like this

> .ÿš2%š%šr%š%š%šr%š2%š2%º%š%š%š2%º2%º2%ºr%š2%º2%šr%šr%š%š2%šþøøþøøþúøøýýøþþþýþþøøøøúýøþÿøøþþøúýþúøøøþøýøþýúøþþøüþþøýþþøýøúø

and it just keeps adding characters. if I don't use `Bridge.begin();` then it correctly prints.

I wrote this short program to replicate the bug:

    #include <Process.h>

    void setup() {
    // put your setup code here, to run once:
    // Start the bridge and serial port.
    Bridge.begin();
    Serial.begin(9600);

     while(!Serial){

     }
    }

    void loop() {
    // put your main code here, to run repeatedly:
    Serial.println("test");
    }

So this will give the scrambled text and when you remove the `Bridge.begin();` it will show the text but I really need to use a Process in my other program so as I understand I need Bridge.

body:
`Bridge` and `Serial` both use the same pins. You cannot use them both.

`Bridge` runs at a much higher baud rate (230400 IIRC) than `Serial`, which is why it all messes up.


body:
You need to use the `Console` class instead of `Serial`. Official example [here][1].

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


message:
Keypad number input and store

i'm stuck with a little problem. I need to create a program that can store a number via keypad (this number will be chosen by the user) and then do something with it. To be more specific i will create a temperature control in which the user will be able to input a value of temperature they need and then with this value control a heater, but that's another story, the main point here is that the program needs to be able to store a value via keypad.

i use the keypad library and some of its commands like getKey() and waitForKey() and so on.

thanks for your answers!

body:
There are many issue when interfacing a processor to a physical switch.  So many that this one question can and has been broken down into several separate questions here on this web site:

 1. How to de-bounce a switch has been asked many times including [here][1].

 2. How to use pull up resistors with a switch has been asked many times including [here][2].

 3. How to scan a switch matrix has been asked many times including [here][3].

Add to that, you need to decide how to parse your data.

 - Will you always expect 2 digits?
 - If so, What will you do if the user enters 3 digits?
 - Will you support a back-space feature?
 - Hows about a clear-entry feature?
 - What about a enter-key feature?

Fortunately many of these questions are addressed in [this tutorial][4].

  [1]: https://arduino.stackexchange.com/questions/17443/how-to-simulate-delay-to-debounce-mechanical-button-using-millis
  [2]: https://arduino.stackexchange.com/questions/25353/why-are-pull-up-resistors-needed
  [3]: https://arduino.stackexchange.com/questions/31885/need-help-in-circuit-diagram-of-88-reed-switch-matrix
  [4]: http://playground.arduino.cc/Main/KeypadTutorial


body:
http://playground.arduino.cc/Code/Keypad#Example here is the setup for you, you should see, what you are pressing.

then try something like this:

    int temp=0;
    bool in_press=false;
    void loop() {
      char key = keypad.getKey();
      if (in_press &&  key == NO_KEY){ in_press=false; return;} // key released
      if ( ! in_press ){
        if (key != NO_KEY){ // if key is just pressed - proceed it
          in_press=true;
          if (key == '*') {temp=0; return;} //cancel input
          if (key == "#') { do_something_with(temp); temp=0;return;} //accept input
          // key is '0'..'9' - add it to result
          temp= temp*10 + (key-'0'); // maybe check it temp is not too high ...
          return;
        }
      }
      // this pass of loop no new key was pressed, do anything else to do
      // if we want, we can test in_press to see, if key is holded or not
      // or ignore it at all
      do_other_stuff_like_blinking_leds_or_what();
    } // end of loop()


message:
Flash String Helper object as variable

So I have a Bunch of commonly used char arrays to build commands in my library.
So to preserve memory, I have them put into flash, via PROGMEM ext,

    typedef const char PROGMEM ProgChar;
    ProgChar AT[] = "AT";
    ProgChar AT_RST[] = "RST";

Then in my program I have it all go out to A port via:

    *hws << AT << PLUS << CWMODE << EQUAL; //hws can be any Print type,

This is handled by overloading the << operator;

    static Print &operator <<(Print &obj, ProgChar* arg) {
      char pbuffbuffer[12]; //create a buffer,
      obj.print(loadProgmemVal(arg,pbuffbuffer)); //Load it, and then pass to obj print method.
      return obj;
    }

But this also overloads the << operator for all const char* Which makes me have to do a workaround:

    hws->print(1); //HACK

At first, I thought I would overload the operator to handle both a char* and a Prog Char Object, But unfortunately, they are both treated as the same thing at run-time which makes that idea useless.

So after snooping I find the __FlashStringHelper type and macro. Which would allow me to have a sepperate type for these variables, and allow me to overload.

But the problem is, I cant find a good way to Create these:

    const __FlashStringHelper MYVAR = F("Some text to be progchared");

Does not compile =/

Now I could probably make some helper method to load them all in, but that is just patching a hack with another hack... Is there any Clean way to do this? So I can use << for all types,

    *hws << AT << PLUS << CWMODE << EQUAL << 1 << "\r\n"; //1 and Return break...

body:
Is this legal?

    typedef const char ProgChar;
    ProgChar AT[] = "AT";

I would think that the PROGMEM can't be in the typedef, i.e.:

    typedef const char ProgChar;
    ProgChar AT[] PROGMEM = "AT";


message:
Arduino Mega web server always returning JSON data even if JSON is not passed in URL

I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.

    if (client) {
      // an http request ends with a blank line
      boolean currentLineIsBlank = true;
      boolean sentHeader = false;
      while (client.connected()) {
        if (client.available()) {
          // client data available to read
          char c = client.read(); // read 1 byte (character) from client
          // buffer first part of HTTP request in HTTP_req array (string)
          // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
          if (req_index < (REQ_BUF_SZ - 1)) {
            HTTP_req[req_index] = c; // save HTTP request character
            req_index++;
          }
          // last line of client request is blank and ends with \n
          // respond to client only after last line received
          if (c == '\n' && currentLineIsBlank) {
            if (!sentHeader) {
              // send a standard http response header
              client.println(F("HTTP/1.1 200 OK"));
            }
            // Ajax request - send JSON output
            if (util::StrContains(HTTP_req, "json")) {
              // Spit out JSON data
              client.println("Content-Type: application/json;charset=utf-8");
              client.println("Server: ArduinoMega");
              client.println("Connnection: close");
              client.println();
              client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
              client.print(tempInC);
              client.print("\"}]}");
              client.println();
              break;
            } else {
              client.println(F("Content-Type: text/html"));
              client.println(F("Connection: close")); // the connection will be closed after completion of the response
              client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
              client.println();
              sentHeader = true;
              client.println(F("<!DOCTYPE HTML>"));
              client.println(F("<title>"));
              client.println(F("Welcome to Arduino WebServer</title>"));
              util::printProgStr(client, htmlStyleMultiline );
              client.println(F(""));
              client.println(c);
              client.print(F("
 LIVE:
"));

Please help.

body:
So figured out the problem, the issue was  I was closing the connection instead when it was json fetched, I had to keep alive the connection.

so replaced `client.println("Connnection: close");` with  `client.println("Connection: keep-alive");`

which fixed the problem.


message:
How can I send/write two doubles via Bluetooth (nRF8001 Bluefruit LE) in Arduino?

I recently purchased an nRF8001 Bluefruit LE and I am now trying to read/send data with an app. But I am not sure how I can write/send a double value. I want to send two double values at once and to successfully send this, do I have to convert these doubles to a byte array? If so I would very much appreciate how that would look!

This is documentation on how my module works:
https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail

Under the headline `Writing data` they give examples on how to send data but as far as I can see (I am a bit new to Arduino code) in their example they only send an int and a string.

I know how to read and set up the module, so it is only the writing/sending doubles that I am struggling with.

These are the two doubles that I wish to send and I control it with:

    double valueOne;
    double valueTwo;

The Bluetooth control:

    Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

So if I for example do this:

    BTLEserial.write(valueOne, valueTwo);

I get this message: `no matching function for call to 'Adafruit_BLE_UART::write(double&, double&)'`

So do I need to convert these two double values to a byte array and if so how would that look?

Appreciate every help, tips, code! :)

body:
As the link ["Adafruit - nRF UART In Detail"](https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout/nrf-uart-in-detail) describes, the function `write(sendbuffer, sendbuffersize);` is waiting for a buffer of `uint8_t` followed by the size of the message.

Here are the step--by-step solution to send the 2 doubles by using that function.

**Step1** - convert the floating-point values into a char string.

> In the Arduino environment, the standard format-specifier `%f or %lf`
> is not well-managed and the function `dtostrf()` is recommended.

The format is `char *  dtostrf (double __val, signed char __width, unsigned char __prec, char *__s)` where:

 - `__val` is the floating-point value to be converted,
 - `__s` is the array of char to store the result,
 - `__width` is the number of characters to store the result,
 - `__prec` is the number of digit

The conversion is:

    char sValueOne[16], sValueTwo[16];
    char sBuffer[33];

    strcpy(sBuffer,dtostrf(valueOne, 15, 8, sValueOne));
    strcat(sBuffer,",");
    strcat(sBuffer,dtostrf(valueTwo, 15, 8, sValueTwo));

**Step2** - write the buffer over the `BTLEserial` object.

    BTLEserial.write((uint8_t *)sBuffer, strlen(sBuffer));

> Alternate output solution using `BTLEserial.print()` function.

    BTLEserial.print(sBuffer);


body:
I didn't try this, but since `Adafruit_BLE_UART` inherits from `Stream`,
which in turn inherits from `Print`, you should be able to

    BTLEserial.print(valueOne);
    BTLEserial.print(",");
    BTLEserial.println(valueTwo);


message:
Digital Reading from a array without using the exact element

Is it possible to read a digital input from an array without using the exact element? Such as

       while(digitalRead(myButtonArray[i]))
         digitalWrite(myLEDArray[i], HIGH);
Reading the myButtonArray one by one and turning on the led one by one doesnt make for clean written code. The following is just an example code. When button on pin 2 which is element 0 is pressed turn on led on pin 7 and turn off when released. When button on pin 3 is pressede turn on led on pin 8 and turn off when released and continue on in the same fashion with the rest of the buttons and leds as well.

     int myButtonArray[] = {2,3,4,5,6};
     int myLEDArray[] = {7,8,9,10,11};

     void setup() {
       for(int i = 0;i<5;i++){
         pinMode(myButtonArray[i], INPUT);
         pinMode(myLEDArray[i], OUTPUT);
       }

     }

     void loop() {
     while(digitalRead(myButtonArray[0]))
          digitalWrite(myLEDArray[0], HIGH);

     while(digitalRead(myButtonArray[1]))
          digitalWrite(myLEDArray[1], HIGH);

     while(digitalRead(myButtonArray[2]))
          digitalWrite(myLEDArray[2], HIGH);

     while(digitalRead(myButtonArray[3]))
          digitalWrite(myLEDArray[3], HIGH);

     while(digitalRead(myButtonArray[4]))
          digitalWrite(myLEDArray[4], HIGH);
     }

body:
It isn't clear from the question or the code what you actually want to do.  Perhaps back up a step: edit the question and write a clear-cut problem specification.

For example, a specification for what the code you have actually does, is:
> For each of five buttons,
>> If button k is on, turn on LED k, and stall in a loop until button k is released.  Leave LED k on when the button is released.


body:
Is this what you want?

     #define NUM_ITEMS 5
     int myButtonArray[NUM_ITEMS] = {2,3,4,5,6};
     int myLEDArray[NUM_ITEMS] = {7,8,9,10,11};

     void setup() {
       for(int i = 0;i<NUM_ITEMS;i++){
         pinMode(myButtonArray[i], INPUT);
         pinMode(myLEDArray[i], OUTPUT);
       }

     }

     void loop() {
         for (int i=0 ; i<NUM_ITEMS ; ++i) {
             while(digitalRead(myButtonArray[i]))
                  digitalWrite(myLEDArray[i], HIGH);
             digitalWrite(myLEDArray[i], LOW);
         }
     }


body:
In your question you wrote

> and turn [the LED] off when [the corresponding button is] released

and yet you never turn the LEDs off in your code. Then, I assume the
code in your question is irrelevant, and you just want the LEDs to show
the states of the buttons at all times. This can be done by writing to
the LEDs the values you read from the buttons. Do this for each
button/LED pair, and loop over the pairs:

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

    void loop() {
        for (int i = 0; i < 5; i++)
            digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
    }


body:
I think, you did not realized, that `digitalWrite(i,value)` sets the pin `i` to `value` **AND** the pin have the `value` until set otherwise. So you probabelly want something like this:

    void loop() {
      for (int i=0;i<5;i++)
        digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
    }

where each LED follows each respective Button both HIGH and LOW.


message:
Sense checking Arduino Uno barebones schematic

I have had some difficulties finding a barebones Arduino board and have had the following made. I just wanted to see if anyone could spot any issues? I think it has everything. I'm really trying to get it as minimalistic as possible, but at the same time able to use a power source like a 12v/24 battery. Any help would be greatly appreciated. Many thanks

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

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

body:
C4 is under the IC, which may (or may not) do problems, regardless which side of PCB you place it actually. The reset is better to connect via resistor to defined level than to leave floating. Usually there is also capacitor there to delay start until power is stabilized. I would put big capacitor near the stabiliser (also I think, it is recomended by manufacturer of the stabiliser for a reason), but maybe if you have good batery and short wires, it could work too. Also small capacitors between GND and VCC as near the IC as possible are common to reduce noise. And reset button is usefull add-on, but not necessary. Anyway I think, it could work as it is (with the reset defined).

If you have some particular application in mind, then you may use also different layout and/or get more connectors for some pins (some of my "arduinos" does not look like Arduino at all, having all periferials on the same PCB instead on some shields.

also http://download.gilhad.cz/arduinobb_12.jpg this is fully working arduino, which I used many times - so you do not miss anything critical (those LEDS are not necessary)


body:
1. You shouldn't put a capacitor under the chip like that. In fact I don't much like the layout of the whole crystal circuit at all.
2. You need capacitors on the 7805 regulator - around 10µF on both the input and output.
3. The RESET pin needs a pullup resistor otherwise the chip won't function at all.
4. You need decoupling capacitors on all VCC pins on your main chip.
5. Instead of meandering ground traces you should use a ground pour.
6. Running from the kind of voltages you propose the 7805 is going to melt. You will need a BigAss™ heat-sink on it. For those kind of voltages you would be better using a switching (aka *buck*) regulator. Maybe as an off-board module to keep your board simple.


message:
Arduino keeps crashing

I've got an Arduino with a WS2812 hooked up to it, powered by the USB on my computer and I am trying to run the following code:

    #include <FastLED.h>

    #define NUM_LEDS 144
    #define DATA_PIN 6
    #define LED_TYPE WS2812B
    #define COLOR_ORDER GRB

    CRGB leds[NUM_LEDS];

    void setup() {
      FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);
      FastLED.show();
    }

    void loop() {
      for(int dot = 0; dot < NUM_LEDS; dot++) {
        fill_solid(leds, NUM_LEDS, CRGB::Red);
        leds[dot] = CRGB::Black;
        leds[dot] = CRGB::Blue;
        FastLED.show();
        leds[dot] = CRGB::Red;
        delay(30);
      }
    }

    void setAll() {

      FastLED.show();
    }

What this does is sets all the LEDs to red, then goes through each one turning it off, then to blue and then back to red.

For some reason, it gets X number of LEDs along and then crashes.  By crashes I mean the Arduino disconnects itself from the computer, but the Arduino stays on with the LED strip still powered up.

Any ideas?  This is a genuine Uno and I can run any of the FastLED or NeoPixel examples for hours on end without an issue

body:
It is inferred from your question that the Arduino is getting powered through the USB port.  As you say the Arduino appears "gone" from the computer when you light up too many LEDs.

All USB ports are only obliged to supply 500mA with out the USB Device (the Arduino) negotiating for more power from the USB Host.  If the load goes beyond 500mA, the USB Host (the computer) can limit the power my reducing the voltage.  At some point the Atmel processor on the Arduino will stop working.

There are many tutorial on how to use LED strips on the web.  Most will indicate power from a larger than normal power supply is necessary.  Also, that the LED strip power should be connected directly to an appropriately chosen power supply.

The following image [from this web page][1] illustrates this:

[![enter image description here][2]][2]

(Note: In this picture PIN 6 was chosen to communicate with the LED strip.  Your specific application (program or sketch) may use a different pin. Also, realize that the power supply in the picture is wired to only power the LED strip. The Arduino still needs to be powered.)

  [1]: http://www.tweaking4all.com/hardware/arduino/arduino-ws2812-led/
  [2]: https://i.stack.imgur.com/9Mk4w.jpg


body:
See [Powering NeoPixels](https://learn.adafruit.com/adafruit-neopixel-uberguide/power).

> Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).

OK, so you have 144 LEDs.

    #define NUM_LEDS 144

That means you need to allow for 8.64 amps to power them!

    144 * 0.060 = 8.64

 (This is a worst-case scenario, but you should probably allow for 2 amps at least).

As st2000 points out, the USB interface will provide 500 mA (0.5 amps). So you are possibly 8 amps short. You need to power the NeoPixels independently, not through the Arduino.

By powering them through the Arduino they are draining the current from the USB port so much that the over-current protection kicks in.


message:
Output specific value using port manipulation

How can I output a specific value on a pin using port manipulation?

Example: I want to use this code but without any arduino functions, just with port manipulation:

    for (int i = 0; i < 255; i++){
    analogWrite(11, i); //write the i value to pin 11
    }
I want to replace the `analogWrite` function with register manipulation. Is that possible?

body:
The `analogWrite` function is just an interface to setting up the hardware timers to do PWM (pulse-width modulation). I have a [page about timers](http://www.gammon.com.au/timers) which you may find helpful.

Depending on which pin you want to output the PWM to, the registers will be slightly different. Here is one example from my page:

    const byte OUTPUT_PIN = 3;  // Timer 2 "B" output: OC2B

    const byte n = 224;  // for example, 1.111 kHz

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

      TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1); // fast PWM, clear OC2A on compare
      TCCR2B = bit (WGM22) | bit (CS22);         // fast PWM, prescaler of 64
      OCR2A =  n;                                // from table
      OCR2B = ((n + 1) / 2) - 1;                 // 50% duty cycle
      }  // end of setup

    void loop() { }

---

> How can I output a specific value on a pin ?

I should point out that the only values you can output are +5V or 0V. There is no provision for outputting (say) 3.7V. The only way you can sort-of do this is by using PWM and then running the result through an RC filter. There is an example on [my page about op amps](http://www.gammon.com.au/forum/?id=11395).

An example circuit could be:

[![Filter circuit][1]][1]

This uses a resistor and capacitor to filter out the "ripple" in the PWM, giving you a reasonably smooth output voltage, proportional to the PWM duty cycle.

For a larger range of output values a rail-to-rail op-amp would be preferable.

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


message:
Arduino Leonardo model differences

I was thinking of buying another Arduino, and the Leonardo looks appropriate.

However I am confused! The [Comparative Tables](http://www.arduino.org/product/boards/comparative-table) seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)

There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?

I assume I can use the Uno Prototyping shield on the Leonardo.

body:
At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.

Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.

The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.

It's still the same chip, and still connected up in the same way.


message:
Millis...alternate flash

I thought I had the Millis() command sorted but i'm stumped on the one. Aim is to get 2 led's alternately dimming, they work great with delay(); of course....but i can't figure where i'm going wrong with Millis().
Please have a look and point out what i've got wrong.
Thanks
Doug

    int LED3 = 5;
    int LED4 = 6;

    // each "event" (LED) gets their own tracking variable
    unsigned long previousMillisLED3=0;
    unsigned long previousMillisLED4=0;

    int intervalLED3 = 500;
    int intervalLED4 = 500;

    void setup() {
        pinMode(LED3, OUTPUT);
        pinMode(LED4, OUTPUT);

          digitalWrite(LED3,LOW);
          digitalWrite(LED4,LOW);

    }

    void loop() {
      //unsigned long currentMillis = millis();
          for(int P=0;P<6;P++){
            //if ((unsigned long)(currentMillis - previousMillisLED3) >= intervalLED3) {
                analogWrite(LED3, 127);
                analogWrite(LED4, 254);
            delay(500);
                  //previousMillisLED3 = currentMillis;

          //if ((unsigned long)(currentMillis - previousMillisLED4) >= intervalLED4) {
                analogWrite(LED3, 254);
                analogWrite(LED4, 127);
           delay(500);
                 //previousMillisLED4 = currentMillis;
          }
    }

Sorry, problems inputting code, but its all there.
I realize that there are some closing brackets missing in the LOOP() section for millis but it is set for delay() to show that it works.

body:
You are trying to use millis() exactly like delay().  The method delay() stops the program from progressing forward.  It blocks the program.  This is frowned upon as the processor could be doing something useful during this time.

The method millis() does not stop the program.  Instead it is like telling you what time it is.  It is your code that then need to know at what time you want to do something.

But in your code, you are doing something odd.  You are switching the brightness of the LEDs then IMMEDIATELY switching them back.  You are using the same time for the two things you want to do.  Instead try to initialize previousMillisLED4 to 500, intervalLED3 to 1000 & intervalLED4 to 1000.


body:
Well, the for loop is useless. Then you need to plan your time cycle. For instance what you want is

    time(ms)  LED3  LED4
       0       127   254
     500       254   127
    1000 -> back to 0

So implement this. One way can be the one suggested by st2000:

    int LED3 = 5;
    int LED4 = 6;

    // just one tracking, since there is only one sequence
    unsigned long previousMillis=0;

    int endOfPhase1 = 500;
    int endOfPhase2 = 1000;

    void setup() {
     pinMode(LED3, OUTPUT);
     pinMode(LED4, OUTPUT);
     digitalWrite(LED3,LOW);
     digitalWrite(LED4,LOW);
    }

    void loop() {
     unsigned long currentMillis = millis();

     if ((currentMillis - previousMillis) < endOfPhase1) {
      analogWrite(LED3, 127);
      analogWrite(LED4, 254);
     }
     else if ((currentMillis - previousMillis) < endOfPhase2) {
      analogWrite(LED3, 254);
      analogWrite(LED4, 127);
     }
     else
      previousMillis += endOfPhase2;
    }

Just a small note about this: I tend to prefer summing the period instead of setting previousMillis to millis because this way small errors do not accumulate.

This way is the simplest, but the state machine oriented is the one I suggest you, since it is more powerful and you will reuse this a lot of times. Moreover it will detect the "change" of state, thus avoiding the continuous analogWrite (in the previous code the analogWrite instructions are executed a lot of times).

Just define a state machine as two states (state 1, where LED3 is 127 and LED4 is 254, and state 2, where LED3 is 254 and LED5 is 127). The transitions will be after 500ms in each state, but I'll make two separate constants so you can trim them later. Usually each state has a function to be performed when you enter the state, a function to run continuously, a function when you exit and one or more transitions. The way to perform this is

 1. calculate if there is a state change
 2. if there is, perform the exit functions of the previous state and the enter functions of the next state
 3. advance to the new state
 4. perform the actions to be done continuously in the new state

In our case just state transition, enter and advance should be implemented. Usually you use a switch case on a variable holding an index for the state. In this case, for instance,

    int LED3 = 5;
    int LED4 = 6;

    // just one tracking, since there is only one sequence
    unsigned long previousMillis=0;

    int state1duration = 500;
    int state2duration = 500;

    uint8_t state;

    void setup() {
     pinMode(LED3, OUTPUT);
     pinMode(LED4, OUTPUT);
     digitalWrite(LED3,LOW);
     digitalWrite(LED4,LOW);

     state = -1; // Invalid state, used to force a transition at startup
    }

    void loop() {
     unsigned long currentMillis = millis();

     // Check the transition
     uint8_t nextState = state;
     switch (state)
     {
     case 1: // Transition for state 1
      if ((currentMillis - previousMillis) >= state1duration)
      {
       nextState = 2;
       previousMillis += state1duration;
      }
      break;
     case 1: // Transition for state 2
      if ((currentMillis - previousMillis) >= state2duration)
      {
       nextState = 1;
       previousMillis += state2duration;
      }
      break;
     default: // When unknown state, go to state 1
      nextState = 1;
      break;
     }

     // If there is a change, perform the enter functions
     if (nextState != state)
     {
      switch (nextState) // enter functions of the next state
      {
      case 1: // Entering state 1
       analogWrite(LED3, 127);
          analogWrite(LED4, 254);
       break;
      case 2: // Entering state 2
       analogWrite(LED3, 254);
          analogWrite(LED4, 127);
       break;
      }
     }

     // Advance to the new state
     state = nextState;
    }

This can be more complicated, but believe me, it is not. Once you get what this means you will be able to solve a lot of problems this way.

According to my experience, never try to simplify this to your particular problem, since it will make things more complicated. Just add, when needed, the exit functions (before switch(nextState) put another switch on state) and the execution (after the advancing, put another switch on state) if needed.


body:
The final sub routine...I did move the counter to get a better result. The variable "ditchFlag" is set in an IF statement further up in the sketch.
The duration of the subroutine is a combination of the timers and the number in "count".

    void ditchDim() {
    while (ditchFlag == 1) {            //set to 1 when conditions are met

    unsigned long currentMillis = millis();

    if ((currentMillis - previousMillis) < endOfPhase1) {
        analogWrite(LED3, 127);
        analogWrite(LED4, 254);
    }
    else if ((currentMillis - previousMillis) < endOfPhase2) {
        analogWrite(LED3, 254);
        analogWrite(LED4, 127);
    }else{
      count = (count+1);
        previousMillis += endOfPhase2;
        }
          if (count == 5) {
            count = 0;
            ditchFlag = 0;
            return;
        }
      }
    }

thanks
Doug


message:
I am making an easy game but something in my code is wrong

I am making a game where you need to push the button when the LED lights up but it is not registering the push at the right time. I need to push the button when LED is about to go off.

My code:

    randNumber = random(2);

    if(randNumber == 0){
      digitalWrite(9, HIGH);
      delay(1000);
      digitalWrite(9, LOW);
    }

    if (btnAddFirst.pressed() && randNumber == 0){
      Serial.println("You did it");
    }
    else {
      Serial.println("u failed");
    }

body:
Don't use `delay()`, since nothing can happen (not even reading a button) while that delay is running.

Instead use `millis()` as in the `BlinkWithoutDelay` example sketch.


message:
Multichannel communication with Arduino and HC-12 transmitter

The HC-12 module has 100 possible channels starting at 433 MHz. Can someone tell me how to program the Arduino to use multiple channels at the same time? My goal is to build an RC transmitter with Arduino and an HC-12 module for a quadcopter. Therefore I need 6 channels, like a normal transmitter does. Thanks in advance!

body:
I believe you are misunderstanding what it means by channels. The HC-12 can transmit on up to 100 channels, which means different frequencies under the 433 MHz band. For example 433.05 MHz or 433.15 MHz. This is so multiple HC-12 modules can be used next to each other and only the module receiving on the channel of the transmitter will receive the data broadcast.

What you need to do for your quadcopter is send an array of bytes that begins with a constant, followed by the data you need (a packet). Example:

    byte packet[] = {0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}

    // in your loop
    packet[1] = ; HOW MUCH THE ENGINE IS THROTTLED
    packet[2] = ; HOW FAR THE CONTROL TO GO FORWARD IS DEPRESSED
    // etc

Iterate through this array writing the data through the serial port to the HC-12. Whenever your receiver detects the constant (in this case 0x00) read the values that follow as the controls for the quadcopter.


body: I'm starting on HC-12 myself and as I understand, you can only access 1 module at a time by selecting each modules individual channel, assuming you have set the modules to separate channels, you cannot receive data from multiple modules even if set to the same channel at the same time, it would just be a jumble of unsortable data. But you may be able to select one channel after another and collect each set of data separately 1 thru 6 and then extract the information you need by using AT+C001,002,etc. Or you could use 1 RX and program the on board arduino to cycle thru the 6 motors sequentially and collect the 6 sets of data that way. this question would be easier to answer with a diagram of you proposed circuit.


message:
How to convert Arduino example sketch to a complete c++ project?

I'm experimenting something new with my Arduino Leonardo. I removed its original bootloader and flashed it with LUFA mass storage example with added functionalities(now its a firmware). I'm trying to now add RFID reader(read/write) example to my firmware. For that I have to convert the sketch to a c++ code. So I copied relevant header file and cpp file from the library folder(libraries->rfid-master->bla.h,bla.cpp). But I'm confused what to do with the .ino file under examples(libraries->rfid-master->examples->ReadAndWrite->blabla.ino). I guess this code should be copied to the main class of my firmware. Any ideas?

body:
Basically *.ino is *.cpp without headers. So you can

 - rename it to *.cpp,
 - If you have any functions which are used before they have been defined, provide declarations for each function before its first use
 - `#include <Arduino.h>` on the top
 - `#include <Wire.h>` if you are using Wire and so on

and you have "normal" CPP file.

If you are making library this way, than you create also *.h file, where you declare all exported functions and objects and #include that file in your *.cpp as first line (than you do not need/have to forward declare any of that exported functions)

You may like to take a look at https://github.com/arduino/Arduino.git https://github.com/sudar/Arduino-Makefile and https://github.com/ladislas/bare-arduino-project

the Bare Arduino have 2 projects each using 2 libraries, so you can get inspiration there


message:
Win10 64bit, IDE 1.8.0 back to IDE 1.6.13 won't compile anything including Blink. 1.6.12 does compile

Arduino: 1.8.0 (Windows 10), Board: "Arduino/Genuino Uno"

c:\program files (x86)\arduino\hardware\tools\avr\bin\../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

body: Try locating the code file in explorer.exe, go to its properties and check if the system has full access to the file. Just to be sure, run the Arduino IDe as an administrator.