# Question
Title: Moving cursor on LCD and changing highlighted value
I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.

```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
    int hours = 11;
    int minutes = 11;
    int seconds = 11;
    lcd.setCursor(0,0);
    lcd.print(hours);
    lcd.print(":");
    lcd.print(minutes);
    lcd.print(":");
    lcd.print(seconds);
    lcd.noBlink();
    delay(300);
    lcd.blink();
    delay(300);

    if (buttons & BUTTON_RIGHT) {
      move cursor right;
      if(lcd.setCursor == lcd.setCursor(0,3) {
        minutes += 1 }

}

```

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.

I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like `if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.`

Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.

Thanks in advance

# Answer
> 1 votes
Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to *11:11:11* after 0.6s of delay.

> lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).

Instead, you should keep track of the location of the cursor with another variable (as mentioned by *gre\_gor*), say *int curLoc*. But note that you have to keep track of the range of values it can go. (*0 \< curLoc \< 16*)

To summarise, the code could look like this:

```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int hours = 11;
int minutes = 11;
int seconds = 11;

int curLoc = 0; //Current cursor location (x-axis)

void setup() {
  lcd.begin(16, 2); //format of display
}

void loop() {
  lcd.setCursor(0,0);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.noBlink();
  delay(300);
  lcd.blink();
  delay(300);

  //move cursor right;
  if (buttons & BUTTON_RIGHT) {
    //Keep the tracker in range
    if(curLoc >= 0 && curLoc < 16){
    curLoc += 1;
    }

    if(curLoc == 3)
    {
      minutes += 1
     }

}

```

---
Tags: arduino-uno, lcd, c, genuino
---


# Question
Title: Recording and storing Midi data with arduino and midi shield
i need help getting started on writing a sketch that would let me record and store midi data from a midi controller connected to a arduino mega through a midi shield. are there any functions in the midi library that will aid in this task?

# Answer
The Arduino MIDI Library allows you to read and write MIDI messages, but only in real time.

Storing MIDI data makes sense only with timestamps, so you have to call `millis()` or `micros()` when you receive a message.

How to actually store the data is something that you have to design yourself; which data structure to use depends on what you want to do with the data later.
> 2 votes

---
Tags: arduino-mega, programming, shields, midi
---


# Question
Title: Erratic readings on Analogread with low voltages
I am using Arduino Uno for measuring sensor voltages. I am using multiplexer to switch between different sensors. The readings measured in the range of 800-900 mv are accurate, but at low millivolts (at about 20 mv) they are erratic. I read repeatedly to get average of 20 values. I get values such as 1.3, 1,4, 2,0, 3.8 etc. Can any one help on why it is happening and how to avoid it.

Additional information: I am using reference voltage of 1.25 volt for better resolution. I tried having delay between two readings, though there is some improvement, still the problem persists.

I appreciate the help by experts. Thanks

# Answer
You are almost certainly running into the noise floor for your setup. When your target signal is a very low voltage your signal to noise ratio (SNR) is small. Because it is the noise floor setting the ADC for better resolution didn't help much. There are many ways to deal with noise. If your signal is "slow" and your noise is random you can try oversampling. If the noise is from the power supply you can add filtering on the input to your sensor. If you have done those and still want to reduce noise more you can try adding shielding to your device/wires.
> 1 votes

---
Tags: arduino-uno, sensors, voltage-level, analogread
---


# Question
Title: Do I really need Ramps 1.4 for laser engraver
I'm making 2-axis laser engraver like system. Arduino waits command from pc, on receive moves laser to next coordinate and send current coordinate to pc.

I have 3 step motors and I'm controlling them with Arduino Uno which is connected to A4988 drivers which is on breadboard. But almost all samples using Ramps. Do I miss something?

# Answer
Ramps 1.4 is one of the proof of concept standards for 3D printer systems. It is a motherboard mostly runs Marlin firmware on it. I advice to to take a look at the firmware if you didn't yet. It is also supporting many motherboards, hardware.

When you open the `configuration.h` file in the firmware and search for this definition `#define MOTHERBOARD` you will be seeing many options available.

After all, the firmware is the key factor. It contains many engineering solutions in it. So, you shouldn't re-invent the wheel. All you have to do is to adapt it with some tweaks as per your design specifications.

But, I would worry more about your motherboard (Arduino Uno) if your design is relatively simple, using less memory and IO pins, it may be just fine. I would consider Mega 2560 instead If I were you.

Good luck with your project.
> 0 votes

---
Tags: arduino-uno, a4988
---


# Question
Title: Accelerometer readings on a moving object
I hope this stack is the right place for this question. I have an accelerometer mounted securely on a swaying object -lets say a stick or pole- this object is swinging back and forth in small angles (+- 20) with a frequency of about 2-3 times a second. Im using the accelerometer output to calculate the tilt of the object, however since the frequency of the swings is relatively high the accelerometer readings are very high as well, and not reliable for calculating the tilt.

from my research i have seen that accelerometers work best in a stable environment. Is there any way to improve the reliability of my accelerometer output in this setup?

# Answer
> 0 votes
A few things to consider.

First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.

Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation. Getting to the max tilt is easier mathematically.

Just for starters.

---
Tags: accelerometer
---


# Question
Title: Too low voltage on digital input on attiny45
I'm using one of my attiny's pins as digital input. I use it with a pulldown resistor. As input I use simple square wave generated by a separate waveform generator. igh state for square wave is 5V, low is 0V.

However, when I look at the voltage on the digital input, voltage of high state is below 2V, while low state is 0V. My arduino doesnt detect high state as "1".

Here is the code:

```
/*
 * Sketch for testing sleep mode with wake up on WDT.
 * Donal Morrissey - 2011.
 * ATTINY85
 */

#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI - comment this out to use with standard arduinos
#include <LiquidCrystal_attiny.h>          // for LCD w/ GPIO MODIFIED for the ATtiny85

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

//uwaga na numer pinu! nie używać tego z resetem
#define STATUS_PIN  1
#define IN_PIN     4
#define LOOP_TIME 5000
#define TIMEOUT 100

#define GPIO_ADDR     0x27
LiquidCrystal_I2C lcd(GPIO_ADDR, 16, 2); // set address & 16 chars / 2 lines

/* f_wdt is a flag used to monitor watchdog status */
volatile int f_wdt=1;

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
ISR( WDT_vect){
  if(f_wdt == 0){
    f_wdt=1;
  }
  else{
  }
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep(void)
{
  lcd.clear();
  lcd.print("Asleep...");

  /* Enable the WD interrupt (note no reset). */
  WDTCR |= (1<<WDIE);

  set_sleep_mode( SLEEP_MODE_PWR_DOWN );   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();
  // Status pin goes low
  digitalWrite( STATUS_PIN, LOW );
  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  // Status pin goes low
  digitalWrite( STATUS_PIN, HIGH );

  /* Re-enable the peripherals. */
  power_all_enable();

  /* Disable the WD interrupt */
  WDTCR &= ~_BV(WDIE);
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup()
{
  /*  Setup the LCD */
  lcd.init();                           // initialize the lcd
  lcd.backlight();                      // Print a message to the LCD.
  lcd.clear();
  lcd.setCursor(0,0);

  /* Inform the user about initialization process */
  lcd.print("Initializing...");
  delay(1000);

  /* Config pins */
  pinMode( IN_PIN, OUTPUT );
  pinMode( STATUS_PIN, OUTPUT );

  /* Initialize pins */
  digitalWrite( STATUS_PIN, HIGH );

  /*** Setup the WDT ***/

  /* Clear the reset flag of watchdog interrupts, so that they are available again. */
  MCUSR &= ~(1<<WDRF);

  /* Enable configuration changes
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);

/*
WDP3       WDP2    WDP1     WDP0         Number of WDT     Typical Time-out at
                                         Oscillator Cycles     VCC = 5.0V
  0         0      0        0             2K (2048) cycles       16 ms
  0         0      0        1             4K (4096) cycles       32 ms
  0         0      1        0             8K (8192) cycles       64 ms
  0         0      1        1            16K (16384) cycles    0.125 s
  0         1      0        0            32K (32768) cycles    0.25 s
  0         1      0        1            64K (65536) cycles    0.5 s
  0         1      1        0            128K (131072) cycles 1.0 s
  0         1      1        1            256K (262144) cycles 2.0 s
  1         0      0        0            512K (524288) cycles 4.0 s
  1         0      0        1            1024K (1048576) cycles 8.0 s
*/
  /* set new watchdog timeout prescaler value */
  WDTCR =  0<<WDP3 | 1<<WDP2 | 1<<WDP1 | 0<<WDP0 ;

  lcd.clear();
  lcd.print("Initialisation");
  lcd.setCursor(0,1);
  lcd.print("complete.");
  delay(500);
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop()
{
  if(f_wdt == 1)
  {
    lcd.clear();
    lcd.print("Awake!");
    int start = millis();
    int end = 0;
    bool movement = false;
    int read = 0;
    lcd.clear();
    lcd.print( "Executing loop" );
    do{
      if( read = digitalRead(IN_PIN) ){
        lcd.setCursor(0,1);
        lcd.print( "Read value: " );
        lcd.print( read );

        //Wait for falling edge
        while( digitalRead(IN_PIN) != 0 );
        //Start counting time
        int endMov = 0;
        int startMov = millis();
        do{
          if( digitalRead( IN_PIN ) ){
            movement = true;
          }
          endMov=millis();
        }while( endMov - startMov < TIMEOUT && !movement );
            if( endMov - startMov >=LOOP_TIME ){
              lcd.clear();
              lcd.print("Time is out");
            }

            else{
              lcd.clear();
              lcd.print("Movement detected");
              lcd.setCursor(0,1);
              lcd.print( "Time: " );
              lcd.print( end-start );
            }
      }
      end=millis();
    }
    while( (end-start<LOOP_TIME) && !movement );

    if( end-start>=LOOP_TIME ){
      lcd.clear();
      lcd.print("Time is out");
    }

    else{
      lcd.clear();
      lcd.print("Movement detected");
      lcd.setCursor(0,1);
      lcd.print( "Time: " );
      lcd.print( end-start );
    }
    delay(1000);
    /* Don't forget to clear the flag. */
    f_wdt = 0;
    /* Re-enter sleep mode. */
    enterSleep();
  }
  else
  {
    /* Do nothing. */
  }
}

```

Does anyone has any idea why is it so?

# Answer
> 0 votes
First thing in my mind would be to check/change the pull-down resistor value.

The pull-down resistor must have a larger resistance than the impedance of the logic circuit, or else it might be able to pull the voltage down by too much and the input voltage at the pin would remain at a constant logical low value

Read more here.

---
Tags: attiny, digital, input, voltage
---


# Question
Title: Blinking cursor on Arduino is inconsistent and misses inputs
I am trying to write a part of a program that prints time and allows the user to move a cursor across it. I have the following code, but there are a few issues with it.

```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16,2);
  setTime(12,30,15,0,0,0);
}
int col = 0;

void loop() {
  uint8_t buttons = lcd.readButtons(); //create readable buttons
  char time_out[16];
  lcd.setCursor(0,0);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());
  lcd.print(time_out);
  lcd.setCursor(col,0);
  lcd.blink();
  delay(100);
  if (buttons) {
    lcd.clear();
    if (buttons & BUTTON_RIGHT) {
      col += 1;
    }
    if (buttons & BUTTON_LEFT) {
      col -= 1;
    }
  } //buttons
}

```

If you upload this to your board, you can tell that the blinking is highly irregular, not at all aesthetically pleasing.

You'll also notice that sometimes, when pressing left/right, the input isn't registered.

I suspect this has to do something with the `delay()` function used, which pauses the entire program.

I looked into the following method, but this does not work when needing to print something in a loop (as the time library requires).

Any idea how I could make this work better (regular blinking times and no miss of user input)?

Thanks a lot!

# Answer
I don't have the hardware to test but, it should be more or less like this; (I have also normalized the code into several functions for better readability.)

```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

unsigned long timerBlink; //Required for periodic blinking
int intervalBlink = 100;

void setup() {
    lcd.begin(16, 2);
    setTime(12, 30, 15, 0, 0, 0);
    timerBlink = 0;
}
int col = 0;

void loop() {
    readButtons();
    printDate();
    if (millis() - timerBlink > intervalBlink) {
        blink();
    }
}

void readButtons() {
    uint8_t buttons = lcd.readButtons(); //create readable buttons
    if (buttons) {
        lcd.clear();
        if (buttons & BUTTON_RIGHT) {
            col += 1;
        }
        if (buttons & BUTTON_LEFT) {
            col -= 1;
        }
    } //buttons
}

void blink() {
    lcd.setCursor(col, 0);
    lcd.blink();
    timerBlink = millis();//Start timer for intervalBlink
}

void printDate() {
    char time_out[16];
    lcd.setCursor(0, 0);
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second());
    lcd.print(time_out);
}

```

Instead of blocking delay function, using timeout with timestamp is a better practice.
> 1 votes

---
Tags: arduino-uno, c, genuino
---


# Question
Title: Cannot get HC-12 to function with Arduino Pro Micro clone
\[first time usage\]

I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.

The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK". I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.

For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.

The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.

I specify:

```
const byte HC12RxdPin = 4; // "RXD" Pin on HC12
const byte HC12TxdPin = 5; // "TXD" Pin on HC12
const byte HC12SetPin = 6; // "SET" Pin on HC12

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

```

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.

I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each. The Arduino IDE is 1.8.2, and I am specifying a Leonardo board. This is the suggestion I found whilst researching.

I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.

Have you any suggestions or solutions \[even better\]?

# Answer
> 0 votes
Solution to problem is as follows: For the Arduino Pro Micro \[as for the Leonardo\], Serial1 must be used instead of a SoftwareSerial specification, e.g.,

```
SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

```

Code is to be modified by changing HC12.available() to Serial1.available(). The same holds true for the reads and writes. Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin. My thanks to @mico for providing the reference that explains it all.

---
Tags: wireless, arduino-pro-micro
---


title: Advanced Arduino Project Help

text:
# Question
Title: Advanced Arduino Project Help
So, I am an Engineer working on a very time tight project.

I want to create a system capable of collecting data from a Photodiode and compiling it in a way that will separate data into four columns which correspond to colours (red, green, blue, yellow) the columns will have rows of data corresponding to a number.

I have elected to use Arduino for this project but need some help on what to get and whether this is possible or not... I have an intermediate knowledge of C, C++ and previous Arduino experience, but have never undertaken something like this.

The project is envisaged to look like this.

Hardware:

* Photodiode with RS232-C connection
* An Arduino (Which sort is best? now I have Uno and Mega but can purchase others should these not be sufficient for the project)
* Touchscreen Interface
* Storage capacity (SD card or email/Bluetooth capability or something alike to collect the data to edit on PC).

The Process should is like this: Input = User interacting with GUI on Touchscreen - First page will have Four Colours Available (Once one of these inputs selected let’s say Red, jump to next page) -\> Page two will have a Touch Number Pad Input (User selects number, let's say 2 in this case and hits enter), For less complexity this could be on one page correct? -\> The Data will then be read off a Photodiode communicating via RS232-C to Arduino and stored in a .csv or something similar under its previously selected values (Red, 2, Photodiode Value)

Output: A compiled list of all the data collected under their relative user inputs.

I currently have these items but am happy to purchase others.

* S130C Thorlabs Photodiode Sensor
* Null Modem Cable (Pins are swapped on S130C)
* RS232 Shield (DFRobot RS232 Shield V0.1)
* Arduino Uno, Arduino Mega
* TouchScreen (Duinotech 2.8” TFT LCD)

After re-reading what I wrote I suppose there are a few:

1. Could I complete this project using Uno and Mega?
2. Is there a method for compiling data and storing/sending using Arduino?
3. What are the capabilities of Arduino? Could a project of this complexity be done using Arduino components or is there another microprocessor or microcomputer which would be a better choice for this project?

# Answer
> 1 votes
Your question is incredibly broad. However:

*1. Could I complete this project using Uno and Mega?*

Yes, almost certainly

*2. Is there a method for compiling data and storing/sending using Arduino?*

What? Yes, you can store data onto an SD card using a simple level-shifting piece of hardware like this:

*3. What are the capabilities of Arduino?*

This isn't a reasonable question (it's too broad). I suggest Googling for things people have done. For myself, I made a humidity and temperature sensor using the same processor as in a Uno. It also runs from batteries.

---

> ... a very time tight project ...

Time is going to be your enemy here. Learning how to drive a touchscreen, save files to an SD card, interpret RS232 data from your sensor, and make it all work reliably is not the sort of thing you will do in 3 days.

Even if you dumped all your hardware on my desk (and I know how to program Arduinos) I would estimate two or three weeks to calmly get each part going individually and then interface them all together.

---

> Would you suggest using breakout boards over shields?

Shields are well and good if they do what you want them to do. A breakout board will have more flexibility.

> because of pin availability would you suggest trying to use the Mega rather than Uno?

Depends how many pins you need. If you use SPI or I2C you can (probably) drive your display with only a handful of pins.

The Uno will probably have enough, and it has the flexibility that you can easily replace the processor chip if you damage it. You can't do that to the Mega. Plus, more code is written for the Uno so you are more likely to find libraries that work "out of the box" for a Uno.

I wouldn't be getting the "more powerful" device unless you have identified a specific reason to have it. For example, some of the faster and more powerful Arduinos (and other boards) with ARM processors may well do more under certain circumstances, but be somewhat harder to use.

---
Tags: arduino-uno, arduino-mega, arduino-ide, shields, datalogging
---


# Question
Title: Problems using an arduino with vex motors and motor controller 29
I am using a VEX 2-wire motor with the Motor Controller 29 to use it like a three-wire motor.

I was told that I am able to program it like a servo using the Arduino `Servo` class. When I use the `write()` function to set the power, it works from values around 50-85 in one direction, slowing down the power as I increase the value, but when the value exceeds around 90 then the motor stops working and makes strange clicking sounds. It is not a hardware problem, because the motor works fine in either direction when I plug it straight into a power source.

Does anyone know what my problem is?

# Answer
VEX motors with Servo library have the following functionality:

0 one direction (full speed)

90 stop

180 opposite direction (full speed)

So at 90, it is trying to remain motionless and hence creating that sound.

btw. You should provide power to motors separately from the Arduino. You might fry your Arduino if you run VEX motors from it. Best solution is to power using 7.2V 3000mAh Flat NiMH High Power Battery Packs.
> 1 votes

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


# Question
Title: How to send data from Arduino Uno with SIM900 GPRS to Firebase
I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from here. Here is some code that I've tried:

```
AT
OK
AT+CREG?
+CREG: 0,1

OK
AT+CGATT?
+CGATT: 1

OK
AT+CIPSTATUS
OK

STATE: IP INITIAL
AT+CIPMUX=0
OK
AT+CSTT="att.mvno","",""
OK
AT+CIICR
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
OK
CONNECT OK

```

and

```
AT+CIPSHUT
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
OK
CONNECT OK

```

If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret? Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

# Answer
> 2 votes
Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.

# Answer
> -1 votes
just remove "https://" its working

---
Tags: arduino-uno, shields, gps
---


title: How to blink 2 led strips without delay

text:
# Question
Title: How to blink 2 led strips without delay
Hi all I use 2 sensors and 2 led strips. I want to let both led strips light up without interrupting each other while reading the different values from the inputs. But Arduino still pauses when one lights up, the other one needs to wait for the time to pass, either one misses reading the value when one is processing the output.

I know delay(wait); makes it block out the coming data, but it lets the strips light up for 6 seconds. If I remove it, the strips will light one 1 second only. What should I do? Thanks so much!

```
#include <Adafruit_NeoPixel.h>
#define PIN 6
int ledFadeTime = 7;
Adafruit_NeoPixel strip3 = Adafruit_NeoPixel(60, 9, NEO_GRB +NEO_KHZ800);//led pin
Adafruit_NeoPixel strip4 = Adafruit_NeoPixel(60, 7, NEO_GRB + NEO_KHZ800);//led pin
const int sensorPin3 = A2;//motion sensor
const int sensorPin4 = A3; //flash sensor

unsigned long strip3OnTime;
unsigned long strip4OnTime;
bool strip3On;
bool strip4On;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {

  Serial.begin(9600);
  strip3.begin();
  strip3.show();
  strip4.begin();
  strip4.show();

  strip3On = false;
  strip4On = false;
}

void loop(){
 int Val3 = analogRead (sensorPin3); // sensor val
 int Val4 = analogRead (sensorPin4);

 Serial.print(Val3);
 Serial.print(" ");
 Serial.println(Val4);

   if (Val3>70) {
     rgbFadeInAndOut3(0, 0, 255, ledFadeTime);
     //analogWrite(strip3, HIGH);
     strip3On = true;
     strip3OnTime = millis();
   }
   if (Val4>70) {
     rgbFadeInAndOut4(0, 0, 255, ledFadeTime);
     //analogWrite(strip4, HIGH);
     strip4On = true;
     strip4OnTime = millis();
   }

   if(strip3On)
     if(millis() - strip3OnTime > 7000) {
       rgbFadeInAndOut3(0, 0, 1, 5000);
       strip3On = false;
     }
   if(strip4On)
     if(millis() - strip4OnTime > 7000) {
       rgbFadeInAndOut4(0, 0, 1, 5000);
       strip4On = false;
     }
 }

 void rgbFadeInAndOut3(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
   unsigned long currentMillis = millis();
   if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip3.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
       }
      strip3.show();
     delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip3.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip3.show();
      delay(wait);
   };
 };
 }
 void rgbFadeInAndOut4(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval){
     previousMillis = currentMillis;

   for(uint8_t b = 0; b <255; b++) {
      for(uint8_t i=0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };

   for(uint8_t b=255; b > 0; b--) {
      for(uint8_t i = 0; i < strip4.numPixels(); i++) {
         strip4.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
      }
      strip4.show();
      delay(wait);
   };
 };
 }

```

# Answer
> 2 votes
Very simple. It takes only 3 steps.

1. Blink an led stripe with no delay.
2. Blink two led stripes, using the code developed in step 1.
3. Enjoy your blinking let stripes.

edit: since you seem to be struggling, here is one (of countless) way(s) to do #1 above.

```
//blinky_ledx2.ino

//blink two led strips independently

//blinky rate
#define LED_DLY         100     //duration for led1, in ms
#define LED             12      //led to be blinked

int led = 13;

//run user routine, non-blocking
void NB_run(void (*func_ptr)(void)) {
    static uint32_t millis_next=0;                          //next match point

    if (millis() >= millis_next) {                          //time is up
        millis_next += LED_DLY;                             //advance match-up time
        func_ptr();                                         //execute user function
    }
}

//blinky example
void blinky1(void) {
    //blink LED
    digitalWrite(LED, !digitalRead(LED));
}

void setup() {
    // put your setup code here, to run once:
    pinMode(led, OUTPUT);
    pinMode(LED, OUTPUT);                                   //LED as output
}

void loop() {
    NB_run(blinky1);                                        //run blinky1 at set intervals for LED
    digitalWrite(led, !digitalRead(led));                   //blink led
}

```

the heart of this is NB\_run() -\> it executes func\_ptr() once the set time has been reached. otherwise, it returns without doing anything, as shown in the example below.

D13 is blinked constantly in the main loop, while D12 is blinked based on LED\_DLY, in a non-blocking fashion.

I purposely wrote NB\_run() so that it needs additional "parameterization" to run multiple tasks - what you have here is the basis of a generic framework for a rudimentary pseudo multi-tasker. it is not difficult at all for you to extend the code to run 2 stripes.

good luck.

edit2: it was pointed out to me, quite correctly, that something like this can be done via rtos. true, but a typical rtos has lots of overhead and requires a more substantial hardware to support.

one exception is macro-based rtos, like protothread. in that particular implementation, you will see that there is little gain in terms of code complexity, but some stylistically.

here is an implementation of running two tasks concurrently via protothread, only code for one task is shown, however.

```
//thread 1
PT_THREAD(protothread1(struct pt *pt, uint32_t pr)) {
    static uint32_t time_next=0;        //time for the next blinking

    PT_BEGIN(pt);
    while (1) {
        PT_WAIT_UNTIL(pt, millis() > time_next);
        time_next += pr;                //advance time to the next match up point
        toggleLED(LED1);                //run user task - blink led1
    }
    PT_END(pt);
}

void loop() {
    protothread1(&pt1, LED1_DLY);       //running thread1
    protothread2(&pt2, LED2_DLY);       //running thread2

}

```

you can see that it retains largely the code structure presented earlier.

here is the outcome of that code, blinking D12/D13 at different rates.

---
Tags: led
---


title: Serial.available() function for Arduino

text:
# Question
Title: Serial.available() function for Arduino
I want to implement a function in another micro-controller which works like `serial.available()`. I don't know how it works. I read about `Serial.available()` in this link.

Whenever I write a string on the terminal, it prints the length of the string. Can anyone tell me how it works?

# Answer
> 2 votes
It reports the difference between the head and the tail of the circular buffer the incoming characters are stored in.

The way serial reception on the Arduino works is:

1. A character is received into the internal hardware RX buffer (`UDRx`)
2. An interrupt is triggered
3. An interrupt service routine (ISR) is executed
4. The character in `UDRx` is read and, if there is room, stored in a circular buffer (`_rx_buffer`).
5. The `head` pointer of `_rx_buffer` is incremented and wrapped if needed.

When you actually read a character with `Serial.read()` the following happens:

1. If the `head` and `tail` of `rx_buffer` are equal, return `-1`
2. Get the character at `tail` from `_rx_buffer`
3. Increment `tail` and wrap if needed
4. Return the character

So when you use `Serial.available()` it just returns `head - tail` (taking into account the wrapping, so the sum is slightly more complex than a simple subtraction).

You should examine the files `HardwareSerial.h` and `HardwareSerial.cpp` in the Ardino AVR core software.

---
Tags: arduino-uno
---


# Question
Title: 127v/220v AC sensor - What's the role of this particular resistor?
After searching for a very long time for a 127v/220v (AC) sensor without using any kind of transformers, I found this very nice idea (image below):  I'd like to understand how this module works because I'll have to replicate it in my project without actually using it. I can already tell what's the role of every component, except for both resistors. The first resistor (10k) is placed between the capacitor's legs and, therefore, I'm assuming it's just a bleeding resistor. Am I right? The second resistor (220k), between the AC source and the optocoupler, I have no clue. I was also thinking whether I can improve this sensor by adding a rectifier bridge between the AC source and the optocoupler, allowing me to use a smaller capacitor to normalize the signal. Does that make sense? Thanks!

# Answer
> 6 votes
The first resistor is working with the capacitor as an RC filter. Since you are sensing AC at 50~60Hz, you need this RC filter to get a constant output instead of a pulsed output. Remember your otpo-coupler has a LED (diode) inside, so it will only produce light when voltage is positive.

The second resistor is there to limit the current from your AC 220Vrms (which is 311V peak) so that is within the opto-coupler's LED forward current range. The voltage between your LED´s pins will always be it´s forward voltage (1.2V to 1.4V), so the resistor will bring down the 311V to 1.2 to 1.4V. Without this resistor, you would have 311V between the LED pins, and this would fry the poor thing.

The equivalent input circuit is something like this:

simulate this circuit – Schematic created using CircuitLab

**Ok so how did they figure out the 220kOhms value?**
First, take the worst case scenario: 220Vrms AC gives us 311Vpeak, and LED forward voltage is 1.2V.
So the voltage between the 311V and the diode is 311 - 1.2V = 309,8V

OHM Law: R = V/I (R=resistance, V=voltage, I=current)

In this case, the current chosen for the LED was about 1.4mA or 0.0014A, so R = 309.8V/0.0014A

R = 221k Ohms. The closest we get to this is 220kOhms

With 127Vrms (179.6Vpeak), your LED current will be: I = 178.4V/220000 = 811uA

I have simplified the calculations, because this is a simple case, but keep in mind that real life engineering calculations will be more complex than this.

---
Tags: sensors
---


title: Interface with mux-controlled LED rope

text:
# Question
Title: Interface with mux-controlled LED rope
I'm working on using a GUI in Processing to control some LED rope from Adafruit, and using this multiplexer.

I've gotten the following Arduino code working the way I want to cycle through the various strands of LED rope and turn them on:

```
#include <SoftwareSerial.h>

//Mux1 control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux2 control pins
int s4 = 12;
int s5 = 13;
int s6 = 14;
int s7 = 15;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage vlaue to write to the LEDs
int testValue = 255;

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

  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(s4, OUTPUT);
  pinMode(s5, OUTPUT);
  pinMode(s6, OUTPUT);
  pinMode(s7, OUTPUT);
  pinMode(SIG_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(s4, LOW);
  digitalWrite(s5, LOW);
  digitalWrite(s6, LOW);
  digitalWrite(s7, LOW);
}

void loop(){

  for(int i = 0; i <= 19 ; i ++){
    Serial.println(i);
    testValue = 255;
    writeMux(i);
    delay(500);
//    testValue = 0;
//    writeMux(i);

  }

}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 8; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
//    Serial.println("CHANNEL IS ");
//    Serial.println(muxChannel[channel][i]);

//    Serial.println("Control pin IS ");
//    Serial.println(controlPin[i]);
  }

  //write the value at the SIG pin
  analogWrite(SIG_pin, testValue);

//    Serial.println("Test value IS ");
//    Serial.println(testValue);

  //return the value
  return 0;
}

```

I'm working on converting this Arduino code to a Processing sketch so I can control the lights with a GUI. I've run the Standard Firmata sketch on my Uno before running my Processing sketch. However, nothing seems to happen...I know that my circuit is working (since it worked for the Arduino sketch), and most of my Processing code should be correct. Logging shows the sketch is trying to write the values I want. Anyone have any ideas? Below is the relevant part of the Processing sketch:

```
import cc.arduino.*;
import processing.serial.*;

int [] muxChannel;

//Mux1 control pins
int s0 = 8;
int s1 = 9;
int s2 = 10;
int s3 = 11;

//Mux2 control pins
int s4 = 12;
int s5 = 13;
int s6 = 14;
int s7 = 15;

//Mux in "SIG" pin
int SIG_pin = 3;

//Voltage vlaue to write to the LEDs
int testValue = 255;

void setup() {
  size(700,400);
  noStroke();
  cp5 = new ControlP5(this);
  println(Arduino.list());

  //// Set up Arduino and pin output modes
  arduino = new Arduino(this, Arduino.list()[1], 96000);

  arduino.pinMode(s0, Arduino.OUTPUT);
  arduino.pinMode(s1, Arduino.OUTPUT);
  arduino.pinMode(s2, Arduino.OUTPUT);
  arduino.pinMode(s3, Arduino.OUTPUT);
  arduino.pinMode(s4, Arduino.OUTPUT);
  arduino.pinMode(s5, Arduino.OUTPUT);
  arduino.pinMode(s6, Arduino.OUTPUT);
  arduino.pinMode(s7, Arduino.OUTPUT);
  arduino.pinMode(SIG_pin, Arduino.OUTPUT);

  arduino.digitalWrite(s0, Arduino.LOW);
  arduino.digitalWrite(s1, Arduino.LOW);
  arduino.digitalWrite(s2, Arduino.LOW);
  arduino.digitalWrite(s3, Arduino.LOW);
  arduino.digitalWrite(s4, Arduino.LOW);
  arduino.digitalWrite(s5, Arduino.LOW);
  arduino.digitalWrite(s6, Arduino.LOW);
  arduino.digitalWrite(s7, Arduino.LOW);
}

void draw() {
  background(bgColor);

    for(int i = 0; i <= 19 ; i ++){
    testValue = 255;
    writeMux(i);
    delay(500);
  }
}

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  final int[][] muxChannels = {
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
    };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    arduino.digitalWrite(controlPin[i], muxChannels[channel][i]);
  }

  //write the value at the SIG pin
  arduino.analogWrite(SIG_pin, testValue);

  int val = 0;
  return val;
}

```

EDIT: I put the project and a little explainer on GitHub to show what this type of project can or can't be useful for here: https://github.com/narner/Analog-LED-Multiplexing-Example

# Answer
You're using a 16-channel analog multiplexer to talk to your devices (the LED ropes) via a single pin on your Arduino. "Multiplexer" is just a fancy name for a switch; "analog" means that it's switching analog connections, basically, wires that can have any voltage on them, as opposed to digital connections that carry only logic high (usually +5 volts) or low (0 volt) signals.

The first place to start is the datasheet. From the product link, we can see that the chip we're using is a CD74HC4067. Their datasheet links don't work, but searching in Octopart for just "74HC4067" eventally led me to an actual datasheet. These datasheets are the key source for information on the parts you're using and are always worth reading through. Even if you don't understand everything in them, they'll usually have the information you need, and reading them gets easier with practice.

Section 5 has a functional diagram (Fig. 1) which shows the important connections.

* Z is what you'll hook up to an I/O pin on your Arduino. When the chip is enabled, Z will be connected to one of the Y connections.
* Y0 through Y15 are what you'll hook up to your individual devices; one (and only one) of these at a time will be connected to Z, connecting the device to your Arduino I/O pin. (The other Y connections will be in a high impedance state.)
* Ē is the "enable" signal, the bar over top indicating that it's "active low." That is to say, when you ground (0 V) Ē the mux will be active and the selected Y will be connected to Z. When you hold Ē high (5 V) the mux will be inactive and all the Ys and Z will be disconnected (high impedance again).
* S0 through S3 are the select inputs to the mux; they determine which Y is connected to Z (when the device is active) in a way we'll show below.

Depending on the project, you may not want to switch the connection between the Z and Y pins (by changing S0-S3) while the devices connected to the Ys are active so that you don't accidentally get a a little bit of signal meant for one device going to another. The steps to do this would be as follows:

1. You start by having Z connected to, say, Y0, with the signal you want to send to Y0 going through Z.
2. Disable the device by bringing Ē high. Now Y0 (and all other Ys) are disconnected.
3. Change the value on S0-S3 to select, e.g., Y1.
4. Change the signal you're sending to Z to the correct signal for Y1.
5. Bring Ē low to enable the device and now Z will be connected to Y1.

In your project you likely don't need to worry about being this careful with your switching so long as you change S0-S3 and Z as closely together as possible, so I'm going to simplify the code I show here by leaving out the enabling and disabling step; you can just wire Ē to ground for the moment.

The key to the switch is what you send on S0-S3 to select which Y is connected to Z. This input is just a binary number, which you'll need to understand to use it effectively. Following is a short summary, but if you don't understand it completely (or the C code later on), there are plenty of tutorials on the web that can give you further help.

Counting in binary is just like counting in tens except you have only the numbers 0 and 1. So instead of counting 0, 1, 2, ..., 9, 10, 11 you count 0, 1, 10, 11, 100, 101, ... (which represent the numbers 0, 1, 2, 3, 4, 5, ... in decimal). The S0 input on the mux is the least signifcant bit (the one furthest right), the S1 in put the second least significant bit (second from the right) and so on.

So you need to hook up four digital ouput pins from your Arduino to the S0 through S3 inputs on the mux and then manipulate those pins to send the appropriate number to the mux to select your chosen Y that you want to connect to X.

The following program, which counts sequentially from 0000 (0) through 1111 (15) on the four output pins; shows you how to do this. It would be a good idea to build up a small circuit on a breadboard with four LEDs (remember to use a 330 Ω or so resistor in series with the LED) that you can hook to your four pins so you can see visually what your program is doing as you experiment.

We start by declaring some constants for the pins:

```
// Multiplexer control pins are assumed to be sequentially
// assigned from `mux_base` onward.
//
const int mux_base = 8;
const int mux_len = 4;                  // 2^4 values, 0 through 15
const int mux_max = (1 << mux_len) - 1;

```

`mux_base` is the first pin of the four sequental pins you'll hook up to the S0-S3 (or the LEDs); I use pin 8 here but you can use pretty much any pin you like. `mux_len` is the number of bits in the mux selector input; S0, S1, S2, S3 is 4 bits, so this determines that I'm using pins 8, 9, 10 and 11 on the Arduino to control the mux.

`mux_max` is purely a calculation (from the previous two constants) of the highest value you can select on the mux; in this case it's 15. The details of how I caculate it are a bit beyond the scope of this answer, but it's worth working out yourself how that C code works from what you learn later in the code and can find out elsewhere on the web.

We need, as usual, to set up our chosen pins as digital outputs; `setup_mux()` does just that:

```
void setup_mux() {
    for (int pin = mux_base; pin < mux_base+mux_len; pin++) {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, LOW);
    }
}

```

We start with the first selector pin and loop through to the last one, for each one setting it to output mode and setting the current value to `LOW` so that we have known starting conditions.

For the selection of the Y to connect to Z on the multiplexer, it's convenient to have a function that takes an `int` indicating that Y and sets our selector pins to the correct values for this. Thus, `set_mux(value)` below. This is probably the most complex part of this answer, and bears detailed study.

```
void set_mux(int value) {
    for (int offset = 0; offset < mux_len; offset++) {
        int bit = (value >> offset) & 1;
        digitalWrite(mux_base + offset, bit ? HIGH : LOW);
    }
}

```
1. The first line loops through our `mux_len` (4 from above) selector pins; each of these will have to be set to the correct `HIGH` or `LOW` value for the desired Y selection.
2. The second line determines the binary bit from `value` for the particular selector pin we're setting in this iteration of the loop. We do this by doing a binary shift of the value to the right, and then clearing all bits except the lowest one, leaving us with a final value for `bit` of 1 or 0. For example, if we pass 14 to the function, which is 1110 in binary, when the offset is 2 in the loop we'll use the `>>` operator to shift that right two bits, through 0111 to 0011. (With each shift the right bit drops off and a 0 is added at the left.) Doing a logcal AND (the `&` operator) of 0011 with 0001 keeps only the bits that are set in both, leaving us with 0001. (Only the far right bit is set in both.)
3. We then need to set the output pin to HIGH if `bit` is 1 or LOW if `bit` is 0; the ternary operator (*condition* `?` *when-true* `:` *when-false*) provides a concise way of doing this.

That's our core "library" code, if you will. In this simple example the only setup we need to do is to call `setup_mux()`:

```
void setup() {
    setup_mux();
}

```

Our main program, for demonstration, will count upwards in binary on the selector outputs, delaying a half second between each count so you can see your LEDs blink:

```
int counter = 0;

void loop() {
    set_mux(counter);
    delay(500);
    counter++;
    if (counter > mux_max)
        counter = 0;
}

```

Once you understand this example, you have everything you need to start using your multiplexer with something more sophisticated than just counting.

One last important thing to emphasize: the mux allows you to use just one signal I/O (plus the four selector outputs) on your Arduino, but that signal I/O is connected to only one device at a time. This won't work if you must always be sending a signal to several devices at the same time, which it appears might be the case from your other question. That said, if there's any time at which you're sending 0 V to a device, that is time you could be spending sending a non-0 V signal to another device.

For example, holding Z at +5 V and cycling the signal outputs through Y0-Y3 quickly will give you what's effectively a +5 V PWM with 25% duty cycle on Y0-Y3. In some cases, this technique can be useful.

Oh, one additional note: this example controls just one multiplexer; you can easily control two with two sets of selector pins, but this starts to use up a lot of pins. Instead, you may wish to have one set of selector pins on the Arduino hooked up to *both* your muliplexors (and one I/O pin hooked up to both Zs) and use two more Arduino pins to control the Ē on each mux, having only one mux enabled at a time. This will save you three pins, at the cost of some complexity, but it's a good exercise to see if you really understand multiplexing technique since it's a straightforward extension of what you're doing with a single mux.
> 5 votes

# Answer
After reading your github page, I came to realize that:

1. you do not require full color control, but only setting the strips to full red or full blue
2. you are using MOSFETs for driving them.

Given these conditions, I believe the project may be feasible with your current setup. The trick is that MOSFETs have some gate capacitance: if you set the gate either HIGH or LOW, and then disconnect it, it will keep that state for some time, until the charge stored in the gate leaks. This means you do not need to address each MOSFET *continuously*: you can just periodically “refresh” them, and let the gate capacitance “remember” the state between refreshes. This is similar to how DRAM memory works.

I wrote the following code based on this idea. Note that I did not test it, as I do not have the required hardware. It uses a timer interrupt firing every 1024 µs to cycle through the ten used mux channels: each channel gets then refreshed every 10.24 ms. It also uses direct port access instead of `digitalWrite()`: not only it's way faster (and you want to be fast in an ISR) but, more importantly, it allows changing several outputs *simultaneously*. This is important in order to avoid glitches.

```
/*
 * Patterns to send to the multiplexers. bit_patterns[mux][chann] is the
 * pattern to send to the multiplexer `mux' in order to update the
 * channel `chann'. Bits 0..3 hold the channel number, bit 4 is the
 * data. The data bits are all initialized to zero.
 */
volatile uint8_t bit_patterns[2][10] = {
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 },
    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
};

/*
 * Periodically cycle through the 10 used multiplexer channels, updating
 * the MOSFETs. The TIMER0_COMPA interrupt has to be enabled for this to
 * automatically run every 1024 microseconds.
 */
ISR(TIMER0_COMPA_vect)
{
    static uint8_t i;            // channel index
    PORTB = bit_patterns[0][i];  // update MUX 0
    PORTC = bit_patterns[1][i];  // update MUX 1
    if (++i >= 10) i = 0;        // cycle channels
}

void setup()
{
    DDRB   =  0x1f;         // set PB0..PB4 as outputs
    DDRC   =  0x1f;         // set PC0..PC4 as outputs
    TIMSK0 |= _BV(OCIE0A);  // enable TIMER0_COMPA interrupt
}

```

This code relies on Timer 0 being in the standard Arduino configuration, where it loops every 1024 µs. It also needs a specific wiring, where each multiplexer is connected to a single AVR port, as follows:

```
Arduino   multiplexers
----------------------
   8      S0 of MUX 0
       ...
  11      S3 of MUX 0
  12      SIG of MUX 0
  A0      S0 of MUX 1
       ...
  A3      S3 of MUX 1
  A4      SIG of MUX 1

```

In order to change the strip colors, you just have to update the stored bit patterns:

```
/*
 * On each of PORTB and PORTC, bits 0..3 are wired to the address select
 * pins of a multiplexer, whereas bit 4 goes to the SIG pin of the same
 * multiplexer.
 */
const uint8_t SIG_BIT = 0x10;

/* These are the only available colors. */
typedef enum { BLACK, RED, BLUE, MAGENTA } color_t;

/* Set the color of a strip. Strips are numbered from 0 to 9. */
void set_color(uint8_t strip, color_t color)
{
    /* Find the relevant multiplexer and channels. */
    uint8_t mux, red_ch, blue_ch;
    if (strip < 5) {
        mux = 0;
        red_ch = 2 * strip;
    } else {
        mux = 1;
        red_ch = 2 * (strip - 5);
    }
    blue_ch = red_ch + 1;

    /* Update the bit patterns. */
    if (color == RED || color == MAGENTA)
        bit_patterns[mux][red_ch] |= SIG_BIT;
    else
        bit_patterns[mux][red_ch] &= ~SIG_BIT;
    if (color == BLUE || color == MAGENTA)
        bit_patterns[mux][blue_ch] |= SIG_BIT;
    else
        bit_patterns[mux][blue_ch] &= ~SIG_BIT;
}

```

The function `set_color()` assumes the following connections between the multiplexers and the strips:

```
MUX  channel    strip  color
----------------------------
 0      C0        0     red
 0      C1        0     blue
 0      C2        1     red
 0      C3        1     blue
            ...
 0      C8        4     red
 0      C9        4     blue
 1      C0        5     red
 1      C1        5     blue
            ...
 1      C8        9     red
 1      C9        9     blue

```

**Hardware considerations**

All this scheme may or may not work depending on some hardware factors such as the gate capacitance of your MOSFETs, the leakage current of the multiplexers when in high-impedance and the timing characteristics of the same multiplexers. If the gate capacitance is too weak to hold the value for 9 ms, you may want to add capacitors in parallel, maybe something in the 100 pF range. If you add more than that, you may also want to put resistors in series with pins 12 and A4 of the Arduino, in order to protect them from the inrush current. But then you may also want to slow down the scanning of the channels, which would require configuring a timer.
> 3 votes

---
Tags: arduino-uno, processing-lang, multiplexer, firmata
---


# Question
Title: i am working on a project smart watch i am getting this error please help
Arduino: 1.6.7 (Windows 10), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

```
WARNING: Spurious .github folder in 'Adafruit SSD1306' library
In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28:0,

                 from sketch\RetroWatchArduino.ino.cpp:1:

bitmap.h:1270: error: expected primary-expression before '__attribute__'

 PROGMEM const unsigned char* const bitmap_array[] = {

 ^

C:\Users\varun\Desktop\retrowatch-master\retrowatch-master\RetroWatch_Arduino\RetroWatchArduino\RetroWatchArduino.ino: In function 'void drawIcon(int, int, int)':

RetroWatchArduino:898: error: 'bitmap_array' was not declared in this scope

   display.drawBitmap(posx, posy, (const unsigned char*)pgm_read_word(&(bitmap_array[icon_num])), 16, 16, WHITE);

                                                                        ^

exit status 1
expected primary-expression before '__attribute__'

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

```

Information about the smart watch

# Answer
PROGMEM is in the wrong loctaion. According to the Arduino Website:

> Note that because PROGMEM is a variable modifier, there is no hard and fast rule about where it should go, so the Arduino compiler accepts all of the definitions below, which are also synonymous. However experiments have indicPROGMEM ated that, in various versions of Arduino (having to do with GCC version), PROGMEM may work in one location and not in another. The "string table" example below has been tested to work with Arduino 13. Earlier versions of the IDE may work better if PROGMEM is included after the variable name.
>
> ```
> const dataType variableName[] PROGMEM = {};   // use this form
> const PROGMEM  dataType  variableName[] = {}; // or this form
> const dataType PROGMEM variableName[] = {};   // not this one
>
> ```

And I will add to that list:

```
PROGMEM const dataType variableName[] = {};   // and definitely NOT this one.

```
> 1 votes

---
Tags: atmega328, arduino-pro-mini, progmem
---


title: Arduino Due: enable reentrant interrupt

text:
# Question
Title: Arduino Due: enable reentrant interrupt
I'm using the TC3 interrupt on my Arduino Due to run some code periodically, like this:

```
void TC3_Handler() {
  TC_GetStatus(TC1, 0); // Remove interrupt flag
  // My code...
}

```

However, as I've found out, the CPU will not service the same interrupt a second time while the interrupt is running. By editing the priorities of each interrupt source, it's possible for a higher priority interrupt to preempt and run over this interrupt (so nested interrupts are possible), but priority manipulation alone does not allow **reentrant** interrupts.

I'd like to know if there is any way to make this interrupt reentrant.

# Answer
In your notion about the meaning of **Reentrant interrupt**, you write:

> interrupt A can preempt handling of interrupt A; interrupt A's handler can be active concurrently with itself

---

**I. The first half of the notion** correctly states a condition that might trigger re-entrance of an ISR (interrupt service routine). Note, an ISR that allows re-entrance might or might not be called reentrant: an ISR's code is *reentrant* if it performs correctly when it is re-entered.

On most processors that use a single stack, code will be reentrant if it has no side effects and does not access variables that are not in its stack frame. It might be reentrant even if it does have side effects or accesses non-local variables, if its actions are idempotent or if some proper concurrency protocol is implemented.

---

**II. The second half of the notion** is misleadingly stated: true concurrency does not occur on a single-thread-of-execution processor. However, time sharing and task overlap may occur on such a processor via task switching using either preemptive or cooperative multitasking.

As explained in the next paragraph, to the best of my knowledge preemptive serial multitasking is what would happen if you re-enable the interrupt system within an ISR.

Let's suppose ISR A is written in a reentrant fashion, and that it clears the interrupt A interrupt flag early in its processing, and enables interrupts so more A interrupts can occur and be processed. Also suppose three interrupt A's occur in quick succession (more precisely, quickly enough that processing of one does not complete before another comes along, but not so quickly that the A flag has not been cleared, which would cause loss of an A interrupt) followed by a hiatus. In this case, the first interrupt A occurs; the ISR entry prologue creates a stack frame for the ISR code to use, then saves a number of registers, then begins executing user code, which we suppose turns interrupts back on. After a bit the second interrupt A occurs. ISR entry prologue creates stack frame and saves registers. User code enables interrupts. Third interrupt A occurs. ISR entry prologue creates stack frame and saves registers. User code enables interrupts. As we've posited a hiatus, no more A interrupts occur for a while. So processing of interrupt 3 proceeds and finishes. The ISR epilogue reloads registers, clears the stack frame, and returns from interrupt, restoring the previous interrupt state. Then processing of interrupt 2 proceeds, finishes, reloads registers, returns from interrupt. Then processing of interrupt 1 proceeds, finishes, reloads registers, returns from interrupt. Then `loop()` \[or whatever is running in the main thread of execution\] resumes its work.

As you can see from this example, interrupt processing will occur in a LIFO (last-in, first-out) order if an ISR simply accommodates re-entrance. If that is what you want, fine. If, however, you want interrupt processing to complete in order; want to do lengthy processing while avoiding interrupt misses; and want to process in a secondary thread of execution, ie, a callback-like system, then the thing to do is have the ISR make a queue entry (in a static or heap-based circular queue) each time it starts; return from interrupt if it was re-entered; and process queue entries until the queue is empty, using atomic operations when changing queue pointers.

---

*Edit 2:* In §10.20.9.1 of the SAM3x/SAM3A datasheet, “Hardware and software control of interrupts”, we find

> A peripheral interrupt becomes pending for one of the following reasons:
>
> > • the NVIC detects that the interrupt signal is HIGH and the interrupt is not active
> > ...
>
> A pending interrupt remains pending until one of the following:
>
> > • The processor enters the ISR for the interrupt. This changes the state of the interrupt from pending to active. Then:
> >
> > > • For a level-sensitive interrupt, **when the processor returns from the ISR, the NVIC samples the interrupt signal.** If the signal is asserted, the state of the interrupt changes to pending, \[...\] Otherwise, the state of the interrupt changes to inactive.
> > > • If the interrupt signal is not pulsed while the processor is in the ISR, when the processor returns from the ISR the state of the interrupt changes to inactive.
> >
> > • Software writes to the corresponding interrupt clear-pending register bit.
> > ...

\[Emphasis added\]

This suggests that although the ISR for a given interrupt source on a SAM3x/SAM3A system can be interrupted by a higher-priority source, a given source can not re-interrupt until “the processor returns from the ISR”. Without some research or testing, it isn't clear to me if that is correct, and whether software can simulate a return from ISR without actually returning. Setting that possibility aside, here is a workaround to allow interrupt A to recur:

Set the interrupt priority of A fairly high, say level *z*. Set up several selected SGI's (software generated interrupts) at levels *p, q, r ...*, all lower-priority than *z*. Initialize an *A level* variable to point to the least-priority SGI ISR among those selected. Upon any A interrupt, the A ISR issues an *A level* SGI, saves any data that SGI ISR needs, updates *A level* to next-higher-priority SGI \[if possible\], and returns from interrupt. This re-enables A interrupts and allows the most recently issued (and currently highest priority) SGI to fire and start doing its thing. When it's done, it atomically sets *A level* equal to its own level. Thus, while any of the SGI ISR's is processing, if another A interrupt occurs, the current SGI ISR's processing suspends; when the A interrupt is handled, the next-higher SGI ISR starts. All higher level ISRs finish before a lower level ISR resumes.
> 1 votes

# Answer
> does not allow reentrant interrupts.

a few suggestions:

1) understand what "reentrant interrupts" means;

2) see if you need it;

3) see what needs to be done to get it to run on your hardware;

4) see if your code does what needs to be done.

hope it helps.
> 0 votes

---
Tags: arduino-due, interrupt, timers
---


title: Power Supply Ticking, Light Flashing

text:
# Question
Title: Power Supply Ticking, Light Flashing
My Arduino came with a 9V 1A power supply to use with it. I decided to test it out with my multimeter. I put the red lead in the connector and the black on the outside. Sure enough I read 9V. However when I tested the amps this did not work. The meter read a low value and the power supply started making a ticking noise and a light started flashing on it.

I did have the multimeter on the correct settings. Looking online I now realize that you cannot test the amps this way and as I was essentially testing a circuit with no load on it.

What I would like to know is what the power supply was doing when it was ticking and flashing. It is alive and well so I suppose it was some sort of internal protection.

# Answer
It was "hiccuping" in order to prevent damage from the short circuit condition. Once the short circuit condition is removed, the PSU restores normal operation.

From the reference: "The operation of hiccup is as follows. When the current-sense circuit sees an over-current event, the controller shuts off the power supply for a given time and then tries to start up the power supply again. If the over-load condition has been removed, the power supply will start up and operate normally; otherwise, the controller will see another over-current event and shut off the power supply again, repeating the previous cycle."
> 2 votes

# Answer
> I was essentially testing a circuit with no load on it.

No, you were imposing a very *high* load. An ammeter (amp meter) should be in *series* with the circuit under test. For example:

```
----(-)-- Power supply (+)-----(+)- Amp meter (-)---|
|                                                   |
|                                                   |
---(-)---- Circuit under test ----(+)----------------

```

When in amps mode the meter has a very low resistance, and measures the voltage drop over that low resistance (probably 0.1 ohms or less). Thus putting the meter *across* the power supply shorts it out.

Hence the noise it makes while trying to recover. The power supply turns itself off and on until the short goes away.

Also you are lucky you didn't blow the fuse in your meter. They are normally fused in case you accidentally do something like that.

---

> Isn't low resistance considered a low load and not a high load?

A low resistance *in series* is a low load. A low resistance *in parallel* is a high load.

Assuming your meter presented a resistance of 0.15 ohms on the 10A range (as mine does) then using Ohms Law we can see that this would give a current of:

```
I = V / R
I = 9 / 0.15
I = 60 amps

```

So, you are trying to draw 60 amps from your 1A power supply, which then turns off.

---

> If the multimeter is rated at 10A and the power supply can provide at most 3A, then why is there a risk of blowing the fuse in the meter?

It depends on the range on the meter. Mine has a 10A range and a milliamp range. The 10A range is fused to slightly more than 10A (naturally) and the milliamp range has a maximum of 400 mA. If you had tested with the milliamp range you would have blown the fuse. Yes, it would survive on the 10A range, if your power supply cannot output 10A.

There will be lots of web pages about measuring amps with a meter, here is one.
> 1 votes

---
Tags: power
---


title: Arduino mega 2560 might be dead

text:
# Question
Title: Arduino mega 2560 might be dead
I was playing with Vin and a transistor when the arduino got disconnected from my pc and after a few seconds it started to smoke. It wasn't much smoke but enough to panic and disconnect everything. I waited a few minutes and then i plugged it into my pc. The power led and the 13 pin led were on but my pc couldn't recognize my device. In arduino ide i couldn't find the port and the tx and rx leds didn't blink at all. I tried to restart my px, reset arduino, i powered it with a 12v source and i got 12v out on Vin but 0 on 5V and 3V. The 13 pin doesn't want to turn off and my pc doesn't recognize it. It is not a ch arduino and it worked perfectly until i did this. I've benn searching on internet for 2 hours now about this but i still couldn't find something relevant. In device manager it sais "unknown usb device (device descriptor request failed)" and inside proprieties at device status this is written:

"Windows has stopped this device because it has reported problems. (Code 43)

A request for the USB device descriptor failed."

I also tried to update drivers automatically and manual but didn't work. I have no idea where that smoke came from.

Is it dead? can i do anything to make it work?

# Answer
> 1 votes
> i powered it with a 12v source and i got 12v out on Vin but 0 on 5V and 3V.

The fuse or the Vin input diode or the 5V voltage regulator or all of them could be damaged.

> i plugged it into my pc. The power led and the 13 pin led were on but my pc couldn't recognize my device. In arduino ide i couldn't find the port and the tx and rx leds didn't blink at all.

1. The MCU could be damaged.
2. The USB chip is dead (Because there is no rx blinking during programming).

If you connect the arduino through USB and there was not 3.3v at the 3.3v supply rail, the 3.3v voltage regulator is dead.

You had better buy a new one or if you want to fix it to gain experience go for it.

# Answer
> 1 votes
I have some troubleshooting steps here: Have I bricked my Arduino Uno? Problems with uploading to board

Whilst specifically written for the Uno, a lot of it applies to the Mega. Depending on what you did, the entire board may not have failed.

Many of the components are SMD (surface mounted devices) and may be difficult to replace, unless you have specialized equipment.

If you "zapped" every chip by applying a negative voltage (say) then it might not be worth it.

---
Tags: usb
---


# Question
Title: Problem activating HC-05 AT command mode with Arduino Uno Bluetooth shield
Please be gentle with me. I am attempting to modify the configurations of my HC-05 bluetooth module by using the AT command set. The method by which I'm trying to do this is by implementing the following connection:

HC-05 GND --\> Arduino GND; HC-05 3.3v --\> Arduino 3.3V; HC-05 TX --\> Arduino Pin 10; HC-05 RX --\> Arduino Pin 11; HC-05 KEY --\> Arduino Pin 9

This is the code which I uploaded to my Arduino (btw my arduino uno is an SMD clone): (code's from http://www.instructables.com/id/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/step2/The-Arduino-Code-for-HC-05-Command-Mode/)

```
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more

 }

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());

}

```

The problem is I can't seem to activate the AT mode. I don't get any response from the Serial Monitor whatever AT command I try. I double-checked the wiring and it's all good. I can't figure out what the problem is.

# Answer
After 3 hours I magically solved my pretty simple problem myself. If you wired the HC-05 and arduino correctly, the module should indicate that it's in AT Mode by blinking the LED in an interval of 2 seconds. You should get response in the Serial Monitor by typing the AT commands by switching from "No line ending" to "Both NL and CR". That's about it.
> 1 votes

# Answer
In `setup()` put pin 9 to low, and delay it for about 1 second and then put it to high.
> -1 votes

---
Tags: bluetooth, hc-05
---


# Question
Title: Connect 2 Arduino UNOs via Bluetooth? (HC-05 and HC-06)?
So I've researched this topic a lot online, but haven't found what I'm looking for. Before I tell you this, I'll give you guys an idea of what I'm trying to accomplish. Please understand that I'm an extreme beginner to Arduino, and that I've only been at this for a month or so, but plan on doing so much more.

My friend and I are building an RC car. We have an Android phone that has a downloadable application which connects to the Bluetooth HC-06 module that is on the Arduino UNO. We have configured our circuit, and it works fine! I want to go a step above and beyond, though.

My goal is to build a physical, handheld controller or remote (literally plopping everything on a breadboard), and connect that controller or remote to our car using Bluetooth. We have an HC-05 and HC-06 module, and the HC-06 is on the car. Now comes the doubt.

I understand how the android application sends characters through to the RC Car via Bluetooth; that's pretty straightforward as the two pieces are paired (using Android's Bluetooth Settings). What I don't understand is how to pair the two HC-05 and HC-06 Bluetooth modules. There isn't too much help online, I feel. I've looked and people have shown that they connect, but they don't explain the theory, so to speak.

What I want to understand is:

1. How the two HC-05 and HC-06 modules pair, and
2. How can I read input from one (remote controller) and execute an action on the other (RC car). From the app-to-Arduino, I was using `Serial.available()` to see if the Serial had any characters sent over from the application. I can't see how I can do that with HC-05 to HC-06 pairing, however. This concept is hard for me to grasp.

Any help is greatly appreciated. Thank you!

# Answer
You need to set HC-05 to master, and this done by soldering pin 34 of BT and connecting it to digital pin on Arduino to enter AT command. Then after powering the Arduino, you need to put pin 34 high. This way it will enter AT command. In serial monitor, follow these AT commands:

```
AT+cmode=0
AT+ROLE=1 // THIS WILL SET THE BT AS MASTER
AT+INIT
AT+LINK= ????,??,??????  // REPLACE ?... WITH HC-06 MAC ADDR

```
> 1 votes

# Answer
1. Have a look at this for how to pair them http://www.martyncurrey.com/connecting-2-arduinos-by-bluetooth-using-a-hc-05-and-a-hc-06-pair-bind-and-link basically you need to use the AT mode.
2. As far as I know you will be using the serial connection to communicate, but if you are using UNOs debugging becomes a bit more difficult, because you can't use serial for debugging.
> 1 votes

# Answer
For this you just have to pair the both bluetooth modules with each other.! For this use AT commands.

You can find those here: https://www.rcscomponents.kiev.ua/datasheets/hc\_hc-05-user-instructions-bluetooth.pdf.

For pairing use MAC address of one module and hardcode it in second module using AT commands. Now from theory point of view for pairing between any two bluetooth modules,there are some handshaking signals which are processed and if they are correctly processed then the device gets paired. Its very hard to debug. But for that purpose use software serial
> 1 votes

---
Tags: arduino-uno, serial, bluetooth, hc-05, hc-06
---


# Question
Title: Navigating menus using buttons on Arduino
I have made a very short version of my code. It has the basic problem I am facing. I explain my code and problem below.

```
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2); //format of display
}

int menu = 0;
int subMenu = 99;
void loop() {

  uint8_t buttons = lcd.readButtons();

  lcd.setCursor(0,0);

  if (menu == 0) {
  lcd.print("Select menu option");
    if (buttons & BUTTON_SELECT) {
      lcd.clear();
      menu = 99;
      subMenu = 1;
    }
  }

  if (subMenu == 1) {
    lcd.print("in sub menu 1");
    if (buttons & BUTTON_SELECT) {
       lcd.clear();
       lcd.setCursor(0,1);
       lcd.print("shouldnt happen");
    }
  }
}

```

I am setting a variable `menu`, which will keep track of what main menu I am on, and a `subMenu`, which keeps track of what sub-menu I am on.

The default value of `menu` (0) prints on the LCD "Select Menu Option".

When pressing SELECT, the LCD is cleared. The `menu` is being set to an unknown number, so that it doesn't print anything, and `subMenu` is set to 1.

If `subMenu` is equal to 1 (which it will be if the user chooses presses SELECT), the LCD prints "in sub menu 1".

Inside this, if the button SELECT is clicked, it should print "shouldnt happen".

The issue I am facing is that when clicking SELECT for entering the menu 1, the SELECT is also carried out to the sub-menu, so instead of waiting for a second key press to confirm going into the sub menu, it goes straight into it.

This makes sense because it is check that SELECT has been pressed, prints a new page, with the button SELECT still having been pressed, so it validated the condition for key press in the sub menu as well.

**The user input to LCD display response should be the following:**

Select menu option -\> presses SELECT -\> in sub menu 1 -\> presses SELECT -\> shouldnt happen

**Currently however, it is like this:**

Select menu option -\> presses SELECT -\> in sub menu 1 shouldnt happen

How can I make it so that these key presses only act on the menu on which they are?

Thanks, let me know if something confuses you, I can explain in more details

# Answer
I'm not sure about built-in buttons, however on my projects I always add a debounce feature to any buttons. Adjust this to your uses. If there's any issues let me know and I'll test it properly as I'm not at my programming workstation to fully test at the moment.

For example:

```
// Updated to include if statements and copy/pasted version of successfully
// compiled version.

// Had to use LiquidCrystal library as I don't have the AdaFruit Display libraries.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//

int menu = 0, subMenu = 99, debounce = 200;
unsigned long pMillis = 0, cMillis;

void setup(){
  lcd.begin(16,2);
};

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();
  lcd.setCursor(0,0);
  if(cMillis >= (pMillis + debounce)){
    if (menu == 0) {
      lcd.print("Select menu option");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  menu = 99;
       *  subMenu = 1;
       *  };
       */
    };
    if (subMenu == 1) {
      lcd.print("in sub menu 1");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  lcd.setCursor(0,1);
       *  lcd.print("shouldnt happen");
       *  };
       */
    };
  pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
  // I always put something similar to this at the end
  // to make sure that when millis() cycles back to 0
  // pMillis is reset to less than cMillis.
  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
};

```

Edit/Update: This compiles fine using the standard LiquidCrystal library, I am unable to test the AdaFruit display as I don't have one. If this still doesn't work, I'll upload it to the Arduino when I get back and see what's up.

New test:

```
// Your libraries here

int menu = 0,
    subMenu = 99,
    debounce = 200;

unsigned long pMillis = 0,
          cMillis;

void setup(){
  lcd.begin(16,2);
}

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();

  if(buttons & BUTTON_SELECT){ // I used "if(digitalRead(buttonPin) == HIGH){ ... }"
    if(cMillis >= (pMillis + debounce)){
      //I'd normally put counter/menu logic in here for the different buttons, for example:
      //"subMenu += 1;
      // if(subMenu >= totalSubMenus) { subMenu = 0; };"
      subMenu = 1;
      pMillis = cMillis;
    }
  }

  if(menu == 0){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Select Menu Option");
    menu = 99;
  }
  if(subMenu == 1){
    lcd.clear();
    lcd.setCursor(0,1);
    lcd.print("In Sub Menu 1");
  }

  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  }
}

```
> 1 votes

---
Tags: arduino-uno, lcd, c, genuino
---


# Question
Title: What types of connectors should I use to connect an HC-06 to an Arduino?
I am new to electronics and I need to connect an Arduino Uno with an HC-06 Bluetooth module.

The problem is that I don't know what types of connectors I should use.

I know I need some Dupont wires but there are 3 types: **male to male** \- **male to female** \- **female to female**.

So my question is: what type of connector should I use?

# Answer
> 0 votes
I'm not sure on the exact package of you HC-06. All of the ones I have are like this picture. If you have one like this, you will need male to female jumper cables. I would recommend a breadboard as well if you plan on connecting anything additional.

---
Tags: arduino-uno, hc-06
---


# Question
Title: Correct Capacitors to use with L7805 Voltage Regulator
I am making my own arduino. I am in the process of hooking up power to the Atmega328.

In both these articles they use the L7805 voltage regulator with two 10uF capacitors.

https://www.arduino.cc/en/Main/Standalone

http://www.instructables.com/id/How-to-Build-an-Arduino-Uno-on-a-BreadBoard/?ALLSTEPS

I am looking at the datasheet for the regulator at http://pdf.datasheetcatalog.com/datasheet\_pdf/sgs-thomson-microelectronics/L7805CD2T\_to\_L7885CV.pdf

The data sheet provides a number of figures for how to correctly hook up the L7805 in different situations (pages 4, 16-23). I think Figure 13 represents our situation (Fixed Output Regulator). In the figure they use 0.33uF and 0.1uF capacitors. Could someone explain why the examples use 10uF and the data sheet specifies 0.33uF and 0.1uF?

# Answer
> 6 votes
The answers are in the notes:

> 2. Although no output capacitor is need for stability, it does improve transient response.
> 3. Required if regulator is locate an appreciable distance from power supply filter.

So the values aren't critical to the operation, but you should have them there. Bigger capacitors give more energy to the regulator and more energy to your circuit (input and output capacitors respectively) but at the cost of lower frequency response. The actual values you select depend on your circuit, not the regulator. 10µF is a good "ballpark" figure to use in most circumstances.

The input capacitor reduces the impedance of the power source by providing a local source of power. The output capacitor is like the "reservoir" capacitor you should have at the power entry to all boards anyway, and reduces the impedance to the rest of your circuit.

For the higher frequency responses you should have smaller value decoupling capacitors by all your active components anyway.

You can also add more smaller capacitors to the output of the regulator to improve high frequency responsiveness if needed - you're not just limited to the one capacitor.

# Answer
> 2 votes
> Could someone explain why the examples use 10uF and the data sheet specifies 0.33uF and 0.1uF?

One obvious reason is that those two examples are non compliant with the datasheet.

But generally speaking the ordinary 78xx regulators use emitter output and are quite tolerant to the output capacitance. 10if is not a bad number.

However, there are also variants of 78xxx that take their output from the collector. They are more sensitive to output capacitance, as most ldos are.

Generally it is a good idea to stay within the datasheet but that doesn't mean you shouldn't step out from time to time.

---
Tags: power, atmega328, voltage-protection, capacitors
---


# Question
Title: Controlling Dynamixel Ax-12 With Arduino Mega
I want to controll two dynamixel ax-12 servos using a arduino mega and I don\`t know the commands that I should send to them using Serial.

Could anyone help me with this? (And please keep in mind that I don\`t want any more hardware. Just arduino board)

# Answer
> 2 votes
With Dynamixel library you can use servo this easily:

```
#include <DynamixelSerial.h>

void setup(){
   Dynamixel.begin(1000000,2);  // Inicialize the servo at 1Mbps and Pin Control 2
}

void loop(){
    Dynamixel.move(1,0);
    delay(2000);
    Dynamixel.move(1,500);
    delay(2000);
    Dynamixel.move(1,1000);
    delay(2000);
}

```

Example moves servo and makes pauses of 2 sec.

Installation is easy:

> Installation:
>
> Copy the files from DynamixeSerial to your IDE libraries folder.

DynamixelSerial folder can be found here: https://sourceforge.net/projects/dynamixelforarduino/files/?source=navbar

---
Tags: arduino-mega
---


# Question
Title: I want to obtain the output of GPS at every 5 secs and store them onto database using Arduino uno,GPS SKG 13BL and GSM module??
I am on a project,in which I need to store the output of GPS from SKG 13BL to a database using Arduino UNO and GSM module.I wrote the following code

```
#include <SoftwareSerial.h>
#include <AltSoftSerial.h>
#include <NMEAGPS.h>

SoftwareSerial GSM(2, 3); // RX, TX: Connect TXD to RX & RXD to TX

static const int RXPin = 8, TXPin = 9;
AltSoftSerial gpsPort(RXPin, TXPin);
static const uint32_t GPSBaud = 9600;

NMEAGPS gps;
gps_fix fix;
uint8_t fixCount = 0;
char dt[15],tm[15];

enum _parseState {
  PS_DETECT_MSG_TYPE,

  PS_IGNORING_COMMAND_ECHO,

  PS_HTTPACTION_TYPE,
  PS_HTTPACTION_RESULT,
  PS_HTTPACTION_LENGTH,

  PS_HTTPREAD_LENGTH,
  PS_HTTPREAD_CONTENT
};

enum _actionState {
  AS_IDLE,
  AS_WAITING_FOR_RESPONSE
};

byte actionState = AS_IDLE;
unsigned long lastActionTime = 0;

byte parseState = PS_DETECT_MSG_TYPE;
char buffer[80],url[80];
byte pos = 0;

int contentLength = 0;

void resetBuffer() {
  memset(buffer, 0, sizeof(buffer));
  pos = 0;
}

void sendGSM(const char* msg, int waitMs = 500) {
  GSM.println(msg);
  while(GSM.available()) {
    parseATText(GSM.read());
  }
  delay(waitMs);
}

void setup()
{
  GSM.begin(9600);
  Serial.begin(9600);
  gpsPort.begin(GPSBaud);

  Serial.println(F("GPS LOADING....."));
  Serial.println(F("Testing by : "));
  Serial.println(F("Billa"));
  Serial.println();

  sendGSM("AT+SAPBR=3,1,\"APN\",\"vodafone\"");
  sendGSM("AT+SAPBR=1,1",3000);
  sendGSM("AT+HTTPINIT");
  sendGSM("AT+HTTPPARA=\"CID\",1");
}

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

  while (gps.available( gpsPort )) {
    fix = gps.read();

    // Once every 5 seconds...
    if (++fixCount >= 5) {
      displayInfo();
      fixCount = 0;
    }
  }

  if ((gps.statistics.chars < 10) && (millis() > 5000)) {
     Serial.println( F("No GPS detected: check wiring.") );
     while(true);
     block=1;
    }
  }

  if ( actionState == AS_IDLE ) {
    if ( now > lastActionTime + 5000 ) {
      sprintf(url, "AT+HTTPPARA=\"URL\",\"http://*****.000webhostapp.com/hinderset.php?date=%s\"", dt); // passing date only now as part of testing
      sendGSM(url);
      sendGSM("AT+HTTPACTION=0");
      lastActionTime = now;
      actionState = AS_WAITING_FOR_RESPONSE;
    }
  }

  while(GSM.available()) {
    lastActionTime = now;
    parseATText(GSM.read());
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (fix.valid.location) {
    Serial.print( fix.latitude(), 5 );
    Serial.print( ',' );
    Serial.print( fix.longitude(), 5 );
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Speed: "));
  if (fix.valid.speed) {
    Serial.print(fix.speed_kph());
    Serial.print(F(" KMPH "));
  } else {
    Serial.print(F("INVALID"));
  }

  // Shift the date/time to local time
  NeoGPS::clock_t localSeconds;
  NeoGPS::time_t  localTime;
  if (fix.valid.date && fix.valid.time) {
    using namespace NeoGPS; // save a little typing below...

    localSeconds = (clock_t) fix.dateTime; // convert structure to a second count
    localSeconds += 5 * SECONDS_PER_HOUR + 30 * SECONDS_PER_MINUTE; // shift timezone
    localTime = localSeconds;              // convert back to a structure
  }

  Serial.print(F("  Date : "));
  if (fix.valid.date) {
    sprintf(dt,"%02d/%02d/20%d",fix.dateTime.date,fix.dateTime.month,fix.dateTime.year);
    Serial.print(dt);
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Time : "));
  if (fix.valid.time) {
    if (localTime.hours>12)localTime.hours-=12;//To convert 24 hr format to 12 hr format
    sprintf(tm,"%02d:%02d:%02d",localTime.hours,localTime.minutes,localTime.seconds);
    Serial.print(tm);
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

void parseATText(byte b) {

  buffer[pos++] = b;

  if ( pos >= sizeof(buffer) )
    resetBuffer(); // just to be safe

  /*
   // Detailed debugging
   Serial.println();
   Serial.print("state = ");
   Serial.println(state);
   Serial.print("b = ");
   Serial.println(b);
   Serial.print("pos = ");
   Serial.println(pos);
   Serial.print("buffer = ");
   Serial.println(buffer);*/

  switch (parseState) {
  case PS_DETECT_MSG_TYPE:
    {
      if ( b == '\n' )
        resetBuffer();
      else {
        if ( pos == 3 && strcmp(buffer, "AT+") == 0 ) {
          parseState = PS_IGNORING_COMMAND_ECHO;
        }
        else if ( b == ':' ) {
          //Serial.print("Checking message type: ");
          //Serial.println(buffer);

          if ( strcmp(buffer, "+HTTPACTION:") == 0 ) {
            Serial.println("Received HTTPACTION");
            parseState = PS_HTTPACTION_TYPE;
          }
          else if ( strcmp(buffer, "+HTTPREAD:") == 0 ) {
            Serial.println("Received HTTPREAD");
            parseState = PS_HTTPREAD_LENGTH;
          }
          resetBuffer();
        }
      }
    }
    break;

  case PS_IGNORING_COMMAND_ECHO:
    {
      if ( b == '\n' ) {
        Serial.print("Ignoring echo: ");
        Serial.println(buffer);
        parseState = PS_DETECT_MSG_TYPE;
        resetBuffer();
      }
    }
    break;

  case PS_HTTPACTION_TYPE:
    {
      if ( b == ',' ) {
        Serial.print("HTTPACTION type is ");
        Serial.println(buffer);
        parseState = PS_HTTPACTION_RESULT;
        resetBuffer();
      }
    }
    break;

  case PS_HTTPACTION_RESULT:
    {
      if ( b == ',' ) {
        Serial.print("HTTPACTION result is ");
        Serial.println(buffer);
        parseState = PS_HTTPACTION_LENGTH;
        resetBuffer();
      }
    }
    break;

  case PS_HTTPACTION_LENGTH:
    {
      if ( b == '\n' ) {
        Serial.print("HTTPACTION length is ");
        Serial.println(buffer);

        // now request content
        GSM.print("AT+HTTPREAD=0,");
        GSM.println(buffer);

        parseState = PS_DETECT_MSG_TYPE;
        resetBuffer();
      }
    }
    break;

  case PS_HTTPREAD_LENGTH:
    {
      if ( b == '\n' ) {
        contentLength = atoi(buffer);
        Serial.print("HTTPREAD length is ");
        Serial.println(contentLength);

        Serial.print("HTTPREAD content: ");

        parseState = PS_HTTPREAD_CONTENT;
        resetBuffer();
      }
    }
    break;

  case PS_HTTPREAD_CONTENT:
    {
      // for this demo I'm just showing the content bytes in the serial monitor
      Serial.write(b);

      contentLength--;

      if ( contentLength <= 0 ) {

        // all content bytes have now been read

        parseState = PS_DETECT_MSG_TYPE;
        resetBuffer();

        Serial.print("\n\n\n");

        actionState = AS_IDLE;
      }
    }
    break;
  }
}

```

When I tested them in separate modules they worked and obtained result But now When I wrote the above code it is showing me "NO GPS DETECTED".Can you please help me in resolving the problem.The objective is I need to **obtain the output from GPS at every 5 secs** (5 secs interval between each output) and store them into database using GSM module

# Answer
### There are three problems:

**1)** You are using `delay`.

**2)** You are *still* using `SoftwareSerial`. It blocks interrupts for long periods of time, interfering with other parts of your sketch. I told you this in your previous post.

**3)** Starting the HTTP action is not synchronized with the GPS clock. The Arduino `millis()` clock is not synchronized with the GPS atomic clock. They will drift in and out of sync over time. I also told you this in the same previous post.

### The solution:

**1)** Don't use `delay`. The GPS device continues to send characters, and they get dropped when the Arduino is blocked at the `delay`.

Instead, just send the command and let your nice `parseATTText` handle the response as it comes in, without waiting. If there are multiple commands to send, add an extra state for each command. When a response for the first command arrives, send the second command *and* step to the next state.

You can use `delay` in `setup` if you don't care about the responses to those initial commands. Or you could add one SETUP\_xxx state for each command to your FSM and let them happen in `loop`. `parseATTText` will advance through those STARTUP states, sending each of those commands.

**2)** Use NeoSWSerial.

**3)** Move the HTTPPARA command into the GPS loop with `displayInfo`:

```
  while (gps.available( gpsPort )) {
    fix = gps.read();

    // Once every 5 seconds...
    if (++fixCount >= 5) {
      displayInfo();

      // Send the next report if the previous one is finished
      if ( actionState == AS_IDLE ) {
        sprintf(url, "AT+HTTPPARA=\"URL\",\"http://*****.000webhostapp.com/hinderset.php?date=%s\"", dt); // passing date only now as part of testing
        sendGSM(url);
        parseState = PS_HTTPPARA_RESPONSE; // a new state
        actionState = AS_WAITING_FOR_RESPONSE;
      }

      fixCount = 0;
    }
  }

```

You should move `sendGSM("AT+HTTPACTION=0")` into `parseATTText` as a `case PS_HTTPPARA_RESPONSE`, and step to the next state (PS\_DETECT\_MSG\_TYPE?)

If you reset `fixCount` inside the `if (actionState == IDLE)` block, it will send a new location when the previous one finally completes, perhaps after 6 new fixes.

Resetting `fixCount` outside the block (as above) means it may send the 5th location, skip the 10th because it's NOT IDLE, and then send the 15th location. If you want it to send the 5th, then the 11th if it's not busy, reset `fixCount` inside the `if` block.
> 1 votes

---
Tags: gsm, gps
---


# Question
Title: Compiling error:passing as 'this' argument
I am trying to make a small keyboard class to handle two buttons(in the future \>2) that are connected to my arduino UNO. The buttons being pressed are detected using interrupts. Here is the code:

**Timer**

```
class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark(){
      start_time=millis();
    }
    uint32_t lapsed(){
      return millis()-start_time;
    }
};

```

**Keyboard**

```
class KeyboardBtn{
  private:
    const static byte clicksDelay=255;      //255 ms max
    struct btn{
      byte state=0;   //0->nothing;1-click;2-dblClick
      Timer clickDelay;
    };
    volatile static btn buttons[2];         //only two buttons for now

  public:
    KeyboardBtn(){
      attachInterrupt(digitalPinToInterrupt(2),this->int_handler_btn0,FALLING);       //Initially the pins are set to HIGH(pullup behaviour)
      attachInterrupt(digitalPinToInterrupt(3),this->int_handler_btn1,FALLING);
    }

    static void int_handler_btn0(){
      btns_handler(0);
    }
    static void int_handler_btn1(){
      btns_handler(1);
    }
    static void btns_handler(byte key){
        if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
          buttons[key].state=2;
        }else{
          buttons[key].state=1;
          buttons[key].clickDelay.mark(); //Pressed one time? mark this and wait for second press
        }
    }
    byte stateChanged(byte key){
      //Function called to get key status
      byte temp_state=buttons[key].state;
      if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
        return 0; //We still wait:don't know if it's a dblClick or single
      }else{
        buttons[key].state=0;
        return temp_state;
      }
    }
};
volatile KeyboardBtn::btn KeyboardBtn::buttons[2];

```

But the compiler gives me headaches(of course my code is wrong somewhere but he could just have kept quite about it):

> C:\Users....\Humidity.ino: In static member function 'static void KeyboardBtn::btns\_handler(byte)':
>
> C:\Users...\Humidity\Humidity.ino:74:68: warning: passing 'volatile Timer' as 'this' argument of 'uint32\_t Timer::lapsed()' discards qualifiers \[-fpermissive\]
>
> ```
>      if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
>
>                                                                 ^
>
> ```
>
> C:\Users...\Humidity\Humidity.ino:78:40: warning: passing 'volatile Timer' as 'this' argument of 'void Timer::mark()' discards qualifiers \[-fpermissive\]
>
> ```
>        buttons[key].clickDelay.mark();
>
>                                     ^
>
> ```
>
> C:\Users....\Humidity\Humidity.ino: In member function 'byte KeyboardBtn::stateChanged(byte)':
>
> C:\Users....\Humidity\Humidity.ino:83:58: warning: passing 'volatile Timer' as 'this' argument of 'uint32\_t Timer::lapsed()' discards qualifiers \[-fpermissive\]
>
> ```
>    if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
>
>                                                       ^
>
> ```

What is the problem? Note:It does allow me to upload the code but I am almost certain it will generate some errors while running...

# Answer
If you want to use an instantiated object as volatile then the functions within it also have to be marked as volatile. That tells the compiler that the instance pointer you will be passing to the function (the auto-inserted `this` parameter) is volatile:

```
class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark() volatile {
      start_time=millis();
    }
    uint32_t lapsed() volatile {
      return millis()-start_time;
    }
};

```
> 4 votes

---
Tags: arduino-ide, compiler
---