# Question
Title: RGBW LED strip: which components are required?
I'm brand new to this community, and in electronics as well.

I'm a software developer and I want to start a new journey with a project in mind: I want to control a 5 meters addressable LED strip for my living-room.

I need all the components for this project... I already know eclipse and Java world, but I need help in choosing the components for the project:

* which Arduino (starter package maybe?)
* LED strip (`smd 5050` on `sw2812b`, `sk6812`, `APA104`...) more than 60 LEDs/m
* Power Supply for the project

Can you point me to the right direction, posts that can be useful to me, so I can start on good basis?

# Answer
## NeoPixels

The strips based on the WS2812 / SK6812 and similar chips, known by some as *NeoPixels*, are clever ways of implementing fully-addressable 24-bit colour LEDs.

One of the clever things is that they only require one data wire, plus power and Gnd, i.e.

* +5V
* Data
* Gnd

The pixel information is sent by precisely timed sequences of 24 bits per pixel. The first pixel "peels off" these 24 bits (ie. 3 x red / green / blue) and then passes the rest on to the next pixel, and so on.

## Libraries

Various people have written libraries to do this for you including:

## Power

Each pixel draws around 60 mA at maximum brightness (showing white) so you need to allow for a heavy-duty power supply. Particularly if you have 5m of 144 pixels/m then that is 720 pixels, which would require 43.2 amps!

According to Adafruit:

> To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps.

Even that means you need 14.4 amps for your 720 pixels!

So bear that in mind when sizing your power supply.

## Addressing methods

The Adafruit library (as far as I can tell) holds the pixel information in RAM, and then "dumps" it to the NeoPixels in one operation. This lets you do fancy things in memory, and copy the results to the pixels. However that means you need enough RAM for all this. At 3 bytes per pixel (24 bits), if you have 720 pixels, that will be 2160 bytes, which is more RAM than the smaller processors (like the Uno) have.

Larger processors (like the Mega) have more RAM.

An alternative method, as explained here does not keep the data in RAM, but generates the colours "procedurally" on-the-fly. This is much less RAM-intensive, but perhaps less flexible. On that page he links to a YouTube video which shows a humble Arduino Duemilanove (similar to a Uno) driving over 1000 pixels!

Procedural generation however can do quite a lot, for example you can set the entire string to a single colour, change that rapidly, or make a rainbow effect by increasing (say) the red value for each successive pixel. You can also make "chaser" effects quite simply.

The library I wrote is also designed to allow you to use minimal RAM. You could conceivably add in your own storage scheme, perhaps only storing one byte per pixel, with less bits per colour (eg. 2 bits each for red, green, blue) and that would reduce RAM requirements by a third.

## Cabling run

You could try sending the data over 2m. I warn you that the timing for a zero-bit is that it has to go HIGH and then LOW within about 400 ns, so you can't afford to have the data signal degrade too much.

When I had a similar string of coloured LEDs set up at Xmas time (not NeoPixels however) I had a long run of a 5V power supply (just using a pair of figure-8 wire), and situated the processor quite close to the pixels. This is probably the safest way of doing it.
> 5 votes

# Answer
I like the `ws2812` RGB LEDs with integrated controller. They can be found on adafruit.com, e.g. here: Adafruit NeoPixel NeoMatrix 8x8.

There are some good tutorials on adafruit.com:

Choosing your Arduino you have to keep in Mind that the Arduino Due runs at 3.3 V, while the Arduino Mega runs at 5 V. The `ws2812`. But you can use a level shifter to connect an Arduino Due to the `ws2812`.

Your Arduino is powered via USB, the LED matrices / stripes need their own power supply, but a DC 5V wall plug (something like a cell phone charger) will do the work (check the max. ampere ratings to be high enough for your LEDs).

A starter package depends on what you already have. Some jumper cables are always good to have, basic tools for electronics as well, e.g. a soldering iron or some prototyping board.
> 3 votes

---
Tags: rgb-led, eclipse, neopixel
---


# Question
Title: How can I easily see which COM port is used by Arduino?
I'm rather disappointed because I just bought arduino and I am unable to upload any projects. The error I get is:

```
avrdude: ser_open(): can't open device "\\.\COM3": Časový limit semaforu vypršel.

```

Can be translated as:

```
avrdude: ser_open(): can't open device "\\.\COM3": Semaphore time out

```

Am I expected to brute-force all available ports to see which one is reserved for arduino? How can I, on Windows 7, quickly determine which port to use given that the IDE for some reason can't do that for me.

# Answer
Start | Control Panel | System | Device Manager | Ports (COM & LTP).

Watch the list change as you plug / unplug the Arduino. The new port is the Arduino.
> 2 votes

# Answer
You may have to install a device driver. There is a "drivers" directory in the IDE download with some in it.

Example:

According to the readme.txt file:

> With this version of Arduino a new all-in-one driver (with security signature for Windows 8) is supplied.
>
> The old (deprecated) drivers are still available in the Old\_Arduino\_Drivers.zip
> 1 votes

---
Tags: windows
---


# Question
Title: How to make an Arduino USB programming circuit?
I am designing a PCB in which I am using the MCU used in **`Arduino UNO`** which is **`Atmega328P`** and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using **`USB B Type`** just like we do it in **`Arduino UNO`**. My friend suggests me to purchase an **`Arduino UNO`** device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the **schematic design** but its very confusing. Can anyone help me out with this.?

# Answer
It is quite a lot simpler to obtain an FTDI USB - TTL Serial cable. (The link goes to the American supplier, Sparkfun, but such cables are available from many online suppliers.) They are typically made with a 6-pin female header instead of a USB B connector; you may have to make up that part yourself, if it is important to you. If you only need USB functionality for programming, one cable can serve any number of boards (one at a time, of course), no need to build it into each board.
> 0 votes

# Answer
Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide
> 2 votes

# Answer
If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: http://www.mouser.com/Search/m\_ProductDetail.aspx?FTDI%2fFT232RL-REEL%2f&qs=D1%2fPMqvA103RC6OU6bKtoA%3d%3d&gclid=CNmDjr7dvssCFYZefgod9jgPeQ
> 0 votes

---
Tags: usb
---


# Question
Title: Arduino Uno not working as usb HID interface
I have an arduino uno rev 3 and it works perfectly fine. I the OS I am using is Kali Linux 2.0 and you can upload everything as normal to the arduino. I am following this tutorial:Arduino Uno as usb HID interface device to use my arduino uno r3 as a hid device. After I upload the

```
Arduino-keyboard-0.3.hex

```

file, I plug cycle the board and I try uploading the example blink program. It always says:

```
Serial Port /dev/ttyACM0 not found.
Retry the upload with another serial port?
/dev/ttyS0

```

the /dev/ttyACM0 is my default arduino port and /dev/ttyS0 is one of my usb devices that is plugged in. Neverless, I tried uploading but it says board isnt responding. Can someone help me with this please?

# Answer
You have reprogrammed the ATMega16U2 chip to be a HID device. Thus it no longer functions as a serial interface between the Atmega328P and your computer. You need to reflash the firmware on the ATMega16U2 to return to normal operation.

I have instructions for how you might to this on my bootloader uploader page. In brief, you need to put the original hex file back:

```
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

```

There are other ways of turning your Uno into a HID device. Search for "Virtual USB Arduino".

More easily, get a Arduino Leonardo or Arduino Micro which are designed for this sort of thing.

---

> Yes but how can I use **it** as a HID? ... it cannot detect **it** so how would I be able to upload code to **it** ...

What is "it" here? Look at this photo:

There are two processors on the Uno. It sounds like you have reflashed the ATMega16U2. Do you want to use the ATMega16U2 as a HID or the Atmega328P as a HID? They need totally different techniques.

Once you reflash the ATMega16U2 you can't "get to" the Atmega328P via the USB interface.

On the page you linked there is a workflow for programming the ATMega16U2. Are you following it? If so, which part is not working for you? If not, why not?
> 2 votes

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


# Question
Title: Using TMRpcm library, the audio does not play
I'm using the https://github.com/TMRh20/TMRpcm/wiki library to play wav files from an SD card to a speaker I have attached to my Arduino.

I have run separate tests/programs that ensures:

1. my speaker is connected properly and can play sound
2. my SD file is connected properly as it can read and files, text files.

However, I'm trying to use the `tmrpcm.play("example.wav")` command and nothing is happening. I used wav files that for sure works (from a demo I found online) so it's not the wav file problem.

Anyone have any clue on what is going on and how I can fix this?

# Answer
> 3 votes
This is now 5 months later - but I recently had the same problem.

Because the TMRpcm library plays through pulse width modulation, make sure your speakers are hooked up to a PWM capable pin.

That caused me no end of headaches trying to figure out.

---
Tags: arduino-uno, sd-card, audio, tmrpcm
---


# Question
Title: Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library
I'm trying to port the MFRC522 Arduino library (from GitHub) to the ARM MCUs. My problem is with the PCD\_ReadRegister function:

```
/**
 * Reads a number of bytes from the specified register in the MFRC522 chip.
 * The interface is described in the datasheet section 8.1.2.
 */
void MFRC522::PCD_ReadRegister( byte reg,       ///< The register to read from. One of the PCD_Register enums.
                                byte count,     ///< The number of bytes to read
                                byte *values,   ///< Byte array to store the values in.
                                byte rxAlign    ///< Only bit positions rxAlign..7 in values[0] are updated.
                                ) {

    if (count == 0) {
        return;
    }
    //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
    byte address = 0x80 | (reg & 0x7E);     // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
    byte index = 0;                         // Index in values array.
    SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
    digitalWrite(_chipSelectPin, LOW);      // Select slave
    count--;                                // One read is performed outside of the loop
    SPI.transfer(address);                  // Tell MFRC522 which address we want to read
    while (index < count) {
        if (index == 0 && rxAlign) {        // Only update bit positions rxAlign..7 in values[0]
            // Create bit mask for bit positions rxAlign..7
            byte mask = 0;
            for (byte i = rxAlign; i <= 7; i++) {
                mask |= (1 << i);
            }
            // Read value and tell that we want to read the same address again.
            byte value = SPI.transfer(address);
            // Apply mask to both current value of values[0] and the new data in value.
            values[0] = (values[index] & ~mask) | (value & mask);
        }
        else { // Normal case
            values[index] = SPI.transfer(address);  // Read value and tell that we want to read the same address again.
        }
        index++;
    }
    values[index] = SPI.transfer(0);            // Read the final byte. Send 0 to stop reading.
    digitalWrite(_chipSelectPin, HIGH);         // Release slave again
    SPI.endTransaction(); // Stop using the SPI bus

} // End PCD_ReadRegister()

```

I read the datasheet several times & can't understand what's the function of this parameter! Based on datasheet for reading a register from rc522:

# Answer
Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in `PCD_ReadRegister()` right before the `for` loop, and then `n` bytes are read, with 0 transferred the last time to stop reading.

A quick look at the library and datasheet shows that the `rxAlign` argument is used in identifying the first valid bit in the first received byte. `txLastBits` serves a similar purpose, only for transmission of the final byte. Both are written to `BitFramingReg` of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.

For example, in the function you have above, if `rxAlign = 3`, it means only bits 7 to 3 are valid in the first **received byte**, extracted with bit mask `11111000`. So the first **valid 'byte'** comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, `txLastBits` indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and `BitFramingReg`.

Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

---

**EDIT**

I'll try to answer your questions:

* In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
* Bit-oriented frames are **necessary** for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
* Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

> Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.

If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward MFRC522 UART library, which doesnt implement anitcollision, by the way.

If you still want to port the SPI-based library, then, a few suggestions:

You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like `PCD_ReadRegister()`, `PCD_WriteRegister()` and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning `rxAlign` and whatnot. Good luck :).
> 0 votes

---
Tags: programming
---


# Question
Title: Append Text to Variable Names: Please Help Me Shorten This Code
I'm trying to shorten the code under "setup" below, where I have over 120 variables that are being read from an external EEPROM. There is a pattern where the variable that stores the position of the EEPROM address is the name of the variable being populated, plus the word "Pos".

```
byte fanSpeed, nl1Toggle, ledsToggle;
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  fanSpeed = readEE(fanSpeedPos);
  nl1Toggle = readEE(nl1TogglePos);
  ledsToggle = readEE(ledsTogglePos);
  //there are over 120 of the above readEE statements in the actual code.
}

uint8_t readEE(uint8_t entry) {
  readEEPROM(AT24C32_ADDRESS, 1, entry);
}

```

Ideally I would like it to work like this (I'm using pseudo code because I don't know how to do this):

```
char* variableNames [] = { "fanSpeed", "nl1Toggle", "ledsToggle" };
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  for (int i = 1; i < 120; i++;) {
    variableNames[i] = readEE(variableNames[i] + 'Pos');
  }

```

Is this possible using C++ / Arduino?

# Answer
> 3 votes
This can be achieved with a simple preprocessor macro:

```
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

```

You can then use:

```
readEE(foo);

```

and it will be expanded out to:

```
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

```

The `##` operator in macros expands out both sides (VAR and Pos) and then concatenates the results together. Since VAR itself is a macro (whatever you pass when you call the macro) it gets replaced with that value, but Pos, because it isn't a macro, just stays as Pos. So you end up with your variable name concatenated with the word Pos.

Note that you can't use that in a loop with variable names in an array - simply because variable names only exist in the source code, not in the compiled code, so you can't do anything with those variable names once the code is compiled. Hence you have to use the preprocessor to do the job.

Yes, it means you still have to write 120 lines of code for all 120 variables, but they are just shortened to `readEE(varname);`.

However a better solution is to either use Mikael's struct method, or to just use an array and think differently about the concept of names:

```
uint8_t data[120];
for (int i = 0; i < 120; i++) {
    data[i] = readEEPROM(AT24C32_ADDRESS, 1, i);
);

```

So now all your variable values are in the `data[]` array, and you just need to know, in your program, which value is which - and you can do that by defining names for each position as preprocessor macros:

```
#define FAN_SPEED 12
#define N1_TOGGLE 95
#define LEDS_TOGGLE 7

```

Then use those macros in place of the numbers:

```
Serial.println(data[FAN_SPEED]);

```

Alternatively you could use the macros to "mask" variable names:

```
#define fanSpeed data[12]
#define n1Toggle data[95]
#define ledsToggle data[7]

```

There is one thing you might have noticed though: Nothing here shortens your code, it just moves things around a bit. Let's face it - you have 120 variables stored in 120 locations. Whatever you do you're still going to have to have 120 pointers of some form to those variables and their locations. All you can really do is choose the method that provides the most readability so that someone else looking at your code can understand what is going on. Whatever you do you have a long list of variables or variable names to define or set up, which means a lot of typing.

# Answer
> 3 votes
```
variableNames[i] = readEE(variableNames[i] + 'Pos');

```

> Is this possible using C++ / Arduino?

No! Very few programming languages allow that as it requires a lot of run-time information.

Let us instead revisit you issue; Load a large set of variables from EEPROM. What mechanisms do we have in C/C++ and AVR library that could help with this?

Here is a really simple solution that results in a "one-liner"; eeprom\_read\_block().

```
struct var_t {
  byte fanSpeed, nl1Toggle, ledsToggle;
};
var_t var;
const void* pos = ...;
eeprom_read_block(&var, pos, sizeof(var));

```

Obviously `var_t` and `var` are not very good names (and you will have to come up with something better) and this is for the internal EEPROM but the same technique can be used for the I2C EEPROM.

Cheers!

BW: What AT24CXXX library are you using? Because this looks strange.

```
 uint8_t readEE(uint8_t entry) {
   readEEPROM(AT24C32_ADDRESS, 1, entry);
 }

```

No return statement, etc.

---
Tags: c++, variables, array
---


# Question
Title: Send JSON via POST on SIM900 shield with AT commands
I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the **AT+HTTPACTION=1** command, it returns a 601 error: **+HTTPACTION:1,601,0**.

I saw here that the error was 601 Network Error. Could someone help me? Following is my code.

```
void connectInternet() {
  if(digitalRead(9 != LOW)) {
    Serial.print("\r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print(" CONNECT ON INTERNET \r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print("\r\n");
    Serial.println("Connecting...\r");
    cmdAT("AT");
    cmdAT("AT+CIPSHUT");
    cmdAT("AT+CIPMUX=1");
    cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
    cmdAT("AT+CIICR");
    cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
    Serial.print("IP Device: ");
    cmdAT("AT+CIFSR");
  }
}

void send2Api() {
  Serial.print("\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print(" SEND TO API\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print("\r\n");
  cmdAT("AT+CSQ");
  cmdAT("AT+CGATT?");
  cmdAT("AT+SAPBR=2,1");
  // Query if the connection is setup properly, if we get back a IP address then we can proceed
  cmdAT("AT+HTTPPARA=\"CID\",1");
  // Set the HTTP session.
  cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
  // set endPoint
  cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  // set content json
  cmdAT("AT+HTTPDATA=100,5000");
  // POST session start
  // JSON payload
  cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
  delay(100);
  cmdAT("AT+HTTPACTION=1");
  // POST session start
  cmdAT("AT+HTTPREAD");
  // Read the data of HTTP server
  cmdAT("AT+HTTPTERM");
  // terminate http
  ShowSerialData();

```

# Answer
The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):

```
        //--if autobauding was enabled, send a blank AT
        command:='AT';
        send_gprs;

        //--switch to minimal mode - this is required to reset the SIM card
        command:='AT+CFUN=0';
        send_gprs;

        //--set dce speed
        command:='AT+IPR=57600';
        send_gprs;

        //--turn off command echo
        command:='ATE0';
        send_gprs;

        //--turn off command echo again - sometimes the first command is ignored
        command:='ATE0';
        send_gprs;

        //--turn on extended error messages
        command:='AT+CMEE=1';
        send_gprs;

        //--set module to full function
        command:='AT+CFUN=1';
        send_gprs;

```

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:

```
        //--check pin
        command:='AT+CPIN?';
        send_gprs;
        //--right answer is +CPIN: READY
        //--wrong answer is +CME ERROR: 772

```

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:

```
    repeat
        //--reset connection
        command:='AT+CIPSHUT';
        send_gprs;

        //--set GPRS APN
        command:='AT+CSTT="internet.vodafone.net"';
        send_gprs;
    until is_ok=1;

```

And finally, open a GPRS connection:

```
    repeat
        //--Open gprs connection
        command:='AT+CIICR';
        send_gprs;

        //--Get local address - for some reason this is required
        command:='AT+CIFSR';
        send_gprs;

        //--Suppress "SEND OK" after at+cipsend
        command:='AT+CIPSPRT=2';
        send_gprs;

    until is_ok=1;

```

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)

Two very important things:

* any command can fail - it is a good idea to send back the response to an AT command to your console window
* AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.
> 2 votes

---
Tags: arduino-uno, serial, programming, gsm, softwareserial
---


# Question
Title: SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino
I would like to know.

I have Pin 6, 7, 8 and 9 as INPUT\_PULLUP. I have switch to each other pin. Why when I press switch at PIN 6. **SOMETIMES** PIN 7 also getting input. Other case, also when I press switch at 7, other pin also trigger. Why?

This case is random. Sometimes everything is ok when I press 10 times, but after that other pin also trigger. Another case only 4-5 times press, then other pin also trigger.

I use switch on/off not temporary switch.

How to fix this? Is it common problem with arduino?

**UPDATE**

Program. (Simple Program)

```
int led1 = 1;
int led2 = 2;
int led3 = 3;
int led4 = 5;

int switch1 = 6;
int switch2 = 7;
int switch3 = 8;
int switch4 = 9;

int led = 13;

//int counter = 0;

void setup()
{
  // put your setup code here, to run once
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(switch1, INPUT_PULLUP);
      pinMode(switch2, INPUT_PULLUP);
      pinMode(switch3, INPUT_PULLUP);
      pinMode(switch4, INPUT_PULLUP);
      pinMode(led, OUTPUT);
}
void loop()
{

if (digitalRead(switch1) == 0){
  digitalWrite(led1, HIGH);
  }

 if (digitalRead(switch1) == 1){
  digitalWrite(led1, LOW);
  }

if (digitalRead(switch2) == 0){
  digitalWrite(led2, HIGH);
  }

 if (digitalRead(switch2) == 1){
  digitalWrite(led2, LOW);
  }

if (digitalRead(switch3) == 0){
  digitalWrite(led3, HIGH);
  }

 if (digitalRead(switch3) == 1){
  digitalWrite(led3, LOW);
  }

if (digitalRead(switch4) == 0){
  digitalWrite(led4, HIGH);
  }

 if (digitalRead(switch4) == 1){
  digitalWrite(led4, LOW);
  }

digitalWrite(led, HIGH);

delay(1000);

digitalWrite(led, LOW);

}

```

**Schematic**

My Circuit is simple as like that for the input. For the output only to led, resistor and ground.

I found similar case http://www.instructables.com/id/Arduino-Push-Switch-Debouncing-Interrupts/

> On the website, He said, "The problem with this setup was when the button was pressed the interrupt was being called multiple times and even toggling other buttons. Why was this happening? It is caused from a switch bouncing feedback."

Is there any solution without modifying the hardware?

**SOLVE**

The problem is the wire.

My wire for switch is jumper cable, and each other closer (touch) to each other cable. I try to separate, and works. There is no other pin will be trigger.

# Answer
You may be getting switching noise between the button wires, which is low-level and brief, but with no debouncing, it could be just enough to cause the effect you're seeing.

I'd suggest 1) writing a short function that debounces and reads any button; and 2) using if/else statements instead of testing each button twice.

A quick test is to hold one pair of wires closer together or farther apart from each other while you press one of those two buttons, and see whether the distance apart changes the effect. If it does, you've found the cause.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Accelerometer axis inputs driving three RGB LED strips - Trinket Pro 5V
I am looking to take the analogRead Value of the x, y and z axis (at pins 0, 2 and 4) and if it's a motion state, perform a rainbow, cylone and cascade LED sequences using Adafruit Neopixel library.

Using serial connection, I saw that x,y,z axis are read at values of approximately 300.

When I run the code it executed the three Neopixel sequences (redPin at pin 3, GreenPin at pin 5 and BluePin at pin 6) and then continues, even if there is no change of the accelerometer position.

What am I doing wrong? I am using Arduino Trinket Pro 5V and working with the x-axis and RGB strip at pin 3 only to start.

Thank you for your help.

```
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"

#define PIN1 3
#define LED_COUNT1 5
#define PIN2 5
#define LED_COUNT2 5
#define PIN3 6
#define LED_COUNT3 5

// Create an instance of the Adafruit_NeoPixel class called "leds".
// That'll be what we refer to from here on...
Adafruit_NeoPixel RedPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel GreenPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel BluePin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

const int sensorPinRed = A0;
const int sensorPinGreen = A2;
const int sensorPinBlue = A4;

int analogValue = 0;

void setup()
{

  RedPin.begin();  // Call this to start up the LED strip.
  //GreenPin.begin();
  //BluePin.begin();
  clearLEDs();   // This function, defined below, turns all LEDs off...
  RedPin.show();   // ...but the LEDs don't actually update until you call this.
  //GreenPin.show();
  //BluePin.show()}

void loop()
{
  do{
   analogValue = analogRead(sensorPinRed);
  // Ride the Rainbow Road
  for (int i=0; i<LED_COUNT1*10; i++)
  {
    rainbow(i);
    delay(100);  // Delay between rainbow slides
  }

  // Indigo cylon
  // Do a cylon (larson scanner) cycle 10 times
  for (int i=0; i<10; i++)
  {
    // cylon function: first param is color, second is time (in ms) between cycles
    cylon(INDIGO, 500);  // Indigo cylon eye!
  }

  // A light shower of spring green rain
  // This will run the cascade from top->bottom 20 times
  for (int i=0; i<20; i++)
  {
    // First parameter is the color, second is direction, third is ms between falls
    cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
  }
  } while (analogValue>300);
}

// Implements a little larson "cylon" sanner.
// This'll run one full cycle, down one way and back the other
void cylon(unsigned long color, byte wait)
{
  // weight determines how much lighter the outer "eye" colors are
  const byte weight = 4;
  // It'll be easier to decrement each of these colors individually
  // so we'll split them out of the 24-bit color value
  byte red = (color & 0xFF0000) >> 16;
  byte green = (color & 0x00FF00) >> 8;
  byte blue = (color & 0x0000FF);

  // Start at closest LED, and move to the outside
  for (int i=0; i<=LED_COUNT1-1; i++)
  {
    clearLEDs();
    RedPin.setPixelColor(i, red, green, blue);  // Set the bright middle eye
    // Now set two eyes to each side to get progressively dimmer
    for (int j=1; j<3; j++)
    {
      if (i-j >= 0)
        RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
      if (i-j <= LED_COUNT1)
        RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
    }
    RedPin.show();  // Turn the LEDs on
    delay(wait);  // Delay for visibility
  }

  // Now we go back to where we came. Do the same thing.
  for (int i=LED_COUNT1-2; i>=1; i--)
  {
    clearLEDs();
    RedPin.setPixelColor(i, red, green, blue);
    for (int j=1; j<3; j++)
    {
      if (i-j >= 0)
        RedPin.setPixelColor(i-j, red/(weight*j), green/(weight*j), blue/(weight*j));
      if (i-j <= LED_COUNT1)
        RedPin.setPixelColor(i+j, red/(weight*j), green/(weight*j), blue/(weight*j));
      }

    RedPin.show();
    delay(wait);
  }
}

// Cascades a single direction. One time.
void cascade(unsigned long color, byte direction, byte wait)
{
  if (direction == TOP_DOWN)
  {
    for (int i=0; i<LED_COUNT1; i++)
    {
      clearLEDs();  // Turn off all LEDs
      RedPin.setPixelColor(i, color);  // Set just this one
      RedPin.show();
      delay(wait);
    }
  }
  else
  {
    for (int i=LED_COUNT1-1; i>=0; i--)
    {
      clearLEDs();
      RedPin.setPixelColor(i, color);
      RedPin.show();
      delay(wait);
    }
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<LED_COUNT1; i++)
  {
    RedPin.setPixelColor(i, 0);
  }
}

// Prints a rainbow on the ENTIRE LED strip.
//  The rainbow begins at a specified position.
// ROY G BIV!
void rainbow(byte startPosition)
{
  // Need to scale our rainbow. We want a variety of colors, even if there
  // are just 10 or so pixels.
  int rainbowScale = 192 / LED_COUNT1;

  // Next we setup each pixel with the right color
  for (int i=0; i<LED_COUNT1; i++)
  {
    // There are 192 total colors we can get out of the rainbowOrder function.
    // It'll return a color between red->orange->green->...->violet for 0-191.
    RedPin.setPixelColor(i, rainbowOrder((rainbowScale * (i + startPosition)) % 192));
  }
  // Finally, actually turn the LEDs on:
  RedPin.show();
}

```

# Answer
It seems to me that you are coding to always display something on the LEDs:

```
  void loop()
  {
    do {
      analogValue = analogRead(sensorPinRed);
      // display stuff
    } while (analogValue > 300);
  }

```

Assuming that you want the LEDs off when `analogValue` is \<= 300, you have the test in the wrong place. That always does the loop at least once. How about:

```
  void loop()
    {
    analogValue = analogRead(sensorPinRed);
    if (analogValue > 300)
      {
      // display stuff
      }
    else
      {
      clearLEDs();   // Turn all LEDs off...
      RedPin.show();
      BluePin.show();
      GreenPin.show();
      }
    }

```
> 1 votes

# Answer
Thanks to @nick-gammon for debugging my code.

I cleaned it up so below is the working sample. X-axis of the accelerometer is related to PWM pin 3 RGB LED strip, Y axis of pin 5 and Z axis to pin 6.

The LED sequence cascades once in spring green color in response to the tilt in direction.

```
#include <Adafruit_NeoPixel.h>
#include "WS2812_Definitions.h"

#define PIN1 3
#define LED_COUNT1 5
#define PIN2 5
#define LED_COUNT2 5
#define PIN3 6
#define LED_COUNT3 5

// Create an instance of the Adafruit_NeoPixel class called "XPin", "YPin" and "ZPin".
// That'll be what we refer to from here on...
Adafruit_NeoPixel XPin = Adafruit_NeoPixel(LED_COUNT1, PIN1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel YPin = Adafruit_NeoPixel(LED_COUNT2, PIN2, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel ZPin = Adafruit_NeoPixel(LED_COUNT3, PIN3, NEO_GRB + NEO_KHZ800);

const int sensorPinX = A0;
const int sensorPinY = A2;
const int sensorPinZ = A4;

int analogValueX = 0;
int analogValueY = 0;
int analogValueZ = 0;

void setup()
{

  XPin.begin();  // Call this to start up the LED strip.
  YPin.begin();
  ZPin.begin();
  clearLEDs();   // This function, defined below, turns all LEDs off...

}

void loop()
{
   analogValueX = analogRead(sensorPinX);
   analogValueY = analogRead(sensorPinY);
   analogValueZ = analogRead(sensorPinZ);
   if ((analogValueX > 400) || (analogValueY > 400) || (analogValueZ > 400) )
   {

  // A light shower of spring green rain
  // This will run the cascade from top->bottom i times
  for (int i=0; i<1; i++)
  {
    // First parameter is the color, second is direction, third is ms between falls
    cascade(MEDIUMSPRINGGREEN, TOP_DOWN, 100);
  }
   }
   else
   {
     clearLEDs(); // Turn all LEDs off
   }
}

// Cascades a single direction. One time.
void cascade(unsigned long color, byte direction, byte wait)
{
  if (direction == TOP_DOWN)
  {
    for (int i=0; i<LED_COUNT1; i++)
    {
      clearLEDs();  // Turn off all LEDs
      XPin.setPixelColor(i, color);  // Set just this one
      XPin.show();
      delay(wait);
    }

    for (int i=0; i<LED_COUNT2; i++)
    {
      clearLEDs();  // Turn off all LEDs
      YPin.setPixelColor(i, color);  // Set just this one
      YPin.show();
      delay(wait);
    }
    for (int i=0; i<LED_COUNT3; i++)
    {
      clearLEDs();  // Turn off all LEDs
      ZPin.setPixelColor(i, color);  // Set just this one
      ZPin.show();
      delay(wait);
    }
  }
  else
  {
    for (int i=LED_COUNT1-1; i>=0; i--)
    {
      clearLEDs();
      XPin.setPixelColor(i, color);
      XPin.show();
      delay(wait);
    }

    for (int i=LED_COUNT2-1; i>=0; i--)
    {
      clearLEDs();
      YPin.setPixelColor(i, color);
      YPin.show();
      delay(wait);
    }

    for (int i=LED_COUNT3-1; i>=0; i--)
    {
      clearLEDs();
      ZPin.setPixelColor(i, color);
      ZPin.show();
      delay(wait);
    }
  }
}

// Sets all LEDs to off, but DOES NOT update the display;
// call leds.show() to actually turn them off after this.
void clearLEDs()
{
  for (int i=0; i<LED_COUNT1; i++)
  {
    XPin.setPixelColor(i, 0);
  }
  for (int i=0; i<LED_COUNT2; i++)
  {
    YPin.setPixelColor(i, 0);
  }
  for (int i=0; i<LED_COUNT3; i++)
  {
    ZPin.setPixelColor(i, 0);
  }
}

```
> 1 votes

---
Tags: arduino-uno, analogread, accelerometer, rgb-led, neopixel
---


title: Strange results trying to count pulses

text:
# Question
Title: Strange results trying to count pulses
I am now hopelessly stuck and need help please.

I am building an automated observatory and now at the stage of trying to control the observatory dome rotation. The dome is rotated using a step motor and it works fine. The rotation of the dome also turns a rotary encoder to give an independent verification that the dome is moving. Although the RE is a quadrature type I am simply counting RE ticks from both channels as I don't need direction information.

What I am trying to do now is to count how many motor driving pulses occur between each pair of RE ticks. The reasoning behind this is to monitor the dome movements and detect jamming. The actual motor pulses will be used for all dome position calculations.

To achieve this, I have built a small board with a ULN2803A inverting buffer and an Arduino Nano. The Nano uses Pin Change interrupts on pins D11 and D12 to count the RE ticks. Pin D7 will also be used to monitor a Home Position sensor although this doesn't exist at present. The motor pulses are sent via the buffer to Pin D2 (INT0) and the motor direction is sent via the buffer to pin D3 (INT1). The external interrupts are then used to count the motor pulses, up or down depending on the motor direction.

For information, there is another board present, a Velleman VM110 USB breakout board, that also receives the rotary encoder ticks. This gives me a simple way to check that my board gives the same answer when I rotate the rotary encoder shaft by hand.

OK - sorry this is so long winded but now it gets weird.

When I rotate the RE without the motor running everything is fine. I get four times as many pulses as the Velleman board as I am using Pin Changes, triggering on each rise and fall, not on full cycles of the encoder. This does happen as predicted and everything is nice and stable.

BUT - when I start the motor running, I get hundreds of RE ticks every time I move the encoder and sometimes I get increasing RE ticks without touching the encoder at all.

The obvious answer is some form of RFI but I have done everything I can to eliminate this. The motor driver and the Nano board that powers it are in a shielded enclosure, the cable to the motor is a shielded cable and I have 10uH chokes on each of the four motor leads. Finally, I have fitted a filter to the incoming power supply to the motor box to minimise any RFI going back down the power lines.

The use of the ULN2803A buffer was my latest attempt to make this work. Previously the signals went direct to the Nano pins. With the buffer, I have used 20k pull-ups on the input side and 10k pull-ups on the outputs. This was a direct copy of the Velleman board input circuit that I knew worked without problems.

I have looked at the motor pulses at the input pin to the Nano on my scope and they are nice looking, sharp edged pulses of duration 70 uS and a frequency of 497 Hz. Not bad as I set the pulse rate using the Accelstepper library to 500Hz.

I now suspect that this is a software problem. This wouldn't surprise me as I am very new to all this, just trying to learn enough at each stage to do what I need. I have attached the code - this is a stripped down version without a lot of I2C stuff that is not relevant to my problems.

Again, for information. I have tried using the `attachInterrupt()` function and by directly setting the relevant registers - no difference!

Anyway, I really really hope someone can help me sort this out.

Regards, Hugh

```
/*
ABoard3
ROTATION MONITORING AND POSITION
Version AB3_stripped
*****************************PURPOSE*****************************************
This sketch is used on an Arduino Nano to count the motor pulses from ABoard1
and the Rotary Encoder ticks. The motor pulse count between encoder ticks is
used to detect dome jamming.
****************************INPUTS*******************************************
PIN CHANGE INTERRUPTS
**********ROTARY ENCODER INPUT*********
The rotary encoder is a Bourns ENA1J-B28 L00064L 1139M MEX 64 cycle per turn
optical encoder. This is connected to ABoard3 Pins D11 and D12. These pins
connect to Channel A and Channel B respectively. Pin change interrupts are used
to receive the rotary encoder output.
(The output pulses from the rotary encoder is also sent to the Velleman board
for use by LesveDomeNet for finding dome position)
*********HOME POSITION INPUT*********
The home position sensor is an Omron EESX671 Optical Sensor.
The sensor output is connected to ABoard3 Pin D7.
Pin change interrupt PCINT21 records activation/deactivation of the sensor.
EXTERNAL INTERRUPTS
*********MOTOR PULSE INPUT***********
The pulses sent to the G251X stepper driver are also sent to Aboard3 Pin D2.
This pin is the External Interrupt pin, vector INT0
*********MOTOR DIRECTION INPUT********
Motor direction is input to ABoard3 from ABoard2. ABoard2 pin, pnVmInRotMotor
(AB2:A0{54}) is connected to Velleman pins DI4 and DO2 and also to AB3:D3.
AB3:D3 is an External Interrupt pin, vector INT1.
*/

#include <Wire.h>
#include "streaming.h"
#include "I2C_AnythingHEG.h"
#include <EEPROMex.h>

//CONSTANTS
//PIN ASSIGNMENTS For ABOARD3
const uint8_t pnMotorPulse = 2;      //Port PD2, INT0, ISR(INT0_vect){}
const uint8_t pnMotorDirection = 3;  //Port PD3, INT1, ISR(INT1_vect){}
const uint8_t pnDomeAtHome = 7;      //Port PD7, PCINT23,ISR(PCINT2_vect){}
const uint8_t pnREChanA = 11;        //Port PB3, PCINT3, ISR(PCINT0_vect){}
const uint8_t pnREChanB = 12;        //Port PB4, PCINT4, ISR(PCINT0_vect){}

//*****************EXPERIMENTAL STUFF FOR PULSE COUNTING*******************************
uint16_t volatile myTest = 0;
int32_t volatile ratioCount = 0L;
int32_t volatile totalCount = 0L;
int32_t volatile tickCount = 0L;
uint8_t volatile halftickCount = 0;
int32_t volatile addPulse = 0L;

void setup() {
  //**********************************SERIAL FOR DEBUG ONLY************************
  Serial.begin(115200);
  //*************************INPUT PIN MODE SETUP**********************************
  //NOTE Set all UNUSED PCINT0:5 pins (D8, D9, D10, D11) to OUTPUT.
  //and set the value to LOW
  //The actual pins used to receive interrupts have external 10k pull-ups.
  //This is to reduce susceptibility to interference causing false triggering.
  pinMode(pnMotorPulse, INPUT); //D2
  pinMode(pnMotorDirection, INPUT); //D3
  pinMode(pnDomeAtHome, INPUT); //D7
  pinMode(pnREChanA, INPUT); //D11
  pinMode(pnREChanB, INPUT); //D12
  pinMode(4, OUTPUT); //D4
  digitalWrite(4, LOW);
  pinMode(8, OUTPUT); //D8
  digitalWrite(8, LOW);
  pinMode(9, OUTPUT); //D9
  digitalWrite(9, LOW);
  pinMode(10, OUTPUT); //D10
  digitalWrite(10, LOW);
  //******************SET UP AddPulse According to Motor Direction******************
  //This is needed to make sure the pulse counting starts in the correct direction
  //as the direction is only checked in the ISR after a change has occurred.
  //If Motor Direction is AntiClockwise, change to Subtract a pulse
  if( digitalRead(pnMotorDirection)) {
    addPulse = 1L;
  } else {
    addPulse = -1L;
  }
  //**************************SET UP PIN CHANGE INTERRUPTS**************************
  //Set the Pin Change Interrupt Masks
  //Clear all bits to start with
  PCMSK0 &= 0b00000000; //Clear all bits
  PCMSK1 &= 0b00000000; //Clear all bits
  PCMSK2 &= 0b00000000; //Clear all bits
  //Mask for PCINTs 0 through 7 is PCMSK0 (Rotary Encoder Pulses)
  //Need to allow interrupts on PCINT3 and PCINT4, so set bits 3 and 4
  //PCINT3 is Nano  pin D11 and PCINT4 is Nano pin D12
  //Use a compound bitwise OR to set the bits
  PCMSK0 |= 0b00011000; //Enable PCINT3 ONLY (bit 3)
  //Interrupt on pins 11 and 12, RE Ticks
  //Mask for PCINTs 16through 23 is PCMSK2 (Home Position)
  //Need to allow interrupts on PCINT23 so set bit 7
  PCMSK2 |= 0b10000000; //Interrupt on pin 7, Home Position Sensor activated
  //Now enable the interrupts (TURN THEM ON) by setting bits in PCICR
  //PCICR is Pin Change Interupt Control Register.Set bit 0 (PCIE0)
  //to enable interrupts PCINT0:7 This catches PCINT3 and 4 - RE Ticks
  //Set bit 2 (PCIE2) to enable interrupts PCINT16:23. Catches PCINT21 - Home Position Sensor
  PCICR &= 0b00000000; //Clear PCICR register
  PCICR |= 0b00000001; //Set bit 0 - Catches PCINT3 & PCINT4 - RE Ticks
  PCICR |= 0b00000100; //Set bit 2 - Catch PCINT21 - Home Position Sensor
  //**************************SET UP 'EXTERNAL INTERRUPTS'**************************
  //Interupts on External Interrupt Pins D2 (INT0) and D3 (INT1).
  //INT0 (Nano pin D2)occurs when a stepper motor driver pulse is received
  //INT1 (Nano pin D3)occurs when the ABoard2 pin, pnVmInRotMotor toggles
  //indicating a motor direction change.
  //To use the 'External Interrupts' the following registers need to be set-up:
  //EICRA External Interrupt Control Register A
  //Need to set Interrupt Sense Control bits ISC11 .. ISC00 (bits 3:0 in EICRA)
  //ISC01     ISC00 (INT0)    Interrupt
  //ISC11     ISC01 (INT1)    Generated by
  //  0         0             Low level on Pin
  //  0         1             Any Logical Change
  //  1         0             Falling Edge
  //  1         1             Rising Edge
  //First clear all bits, then set as follows:
  //For INT1 - Motor Direction - Generate on ANY LOGICAL CHANGE
  //bit 3 ISC11 0
  //bit 2 ISC10 1 This combination = Any logical change causes interrupt
  //For INT0 - Stepper Motor Pulses  - Generate on RISING EDGE
  //bit 1 ISC01 1
  //bit 0 ISC00 1 This combination = Rising edge of pulse causes interrupt
  //NOTE: To provide some immunity to RFI, Aboard3:Pins 2 & 3 are pulled high
  //using 10k resistors.
  //So, code is
  EICRA &= 0b00000000; //Clear EICRA register
  EICRA |= 0b00000111; // Set bits 0,1 and 2 in EICRA register
  //EIMSK External Interrupt Mask Register
  //Need to set External Interrupt Request Enables INT1 & INT0  (bits 1:0)
  //First clear both bits, then set as follows:
  //bit 1  INT1  1 External interrupt pin (D3) enabled
  //bit 0  INT0  1 External interrupt pin (D2) enabled
  //So, code is
  EIMSK &= 0b00000000; //Clear EIMSK register
  EIMSK |= 0b00000011; // Set bits 0 and 1 in EIMSK register
  //NOTE: Setting EIMSK TURNS ON THE EXTERNAL INTERRUPTS
  //************VARIABLE INITIALISATION*********
  myCommand = 0;
  myTest = 0;
  tickCount = 0L;
  totalCount = 0L;
} //END of setup

void loop() {
  //******************************COMMAND ACTIONS******************************
  if (myTest == 3) (
    //RE tick
    Serial << "Tick Count = " << tickCount << "  totalCount = " << totalCount << "\n";
    myTest = 0;
  }
}
//*************************FUNCTIONS / ISRs FROM HEREON*************************
ISR(INT0_vect) {
  //Triggered by stepper motor drive pulse from ABoard1
  totalCount = totalCount + addPulse;
}
ISR(INT1_vect) {
  //Triggered by a change in motor direction
  if(digitalRead(pnMotorDirection)) {
    addPulse = 1L;
  } else {
    addPulse = -1L;
  }
}
ISR(PCINT0_vect) {
  //Triggered by a ROTARY ENCODER TICK
  halftickCount++;
  if (halftickCount == 2) {
    //Make count same as Velleman
    tickCount++;
    halftickCount = 0;
    myTest = 3;
  }
}
ISR(PCINT2_vect) {
  //Triggered by activation of Home Position Sensor
  myTest = 4;
}

```

# Answer
There is no need to use int32\_t for some of the variables. The problem with using variables that are more than 8 bits on a 8-bit processor, is that the processor needs 4 reads to get the value. In the middle of those reads an interrupt might occur, resulting in a value that has some bits of the old value, and some bits of the new.

Some variable only need 8 bits.

```
uint8_t volatile myTest = 0;
int32_t volatile totalCount = 0L;
int32_t volatile tickCount = 0L;
uint8_t volatile halftickCount = 0;
int8_t volatile addPulse = 0L;

```

The next thing is to make the reading of the value atomic.

```
void loop()
{
//******************************COMMAND ACTIONS******************************

if (myTest == 3)   //RE tick
{
    noInterrupts();
    int32_t tickCountCopy = tickCount;
    int32_t totalCountCopy = totalCount;
    interrupts();
    Serial << "Tick Count = " << tickCountCopy << "  totalCount = " << totalCountCopy << "\n";
    myTest = 0;
}
}

```

PS. this is not necessarily an answer, but it didn't fit in the comments.
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: ATMEL SAMD11 SPI (Slave) With Arduino (Master)
I am trying to get my Atmel SAMD11 XPLAINED PRO and arduino to talk to each other using SPI. I have set up the arduino as the master, with the SAMD11 as the slave. On the ATMEL, I have the following code:

http://asf.atmel.com/docs/latest/samd21/html/asfdoc\_sam0\_sercom\_spi\_slave\_callback\_use.html

Essentially, it waits until the master sends data, compares the data with what it expects, and updates an LED accordingly. On the arduino side, I have the following:

```
#include <SPI.h>

#define BUF_LENGTH 20
int slave_select = 10;

void setup (void)
{
  // Initialize serial for DEBUG.
  Serial.begin(9600);
  pinMode (slave_select, OUTPUT);
  digitalWrite(slave_select, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0
  // Master initialized.
  Serial.println("Master Initialized");
}  // end of setup

void loop (void)
{
  static uint8_t buffer_expect[BUF_LENGTH] = {
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
     0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13
  };
  // enable Slave Select
  digitalWrite(slave_select, LOW);    // SS is pin 10

  //write the 20 bytes
  for (int I=0;I<20;I++)
  {
    SPI.transfer(buffer_expect[I]); //write data byte
    delay(20);
  }

  // disable Slave Select
  digitalWrite(slave_select, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

```

When I run the code, the LED on the SAMD11 isn't updated, which means that it is waiting for data to be sent, and hasn't received any, despite what the arduino code writes. On the hardware side, I have GND connected on both boards, VCC on the SAM to 5V on the arduino, and SPI\_SS\_A, MOSI, MISO and SCK connected to pins 10,11,12 and 13 on the arduino respectively.

# Answer
> 1 votes
You haven't set your SS pin as an output anywhere in your code.

The arduino page you linked to has a note near the bottom which reads:

> Note about Slave Select (SS) pin on AVR based boards
>
> All AVR based boards have an SS pin that is useful when they act as a slave controlled by an external master. Since this library supports only master mode, this pin should be set always as OUTPUT otherwise the SPI interface could be put automatically into slave mode by hardware, rendering the library inoperative. It is, however, possible to use any pin as the Slave Select (SS) for the devices. For example, the Arduino Ethernet shield uses pin 4 to control the SPI connection to the on-board SD card, and pin 10 to control the connection to the Ethernet controller.

The Example code given for the teensy board on the other page you linked has:

```
pinMode (slaveSelectPin, OUTPUT);

```

in its setup() function.

So that's what you're missing.
Setting the pin high or low is not going to achieve anything if its not an output.

Remember that SPI can access many diffrent devices using the same MOSI/MISO/SCK pins, but each slave device has its own Slave-Select pin which needs to be individually driven by the master.
Your master can therefore have many different SS pins, all set as outputs - and there is no single standard pin for this.

---
Tags: spi
---


# Question
Title: Unable to use RGB matrix and the serial monitor at once
Recently I bought the following matrix: https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview

I own an Arduino Uno for those who are interested.

I got the 32x32 variant and I am very happy with it. I managed to connect all the wires correctly and get the examples of the library working.

The problem I am facing right now is I can't get it to work properly for a personal project of mine. Somehow I am unable to use the serial functions and the matrix library functions in one project.

Currently my project looks like this:

My Arduino is connected like this:

And the code I wrote is:

```
#include <gamma.h>
#include <RGBmatrixPanel.h>
#include <Adafruit_GFX.h>
#include <gfxfont.h>

#define CLK 8
#define OE  9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2
#define D   A3

RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false);
String incomingCommand = "";

void setup() {
  Serial.begin(9600);
  matrix.begin();
  matrix.fillRect(0, 0, 32, 32, matrix.Color333(0, 0, 0));
}

void loop() {
  if (Serial.available() > 0) {
    int incomingByte = Serial.read();
    char receivedChar = (char) incomingByte;
    incomingCommand += receivedChar;
  }

  if (incomingCommand.indexOf('#') > - 1 && incomingCommand.indexOf('%') > - 1) {
    String rawCommand = incomingCommand.substring(incomingCommand.indexOf('#'), incomingCommand.indexOf('%') + 1);
    rawCommand = rawCommand.substring(1, rawCommand.length() - 1);
    Serial.print("Following command received: ");
    Serial.println(rawCommand);
    if (rawCommand == "turnledon") {
      matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
    }
    incomingCommand = "";
    rawCommand = "";
  }
}

```

The idea is that a command gets sent from the serial monitor. Based on the command one led on the matrix will turn on. An example of a future command will look similar to this: "#drawPixel\_X1\_Y2%", hence the part that checks on "#" and "&".

The problem is that the functionality of the serial monitor isn't working with line 14 and 48 of the code. As soon as I remove those lines, the serial monitor works perfectly and I can receive and write to the serial monitor. I have no idea what is causing this.

I was wondering if someone ever faced a similar problem or knows what I am doing wrong right now.

Thank you in advance!

# Answer
According to Adafruit https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview these led matrixes require active scanning. It means that the RGBMatrixPanel will set up some scanning interrupt to refresh the screen periodically.

This can very much interfere with serial receive, as according to Adafruit, the panels require a serious data transmission all the time.

Try the followings:

* have one byte serial commands, e.g. N for "on" and F for "off" (I know you will need more complex commands, but this is just to verify the theory)
* remove all debug Serial.printlns (those also consume some time)

So try this:

```
void loop() {
  if (Serial.available() > 0) {
    char incomingByte = Serial.read();
    if (incomingByte=='N') {
       matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
    }
    if (incomingByte=='F') {
       matrix.drawPixel(0, 0, matrix.Color333(0, 0, 0));
    }
  }
}

```
> 2 votes

---
Tags: arduino-uno, adafruit, rgb-led
---


# Question
Title: Smallest digital 3-axis gyroscope pcb for arduino?
What is the smallest size digital 3-axis gyroscope pcb compatible with an arduino that I can buy or maybe make if its simple enough. I need one really really tiny probably around 0.8x0.1x0.5 (doesn't have to be that small but the smaller the better).

Thanks,

# Answer
smallest board is no board. pick a small BGA or LGA shaped accelerometer and superglue it face down to the arduino board then solder fine wires beween the chip terminals and arduino terminals.

search digikey for 'spi accelerometer'
> 3 votes

# Answer
Arduino accesories are generally large because they are meant to be easy to use. mpu-6050 is a good example and you can find many decent breakout boards for it. But if you really want it to be very small, you should consider a custom solution for your problem like designing a PCB that holds both the microcontroller and the accelerometer.
> 1 votes

# Answer
Bosch CNO055 chip is an IMU-Cortex combo capable of outputting 3-D coordinates directly in several formats via several data interfaces. Adafruit has a product based on this chip, along with Arduino library (the CNO055 is in the middle to get you an idea about minimum size) -\> https://www.adafruit.com/products/2472.
> 0 votes

---
Tags: gyroscope
---


# Question
Title: When I call the tone function on a Uno, why do I not have to declare the pinmode in setup?
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup? Like so:

```
// Simplest tone
void setup() {
}

void loop() {
    tone (8,500); //on pin 8 output 500 Hz
}

```

# Answer
Because the `tone(hertz)` code initializes the pinmode, along with the timer/counter control registers to produce the appropriate frequency.

```
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
{
  uint8_t prescalarbits = 0b001;
  long toggle_count = 0;
  uint32_t ocr = 0;
  int8_t _timer;

  _timer = toneBegin(_pin);

  if (_timer >= 0)
  {
    // Set the pinMode as OUTPUT
    pinMode(_pin, OUTPUT);
   ...

```

See Tone.cpp - line 255 for the source.
> 7 votes

---
Tags: arduino-uno
---


# Question
Title: How to connect more than 10 sensors to Arduino uno r3
How I can connect more than 10 sensors to Arduino Uno R3? I calculated it and I can connect just 4 fire flame sensors (sensors which can find a fire (a candle, for example)) and maybe 1 ultrasonic sensor. I need more for my project. I need an IR Sensor, a fire flame sensor on every side, and 1 ultrasonic sensor in front. Additionally, I need to connect 2 DC motors, 1 fan, and 1 servo-motor for ultrasonic sensor. How can I solve this? I must buy Arduino Mega?

# Answer
You can easily increase number of I/O pins using an expander, e.g. PCF8574. The expander can be connect using your SCL/SDA pins located next to GND/AREF pins. (Here you can find detailed photo: http://forum.arduino.cc/index.php?topic=84190.0) You can connect up to 8 such expanders to extend the number of your digital pins to 64.
Once you connect it, here is a code snippet of how to use it:

```
#include <PCF8574.h> //library available at: https://github.com/skywodd/pcf8574_arduino_library

void setup() {
  PCF8574 sensors;
  sensors.begin(0x20); //0x20 means that you connected A0, A1, A2 pins of PCF8574 to the ground
  sensors.pinMode(0, INPUT_PULLUP);
  sensors.pinMode(1, INPUT_PULLUP);
/*...*/
}
void loop() {

  byte sensorValue = sensors.digitalRead(0); //reads digital value of 1st sensor connected to pin 0 of PCF8574 expander
  /*...*/
}

```

You can read more with this tutorial (note: they are using wire interface, so the code will differ. Choose the one you prefer).
> 7 votes

# Answer
I wouldn't recommend multiplexing, but I do agree that one way is to add a second MCU.

Another better option is to use an N-bit shift register. These are little IC's that are exactly what the name entails: shift registers, and are much easier to setup and interface to than wasting a whole other microcontroller to add I/O's or multiplexing (which limits your application). You effectively shift in the I/O settings that you want and then can latch those registers when you have the proper I/O sequence loaded into the register. In other words if I wanted to have 8 new I/O pins, I could connect an 8-bit shift register to my MCU and if I wanted 4 of the first pins HIGH and the last 4 low, I would shift in 00001111b, then latch the data so that it appears on the output just as if it were any regular I/O pin on the MCU.

They only require a few pins to operate them (, so this is an easy way to add more sensors to your system. As always, check the datasheet to make sure the IC meets your specs (in terms of current draw, voltage, etc).

A disadvantage to this is that for an N-bit shift register, you will burn N clock cycles to load in the data. For most applications this should be fine, but it is worth noting. It also makes for slightly more complex code (although I am sure there are libraries for them out there).

Note: I saw that you mentioned controlling things such as DC motors, etc. Make sure you are not trying to directly drive them with the I/O pins, and are using a switch or transistor to control these types of peripherals.
> 2 votes

# Answer
The Mega is the easiest way to get many pins is, as you said, the Mega. It has many other advantages, such as more amperage, more memory, and more UART ports. I highly recommend doing this route for a beginner, even if you get a clone instead of an official board. If none of this would be an advantage to you, there are a few different things.

* **Second MCU.** You can get another chip identical to the Uno's to connect. This is called an ATmega standalone. They're fairly cheap. I2C is the easiest way to connect them, using only two pins from each chip. The setup will depend on the project.
* **Multiplexing.** There is a way that you can connect more stuff than there is pins on the Arduino. This is called *multiplexing*. It does affect performance a little, but for some applications it is worth it. Note: this won't work well with libraries or SPI/I2C. The 4051 chip seems like a decent chip. The Arduino playground has good introduction article on this chip..
> 1 votes

# Answer
There are a number of ways to get more inputs and outputs, with different implications. And it depends on the types of sensors, and on the libraries or code snippets you want to use.

The first thing you need to do is list the sensors you want, along with the type of interface each uses; I use a spreadsheet.

For example, a flame sensor could just use a single digital output (going to a digital input on the Arduino), with the threshold set with a pot on the module. Or it could output an analog signal which goes to an analog input on the Arduino, allowing the code to detect intensity or set varying thresholds without needing to move the pot. Each approach has different implications.

There are still other sensor and actuator interfaces besides these two (simple digital and analog). Some give a variable value (like analog) but based on timing a pulse on a digital signal; this is how most inexpensive ultrasonic rangefinders work. And of course there are sensors which use standard (I2C or SPI) or proprietary (one-wire protocol, or the DHT-xx temp & humidity sensors).

Likewise some outputs will need PWM or other signally, beyond simple on/off.

Extra simple digital inputs, or outputs, can be had fairly easy with I2C extenders, or with shift registers. For example, checking a digital output flame sensor, or turning on a light.

Extra analog inputs can be done with analog multiplexing (like an electronic switch), or via external ADC modules using I2C or SPI.

If timing is required, there are larger potential problems. Often you would use a library to handle such things.

**Libraries.** Most sensor and actuator libraries will be written to use direct input and output pins on the Arduino. You may be able to pass a pin number when initializing, but if you are using a shift register or extender there's no way to tell the library how to use your custom extension. In this case you will have to roll our own code without using the library, or make a modified version of the library which does I/O through your hardware extension hardware.

**Special Pin Functions.** A second problem is special pin functions; if the library or code snippet you want to use expects to use a special feature of a pin (like a pin interrupt, or a timer input capture), that may not be available from your extension hardware, or may be extra work to handle. For example, some extenders may be able to signal an interrupt pin on the Arduino when one of their inputs changes - but you'll have to write your own interrupt handler to catch that, and replace the functionality of the direct pin interrupt.

**Timing.** And a third problem is that sometimes tight timing is hard to manage through extension hardware.

Most of these can be resolved with appropriate effort, sometimes easy and sometimes not. Look through your list of sensors and actuators; sort out which ones can most easily be attached to extension hardware (like a shift register), and which ones should be directly attached to the Arduino for simplicity or performance. You could be lucky.

**Recommendations**

1) If you can handle any fancy sensors or actuators with direct pins, and cover any simple ones with shift registers or I2C extender chips, that's a viable option. For example, if your code wants to check occasionally whether a flame has been sensed (digital version), or wants to turn on a motor, it's not that hard to go through a shift register instead of doing a direct pin access.

2) If you go beyond that, and run out of pins for things that are much easier to handle when directly connected, then I suggest going to a Mega or Mega2560. It has more digital pins and more analog inputs and more PWM outputs. Most (tho not all) libraries will adapt just by changing pin numbers. It's much easier than rewriting libraries to use external digital and analog pins.
> 0 votes

---
Tags: arduino-uno, sensors
---


# Question
Title: Arduino development vs nRF51 development
Originally I had an idea to develop an Arduino-compatible project using an **ATmega328P**, some sensors and the **nRF51822** as the BLE radio. As I progressed, I realized that if I relaxed the Arduino-compatible requirement, I could actually do away with the ATmega328P and write the application directly on the nRF51822 as it is a more capable MCU (32-bit, more memory, faster, has SPI, I2C and TTL serial, etc.) I'm not familiar with writing native applications for the nRF51822 but it seems much more complicated.

For someone that has experience in both platforms, can you please list some of the tradeoffs of developing using an ATmega328P for application + nRF51822 for radio and using the nRF51822 for both application and radio?

# Answer
First, there are various ports of the Arduino environment to the NRF51822, but I'll leave that aside for the moment and address using Nordic's codebase or the mbed one.

Generally speaking, one of these paths will put you more in the current "real world" of professional level embedded development, in which the ARM cortex parts play a leading role. You will have conventional multiple source file projects tied together by more ordinary means such as a Makefile or explicit IDE configuration, rather than the rather oddball way the Arduino IDE has evolved to do things. The basic lower level APIs you will be writing against will be much more conventional - ie, your code will start in `main()` rather than `setup()` and `loop()`, you will generate debug messages with `printf()` or similarly styled member function on mbed, rather than Arduino type `print()`/`println()` (though of course you can use `printf()` on an Arduino with some setup). This tends to make it a lot easier to port or share code between this and other embedded systems, or even between an embedded system and a phone or desktop communicating with or simulating it. Of course you can treat an Arduino as a plain ATmega and do this with that as well, up to the limits of the CPU and its memories.

People tend to think of the mbed option as being an online "toy" for certain boards, but you can generally use others just by setting it for a board using the same MCU in a similar way. And in most cases you can download a zipfile of a project with a Makefile in it that will drive arm-gcc or a few other compiler choices. The NRF51822 does come in varieties with different onboard storage sizes, and this can sometimes require care and attention to the linker script - in a few cases a project that fits in the online build (apparently with the Keil compilation engine as its backed) will not build in the downloaded GCC configuration unless you adjust the linker script to reduce the stack size, or perhaps change compiler optimization levels.

Countering reasons you might end up keeping the ATmega would be if you need some of its I/O peripherals or its 5v I/O capability. For example, the NRF51822 has limited hardware PWM capability compared to an ATmega so that must generally be done in software.

If you are really at home with "The Arduino Way" switching to anything more traditional may take some adjustment of thinking and habits. On the other had, if you look at the benefits of Arduino being the variety of works-out-of-the-box, easily modified examples you can use to explore the possibility of a project, but often find yourself annoyed by the legacy of its countless quirks and atypical approaches in the longer run, then you'll probably find the adaptation to using the NRF51822 directly to have been worthwhile.
> 0 votes

---
Tags: bluetooth, nrf51
---


title: Multiple Wireless Sensors to an Arduino

text:
# Question
Title: Multiple Wireless Sensors to an Arduino
I am looking for ideas on how to connect 12 sensors to an Arduino wirelessly. The sensors will be about 10ft from the Arduino. They need to send one byte of data every 100ms-250ms to the Arduino in an organized manner.

* I have investigated MQTT and pubsubclient, but have not found a way to make an Arduino a Broker, and have been told it is very inefficient for my application.
* I have looked at NRF24L01, but it appears to be limited to just 6 pipes to receive data in an organized fashion.
* I researched Xbee, but have been told that it cannot keep up with the data rate.

Other suggestions are appreciated... Thank you.

# Answer
> 2 votes
I would recommend the nRF24L01.

You don't need one pipe per node - just one pipe.

Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.

The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.

# Answer
> 1 votes
It might be easiest to send a UDP packet over WiFi. There is no extra packet overhead for this "connectionless" protocol: no OPEN, no ACK/NAK, no CLOSE, etc. The incremental cost for additional bytes is very small, so if you decide you need to send 2 bytes, or even 100 bytes, it won't affect the throughput very much.

If you can "batch" the bytes, that would be even better. For example, could you send 8 bytes per node, once every 800ms-2000ms? If not, WiFi speeds should allow the single-byte UDP packet to get through without much latency. Do you know what latency the receiver can accommodate? You might get lower *average* latency with batched packets, depending on the network access time (i.e., how long it takes to hop on to the air).

A roll-your own approach would be to use a raw RF transmitter/receiver with something like VirtualWire. With proper synchronization from the "master", the slaves could each have their own time slot, avoiding collisions (which keeps the network access time low)

# Answer
> 1 votes
Use nRF24L01. To avoid collisions you can query the sensors (as Chris suggested in comment). The setup would be: Each sensor would have unique address. Central unit would transmit request and sensor node would respond to it. Central unit would have different address and all sensors would transmit to that address. You can also use data in ack to pack response.

* Central node (Addr0) -\> Sensor 1 (Addr1): Request
* Sensor 1 (Addr1) -\> Central node (Addr0): Response, sensor data
* Central node (Addr0) -\> Sensor 2 (Addr2): Request
* Sensor 2 (Addr2) -\> Central node (Addr0): Response, sensor data
* Central node (Addr0) -\> Sensor 3 (Addr3): Request
* Sensor 3 (Addr3) -\> Central node (Addr0): Response, sensor data
* ...

---
Tags: arduino-uno, sensors, wireless
---


title: Clone vs Counterfeit (Arduino)

text:
# Question
Title: Clone vs Counterfeit (Arduino)
On this page on Arduino's website, it states

> "HUNDREDS OF COMPANIES AROUND THE WORLD ARE USING IT *\[Arduino Software\]* TO PROGRAM THEIR DEVICES, INCLUDING COMPATIBLES, **CLONES, AND EVEN COUNTERFEIT**." (Emphasis Added)

With open source electronics, what is the difference between a clone, and a counterfeit?

# Answer
> 7 votes
This is not gospel, but here is what those terms are generally used to indicate (as I understand it):

* compatible: a dev board which is compatible with the Arduino IDE/toolchain. The Arduino UNO uses an ATmega328 MCU, while other platforms may use different MCUs i.e. there are multiple MCUs that are compatible with the Arduino IDE. It may or may not have the same form factor. Keep in mind that this term can also be used for shields, "Arduino-compatible" shields are add-on boards that are meant to mate with an Arduino. The Sparkfun RedBoard is an example.
* clone: a dev board which has the same (or very similar) circuitry as an Arduino and the same physical board/layout. They are branded differently, but are, for all intents and purposes, exactly the same as a real Arduino. These boards are permitted under the open-source licensing of the Arduino design. An Freeduino might be an example.
* counterfeit: a dev board which is identical to an original Arduino, and is branded and sold as an original Arduino. As I understand it, the open-source licensing *does not* permit this, however, this does not deter the flood of shops churning out counterfeit Arduinos. A search on eBay or Aliexpress will turn up loads of examples; note the Arduino guide to spotting counterfeits, in general, the silkscreen is blue and the quality of assembly is not quite as good.

The difference between "compatible" and "clone" is a bit blurry, but it's not really important. The main difference between counterfeit and non-counterfeit is that counterfeit Arduinos are boards that are *not sold by Arduino but are branded as such*.

# Answer
> 2 votes
> With open source electronics, what is the difference between a clone, and a counterfeit?

**Counterfeit**: the vendor says/implies that the Arduino board is produced by Arduino/Genuino, an "original", but it is not. The screen-print is the same, but looking closer at the components and PCB there are some differences. You think you can turn to Arduino/Genuino for product support but you cannot.

**Clone**: the vendor states that the board is a "compatible copy", uses all the open-source bill-of-material, schematics, etc, (or slightly changed for cheaper components) when produced, and it is obviously not produced by Arduino/Genuino. You know that you cannot turn to Arduino/Genuino for product support.

The punishment for selling and buying (!!) counterfeit fashion in Italy is very severe.

Counterfeiting is a trademark violation issue.

Cheers!

---
Tags: clones, counterfeit
---


title: What is the point of D0-D3 on LCD?

text:
# Question
Title: What is the point of D0-D3 on LCD?
The Arduino LiquidCrystal library has 4 constructors with different arguments:

```
LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

```

The following comments are stated for the constructor arguments:

> \[...\] d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using only the four data lines (d4, d5, d6, d7).

What is the point of `d0-d3` if they are not needed? Will they decrease the response time?

# Answer
That type of LCD has two main modes of operation: 4-bit mode which uses 4 data pins (d4-d7), and 8-bit mode which uses all 8 data pins (d0-d7).

4-bit mode has the advantage of requiring fewer output pins on your Arduino. However, it means your sketch needs to send each command/character as two separate batches of 4-bits (one after the other). This is handled for you automatically by the LiquidCrystal library, so you won't need any extra complexity in your code. However, it does mean that your sketch requires roughly double the number of processor cycles to send anything to the LCD.

In contrast, 8-bit mode sends each command/character as a single batch of 8-bits. That simply means it technically runs a little faster.

With that said, a person looking at the display probably won't see a significant speed difference most of the time, as it still goes very quickly. The main impact will be on the microcontroller (the Arduino in this case). If it can use the faster 8-bit mode then it can devote a little more processing time to other things. That can be particularly helpful for timing-critical applications.
> 14 votes

# Answer
The answer is on the same page as the quote you mentioned (I have highlighted the important statement):

> Creates a variable of type LiquidCrystal. **The display can be controlled using 4 or 8 data lines**. If the former, omit the pin numbers for d0 to d3 and leave those lines unconnected. The RW pin can be tied to ground instead of connected to a pin on the Arduino; if so, omit it from this function's parameters.

It turns out that the Hitachi HD44780 LCD display can work in 4-bit or 8-bit modes.
> 3 votes

# Answer
The presence of those pins is a requirement of the technique that had to be used to interface the LCD to the microprocessors that were available back when the HD44780U controller chip was developed.

Single chip microcontrollers as we know them were still in the future and the LCD had to be interfaced to the 8-bit microprocessor chips of the times using the same techniques as any other 8-bit I/O or memory device which was an 8-bit bus.
> 2 votes

---
Tags: lcd
---


# Question
Title: How to program pressure sensor and motor with motor shield
I was working on controlling a high power motor with a heavy duty motor controller, and I was able to make my motor spin, but I wasn't able to incorporate a program for my pressure sensor and make it determine the speed of the motor. I'm pretty sure I connected the parts correctly on my circuit board, so I figure my code must have some mistake, or something missing. The pressure sensor I'm using: The motor controller I'm using: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html#Useful The code I have:

```
int motorValue=0;
int sensorValue=0;
int sensorPin=A0;
int EnablePin=8;
int PWMPin2=3;

void setup() {
  // put your setup code here, to run once:
pinMode(EnablePin, OUTPUT);
//pinMode(sensorPin, OUTPUT);
Serial.begin(9600);
pinMode(PWMPin2, OUTPUT);
pinMode(sensorPin, INPUT);
}

void loop() {
// put your main code here, to run repeatedly:
sensorValue = analogRead(sensorPin);

//float voltage = sensorValue * (5.0 / 1023.0);

//Serial.println(voltage);

delay(50);

motorValue=map(sensorValue,0,1023,0,255);
//motorValue=sensorValue / 4;
//analogWrite(motorPin,motorValue);
digitalWrite(EnablePin, HIGH);
analogWrite(PWMPin2, motorValue);
}

```

Edit: The sensor works by reading the voltage. Here's an actual picture of how I wired it:  I used this wiring to print out the voltage with just the Arduino and it worked, and I'm using it with the same wiring but while having the motor shield on top, so that's why I'm guessing that I must not be programming the sensor right with the motor controller. I couldn't get the voltage readings when I used this setup with the motor driver shield.

# Answer
> 0 votes
Depending on the jumper settings, the MegaMoto shield will drive current sense voltages onto one or two of the Arduino analog inputs.

Your picture shows the shunt installed to drive A0, which is of course going to conflict with your attempt to use the same pin for the force sensor.

If you are not using current feedback, it seems like you may be able to just remove that jumper, otherwise you will need to pick distinct pins for the current sense and your force sensor. Consult the manual to be certain.

(The other placement of the other jumper in that block looks a bit suspicious too, almost seems it may be shorting the two current sense channels together, but not certain about that)

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


# Question
Title: What does it mean in I2C, "NACK received"?
I am reading about I2C. On this site:

http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission

It says that `endTransmission()` can return one of the following status codes:

* 0: Successful send.
* 1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
* 2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
* 3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START. 4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?

Here is my example code

```
#include "Wire.h"
void setup() {
  Serial.begin(9600);
  Wire.begin();
}
void loop()  {
  Wire.beginTransmission(42);
  Wire.write(0);
  byte status = Wire.endTransmission();
  Serial.println(status); // always prints 2
}

```

# Answer
> 10 votes
A `NACK` is signaled by an acknowledgement slot in which `SDA` remains high while `SCL` cycles under control of the master.

Since high is the un-driven state of the pulled-up bus, in the absence of a peripheral at the selected address to positively acknowledge by pulling it down, a `NACK` condition will *passively* result.

---
Tags: i2c
---


title: Comparison of a bit vs. setting a bit

text:
# Question
Title: Comparison of a bit vs. setting a bit
Simple question really, I just want to be sure that I understand it correctly. I understand this isn't necessarily Arduino specific.

With regards to the ATmega2560 I'm doing 3 back-to-back A/D conversions - one immediately after the previous finishes. I'm accomplishing this by calling a Single Conversion each time.

I stumbled across this useful code to wait for the conversion to finish:

```
while(ADCSRA & (1<<ADSC))

```

I understand that it is waiting for the conversion to finish and that when this is done the ADSC will be set to 0. (Conversely, I could wait for ADIF to be set to 1.) I'm not as clear on how exactly this line is interpreted.

Normally when I see something along the lines of `(1<<ADSC)` it means write a 1 to the ADSC bit.

But, in this instance, that isn't the case.

Why not just write:

```
while(ADSC);

```

# Answer
You misunderstand the meaning of:

```
1 << ADSC

```

That actually means *Bit-shift 1 left by the number of bits specified by the value ADSC*.

`ADSC` in this case is 6:

```
#define ADSC    6

```

So if you did:

```
while(ADSC);

```

you would actually be doing:

```
while(6);

```

Which of course will never end, since 6 is not 0, so is true.

Instead you shift 1 left 6 times, which in binary would be:

```
00000001
    << 6
01000000

```

That, of course, is 64, or 0x40 in hexadecimal. That is then ANDed with the value of the ADCSRA register to return the value of one single bit within that register. It's then the result of that AND that you control the `while` with. So it ends up as:

```
while(ADCSRA & 0x40);

```

Which will either equate to:

```
while(0x40);

```

if the 7th bit is set, or if it's not set:

```
while(0x00);

```

And since 0x00 is 0 it will equate to false when the bit isn't set and the `while` will finish.
> 4 votes

---
Tags: adc
---


# Question
Title: Why is 1020 steps used for crossfading colors on an RGB LED?
I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it: https://www.arduino.cc/en/Tutorial/ColorCrossfader

I understand all parts of the code except for one thing. The values for red, green and blue are changed incrementally through 1020 steps, because 255\*4 = 1020. But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?

# Answer
> 2 votes
Extract from code:

```
int wait = 10;      // 10ms internal crossFade delay; increase for slower fades

for (int i = 0; i <= 1020; i++) {
  redVal = calculateVal(stepR, redVal, i);
  grnVal = calculateVal(stepG, grnVal, i);
  bluVal = calculateVal(stepB, bluVal, i);

  analogWrite(redPin, redVal);   // Write current values to LED pins
  analogWrite(grnPin, grnVal);
  analogWrite(bluPin, bluVal);

  delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  if (DEBUG) { // If we want serial output, print it at the
    if (i == 0 or i % loopCount == 0) { // beginning, and every loopCount times
    }
    DEBUG += 1;
  }
}

```

The 1020 in the loop determines the time taken to make the crossfade from the current colour to the next - not the total cycle as you seem to think. In the main loop we have

```
crossFade(red);
crossFade(green);
crossFade(blue);
crossFade(yellow);

```

And each of these crossfades will take 1024 * wait ms to complete. 'wait' is set to 10 ms so I would expect it to take 10.24 s to complete a fade from one colour to the next.

\[Edit\]

I think the large number (1020) is just to give a fine resolution in the steps calculation which is all done with integers. (What struck me as odd is that it doesn't use 256 * 4 = 1024.) The larger we make this number the finer the step resolution becomes. With coarse steps the ramp will complete too early.

Let's say we had 255 steps and we wish to go from 134 to 0.

```
step = 255 / (endValue - prevValue)
step = 255 / (134 - 0 ) = 1.9 which will be rounded down to 1.

```

This means that the crossfade will be complete in 134 steps instead of 255. i.e., it will finish 47% early.

If we use 1020 steps and we wish to go from 134 to 0.

```
step = 1020 / (endValue - prevValue)
step = 1020 / (134 - 0 ) = 7.6 which will be rounded down to 7.

```

This means that the crossfade will be complete in 938 steps instead of 1020. i.e., it will finish 8% early.

# Answer
> 0 votes
For my transition between colors I used arrays during the setup to collect the main transitions (bigger jumps between RGB values) then during the loop I used a series of `analogWrite()` commands essentially splitting the jumps by a 16th, for example starting at `255, 0, 0` the next array value was `223, 0, 0` in the loop it went from `255, 0, 0` to `253, 0, 0` to `251, 0, 0` finally landing the last loop value of `225, 0, 0` before starting the loop over at the next array value of `223, 0, 0`. It's important to realize what colors transition into others and what the corresponding RGB values are of that transition.

Tomorrow I'll post my code, it's a bit messy as it was more proof of concept that starting with a distinct plan.

---
Tags: led
---


title: Sizing relays for audio circuit?

text:
# Question
Title: Sizing relays for audio circuit?
Non-technical person here, so please be gentle. I moved into a place that has ceiling speakers in each room (I tried, but they don't come apart, aren't marked other than manufacturer, and that is a company that went out of business 15+ years ago). So, let's assume they are 8 ohm speakers.

I have a media amplifier, and have successfully played music over all the speakers so I know that they work.

My wife would like the ability to select which speakers are on or off, so I'm thinking a quick Arduino project and relay board with 8-12 relays... but I'm not sure how to estimate the load, so I don't know how to appropriately size the relays.

Any suggestions on the best way to do this, or should I just get mains-rated relays and over-engineer the heck out of this?

# Answer
> 0 votes
If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle. Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind. But as you can see from pictures of 5W, 10W, and 40W speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.

If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.

In any case, due to the I² term in the power formula, the range of current to plan for is relatively small. For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I = 0.79 A. If it's 40W, then I = 2.24 A. This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.

*Note 1:* A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC. Audio is low-voltage AC and relay derating probably isn't needed. *Note 2:* The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry. This might not be a problem with low-voltage audio. *Note 3:* Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's high-voltage audio distribution systems article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.

---
Tags: current, audio
---


# Question
Title: Arduino digital input fluctuates with neighbouring pins
I am using digital pins (2,3,4,5) to play midi notes on and off with 3pdt switches with pull down 10k resistor between input pin and ground.

However when I press button 2 randomly at different time interval it sometimes shows pin 3 high in the monitor. (after reading forums here I have realised that it might be due to big switches that I am using where the physical contact plates might be reason for this). I have even changed wires and isolated them from each other to rule out the noise from the wires. I have checked all the connections and soldered the Arduino board pins with best possible skills that I have and tracks are all clear.

Same case occurs between other buttons as but its not always. However after reading about Debounce I have made changes to the code as following, now I got the error only once after that I havent seen it. Can someone have look at the code and advice me if I have assigned Debounce function to multiple switches correctly and if not, what should it be as I am new with coding Since I am using 3pdt switch I have added switch mode..

```
#include <MIDI.h>

int buttonPin[] = {2, 3, 4, 5};
byte mode[] = {0, 0 , 0 ,0};
boolean currentState = LOW;
boolean lastState = LOW;
int buttonPinM[] = {6, 7, 8, 9};
byte mode1[] = {0, 0, 0, 0};

boolean currentState1 = LOW;
boolean lastState1 = LOW;

long lastDebounceTime = 0;
long debounceDelay = 50;

void setup (){
    MIDI.begin(MIDI_CHANNEL_OMNI);

    int i;
    for (i = 0; i < 4; i++) {
        pinMode(buttonPin[i], INPUT);
    }
    int j;
    for (j = 0; j < 4; j++) {
        pinMode(buttonPinM[j], INPUT);
    }

    {
        int i;
        for (i = 0; i < 4; i++);
    }
    {
        int j;
        for (j = 0; j < 4; j++);
    }
}

// This will track which pin/mode we're using

int j = 0;
int i = 0;

void loop () {
    {
        currentState = digitalRead(buttonPin[i]);

        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode[i]) {
                case 0:
                    if (currentState == HIGH) {
                        MIDI.sendNoteOff (i+55, 0, 1);
                        mode[i] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState == HIGH)
                        mode[i] = 2;
                    break;
                case 2:
                    if (currentState == LOW) {
                        MIDI.sendNoteOn (i+55, 127, 1);
                        mode[i] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState == LOW)
                        mode[i] = 0;
                    break;
            }
        }
        lastState = currentState;
        if (++i > 3)
            i = 0;
    }
    {
        currentState1 = digitalRead(buttonPinM[j]);
        if ( (millis() - lastDebounceTime) > debounceDelay) {
            switch (mode1[j]) {
                case 0:
                    if (currentState1 == HIGH ) {
                        MIDI.sendNoteOn (j+61, 127, 1);
                        mode1[j] = 1;
                        lastDebounceTime = millis();
                    }
                    break;
                case 1:
                    if (currentState1 == HIGH)
                        mode1[j] = 2;
                    break;
                case 2:
                    if (currentState1 == LOW) {
                        MIDI.sendNoteOff (j+61, 0, 1);
                        mode1[j] = 3;
                        lastDebounceTime = millis();
                    }
                    break;
                case 3:
                    if (currentState1 == LOW)
                        mode1[j] = 0;
                break;
            }
        }
        lastState1 = currentState1;
        if (++j > 3)
            j = 0;
    }
}

```

# Answer
> 0 votes
Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.

Ok, so there are a couple of things in your code I don't understand:

**1: in the setup()**

```
{
    int i;
    for (i = 0; i < 4; i++);
}
{
    int j;
    for (j = 0; j < 4; j++);
}

```

What are these for?

**2: debouncing**

You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).

**3: modes 1 and 3**

They are quite useless. What are they for?

**4: pins 6,7,8,9**

What are they for?

**5: variable laststate**

What is it for? You never use it

**6: updating one button per loop**

Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.

**In the end**

Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.

One more thing: debounce delay can be lowered (even to just 5ms):

```
#include <MIDI.h>
#include <Bounce2.h>

int buttonPin[] = {2, 3, 4, 5};
int buttonPinM[] = {6, 7, 8, 9};

Bounce debouncers[4];
Bounce debouncersM[4];

int debounceDelay = 50; // Usually is lower - even 5ms is fine
uint8_t i = 0;

void setup ()
{
    MIDI.begin(MIDI_CHANNEL_OMNI);

    for (i = 0; i < 4; i++)
    {
        pinMode(buttonPin[i], INPUT);
        debouncers[i].attach(buttonPin[i]);
        debouncers[i].interval(debounceDelay);

        pinMode(buttonPinM[i], INPUT);
        debouncersM[i].attach(buttonPinM[i]);
        debouncersM[i].interval(debounceDelay);
    }
}

void loop ()
{
    for (i = 0; i < 4; i++)
    {
        debouncers[i].update();
        debouncersM[i].update();
    }

    for (i = 0; i < 4; i++)
    {
        if (debouncers[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOff(i+55, 0, 1);
        if (debouncers[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOn (i+55, 127, 1);
        if (debouncersM[i].rose()) // button i switched from 0 to 1
            MIDI.sendNoteOn (i+61, 127, 1);
        if (debouncersM[i].fell()) // button i switched from 1 to 0
            MIDI.sendNoteOff(i+61, 0, 1);
    }
}

```

---
Tags: arduino-uno
---