# Question
Title: Multiple transmitters and problem with ref
There are three Arduinos on a model. Each of them has a DS18B20 Dallas temperature sensor and an nRF24L01 antenna wireless communication. There is also an independent device consisting of an Arduino and an nRF24L01 antenna. Device acts as a receiver. Arduino and antenna play the role of transmitter. The code is:

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Wire.h>

int temp1;
int WindSpeed;
int temp2;
int temp3;
RF24 radio(7, 8);
const uint64_t pipes[3] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0E2LL, 0xF0F0F0F0E3LL};
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(0, pipes[1]);
  radio.openReadingPipe(1, pipes[2]);
  radio.openReadingPipe(2, pipes[3]);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    radio.read(&temp1, sizeof(temp1));
     Serial.println("Temp1:");
     Serial.println(temp1);
     delay(50);
     radio.read(&WindSpeed, sizeof(WindSpeed));
     Serial.println(" WindSpeed Bf : ");
     Serial.println(WindSpeed);
     delay(50);
     radio.read(&temp2, sizeof(temp2));
     Serial.println("temp2:");
     Serial.println(temp2);
     delay(50);
     radio.read(&temp3, sizeof(temp3));
     Serial.println("temp3:");
     Serial.println(temp3);
     delay(50);
  } else {
    Serial.println("No radio Data avaliable");
  }
  delay(3000);
}

```

The problem is that the code sends some values but the correspondence isn't right in `AnalogRead`. How can I watch each pipe with the antenna of corresponding Arduino in order to have the right results, and each Arduino sends to the receiver through its own antenna the value of its sensor?

Thanks all for your time!

# Answer
> 1 votes
You appear to be using the multiple pipes of the nrf24L01 to keep your data feeds distinct, and to be asking how you can differentiate the pipes on receive.

It's not clear *which* exact `RF24` library you are using, but if you look at the headers of a typical one you will find something like:

```
  /**
   * Test whether there are bytes available to be read
   *
   * Use this version to discover on which pipe the message
   * arrived.
   *
   * @param[out] pipe_num Which pipe has the payload available
   * @return True if there is a payload available, false if none is
   */
  bool available(uint8_t* pipe_num);

```

Additionally, you do not want to use any delays in receiving code, as that could cause you to miss transmissions - if you use delays for pacing, they should be on the transmit side.

It's not clear if you have 3 or 4 pipes (**and in your setup you have forgotten that C/C++ array indexing starts at 0 not 1**) but to read 3 of potentially 4, you could do something like:

```
#define INTERVAL_MS 10000
unsigned long lastMsg = 0;
int values[4];
char *pipeNames[] = {"Temp1:", " WindSpeed Bf : ", "temp2:", "temp3"};
void loop() {
   uint8_t pipe;
   if (radio.available(&pipe) {
     if (pipe < 3) {
        radio.read(&values[pipe], sizeof(int));
        Serial.println(pipeNames[pipe]);
        Serial.println(values[pipe]);
        lastMsg = millis();
     }
     else radio.flush_rx(); //unclear if this is needed to allow new data on a pipe that is of interest
   }
   /* warning - may mis-operate after ~50 days */
   if ((millis() - lastMsg) > INTERVAL_MS) {
      Serial.println("no data received in past 10 seconds");
      lastMsg = millis();
   }
}

```

# Answer
> 0 votes
You want to send data from 3 (or 4?) different Arduino transmitters to one Arduino receiver and you want to be able to distinguish the packets sent by each transmitter as they are received. The most straightforward way is to create a struct for your data and attach a unique header and trailer that can be used to identify the sender.

```
typedef struct {
  uint8_t header = 0x01;
  int temp1;
  uint8_t trailer = 0x10;
} PACKET;

```

Something like this should be present in each transmitter but with unique header and trailer for each one. Then the receiver should have the header and trailer bytes for all the transmitters and, whenever it receives data, it checks the first received byte against the list of header bytes to know who sent the data before it continues. Finally, it checks the last byte to know if it's the correct trailer byte for the assumed sender and also as an additional (but perhaps unnecessary) layer of error detection to know if the received packet is a complete valid one.

---
Tags: arduino-uno, nrf24l01+
---


# Question
Title: How can I generate a sinewave with Arduino Uno?
I would like to generate a sine wave with my Arduino Uno. As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong), so the only option available is to write a function to generate the signal from scratch.

As far as my understanding of digital electronics goes, I believe it is possible to generate a sine wave signal by using PWM and varying the duty cycle accordingly. However, this route seems to me quite long, what other options do I have?

# Answer
> 5 votes
> As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong)

You are wrong, there is Mozzi, the sound synthesis library for Arduino. It works essentially along the lines sketched by uint128\_t. Take a look at the Sinewave.ino for an example on how to make a (lookup table-based) sine wave. It can also do much more.

In its default mode, Mozzi works with a 16,384 Hz sample rate and a 32,768 Hz (not audible) PWM frequency.

# Answer
> 4 votes
There are two parts to this:

One is the creation/derivation/storage of the *digital representation* of a sine wave. The other is the conversion of the digital representation of a sine wave to an analog voltage (if I understand what you want).

---

The easiest way to obtain the digital representation of a sine wave is a lookup table. Precompute the digital values, and store them in an array. Simple. It is up to you to decide how much resolution (both in vertical accuracy/number of bits and horizontal accuracy/number of samples) you require.

It is also possible to compute the values directly. There are a number of ways of doing this, but be aware that using floating point math on the Arduino is very slow and space-intensive. You may want to look at CORDIC for one possible solution to this.

---

Next is the conversion to analog. You are right, PWM is one way to do this, and one of the easiest as far as external components go: you only need an RC filter to smooth the PWM. However, PWM is limited in resolution, and performs poorly when your wave frequency becomes a significant fraction of your PWM frequency. Also, the Arduino doesn't run very fast, so your PWM frequency is limited.

Other DAC solutions (there are many many many, so I'm not going to go in depth on this):

* R2R DAC: simple to construct, but requires precision resistors for decent resolution, limited in resolution, and requires many IO pins.
* "proper" DAC: an I2C/SPI DAC can give you far better performance, but you will have to learn how to communicate with it. And it's going to be more expensive, and involve several components.

---

> However, this route seems to me quite long, what other options do I have?

I'm not sure what you mean by "quite long", but this is pretty straightforward. For example, here's how I'd go about it:

* store a sine wave in a lookup table
* set up an interrupt to trigger at regular intervals
* in the interrupt, pull a value from the lookup table and write it to PWM

You can now vary the frequency of your sine wave by either adjusting your interrupt interval, or adjusting the increment of your LUT position. You can vary the amplitude by simply multiplying the LUT values by a variable.

This is quite straightforward.

# Answer
> 2 votes
You can get a very fast, accurate, and compact sin(theta) function using a simple table of values. Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c\_src/cordic/cordic.html. C runs in Arduino sketches almost out of the box. You may or may not need some things from the cordic.h. That's why I said "almost". The cordic\_prb.c test file has a function test002() that shows you how to call the sine function.

Because the Uno does not have a real D-to-A converter, you will only get a rectangular wave that has digital noise over the primary harmonic. That's the down side of the pulse width modulation of the lower end Arduino chips. You will need a filter on the analog output if you need to remove the higher frequency noise harmonics.

# Answer
> 1 votes
I found that the Mozzi sinewave.ino demanded more and more include files during compile efforts, and once these (easy) problems were resolved, it ended up with horrific compile errors due to something missing in the code. NBG for a "C" dummy like me!

---
Tags: arduino-uno, signal-processing
---


# Question
Title: Removing Robot IR Arduino Library on Macbook
I'm trying to use my IR receiver on my Arduino Uno Board. First I need to remove my IR Robot library because it interferes with the IRremote library. On my Mac, I have gone into the Arduino/library folder, but the name of the library I have to remove is not there.

I cannot figure out how to remove this. Please help!!

# Answer
The folder name is **RobotIRremote**.

It's actually not necessary to remove that folder, though that will solve your problem. A better solution is to change the folder name of the IRremote remote library so that the file named IRremote.h found in that library will be given include priority over the one found in the RobotIRremote library. This is better because you would need to remove the RobotIRremote library every time you update to a new version of the Arduino IDE. The Arduino IDE gives include priority to files that match the name of the library folder but unfortunately if you install the IRremote library manually it will tend to have the folder name **Arduino-IRremote-master** which causes the wrong file to have priority. So you just need to find that folder and rename it **IRremote**.

If you don't know where it is the library folder can be found by:

1. File \> Examples \> IRremote \> AiwaRCT501SendDemo
2. Sketch \> Show Sketch Folder
> 2 votes

---
Tags: osx
---


# Question
Title: Adapt a differently pin-interspaced chip to be used with an Arduino
Happy new year to everyone!

This is how my chip looks like:

Those numbers are millimeters. Both the pin spacing and pin width are different from what Arduino uses.

Is there any quick (or less quick) and reliable way to connect this chip to an Arduino Uno ?

# Answer
> 0 votes
The simplest option is to buy a pre-made ribbon cable with 2mm pitch (7x2) IDC connector on it.

Solder the free end (or cut the second connector off and strip it if you have a two-ended cable) and solder it to strip-board on which you have already soldered a 14-pin header for breadboard use.

# Answer
> 4 votes
Adapters from 2mm to 2.54mm (0.1") spacing exist.

Here is an example and another example.

Alternatively you could make up a little PCB or, as suggested by @jfpoilpret, solder wires on.

A further option is to cut a piece of stripboard, score down the middle to break the tracks, stick your chip on, and run wires from the 2mm-spaced pins to the 2.54mm-spaced pins. Off-cut resistor legs work fairly well, in my experience. Here's one I made (fairly clumsily) earlier. Your soldering skill may be better than mine. .

---
Tags: pins
---


# Question
Title: Controlling DC motor using the Servo pins
I have a L293D motor shield for arduino uno. It has capability of controlling 2 servo motors and 4 DC motors. But I want to control 5 DC motors for my project. So my question is can I use the 3 pins that are there in motor shield ( to control servo motors) for controlling a DC motor? Or any other solution if any without using any other hardware?

# Answer
> 1 votes
No. A servo motor has its own built-in driver and you just send a low-level PWM signal to control it. That cannot directly drive a DC motor.

If you want more DC motors you will need more DC motor driving hardware. For simple speed control in one direction that could be as simple as a NPN transistor (or N-channel FET), a base resistor, and a flyback diode (just like driving a relay). For direction control you will need a H-bridge like the L293D (which incidentally is a very poor choice of driver by today's standards - very inefficient and lossy. I wish people wouldn't persist in selling it.)

---
Tags: arduino-uno, motor, arduino-motor-shield
---


# Question
Title: Mac OSX Yosemite no serial ports showing for Uno R3
I have a MacBook Pro running OS X Yosemite (10.10.3). I connected my Arduino UNO R3 to my computer for the first time after the Yosemite upgrade - it worked fine before this!

When I opened the Arduino IDE I selected Tools \> Board \> "Arduino UNO", but when I try to choose a Serial Port the only options are:

```
/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

```

I have followed several tutorials and threads on how to 'fix' this issue, all to no avail:

I've installed the latest version of the FTDI drivers (even though, from what I recall the UNO doesn't even need them): FTDIUSBSerialDriver\_v2\_3.dmg

Downgraded to a prev. version of the FTDI driver hoping that would clear it up: /Volumes/FTDIUSBSerialDriver\_v2\_2\_18

I followed a tutorial of how to remove the existing Apple drivers and removed the kext files, etc...

Tried connecting arduino to both USB ports.

Tried various cables, including the one that a I used before the Yosemite upgrade.

Tried installing updated Silabs drivers: Arduino compatible's serial port not showing Mac OSX

Walked through the entire Arduino Mac OSX guide: http://www.arduino.cc/en/guide/macOSX

After looking into the system info of my Macbook Pro, I can see the USB Controller is Broadcom based, in case that helps. I searched for Broadcom USB drivers but got hits for Silabs one instead.

Under my Tools \> Port menu.. I can see these options: clicking the Serial Ports option doesn't do anything.

Running `ls -1 /dev/tty.*` or `ls -l /dev/tty.usb*` from terminal gives me:

```
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem

```

The Board does NOT show up under system networking (as it has for others), so it's not recognized as an incorrect device.

I'm at a complete loss. The board powers up... but I cannot connect to it.

SIDE NOTE: This is a legit Uno R3, not a clone.

# Answer
> 44 votes
Probably, you have Chinese Uno analog which works on **CH340** USB-to-serial chip, so you need to install driver for it.

Steps to fix:

1. Install the CH340 driver
2. Run the command in Terminal: `sudo nvram boot-args="kext-dev-mode=1"` (disable kext signing introduced in Mac OS X 10.9 Yosemite)
3. Reboot

Also you're right according to Uno and FDTI:

> **Differences with other boards**
>
> The Uno differs from all preceding boards in that it **does not** use the FTDI USB-to-serial driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a USB-to-serial converter.

# Answer
> 15 votes
The cable that shipped with my Arduino Uno worked for power but not data transmission so the /dev/tty.usbmodem was not showing up in the Tools --\> Port menu. After I switched to a different cable, the /dev/tty.usbmodem port showed up and it worked beautifully.

# Answer
> 6 votes
This fixed the problem for me:

http://blog.sengotta.net/signed-mac-os-driver-for-winchiphead-ch340-serial-bridge/

... and the direct link to download.

**EDIT**: I have one of the cheap clones with a CH340 USB chip. So this might not solve *your* problem, but could be beneficial to others.

# Answer
> 5 votes
Yosemite 10.9 (and OS X 10.10 and newer) requires a signed USB driver kext (kernel extension). You can find one on the FTDI web site here: http://www.ftdichip.com/Drivers/VCP.htm
Use version 2.3 for 64-bit OS X 10.9 or later. Install and reboot.

Plug in your Arduino, and the Terminal command:

> /usr/sbin/kextstat | grep FTDI

will tell you if the FTDI VCP driver actually loaded.

Also a /dev/tty.usbserial-xxxxxxxx entry should appear in your /dev directory.

If not, the Mac USB port isn't talking to your Arduino. So it's no use trying the Arduino IDE application.

Also make sure your USB cable isn't for power only, but fully connected.

# Answer
> 5 votes
This site fixed the problem for me:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

...somebody else has made an alternative to the ftdi drivers, and this website show you how to install them correctly.

# Answer
> 4 votes
This exact same thing happen to me on my mac running the same operating system. I had to restart this system a few times to get it to work. I restarted it with the arduino plugged in; and that worked rather than my previous attempts when i rebooted then plugged in.

# Answer
> 1 votes
Check this video https://www.youtube.com/watch?v=0zuRukW7o0A

* Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
* Open Terminal from Recovery mode
* Run the command csrutil enable --without kext
* Reboot
* Install driver

# Answer
> 1 votes
I have an osepp r3, seemingly an accurate clone. Computer is Mac os10.10.5.

A lot of sites claimed that the mac osx.\* does not require FTDI drivers, but.....

After an awkward, google searching beginning, where the board only accepted a new sketch after being physically unplugged and replugged, I downloaded the latest FTDI driver, installed, and RESTARTED the mac. Now, joy and peace reigns. No side-effects with other mac functions, thankfully. Hope this helps.

# Answer
> 0 votes
Stumbled across this. It worked for Mac OS X Yosemite 10.10.5

install the CH340 driver Run the command in Terminal: sudo nvram boot-args="kext-dev-mode=1" Reboot

However, I installed: MAC system：www.wch.cn/downfile/178

so YMMV

a user here: http://forum.makeblock.cc/t/mac-os-x-yosemite-arduino-1-0-6-doesnt-recognize-makeblock-orion/728

found the solution, there: http://forum.arduino.cc/index.php?topic=261375.15

so kudos - to all that sweated out the driver, uninstall, install, and activation...

Ted

# Answer
> 0 votes
In my case, there was some kind of incompatibility with the ESP8266 connected to the Nano board. As soon as I removed it the Serial Port appeared again.

# Answer
> 0 votes
First, check the USB cable - I had the same problem. If you have checked it, try the HoodLoader2:

I am using it and it works with Arduino Leonardo.

---
Tags: arduino-uno, usb
---


title: IR communication not consistent

text:
# Question
Title: IR communication not consistent
I have an IR Receiver hooked up to my arduino and a remote with an IR Trasmitter in it. I have some code to decode the values that are received but the values change even when I am pressing the same button!

Here is the code I am using:

```
#include <IRremote.h>

int IRpin = 8;
IRrecv irrecv(IRpin);
decode_results results;

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

void loop()
{
  if (irrecv.decode(&results))
    {
      Serial.println(results.value, HEX);
      irrecv.resume();
    }
}

```

and here is me pressing the same button 10 times and the output for it:

> 9C01C8E1
> FFFFFFFF
> 82A6A14C
> FFFFFFFF
> FFFFFFFF
> 70D67871
> FFFFFFFF
> BCB5C227
> FFFFFFFF
> B358F5ED
> FFFFFFFF
> FFFFFFFF
> FFFFFFFF
> FFFFFFFF
> FFFFFFFF
> FFFFFFFF
> 58EE9A27
> FFFFFFFF
> 90750A0D
> FFFFFFFF
> FFFFFFFF
> FFFFFFFF

# Answer
> 1 votes
Get TSOP1738 or any good IR receiver to decode. Above code is appropriate and does not need any changes. you will surely get some fluctuations and different decoded hex codes but it would provide only 2 different values for single button so that while controlling any device using ir , you can use 'or' operator in conditional statement and hence you will get desired results. Getting absolute results from a cheap IR receiver is a myth.But it will work well for your project at lower level.I had worked with that and my device is working in my room with no difficulty.

# Answer
> 1 votes
I eventually figured it out. The IR Receiver that I had was made by a company called Sharp. Every company has different methods of encoding and decoding IR signals, and it just so happens that decoding Sharp messages is not yet supported in the IRremote library, the library I was using for IR communication. I found a different IR receiver from an old electronic device that I had, I tried that and it worked perfectly.

---
Tags: arduino-uno, serial, ir
---


# Question
Title: Arduino - Windows can't find the drivers
I bought an Arduino UNO R3 Yesterday. It's a Chinese clone. But it has the Atmega328p and MEGA16U2 both. I've installed the IDE fully. But it can't find the ports. The Tools \> Ports option is greyd out, Cannot find The options Named "Ports (COM & LPT)" or "Other Devices" in device manager. Can't upload any sketch to board. I tried this on my both Win7 SP1(32 BIT) & Win10, which are installed in the same pc but in different partitions. I've roamed accross stackexchange but no successful result.

# Answer
You may not have installed the drivers when installing the IDE. The only way I know to reinstall the drivers is to reinstall the IDE and make sure when you get to this screen you tick every box:

Otherwise you may not have selected your board correctly. To select your board in the IDE, go to Tools \> Board \> Arduino Uno/Genuino Uno

Your port select may then appear, it should be COM1 or something similar. If you have multiple, just try them all by selecting one and then upload a sketch to it. The Arduino Uno should flash some lights if it worked correctly.
> 1 votes

---
Tags: arduino-uno, arduino-ide, windows, installation
---


title: Cameras modules for my project

text:
# Question
Title: Cameras modules for my project
I would like to implement a camera to my Arduino project.

So far I have worked with some sensors (e.g. distance), Wifi and Bluetooth modules, buzzer etc. You can find some very good examples on the web on how to use these things on your project, from the wiring to the sketch.

But when we talk about cameras, I feel like things start to be more difficult - I don't know if it's because camera users should know better what they are doing and therefore don't need a step by step guide, if simply there is a lack of information.

I see myself like this guy and this guy. We just can't find a tutorial!

I'm looking forward to buy a *VGA OV7670 AL422 FIFO* camera or a *Serial TTL JPEG with NTSC video*, but I don't want to spend my money on something I won't be able to use.

There is any better camera I could buy (by better I mean an easier camera to start working and with some information for the implementation)?

Thank you.

# Answer
> 0 votes
I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html

I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible. You can slow down the Pixel Clock of this module to 375kHz, bit I think the GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...

# Answer
> 0 votes
Take a look at the Arducam mini (http://www.arducam.com/tag/arducam-mini/)

I just made a custom Arduino based PCB using this camera and it works great.

# Answer
> 0 votes
I am using this camera, it has an OV568 on board. Getting a photo takes a few seconds, on the UART, which is slow, but could probably sped up if I change the baud rate. But for now I don't need to fiddle with that. Also the image is a JPEG, and what can you do with that in an Arduino? In my little project, it doesn't matter, the Arduino passes the data along to a computer, which handles it. *No problemo.*

But as a proof of concept, I used the JPEGDecoder library to display the photo on my Arduino Mega, with a small 2.2" TFT screen. If takes between 50 to 60 seconds to decode the JPEG and display it on the screen. And that JPEG was in an array, not even on an SD card. Gasp.

So depending on what you're looking into, you might want to rethink the whole idea. You'd be better off with a Raspberry Pi or a Beagle. Arduino won't cut it. There may be some 32-bit MCUs, like the Chipkit series, that could provide a performance boost.

---
Tags: arduino-uno
---


title: Port Not Being Found

text:
# Question
Title: Port Not Being Found
Hey everyone I know this is a pretty common question, and I have read/tried almost everything on all the other posts here and on the arduino.cc forums, but I have been unable to fix my problem. Basically I have been using my Arduino Leonardo for a little over a month now for all sorts of things and have never had this issue with the Arduino not showing up under the port tab on the menu. I have no idea why this just started happening to me, I am using the same cable, etc, and was hoping someone could help me out. I am on a MacBook Pro by the way.

Thanks in advance.

# Answer
> 0 votes
If you have uploaded a sketch that doesn't use the serial port, then after a couple of seconds, the Leonardo won't show up in the ports list.

To upload a new sketch you need to press and release Reset a moment after the upload to the board starts.

# Answer
> 0 votes
Try this... Go to your Arduino IDE. Under the Tools tab, go to "Board" and select Arduino Leonardo. Then in the Tools tab, go to Port and check to see if a port is selected. Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.

Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.

---
Tags: usb, arduino-leonardo
---


# Question
Title: ESP8266MOD does not respond to my Uno (Custom board) AT+RST command
This is my very first project with a Uno board and ESP module. I have some experience with 8051 uP. I'd like some guidance in addressing my issue.

Objective:

To connect ESP8266MOD to my wifi network and send a TCP message to my HOME\_SERVER whenever required.

Hardware Module: UNO (Induino R5 Arduino R3 USB Clone Board) --\> level shifter --\> ESP8266MOD

As a first step, I am trying to send AT+RST command from the Uno to the connected ESP. But there is no response from the ESP. However, I am able to notice a LED blink on the ESP, whenever there is TXD operation in my Uno.

Hardware Connection:

```
UNO - Uses USB Power supply from laptop
ESP8266MOD- Uses 3 1.5V AA Batteries

                 ||
    UNO PINS       TXD      RXD     5V GND
                    ||      ||      ||
    LEVELSHIFTER     >>RXI   <<TXO  HV,GND
                        ||      ||
                    RXO<<    TXI>>  LV,GND
                    ||      ||      ||
    ESP8266MOD      RXD     TXD     3.3V,GND

ESP8266MOD Settings:
    CH_PD ->> 3.3V
    GPIO2 ->> 3.3V
    GPIO0 ->> GND
    GPIO15->> GND

```

Uno Code:

```
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(3000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  delay(3000);
  ESP8266.println("AT+RST");
  delay(30);
  String response = "";
  while(ESP8266.available()) {
    char c = ESP8266.read();
    response+=c;
  }
  if(response != "") {
    Serial.println(response);
  } else {
    Serial.println("Empty\r\n");
  }
}

```

Output Video: Output video view

--\>

# Answer
If it is a new ESP module, your problem is quite likely a baud rate mismatch, since you are seeing an LED response but getting no reply.

The last batch of ESP-01s I received defaulted to 115200 baud, but that is too fast for SoftwareSerial (SS). You'll need to change it to 9600. My answer to a related question describes one way to change it.

You could also change it with SS. You'd have to start off SS at 115200 baud, which will usually transmit OK; just ignore the apparent garbage that comes back. Then change SS's baud rate to 9600 to match, and you should have solid communication.

These are the three commands you need to send the ESP to accomplish the change:

```
AT                             # ESP should respond "OK"
AT+RST                         # Resets the ESP
AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

```

Note: Your module might have been preset to some other rate than 115200, in which case you'll have to try various rates until you can get an intelligible reply. Once you do, set the default rate to 9600.
> 1 votes

---
Tags: arduino-uno, serial, esp8266, wifi
---


title: matrix buttons 8x8

text:
# Question
Title: matrix buttons 8x8
Hi I have 8 buttons on my Arduino uno and I want to create a matrix 8x8 and give each button a row and a column respectively it is not a keypad just 8 buttons each button have a row and a column ex: y x(0,0,0,0,0,0,0,1) 1,0,0,0,0,0,0,0 ..... to compare it with other values on my visual studio c# , I can't find anything about this . anyone can help ?

# Answer
> -1 votes
Does this do what you want?

```
int col;
int row;

int buttonPressed = readButtons();  // <-- You implement this!

switch (buttonPressed) {
    case 1:
       row = 7;
       col = 3;
       break;
    case 2:
       row = 1;
       col = 2;
       break;
    case 3:
       row = 0;
       col = 4;
       break;
    // and so on
}

```

---
Tags: button
---


# Question
Title: 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?

# Answer
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.
> 1 votes

# Answer
Change:

```
pinMode(PIN_MISO, INPUT);

```

to

```
pinMode(PIN_MISO, INPUT_PULLUP);

```

This will enable the internal 20k pull-up and you should then always read HIGH is the pin is floating.

Using INPUT does not enable the internal pull-up (Ref: https://www.arduino.cc/en/Reference/pinMode)
> -1 votes

---
Tags: arduino-uno
---


# Question
Title: const int re-declaration - memory leakage
I am re-declaring a const int variable a few times in a switch-case statement of a function as shown following:

```
void functionB(type param1, type param2, ..., const int paramConstInt = 100);

void setup() {
    ...
}

void loop() {
    ...
    functionA();
}

void functionA() {
    ...
    switch(var) {
        case 0: {
            const int paramConstInt = 200;
            ...
            functionB(param1, param2,..., paramConstInt);
            break;
        }
        case 1: {
            const int paramConstInt = 300;
            ...
            functionB(param1, param2,..., paramConstInt);
            break;
        }
        case 2: {
            functionB(param1, param2,...);
            ...
            break;
        }
        ...
        default:
            // if nothing else matches, do the default
            // default is optional
            break;
        }

}

void functionB(type param1, type param2,..., const int paramConstInt) {
    ...
}

```

Does standard C++ allow for it? I am asking so because, if I try to change one of the *paramConstInt* inside a switch case to 1000 or so I have a strange behaviour similar to that given by a memory leakage. I think anybody willing to replicate this oddity can do it and report. If *const int* is replaced by just *int*, the problem seems to disappear.

# Answer
> -1 votes
Sorry for alerting the community for one of my faults. I'll try to explain what happened in my code and why "const int" made a difference against just "int". In my code, functionA() is not being called by loop() as sketched above but it is actually repeatedly called by a third function, say functionAcaller(), which keeps control while in a millis-interval. Moreover, functionB being called by functionA in turn, has several parameters among which an array vital to the correct functioning of the program, name it MAIN\_ARRAY. I didn't notice up to the time I started debugging the "const int" issue that MAIN\_ARRAY is local and declared (not initialized) within each switch case (same array size for all switch cases) though every time I enter again one of the switch-cases I actually need to change the values the array contained in the previous run. In spite of the fact that I (re)declared MAIN\_ARRAY every time I entered functionA() switch-cases, things were fine since the previous values were not probably cleared by the micro. Well, there was in reality a problem given by "const int paramConstInt". When I set it too big, the program lagged. I guess it had to do with its default value being only 100. Another problem was possibly the order of (re)declaration: whether the first variable being (re)declared was MAIN\_ARRAY or const int paramConstInt. **Anyway, even when MAIN\_ARRAY was (re)declared as first thing once back to functionA() switch-cases, a too big const int paramConstInt caused problems while int alone of the same value was just fine.** Sorry again for not having delved into this issue more deeply in advance but since everything was all right except for "const int" I really thought that was the problem.

---
Tags: arduino-uno, c++, switch, constants
---


# Question
Title: Hardware logic gates for a simple demo with LEDs
I need some logic gates for a simple demo like this one. I will use a regular breadboard and an Arduino UNO as a 5 V and GND supply.

I found these ICs from Texas Instruments SN74LSxxN (NOT, AND, OR, NAND, NOR, XOR). For my demo I only need two inputs (well obviously only one on NOT) and one output on each chip. I want to connect the output to a LED via resistor to demonstrate that for example 1 XOR 1 equals 0 (LED off), or NOT 0 equals 1 (LED on):

My LSs seem to work as expected without an LED connected:

```
int value;

void setup() {
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 Serial.begin(1200);
}

void loop() {
 digitalWrite(10, LOW);
 digitalWrite(11, LOW);
 value = digitalRead(5);
 Serial.println(value);
}

```

…but it would be great to make an LED demo too.

These ICs are probably a better choice in my case?

* SN74ACT04N (NOT)
* SN74ACT08N (AND)
* SN74ACT32N (OR)
* SN74ACT00N (NAND)
* CD74ACT02 (NOR)
* SN74ACT86N (XOR)

For everyone who isn't happy with Arduino as power supply here an alternative circuit with the same question - which IC family should I use?

**Update:** Well, probably I should better use something like LogicBlocks for my demo. There is no NOR, XOR or NAND in this set, but it should be much easier to handle.

# Answer
> 0 votes
The circuit I was looking for looks like this:

And the HC family seems to do the job. Thanks to **dlloyd** (link).

# Answer
> 2 votes
The SN74HC04 has a documented output driver capability of ±4 mA when running at 5V:

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:

```
(5 - 1.6) / 0.004 = 850 Ω

```

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

---

> I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)

See Mike Cook's tutorial The care and feeding of LEDs. As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".

It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.

The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".

---
Tags: arduino-uno, electronics
---


# Question
Title: How do I program my Arduino Yun Shield when I keep getting this AVRDUDE error message?
The error message is:

> avrdude: AVR device initialized and ready to accept instructions
> avrdude: Device signature = 0x1e950f
> avrdude: Expected signature for ATmega32U4 is 1E 95 87
> Double check chip, or use -F to override this check.

This error message is thrown when I attempt to upload any program to the Yun shield through an Arduino Bridge between the Uno and Yun shield with the Uno’s ATMega32 shorted into reset mode.
Any advice on how to get this working? Thanks.

# Answer
Make sure the board selected in the *Yun Shield* is the correct one (in this case *Arduino UNO*).

## Steps for selecting the board on the Yun Shield

1. In your web browser load the *Yun Shield* page and log in (how to do this is described in the Quick Start Guide).
2. Click on the SENSORS menu button.
3. Under *Arduino Board Type* select the correct one.
4. Click on the *CONFIGURE & RESTART MCU* button to apply settings.
5. Maybe manual restart of the board would be needed (power unplug).
> 2 votes

# Answer
Apparently there is no `ATMega32U4` on that board but `ATmega328P` according to the signature `0x1e950f`.

Anyway, you may have to change or add new board with correct MCU setting.

Now I can see the difference between Yun and Yun shield. Shield can be connected to any Arduino board and Yun is similar like Shield + Leonardo.

I've found board definition for Arduino UNO:

```
unoyun.name=Arduino Uno -- Dragino Yún
unoyun.upload.via_ssh=true

unoyun.vid.0=0x2341
unoyun.pid.0=0x0043
unoyun.vid.1=0x2341
unoyun.pid.1=0x0001
unoyun.upload.tool=avrdude
unoyun.upload.protocol=arduino
unoyun.upload.maximum_size=32256
unoyun.upload.maximum_data_size=2048
unoyun.upload.speed=57600
unoyun.upload.disable_flushing=true
unoyun.upload.use_1200bps_touch=true
unoyun.upload.wait_for_upload_port=true

unoyun.bootloader.tool=avrdude
unoyun.bootloader.low_fuses=0xff
unoyun.bootloader.high_fuses=0xde
unoyun.bootloader.extended_fuses=0x05
unoyun.bootloader.file=optiboot/optiboot_atmega328.hex
unoyun.bootloader.unlock_bits=0x3F
unoyun.bootloader.lock_bits=0x0F

unoyun.build.mcu=atmega328p
unoyun.build.f_cpu=16000000L
unoyun.build.board=AVR_YUN
unoyun.build.core=arduino
unoyun.build.variant=standard

```

More info about it here: https://www.arduino.cc/en/Guide/ArduinoYunShield or similar product http://wiki.dragino.com/index.php?title=Yun\_Shield
> 1 votes

---
Tags: arduino-ide, shields, arduino-yun, avrdude
---


title: Having Arduino read a video game screen

text:
# Question
Title: 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?

# Answer
> 3 votes
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 about using a light sensor with an Arduino. Most of the circuit is for the display of which you need not bother with.

---
Tags: arduino-uno
---


title: List of connected clients to server

text:
# Question
Title: 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; 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 (?)
  }
}

```

# Answer
The WiFiClient.h header and WifiClient.cpp source files are useful for reference.

> Is the best data structure a linked list?

Probably not here. Possibly not ever. 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.
> 5 votes

# Answer
> 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 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:

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:

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

---
Tags: wifi, networking
---


title: Oxygen sensor up to 50%

text:
# Question
Title: Oxygen sensor up to 50%
Are there any oxygen sensors that measure up to 50%?.

As I understand, there are sensors that measure only in range 0-30%.

Is it possible to increase the threshold of sensitivity of the sensor?

# Answer
You can try SO002 or DS-TR250.

> Is it possible to increase the threshold of sensitivity of the sensor?

I don't think its possible. Perhaps you can tweak the reading sensitivity, but since the sensor are mostly analog, it's not possible. And maybe that also the reason the 2 sensors I've mentioned above have several series based on their measuring threshold.
> 1 votes

# Answer
The Bosh LSU 4.X sensor(s) are what I think you are looking for. Here are some related links:

http://www.waltech.com/open-source-designs/wbo2\_report/

https://github.com/Hell-Fire/WidebandO2
> 0 votes

---
Tags: sensors
---


title: DFPlayer library using RT TX pins

text:
# Question
Title: DFPlayer library using RT TX pins
I am using the DFRobotDFPlayerMini-1.0.1 library by Angelo. I am trying to use the actual RX TX pins on a Uno R3, but it doesn't connect unless I type in an alternate digital pin number. This is no good for my application as I have a major pin shortage. I have tried typing in `(0,1)` but that is not being accepted.

The reason for using this library is because it provides a LOOP function that works well.

1. How do I use the RX TX pins with this library?
2. Is there another library that has a good LOOP function in it?

Thanks.

Doug

# Answer
On a classic Arduino pins 0 and 1 are used for serial communication with the host PC, so you cannot use them to talk to a peripheral without conflicting with that. The library may well be coded to trap and reject such an attempt.

On various alternate (ARM, Atmega32u4, etc) boards these pins may be usable, though the library may not be aware of that. Also on such boards you would generally want to use an available hardware UART rather than a software simulation of one, which may be fairly ATmega-specific anyway - the end result of which is that library code may well need modification to work on a non-traditional device.
> 1 votes

# Answer
When you say "type in `(0, 1)`" I suppose you mean this:

```
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;

```

Reference

You cannot use (0, 1) in SoftwareSerial. However, what you could do is pass `Serial` to the init string:

```
void setup() {
  // mySoftwareSerial.begin(9600);
  Serial.begin(9600);
  // if (!myDFPlayer.begin(mySoftwareSerial)) {
  if (!myDFPlayer.begin(Serial)) {
    //Use softwareSerial to communicate with mp3.
  }

```

However that means you cannot use Serial for debugging. You'll have to find another way to log errors and messages.
> 1 votes

---
Tags: library
---


# Question
Title: 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:

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

# Answer
> 1 votes
```
//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?

---
Tags: arduino-uno
---


# Question
Title: 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?

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.

# Answer
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.
> 2 votes

---
Tags: sensors
---


# Question
Title: 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?

# Answer
> 4 votes
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.

# Answer
> 2 votes
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.

---
Tags: arduino-uno, relay, transistor
---


# Question
Title: How do I turn off the blinking cursor/caret in the Arduino IDE?
I just purchased a RedBoard, knowing that it would work on Linux, and knowing that it could allow me to easily interface with some electronics project. I am aware of the `ino` command line tool but I wanted to try interfacing with my board using the Arduino IDE because the latter seems to be somewhat standard. However, when I open the IDE I see a blinking cursor and for whatever reason I can't deal with this. How do I turn off the blinking cursor in the IDE?

I've managed to fix the blinking cursor problem in Firefox, GNOME, KDE, and my terminal... just not sure what to do with Java applications like Arduino IDE.

# Answer
> 2 votes
As suggested by Gerben, you can go into Preferences and check the box "Use external editor":

Now you can edit with your favourite editing program.

With this option active the IDE will show your sketch but in a non-editable way, and with a blue (cyan?) backwash:

Whenever you save the file in your external editor the IDE will detect the change and refresh the code shown in the internal editor.

Effectively you have replaced the IDE's editor with your own, but still use the IDE to compile and upload your sketches.

# Answer
> 3 votes
**Note:** does not work with version 1.6.11. Works with 1.0.6

* Open the Arduino IDE
* Go to File
* Then go to Preferences
* At the bottom of the page is the file location you can enter to set additional preferences
* Exit the Arduino IDE
* Go to the preferences file location then set `editor.caret.blink=false`
* Then save
* Then restart the IDE and the **caret** will not flash

---
Tags: arduino-ide, linux, java
---


title: Win10 PCs won't see ATtiny boards

text:
# Question
Title: 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?

# Answer
> 0 votes
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!

---
Tags: usb, attiny
---


# Question
Title: 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.

# Answer
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.
> 3 votes

---
Tags: serial, arduino-due, uart, flash
---


# Question
Title: 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;

```

# Answer
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
> 1 votes

---
Tags: serial, c, timers
---


title: Keypad number input and store

text:
# Question
Title: 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!

# Answer
> 1 votes
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.
2. How to use pull up resistors with a switch has been asked many times including here.
3. How to scan a switch matrix has been asked many times including here.

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.

# Answer
> 2 votes
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()

```

---
Tags: arduino-uno, programming, sketch
---


# Question
Title: How can I speed up reading of an SD card?
I am working on a project using an Arduino as a web server.

Code:

```
webFile = SD.open("index.htm");
if (webFile) {
  while(webFile.available()) {
    client.write(webFile.read());
  }
webFile.close();

```

This sends data line by line, leading to a long time to load the webpage. Is there a faster way to load this page?

# Answer
> 1 votes
Well I have two ideas on the SD card side, though neither really seem *great* to me they could still help you. I read on the Arduino forum that the SD card R/W speeds generally come out to 600kB/s, I'm not really sure why, the Arduino SPI can go up to 8 MB/s and I didn't think there would be that much protocol/data-handling in SD.

1. Sector R/W - As Chris Stratton said, this is an obvious method, it's probably much faster to do sector reads. You may have to greatly change your code to implement it, but I imagine you'd see performance increase in the end. Apparently there's an unofficial library for it, though it seems to impart some potentially serious limitations.
2. RAM - This is the second thing that came to mind when thinking about the problem is that you could use external RAM, when not handling network transfers (Idling, should be most of the time) the Arduino transfers data to external SRAM which you add. SPI RAM is most likely the easiest to implement, but not likely to be any faster than an SD card. Parallel RAM is going to be difficult to implement, you'll likely need to write your own class/library, but it could be much faster than SPI RAM or an SD card.

I'm not actually sure if either of these would be any faster, it's all just theory and I hope others will share their thoughts. If you have trouble finding the download link for the SD Card library, it's right here. In that ZIP folder there's a file called *SDCARD*, just move that folder into your Arduino libraries folder on your computer.

# Answer
> 0 votes
maybe you should use SdFat library; a library which is almost the same as the standard SD library, but also it can support Long Filenames.

I did some tests with read and write; it is most of the times \> 60% faster!! https://github.com/greiman/SdFat

---
Tags: arduino-uno, serial, arduino-mega, ethernet
---


title: bridge messes up serial.print

text:
# Question
Title: 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.

# Answer
> 0 votes
You need to use the `Console` class instead of `Serial`. Official example here.

# Answer
> 1 votes
`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.

---
Tags: arduino-uno, arduino-ide, arduino-yun
---


# Question
Title: 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);
 }

```

# Answer
> 0 votes
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);
     }
 }

```

# Answer
> 1 votes
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.

# Answer
> 0 votes
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.

# Answer
> 0 votes
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:

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

```

---
Tags: programming, sketch, array
---


# Question
Title: 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! :)

# Answer
As the link "Adafruit - 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);

```
> 1 votes

# Answer
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);

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Can't read two bytes through Serial.read - Arduino
I'm sending via Bluetooth with an Android App two bytes like this:

```
private void _sendCommand(byte command, byte arg)
{
    if (CONNECTED)
    {
        try
        {
            os.write(new byte[]{command, arg});
            os.flush();

        } catch (IOException e) {
            Log.e(TAG, "Error sending command: " + e.getMessage());

        }
    }
}

```

And this is the code I'm using to receive them with Arduino:

```
byte _instruction;
byte _arg;

void loop()
{
  while(Serial.available() < 2)
  {
    digitalWrite(LED_BUILTIN, HIGH);
  }

  digitalWrite(LED_BUILTIN, LOW);

  _instruction = Serial.read();
  _arg = Serial.read();
  Serial.flush();

  switch (_instruction)
  {

     ...

  }
}

```

I don't have any problems sending just one byte (modifying the code to receive just one), but I can't do the same with two bytes. It's always stuck in the while. Any idea of what I'm doing wrong?

---

EDIT: As ST2000 pointed out, there was a problem of syncronization, so this is the code working properly:

```
void loop()
{
  // Wait until instruction byte has been received.
  while (!Serial.available());
  // Instruction should be read. MSB is set to 1
  _instruction = (short) Serial.read();

  if (_instruction & 0x80)
  {
    // Wait until arg byte has been received.
    while (!Serial.available());
    // Read the argument.
    _arg = (short) Serial.read();

    switch (_instruction)
    {
      ...
    }
  }

  Serial.flush();
}

```

Thanks,

# Answer
There may be a underlying problem with synchronizing the transmitter and receiver. They both have to agree / know which is a command byte and which is a data byte.

In order to do this, some protocols sacrifice a bit. For example you could set the most significant bit for commands and not set the most significant bit for data. However, that does mean you can only send data in the range of 0 to 127. And it does restrict you to only 128 commands. If you need more, and want to stick to this "most significant bit" approach, you could break your data into chunks and only send 7 bits at a time. The possibilities are many. Use this one or make one up that fits your needs better.

In order to implement this approach, you will need to read and process each byte as it arrives. You can not wait until you accumulate the expected number of bytes as this assume you are always in sync with the transmitter. Which may not be the case.
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, android
---