title: Ignore event until x minutes

text:
# Question
Title: Ignore event until x minutes
I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.

Here is the code I come up with:

```
if (digitalRead(sensor_event)==HIGH)
  {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute > time_pushed+5)
                           time_set=0; // Unlock
                 }
               else
                 {
                        if (tm.Minute >= 55)
                          time_pushed=0;
                        else
                          time_pushed=tm.Minute; // Set global volatile min value

                        print("Sensor event");
                        time_set=1;
                 }
      }
  }

```

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.

The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time\_pushed would be set to 56 then the time\_pushed+5 would give 61 (which of course is never reached).

Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.

Thanks

# Answer
> 1 votes
Use the `millis()` function instead if you can accomodate a rollover after 50 days.

* Take a reading of millis() at the start time.
* time\_pushed = millis() + 5 * 60 * 1000; // 5 minutes into future.

The rest of your code shouldn't require too much editing.

# Answer
> 0 votes
Calculate target time, rollover if necessary and check if time is already passed that point. As long as you are checking the time multiple times per minute you shouldn't run into any issues.

```
if (digitalRead(sensor_event)==HIGH)
{

  if (RTC.read(tm)) {

          if(time_set)
            {
                   if (tm.Minute >= targettime)
                       time_set=0; // Unlock
             }
           else
             {
                    targettime=tm.Minute+5; // Set global volatile min value
                    targettime=targettime % 60;

                    print("Sensor event");
                    time_set=1;
             }
  }
}

```

# Answer
> 0 votes
The proper way to do that depends on whether the event is guaranteed to happen at least once every 49.7 days. If this is the case then, as Tom Carpenter suggested in a comment, you can just test for `now - last_event >= hold_time`:

```
void loop()
{
    uint32_t now = millis();
    static uint32_t last_event = -hold_time;

    // Detect the event if it did not happen in the last five minutes.
    if (now - last_event >= hold_time
            && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        last_event = now;
    }
}

```

If you can have 49.7 days without a single event, then this approach fails because `last_event` is ambiguous. The simplest solution is probably to implement a state machine with only two states, as the event detection is either “on hold” or it is not:

```
void loop()
{
    uint32_t now = millis();
    static bool on_hold;
    static uint32_t last_event;

    // Remove the hold after five minutes.
    if (on_hold && now - last_event >= hold_time) {
        on_hold = false;
    }

    // Detect the event.
    if (!on_hold && digitalRead(sensor_event) == HIGH) {
        Serial.println("Sensor event");
        on_hold = true;
        last_event = now;
    }
}

```

Now I would want to insist on a specific point: in either approach the millis() rollover is not an issue. The choice between the first and the second approach depends solely on the maximum time between the events, not on how long the program is meant to run.

# Answer
> 0 votes
Just to save a lot of headaches for everybody who wonders here and still have a problem with this code:

```
uint32_t hold_time = 1*60*1000; // 1 minute will never work

uint32_t hold_time = 60000; // 1 minute will work

```

You must define the value as an EXACT number, not putting in multiplication and rely on the compiler to calculate it for you.

Probably because it's unsigned long and screws up something with the multiplication but with the first example you will be put on hold for days, maybe forever.

# Answer
> -1 votes
Don't bother with the RTC, just use millis(). Or just convert the time in hours/minutes/seconds to a single number in seconds (i.e. UNIX timestamp) and use that. Then use these time comparison macros:

```
#define time_after(unknown, known) ((long)(known) - (long)(unknown) < 0)
#define time_before(unknown, known) ((long)(unknown) - (long)(known) < 0)
#define time_after_eq(unknown, known) ((long)(unknown) - (long)(known) >= 0)
#define time_before_eq(unknown, known) ((long)(known) - (long)(unknown) >= 0)

```

Then do something like this in your main loop, with a variable unsigned long sample\_timer that's initialized to 0 at the start of your program:

```
if (time_after_eq(millis(), sample_timer))
{
    if (event)
    {
        sample_timer = millis() + 5*60*1000;
        // handle event...
    }
}

```

These time comparison macros will properly handle overflow if you use unsigned long for your timestamps.

---
Tags: time
---


title: Why FIFO is important in camera?

text:
# Question
Title: Why FIFO is important in camera?
I want to buy a camera module for Arduino. I came across this **OV7670 CMOS Camera Module Lens CMOS 640X480 SCCB W/ I2C Interface Arduino** and **CMOS With AL422 3M-Bits OV7670 FIFO Camera** .

I want to know what difference does FIFO makes in a camera? If I dont use a FIFO will the quality of video be compromised?

# Answer
> 2 votes
Its not FIFO that is the issue, its the FIFO *Buffer* that you need with an Arduino. The Arduino can't download the data from the camera at the same speed as the camera can send it. Adding this extra buffer in lets the camera generate the data and the Arduino download it (in the same order that it was generated) at its own pace.

You might not need the FIFO buffer for faster microprocessors, but you do need it for the Arduinos. You could get your own buffer and rig that up, but for a few extra bucks let them do it for you.

---
Tags: arduino-uno
---


# Question
Title: 8 bit arduinos: What happens to the data in registers during a function call? During an interupt?
If I have one function that uses registers heavily calling another that does the same thing, what happens? Does the data get destroyed? What, then, would happen on return to the first function? Is this different for interrupt handlers?

# Answer
> 4 votes
The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.

---
Tags: avr
---


# Question
Title: Can I use GSM and GPS modules at the same time?
In my project I want to retrieve the Latitude and longitude and then transmit to a cell phone through GSM module. But the GSM as well as GPS modules uses the same pins i.e. Tx and Rx, so is it possible to use both modules at the same time?

Link to products

GSM - http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-SIM-Board-Quadband-PCB-Antenna-for-MCU-Arduino-/191611848583?hash=item2c9cf4c787

GPS-- http://www.ebay.co.uk/itm/New-1PC-Ublox-NEO6MV2-GPS-Module-Aircraft-Flight-Controller-For-Arduino-/400830328802?hash=item5d53596fe2

Thank you.

# Answer
Yes. Use SoftwareSerial for one of them. That way you can use any pins you like for that module.

I'd recommend using the GPS module on the SoftwareSerial since it's (mainly) half duplex, and SoftwareSerial can't both transmit and receive at the same time like the hardware UART can.

Either that or switch to a different Arduino board that has more than one hardware UART.
> 2 votes

# Answer
If you are using two software serial then you can always use the `listen()` function to listen to specific object.

Suppose you have two software serial objects named GSM and GPS.
Now if you are reading or writing data to GSM then start with this, `gsm.listen();`
Now you can read/write data to GSM.
Next if you plan to read or write data to GPS then do this, `gps.listen();`
> 0 votes

---
Tags: gsm, gps
---


# Question
Title: How do I implement a userspace bootloader on Arduino Due?
Is it possible to use a custom bootloader, that loads and executes a main program stored for example on an SD card? The idea is to make it possible to update the Arduino remotely.

I tried this with a bootloader, which writes the program into the flash storage with a 32KB offset and then uses a function pointer with that address (0x88000) to continue execution there. The 0x80000 is as far as I am informed the address offset of the flash storage. It can be written on Due boards with this library: https://github.com/sebnil/DueFlashStorage. The problem was that this just hasn't worked, the Arduino simply stopped responding after the function pointer being executed. I would appreciate any information or hints on this topic.

# Answer
The guys at Phoenard did just that with an AVR2560. They wrote a bootloader that loads and saves FLASH memory from/to the Micro-SD card. You can save HEX files on an SD card and then load one of them in the FLASH memory and run it.
> 1 votes

# Answer
Not sure if you could get the bootloader to support SD, but I have little experience with bootloader code, so the way I would go about it would be to make the sketch load content from the SD that then affects the sketch process.
> 0 votes

---
Tags: arduino-due, flash
---


# Question
Title: Sending Arduino data to MySQL using phpMyAdmin and XAMPP using Windows10
I want to send my Arduino's sensor data to a MySQL database, using XAMPP and phpMyAdmin. I have been using an ESP8266 for the wifi connection. But I am unable to send the value. And actually I have to send four values, but for the time being I am sending only one value. So also please tell how to send multiple values. I have written the PHP file and saved in to Apache's htdocs.

```
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include <SoftwareSerial.h>
#include <PubSubClient.h>
#include <SPI.h>
IPAddress ip(192,168,8,1);
char ssid[] = "ZONG MBB-E8372-B67D"; // your network SSID (name)
char pass[] = "08522547"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
int photocellPin = 4; // Analog input pin on Arduino we connected the SIG pin from sensor
int photocellReading; // Here we will place our reading
char server[] =  "192.168.8.1";
// Initialize the Ethernet client object
WiFiEspClient espclient;
SoftwareSerial soft(2,3); // RX, TX

void setup() {
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  soft.begin(115200);
  // initialize ESP module
  WiFi.init(&soft);
  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }
  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
}

void loop() {
  photocellReading = analogRead(photocellPin);
  // Fill the sensorReading with the information from sensor
  // Connect to the server (your computer or web page)
  if (espclient.connect(server, 80)) {
    espclient.println("GET /write_data7.php?"); // This
    espclient.println("value="); // This
    espclient.println(photocellReading);
    // And this is what we did in the testing section above.
    // We are making a GET request just like we would from our browser
    // but now with live data from the sensor
    espclient.println(" HTTP/1.1"); // Part of the GET request
    espclient.println("Host: 192.168.8.1");
    // IMPORTANT: If you are using XAMPP you will have
    //to find out the IP address of your computer and put it here
    // (it is explained in previous article). If you have a web page,
    // enter its address (ie.Host: "www.yourwebpage.com")
    espclient.println("Connection: close");
    // Part of the GET request telling the server
    // that we are over transmitting the message
    espclient.println(); // Empty line
    espclient.println(); // Empty line
    espclient.stop();    // Closing connection to server
  } else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

```

Following is the PHP code:

```
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'connected_car_1');
define('DB_USER','Maryam1');
define('DB_PASSWORD','telecom1213');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

$sql = "INSERT INTO connected_car_1.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql,$con);
mysql_close($con);
?>

```

And this is my serial monitor output:

I am very new to coding in Arduino as well as PHP and databases. So kindly tell me what I am doing wrong. And do I have to provide the IP address of the server, ie. 127.0.0.1? If yes, then where?

# Answer
You should write the PC IP, for example: `192.168.1.53`, because `127.0.0.1` is the IP used only for phpmyadmin and the database inside your computer.
> 1 votes

---
Tags: arduino-uno, esp8266
---


# Question
Title: Where is the inaccuracy of my arduino thermistor circuit coming from?
I've setup four thermistors and a known resistor in series and connected them to the 3.3V output (as I've heard it's cleaner than the 5V) of an Arduino Uno (with the 3.3V also connected to ARef to increase accuracy), with the four analog inputs testing the voltage drop across each thermistor to determine its resistance, and hence temperature.

But even with no change in the thermistor temperatures, the voltages I get from the arduino vary significantly. See below an example readout of the four arduino inputs (with thermistor temperatures/resistances same throughout):

230 424 634 849

212 412 597 819

241 415 611 857

204 413 654 845

The accuracy I come out with is around 5-10 degrees - way more than I expected. Why is this? And what can I do to get it down to less than one degree? Many thanks

UPDATE: A MASSIVE THANKYOU to all those who helped me on this, particularly @NickGammon, @Talk2 and most of all @JRobert for the brilliantly clear and simple to follow circuit instructions to follow, all of which helped to thoroughly solve my problem! The sensor works great now, many thanks!!

# Answer
Why are you using the voltage divider and measuring by parts? As @nickgammon points out, you are measuring only a 1/5 of full scale at each measurement, meaning your resolution is down by 5:1 over what the A/D is capable of. Also, the divider network comes to around 500KOhms. Work out the current through that and you get a very feeble \<7 microAmps. The wires are antennas that could well be contributing noise at a significant fraction of that level.

Is there a reason for the divider circuit? Could you use a single thermistor from Vcc to Gnd plus a resistor in a 2-way divider? That will have the advantages of:

* Using (more of) the full range of A/D;
* Taking only one reading instead of several (and the several are necessarily skewed in time since you're multiplexing the one A/D);
* A larger current (ok, only 33 microAmps, but 5x better than before);
* Presumably less pickup into the network than with 5 leads. Keeping the measurement lead as short as possible may help, too.

Update:

Then you probably want a 2-component divider for each temperature you need to measure, paralleled between the power rails. I just guessed, not calculated, the resistances of R1, R3, R5, & R7. You'll want to estimate the maximum and minimum temperatures of interest in each channel and pick values that will give you the best ranges without drawing excessive currents when the thermistor values are low.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

# Answer
Without exactly knowing part names, models and source code is difficult to tell what to expect. But a few techniques can be used to improve the stability of an analog reading. Here a few things you might want to consider:

1. Use INTERNAL vref of 1.1V, this is a very stable voltage reference
2. Use a stable/good quality series resistor, with little tolerance, like 1%
3. Add a 22pF capacitor, connecting the analog input to ground. This helps stabilizing the signal
4. Perform multiple consecutive readings, let's say 5 readings, and use the average. You might also want to remove the biggest and lowest values before averaging.
> 1 votes

# Answer
I may be mistaking, but what you did is a voltage divisor where you read the voltage across resistors in series (your thermistors).

When resistors are in series as you know you add their value. So A4 is reading the value across TR1+TR2+TR3+TR4. A3 is reading the value across TR1+TR2+TR3 and so forth.
> 1 votes

---
Tags: arduino-uno, electronics, temperature-sensor
---


# Question
Title: WDT & Software RESET in ESP8266 + Arduino IDE
I am working on ESP8266 in Arduino IDE. I want to know how to Software RESET the ESP8266. Any sketch/example would be useful. Moreover, how to initialise WDT in ESP8266.

Kindly help!

# Answer
> 3 votes
Software reset in ESP8266 is achieved using `ESP.reset()`

as per WDT, the other answer has info on that, i.e. software WDT is cleared using `yield()` \- hardware WDT is not accessible through software

---
Tags: arduino-ide, esp8266, timers, reset
---


# Question
Title: Array variable name changes from readings1 to readings2
I've been using two MB1240 Ultrasonic Sensors with analogRead, and have found that after using bubble sort, the array is found in array readings2, and not readings1. This is important because I would like to find the distance from each sensor.

Below is the code I've put together that uses buttons to determine when each sensor should be triggered.

```
const int anPin1 = 1;
const int anPin2 = 2;

const int triggerPin = 2;
long anVolt1, anVolt2;

// button Pins
const int buttonPin1 = 11;
const int buttonPin2 = 13;

int buttonState1;
int buttonState2;
int lastButtonState1 = false;
int lastButtonState2 = false;

long lastDebounceTime1 = 0;
long lastDebounceTime2 = 0;
long debounceDelay = 50; //ms

// initialise averaging array
const int numberOfReadings = 10; // reasonable DOF
long readings1[numberOfReadings];
long readings2[numberOfReadings];
long median;

void setup() {
  Serial.begin(9600);
  pinMode(triggerPin,OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  delay(200); // Datasheet: Sensors require 175 ms to calibrate
}

void start_sensor(){
  digitalWrite(triggerPin,HIGH);
  delay(10);
  digitalWrite(triggerPin,LOW);
}

long read_sensor1(){
  //Used to read in the analog voltage output that is being sent by the XL-MaxSonar device.
  //Scale factor is (Vcc/1024) per centimeter. A 5V supply yields ~4.9mV/cm for standard range sensors
  anVolt1 = analogRead(anPin1);
  return anVolt1;
}

long read_sensor2(){
  anVolt2 = analogRead(anPin2);
  return anVolt2;
}

void printall(long readings[]) {
  int med = numberOfReadings/2;
  median = (readings[med-1] + readings[med])/2;

  Serial.print("Sensor: ");
  for (int i = 0; i < numberOfReadings; i++) {
    Serial.print(readings[i]);
    Serial.print("cm ");
  }
  Serial.println();

  Serial.print("Median: ");
  Serial.print(median);
  Serial.println(" cm");
}

void loop () {
  int reading1 = digitalRead(buttonPin1);
  int reading2 = digitalRead(buttonPin2);

  // for noise
  if (reading1 != lastButtonState1) {
    lastDebounceTime1 = millis();
  }

  // for noise
  if (reading2 != lastButtonState2) {
    lastDebounceTime2 = millis();
  }

  if ((millis() - lastDebounceTime1) > debounceDelay) {
    if (reading1 != buttonState1) {
      buttonState1 = reading1;
      if (buttonState1 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++){
         start_sensor();
          readings1[i] = read_sensor1();
          delay(150); // From datasheet: Period = 99ms
        }

            **// bubble sort with flag
        for (int i = 0; i < sizeof(readings1)-1; i++) {
            bool flag = true;
            for (int j = 1; j < sizeof(readings1)-1; j++) {
                if (readings1[j-1] > readings1[j]) {
                    int t = readings1[j-1];
                    readings1[j-1] = readings1[j];
                    readings1[j] = t;
                    flag = false;
                }
            }
            if (flag) break;
        }
       printall(readings1);**
      }
    }
  }

  lastButtonState1 = reading1;

  if ((millis() - lastDebounceTime2) > debounceDelay) {
    if (reading2 != buttonState2) {
      buttonState2 = reading2;
      if (buttonState2 == HIGH) {
        for (int i = 0; i < numberOfReadings; i++) {
          start_sensor();
          readings2[i] = read_sensor2();
          delay(150);
        }
       printall(readings2);
      }
    }
  }
  lastButtonState2 = reading2;

  //clear previous readings
  memset(readings1, 0, sizeof(readings1));
  memset(readings2, 0, sizeof(readings2));
}

```

Scenario: I have clicked the first button to return a reading from the first sensor, and I am expecting the results to be stored then sorted in array readings1. After the bubble sort, if I enter printall(readings1), it returns an array of zeros, but if I use a printall(readings2), it returns the sorted array I expected.

I can't find where I'm going wrong with this one, any help would be greatly appreciated. Thank you!

# Answer
> ```
> for (int j = 1; j < sizeof(readings1)-1; j++) {
>
> ```

`sizeof(readings1)` is **not** the number of elements in the array, it is the size of the array in bytes (in your case, 40). You are exceeding the bounds of the array. You know the number of items (`numberOfReadings`) - why not use that?
> 2 votes

---
Tags: arduino-uno, c++, button, array
---


# Question
Title: Arduino IDE "Tools > Serial Port" grayed out (Ubuntu)
I know this has been asked before, but no one's solutions I've seen have worked so far. I just got started with Arduino and downloaded Arduino IDE from the Software Center. When trying to to set up my Serial Port, the option in the toolbar is gray/unaccessible.

I also downloaded it as a tar.xz instead of from the Software Center and had the same problem.

When I plug in my Uno, the green light turns on so I know it's being connected at least.

One solution I saw said it was a problem with my user group. However, I entered

`sudo groups <username>`

and came up with `<username> tty dialout sudo audio video plugdev input` so I think my groups are okay, right?

Anyway, I would really appreciate some help if anyone knows of a fix. I run 12.04 Ubuntu (I recently re-installed trying to fix this problem; I'm going to update to 14.04) on a Chromebook.

# Answer
I did what Chris Stratton's comment suggested,

> To investigate this, edit the output of ls -l /dev/ttyUSB\* and ls -l /dev/ttyACM\* (done while the board is connected) into your question. Also if you recently changed any group memberships make sure you have logged out (or more simply, rebooted) since.
> If neither of those is turning up anything, then it sounds like nothing is recognizing your USB serial device. You can look for differences in the output of lsusb when it is and isn't connected, or you can check for error messages shortly after connection with demsg. At this point it could be anything - bad board, bad cable, damaged connector, missing kernel modules, or bad/atypical rules for udev or similar.

and there was no difference between the output of `lsusb` with or without the arduino in it (arduino Mega 2560, and my pc is debian 8.6). I tried it with a diffrent cable but that made no difference. I tried it with an other arduino (uno) and then I did saw differnce in `lsusb` and I could select a port. My mega had the 'on' led on. So even though lights are on and/or binking, it might be that your arduino is broken. If you can, try it with an other arduino. Otherwise you can try an other cable and usb port on your pc.
> 1 votes

---
Tags: serial, arduino-ide, ubuntu
---


title: Two signal with delay

text:
# Question
Title: Two signal with delay
I have a two pins for two blinks leds but I need delay the second signal from first. I start the first signal and I need start the second signal 50ms later. The first signal is 500ms HIGH and 500ms LOW, and the second signal is 400ms LOW and 600ms HIGH. If I start the second signal 50ms later, I can center the high period of the first signal with the low period of the second signal.

This is my code:

```
long DelaySecondSignal = 50;
int A = 1;

while (A == 1)
{
    long millis_actuales = millis();

        //Control Salida_A
        if (millis_actuales - TiempoTranscurrido_SalidaA > (Estado_SalidaA ? 500 : 400)) {
            digitalWrite(SalidaA, Estado_SalidaA = !Estado_SalidaA);
            TiempoTranscurrido_SalidaA = millis_actuales;
        }

        if (millis_actuales > DelaySecondSignal)
        {
            //Control Salida_B
            if (millis_actuales - TiempoTranscurrido_SalidaB > (Estado_SalidaB ? 500 : 600)) {
                digitalWrite(SalidaB, Estado_SalidaB = !Estado_SalidaB);
                TiempoTranscurrido_SalidaB = millis_actuales;
            }
        }
}

```

TiempoTranscurrido\_?? is a int and Estado\_Salida? is a boolean.

I need start the second signal with 50ms of delay but "if (millis\_actuales \> DelaySecondSignal)" no work.

Thanks.

# Answer
Your problem is that you are treating both signal separately. Instead you need to think about the *events* of turning LEDs on and off and where they lie on a *combined* timeline:

```
     0    100   200   300   400   500   600   700   800   900  1000
     |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
     ^  ^                       ^  ^
  1 on  2 off                2 on  1 off
  1: ooooooooooooooooooooooooooooooo
  2: oooo                       oooooooooooooooooooooooooooooooooo

```

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.

You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:

```
void loop() {
    digitalWrite(led1, HIGH);
    delay(50);
    digitalWrite(led2, LOW);
    delay(400);
    digitalWrite(led2, HIGH);
    delay(50);
    digitalWrite(led1, LOW);
    delay(500);
}

```

All the `delay()` calls add up to 1000ms and it keeps looping around.

If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline. So you:

Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

* 0: When 50ms have passed turn off LED 2 and move to state 1.
* 1: When 400ms have passed turn on LED 2 and move to state 2.
* 2: When 50ms have passed turn off LED 1 and move to state 3.
* 3: When 500ms have passed turn on LED 1 and move to state 0.
> 1 votes

# Answer
I'd just base everything of `millis`.

```
int A = 1;

while (A == 1)
{
    int phase = millis() % 1000;// modulo 1 second

    // turn on A for the first 500ms of a period, and off for the rest
    if( phase<500 )
        digitalWrite(SalidaA, HIGH);
    else
        digitalWrite(SalidaA, LOW);

    // turn on B for the first 50ms, and last 550ms of a period, and off for the rest
    if( phase<50 || phase>=450 )
        digitalWrite(SalidaB, HIGH);
    else
        digitalWrite(SalidaB, LOW);

}

```
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: How many Ultrasonic sensors can be connected to an Arduino Uno R3?
How many Ultrasonic sensors (HC SR04 ) can be connected to an Arduino Uno R3 board?

# Answer
> 1 votes
If you look into any example sketch, like this from sparkfun:

```
/**
 * HC-SR04 Demo
 * Demonstration of the HC-SR04 Ultrasonic Sensor
 * Date: August 3, 2016
 *
 * Description:
 *  Connect the ultrasonic sensor to the Arduino as per the
 *  hardware connections below. Run the sketch and open a serial
 *  monitor. The distance read from the sensor will be displayed
 *  in centimeters and inches.
 *
 * Hardware Connections:
 *  Arduino | HC-SR04
 *  -------------------
 *    5V    |   VCC
 *    7     |   Trig
 *    8     |   Echo
 *    GND   |   GND
 *
 * License:
 *  Public Domain
 */

// Pins
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;

// Anything over 400 cm (23200 us pulse) is "out of range"
const unsigned int MAX_DIST = 23200;

void setup() {

  // The Trigger pin will tell the sensor to range find
  pinMode(TRIG_PIN, OUTPUT);
  digitalWrite(TRIG_PIN, LOW);

  // We'll use the serial monitor to view the sensor output
  Serial.begin(9600);
}

void loop() {

  unsigned long t1;
  unsigned long t2;
  unsigned long pulse_width;
  float cm;
  float inches;

  // Hold the trigger pin high for at least 10 us
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Wait for pulse on echo pin
  while ( digitalRead(ECHO_PIN) == 0 );

  // Measure how long the echo pin was held high (pulse width)
  // Note: the micros() counter will overflow after ~70 min
  t1 = micros();
  while ( digitalRead(ECHO_PIN) == 1);
  t2 = micros();
  pulse_width = t2 - t1;

  // Calculate distance in centimeters and inches. The constants
  // are found in the datasheet, and calculated from the assumed speed
  //of sound in air at sea level (~340 m/s).
  cm = pulse_width / 58.0;
  inches = pulse_width / 148.0;

  // Print out results
  if ( pulse_width > MAX_DIST ) {
    Serial.println("Out of range");
  } else {
    Serial.print(cm);
    Serial.print(" cm \t");
    Serial.print(inches);
    Serial.println(" in");
  }

  // Wait at least 60ms before next measurement
  delay(60);
}

```

You can see it is used only two pins. So, as long as you **can provide power** to sensors and pins to it, you can have as much as you like. You can even expand with more IO pins using other electronics or go into some kind of multiplexing.

---
Tags: arduino-uno
---


title: What is micro C in a circuit diagram?

text:
# Question
Title: What is micro C in a circuit diagram?
This is probably a simple question but I am a beginner with these things. What does the micro C part of the circuit diagram mean? The diagram is from the datasheet of the tssp77038 IR receiver. Does it want there to be a capacitor on the output? (http://www.farnell.com/datasheets/1915248.pdf?\_ga=1.234529246.1943069395.1480959857)

# Answer
It means "Micro Controller" - you know it as "Arduino".
> 7 votes

---
Tags: sensors, ir, resistor
---


# Question
Title: Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266
I'm currently working on a Home Automation project where I have a Raspberry Pi on Windows IoT which communicates with multiple arduinos running on FreeRTOS (I need multi-tasking). At the moment the communication is through the serial port using Xbees, the Pi sends a command, and the arduino send's back a string in JSON format.

For cost optimisation reasons, I want to try to switch the Xbees with ESP8266 modules. Is it possible to get the same kind of serial communication over WIFI?Thanks.

# Answer
> Is it possible to get the same kind of serial communication over WIFI?

Not precisely, no - but TCP sockets are a similar concept.

You would be best programming the ESP8266 directly to implement a simple TCP to UART bridge firmware instead of fighting with the crummy AT firmware that comes with them.
> 1 votes

# Answer
Its possible to do something similar, but you could reduce the cost even more and drop the Arduinos if you can get FreeRTOS to work on ESP-8266.

These links gives you a brief guide to using the ESP8266 shield for serial over WIFI and how to program the ESP8266 directly.

https://learn.sparkfun.com/tutorials/esp8266-wifi-shield-hookup-guide https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide

Of course you could also look at an ESP32s which is a dual core microprocessor with loads of networking stuff baked into the chip, its about £7/$8 at the moment.
> 1 votes

# Answer
Carlos, have a look at the ESP-Link project that will, I believe, provide the system you require. As said you may be able to drop the Arduino's using ESP12's. You may also like to consider MQTT to communicate from the Pi to the ESP's
> 0 votes

---
Tags: esp8266, raspberrypi, windows
---


# Question
Title: Using Arduino project migrated to breadboard with 12 MHz crystal instead of 16 MHz
I am moving my Arduino Uno project from Uno to Bread and as we know, this requires two 22 pf capacitors and 16 MHz on the breadboard (and the other things too like the power-but my question is about the crystal frequency so I'll focus on that).

If I replace the 16 MHz crystal with a 12 MHz crystal then the project will work as expected on a breadboard-is that correct?

It seems that the fuse setting to use 16 MHz crystal is the same as for the 12 MHz crystal for Arduino Uno-so I guess a change to the fuse setting or bootloader is not required. Am I missing anything?

I guess it's as simple as replacing a 16 MHz crystal by a 12 MHz crystal.

# Answer
> 2 votes
Some of the code running on the microcontroller needs to know the clock speed it's running at for correct timing. For this reason the macro `F_CPU` is set with this value. In the Arduino IDE this value is commonly defined in the boards.txt `build.f_cpu` property. If you're using a bootloader(which is used for uploading sketches over serial) it also needs to know the clock speed so that it can get the baud rate of the upload correct. The bootloader is not compiled in the Arduino IDE so it is not affected by your setting in boards.txt. You can recompile the bootloader with the correct clock speed setting and then install the compiled file on your microcontroller using an ISP.

There is a much more simple solution. All the hard work has already been done for you in MiniCore: https://github.com/MCUdude/MiniCore

You only need to:

1. Install MiniCore following the instructions at https://github.com/MCUdude/MiniCore
2. Tools \> Board \> ATmega328
3. Tools \> Variant \> 328P / 328PA
4. Tools \> Clock \> 12 MHz external
5. Tools \> Burn Bootloader

# Answer
> 0 votes
Yes it will work correctly IF you change the compile setting so that everything is in sync. This is because when you select an Arduino UNO from the IDE, it will process that as if your Arduino has 16Mhz. Here is a link for more information..

---
Tags: arduino-uno
---


# Question
Title: GSM module connected with arduino uno giving garbage values in response
I connected a GSM module with the Arduino UNO. The connections are as follows:

> Gnd of gsm -----\> Gnd of arduino
>
> TX of gsm -----\> pin 9 of arduino
>
> Rx of gsm -----\> pin 10 of arduino

GSM is powered from a 9V-1Amp wall adapter.

The GSM is performing according to all the `AT` commands (like making a voice call, hanging a call, answering a call) which are given, but it is displaying garbage values on serial monitor in response.

Here is the code:

```
#include <SoftwareSerial.h>
SoftwareSerial myserial(9, 10);

void setup() {
    Serial.begin(115200);
    myserial.begin(9600);
    myserial.println("ATDXXXXXXXXXX;");
    delay(30000);
    myserial.println("ATH");
}

void loop() {
    if (myserial.available()>0){
        Serial.println(myserial.read());
    }
}

```

What could be reasons for the GSM to output garbage values and how can I resolve it?

# Answer
> 1 votes
```
    Serial.println(myserial.read());

```

`myserial.read()` returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there is no character to read.

You then print that integer, each one on its own line.

So the response "OK\r\n" from, say, "AT\r\n" would look like:

```
79
75
13
10

```

Instead you need to `write` the data, not `print` it:

```
Serial.write(myserial.read());

```

Also, the way you have written your code, you will get no response for 30 seconds - that is, until everything has already happened. Only after it has all finished will you get some feedback - and that may not be complete since you may overrun the buffer depending on what the modem sends.

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


title: Random numbers recived by wifi shield

text:
# Question
Title: Random numbers recived by wifi shield
So I am sending a web request to a server, but for some reason the result is the number: `728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311`

Any ideas?

```
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Lcd(0x27, 16, 6);

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "AESRO2-2.4G";
char password[] = "EA8TDKNFGE";

int status = WL_IDLE_STATUS;

WiFiClient client;

String serverReturn;

String page[]
{
  "Flashlight",
  "Message",
  "S.O.S"
};
void displayPage(int pageNumber)
{
  Lcd.clear();
  Lcd.print(page[pageNumber]);

  Lcd.setCursor(0,1);
  Lcd.print("[Open]");
  Lcd.setCursor(10, 1);
  Lcd.print("[Next]");
}
int currentPage = 0;
int lastPage = 1;

void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8,OUTPUT);

  Lcd.begin();

  Lcd.print("BrickOS V5.0.0");
  digitalWrite(6, HIGH);
  delay(300);
  digitalWrite(6, LOW);

  delay(1000);

  if(WiFi.status() == WL_NO_SHIELD)
  {
    Lcd.clear();
    Lcd.print("No wifi shield");

    while(true);
  }

  String fv = WiFi.firmwareVersion();
  if(fv != "1.1.0")
  {
    String secline = fv += "->1.1.0";
    Lcd.clear();
    Lcd.print("Firmware update");
    Lcd.setCursor(0,1);
    Lcd.print(secline);

    while(true);
  }

  while(status != WL_CONNECTED)
  {
    Lcd.clear();
    Lcd.print("Connecting to");
    Lcd.setCursor(0, 1);
    Lcd.print("network...");

    status = WiFi.begin(ssid, password);

    delay(3000);
  }

  Lcd.clear();
  Lcd.print("Connected to:");
  Lcd.setCursor(0, 1);
  Lcd.print(ssid);
  delay(1000);
}

void loop()
{
  if(lastPage != currentPage)
  {
    if(currentPage > sizeof(page))
    {
      currentPage = 0;
    }
    displayPage(currentPage);
  }
  lastPage = currentPage;

  serverReturn = "";
  while(client.available()) {
    serverReturn += client.read();
  }
  client.stop();
  if(client.connect("www.nightfall.huskyclick.info", 80))
  {
    client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
    client.println("Host: nightfall.huskyclick.info");
    client.println();
  }
  else
  {
    Lcd.clear();
    Lcd.print("Failed to check");
    Lcd.setCursor(0, 1);
    Lcd.print("for messages");
  }

  Serial.println(serverReturn);

  if(serverReturn != "false" && serverReturn != "")
  {
    digitalWrite(8, HIGH);

    Lcd.clear();
    Lcd.print("Message received!");

    digitalWrite(6, HIGH);
    delay(500);
    digitalWrite(6, LOW);

    delay(1000);

    Lcd.clear();
    Lcd.print(serverReturn);

    delay(5000);
  }

  delay(5000);
}

```

# Answer
> 1 votes
The fault lies here:

```
while(client.available()) {
  serverReturn += client.read();
}

```

`client.read()` returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.

You then append that integer to the end of a `String` which gets converted to the ASCII representation of that integer before being appended.

So the string `HTTP`, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".

Instead you need to cast the integer to a char before appending:

```
serverReturn += (char)client.read();

```

Or better still don't use any `String` variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.

---
Tags: arduino-uno, wifi, http
---


# Question
Title: Why does this code not respond promptly to changes in the LDR reading?
So, I wrote some simple code like this :

```
void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  Serial.begin (9600);
}

void loop() {
  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);
  delay(50);
}

```

The line will print the value of LDR sensor simultaneously, but when I add this "if" condition inside the loop :

```
 if (LDRValue < 100) {
   colorWipe(strip.Color(255, 0, 0), 50);
   colorWipe(strip.Color(0, 255, 0), 50);
   colorWipe(strip.Color(0, 0, 255), 50);
   colorWipe(strip.Color(0, 0, 0, 255), 50);
   theaterChase(strip.Color(127, 127, 127), 50);
   theaterChase(strip.Color(127, 0, 0), 50);
   theaterChase(strip.Color(0, 0, 127), 50);
   rainbow(20);
   rainbowCycle(20);
   theaterChaseRainbow(50);
  }

```

the LDR value only printed once..

Is it a wrong "if" condition code ? I know it's kinda lame, but please give me some starting point, doesn't need to be fancy just a small lead will do, thanks!

***edit :*** complete library

# Answer
> 1 votes
I'm going to lever off gre\_gor's comment on the question.

The code you are calling (for example, `rainbow`) has delays in it:

```
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

```

So we can see straight away that calling `rainbow(20);` is going to take at least 20 x 256 ms (256 iterations of the loop with a 20 ms delay) plus more because of whatever else it does. That is over 5 seconds already!

Then you call `rainbowCycle(20);` and then `theaterChaseRainbow(50);` so you won't get back to the main loop for a while.

How to fix? Well, it isn't just a case of adding a line or two. One solution is to rewrite without delays, but instead have a state machine.

An alternative would be to test the sensor in each loop. Let's guess your objective is to stop the display if the LDR gives a higher reading. You could copy/paste the functions in question, but test the LDR inside them, eg.

```
void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {

    int LDRValue = analogRead(LDRSensor);   // <--- add these 3 lines
    if (LDRValue >= 100)
       return;

    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

```

---

## Suggested improvement to example

The code below uses a technique of supplying a "callback function" to the functions that do the pixel displays. I modified the Adafruit example to show the idea:

```
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

typedef bool (*AbortFunction) ();

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// function prototypes
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void rainbow(uint8_t wait, AbortFunction fAbort = NULL);
void rainbowCycle(uint8_t wait, AbortFunction fAbort = NULL);
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort = NULL);
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort = NULL);

const byte LDRSensor = 0;

bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

void loop() {
  // start with black
  colorWipe(strip.Color(0, 0, 0), 0); // Black

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50, checkLDR); // Red
  colorWipe(strip.Color(0, 255, 0), 50, checkLDR); // Green
  colorWipe(strip.Color(0, 0, 255), 50, checkLDR); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50, checkLDR); // White
  theaterChase(strip.Color(127, 0, 0), 50, checkLDR); // Red
  theaterChase(strip.Color(0, 0, 127), 50, checkLDR); // Blue

  rainbow(20, checkLDR);
  rainbowCycle(20, checkLDR);
  theaterChaseRainbow(50, checkLDR);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    if (fAbort && fAbort ())
      return;
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      if (fAbort && fAbort ())
        return;
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait, AbortFunction fAbort) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    if (fAbort && fAbort ())
      return;
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.AbortFunction fAbort
void theaterChase(uint32_t c, uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait, AbortFunction fAbort) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      if (fAbort && fAbort ())
        return;
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

```

The important addition is to add another optional argument `AbortFunction fAbort` to each function call. The default is NULL, in which case the function behaves the same as before. However, if supplied, the function is called. If it returns `true` then the display function exits (thus avoiding the delays), like this:

```
if (fAbort && fAbort ())
  return;

```

The first test is "does the function exist?" and if so, the second test calls the function and checks to see if it returns true or false.

The modified example shows the scrolling patterns on the NeoPixels, provided A0 returns 100 or less. The function that does this is here:

```
bool checkLDR ()
  {
  int LDRValue = analogRead(LDRSensor);
  return LDRValue > 100;
  }

```

That function is passed as an argument to the other functions, eg.

```
rainbow(20, checkLDR);

```

I have a page about writing callback functions.

---
Tags: c++, neopixel
---


# Question
Title: Is there any way to control current precisely with Arduino without using a DC-DC converter?
I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?

# Answer
The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.

You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).

If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.
> 1 votes

---
Tags: arduino-uno, current
---


title: Arduino GSM Shields stacking

text:
# Question
Title: Arduino GSM Shields stacking
I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

# Answer
Yes, that is easy. You need multiplexer (MUX) to forward communication pins (2 & 3) to the right GSM shield. Google for it to find the one that suits your budget.
> 1 votes

# Answer
Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The product page says each shield may require up to 1000mA.

Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.
> 1 votes

# Answer
Stacking might be hard, since they communicate on pins 2&3. But if you work around that somehow, you could use Software Serial to access multiple GSM devices.

I think the GSM library has hardcoded the pins, and it might not share well with multiple, but you might be able to use SoftwareSerial or AltSoftSerial to do multiple connections, but that would be less straightforward.
> 0 votes

---
Tags: shields, gsm
---


# Question
Title: Feather32u4 device not accepting address 5, error -71
I'm using a Feather 32u4 bluetooth device connected

to a AM2302 temperature sensor via I/O pin to my Linux PC via USB

Everything was working fine, uploading the code to the micro via Artuino IDE and reading the temperature on the Rapsberry PI connected via bluetooth to the Feather 32u4, until I decided to use the Raspberry PI3 to provide power feeding to the Feather (via USB). After that attempt, I tried again to connect the Feather 32u4 to the Linux PC, but I've neve been able to do that. Everywhen I connect the Feather to the USB port of the PC it is not shown in the available serial ports of Arduino IDE and the dmesg is

```
[  358.028022] usb 8-2: new full-speed USB device number 6 using uhci_hcd
[  358.148026] usb 8-2: device descriptor read/64, error -71
[  358.372024] usb 8-2: device descriptor read/64, error -71
[  358.588029] usb 8-2: new full-speed USB device number 7 using uhci_hcd
[  358.708024] usb 8-2: device descriptor read/64, error -71
[  358.932024] usb 8-2: device descriptor read/64, error -71
[  359.148028] usb 8-2: new full-speed USB device number 8 using uhci_hcd
[  359.556026] usb 8-2: device not accepting address 8, error -71
[  359.668028] usb 8-2: new full-speed USB device number 9 using uhci_hcd
[  360.076038] usb 8-2: device not accepting address 9, error -71
[  360.076056] usb usb8-port2: unable to enumerate USB device

```

Is it possible that using the Rapsbery PI3 providing power feeding to the Feather destroyed its USB port? Why?

When I reset the Feather (using the reset button) the following is the dmesg

```
[53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
[53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
[53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[53215.993049] usb 3-1: Product: Adafruit Feather
[53215.993051] usb 3-1: Manufacturer: Adafruit In
[53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
[53216.074154] usbcore: registered new interface driver cdc_acm
[53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
[53225.664064] usb 3-1: USB disconnect, device number 10
[53225.904030] usb 3-1: new full-speed USB device number 11 using uhci_hcd
[53226.024024] usb 3-1: device descriptor read/64, error -71
[53226.248024] usb 3-1: device descriptor read/64, error -71
[53226.464024] usb 3-1: new full-speed USB device number 12 using uhci_hcd
[53226.584023] usb 3-1: device descriptor read/64, error -71
[53226.808022] usb 3-1: device descriptor read/64, error -71
[53227.024030] usb 3-1: new full-speed USB device number 13 using uhci_hcd
[53227.432025] usb 3-1: device not accepting address 13, error -71
[53227.544024] usb 3-1: new full-speed USB device number 14 using uhci_hcd
[53227.952021] usb 3-1: device not accepting address 14, error -71
[53227.952040] usb usb3-port1: unable to enumerate USB device

```

---

## NEW EDIT

I tried the suggestion from @Majenko and the result is the following

```
Sketch uses 19,712 bytes (68%) of program storage space. Maximum is 28,672 bytes.
Global variables use 730 bytes of dynamic memory.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
PORTS {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } / {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } => {}

<... a long list of similar PORTS rows>

Uploading using selected port: /dev/ttyACM0
/home/storassa/work/Arduino/hardware/tools/avr/bin/avrdude -C/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/build133016433f76cdf39b8ff61da42c5037.tmp/Antoz.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/storassa/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
avrdude: ser_send(): write error: Bad file descriptor
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

I also tried with a

```
chmod 777 ttyACM0

```

with the same result

---

## LAST EDIT

I tried again multiple times and eventually I was able to upload the sketch. Everything works fine now

# Answer
The sketch on your Feather has no CDC/ACM interface - either because it was disabled in your code, or because the sketch has become corrupted somehow.

You need to re-flash the feather with a new sketch - but that's not going to be easy with no CDC/ACM device to access to start programming - except that you do for a short time.

You need to press reset and then upload in the few seconds you get while the CDC/ACM device is available:

```
\/\/\/ Reset pressed and bootloader entered \/\/\/
[53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
[53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
[53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[53215.993049] usb 3-1: Product: Adafruit Feather
[53215.993051] usb 3-1: Manufacturer: Adafruit In
[53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
[53216.074154] usbcore: registered new interface driver cdc_acm
[53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
*** UPLOAD RIGHT NOW!!! ***
*** You get about 9 seconds, because... ***
\/\/\/ Bootloader times out and your corrupt sketch runs \/\/\/
[53225.664064] usb 3-1: USB disconnect, device number 10

```
> 1 votes

---
Tags: arduino-ide, usb
---


title: Environment Variable to change build

text:
# Question
Title: Environment Variable to change build
Is there a way to get the build to see an environment variable so that all the files can be built differently with one Environment variable change. Such as

```
#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

```

# Answer
Not environment, no.

If you have access to the compilation command line you can do the equivalent of `#define` from there:

```
avr-gcc ... blah blah ... -DUseFirstDir

```

That is most effective if you are using a *Makefile* build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).

A better IDE, though, can do it. Facilities for setting control flags like that exist within UECIDE and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).

Or you can just have a list of `#define` options at the top of your sketch:

```
/* Uncomment this to use the first directory. */
// #define UseFirstDir

// .... later ....

#ifdef UseFirstDir
    #include <C:\MyFirstDir\ImportantIncludes.h>
#else
    #include <C:\MySecondDir\ImportantIncludes.h>
#endif

```
> 0 votes

---
Tags: build
---


# Question
Title: How to add extra USB port to Arduino Nano?
I'm trying to use V-USB library to emulate a keyboard using Arduino Nano but because of precaution, I don't want to use it's built-in USB port.

My idea is to add another USB port so I cant power my device with the new USB port and use free digital pins as input/output of the new USB serial port in V-USB project.

What circuit I should use and how to add extra USB port to Arduino Nano.

# Answer
> 4 votes
USB is deceptively simple. The underlying protocol is very complex. So a complete answer to your question requires some USB background.

USB is divided into 2 types. USB Hosts and USB Devices. We are not concerned about USB Hosts here. USB Devices only need to know about their own functions / features. If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the serial CDC USB protocol. If the USB Device was a keyboard, it only needs to know the basic USB protocol and the HID USB protocol.

In order to offer up a USB port the Arduino Nano uses an FTDI chip FT232RL. This chip supports a Serial Port USB Device. It does not appear to support HID USB Devices. So your decision to use V-USB is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

> What circuit I should use and how to add extra USB port to Arduino Nano.

The circuit suggested is on the V-USB web page appears to contain the necessary information:

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.

# Answer
> 1 votes
You can use a USB host mini module for the Arduino NANO and the USB Host Library r2.0

You can implement a keyboard with this...

---
Tags: arduino-nano, usb, keyboard
---


# Question
Title: Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64
I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens. My laptop: Toshiba Satellite C50-A630 The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

# Answer
I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.
> 1 votes

---
Tags: arduino-ide, ide, windows
---


title: SPI conflict with two shields - IOREF?

text:
# Question
Title: SPI conflict with two shields - IOREF?
**Update:**

I've refactored the code to be very resilient to boards missing or not being able to talk to them. Then I tinkered with a bunch of pins and learned that it all comes down to the IOREF pin being connected to the USB Host shield or not. If it's connected, the USB shield "takes over", allows communication with it, but the CAN shield does not work. If the USB shield IOREF pin is not connected, but the rest of the shield's pins are, CAN works. If I disable the IOREF pin going into the CAN shield (and thus the USB shield also since it's on top), the CAN shield works fine still, but the USB shield does not.

Something happens when the IOREF is powered into the USB board and if it's not powered, you can't talk to it.

**Original post:**

I have the following setup:

1. Yourduino RoboRED board
2. Seeed CAN Bus Shield v1.2 http://wiki.seeed.cc/CAN-BUS\_Shield\_V1.2/
3. USB Host Shield https://www.arduino.cc/en/Main/ArduinoUSBHostShield

My issue is that if I connect only the CAN bus shield, I can initialize it without any problem, but when I connect the USB host shield on top of the CAN, the CAN shield becomes unresponsive.

I looked into the wiring and per the specs, the following is how the hardware is set up:

* SPI bus runs on ICSP header for both shield, not on D11, D12 & D13. I could switch it for the CAN bus shield if I wanted/needed to, but I don't believe I shoudl be.
* The trigger pin for the USB host is D10
* The trigger pin for the CAN bus is D9 (since it's v1.2 of the board)
* Both boards have power. USB board is on top since it does not have an ICSP male connector on the top side, only female on bottom.

I started to debug the code and traced down to this CAN bus function in mcp\_can.cpp, which I've instrumented with debug:

```
INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
{
    Serial.print("mcp2515_setCANCTRL_Mode with newmode = ");
    Serial.println(newmode);
    INT8U i;

    mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);

    i = mcp2515_readRegister(MCP_CANCTRL);
    i &= MODE_MASK;
    Serial.println("i & MODE_MASK");
    Serial.println(i);
    Serial.println(MODE_MASK);

    if ( i == newmode )
    {
        return MCP2515_OK;
    }

    return MCP2515_FAIL;
}

```

The output when it fails is:

```
USB started ok
past SPI begin
mcp2515_init called
mcp2515_setCANCTRL_Mode with newmode = 128
i & MODE_MASK
0
224
Enter setting mode fall
res = 1

```

For reference, this is the mcp2515\_modifyRegister function:

```
void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
{
    #ifdef SPI_HAS_TRANSACTION
        SPI_BEGIN();
    #endif
    MCP2515_SELECT();
    spi_readwrite(MCP_BITMOD);
    spi_readwrite(address);
    spi_readwrite(mask);
    spi_readwrite(data);
    MCP2515_UNSELECT();
    #ifdef SPI_HAS_TRANSACTION
        SPI_END();
    #endif
}

```

The whole file is here: https://github.com/Seeed-Studio/CAN\_BUS\_Shield/blob/master/mcp\_can.cpp. I've tried setting SPI\_HAS\_TRANSACTION to `true` with no change in the outcome, though I also don't know exactly what this does.

This is my init:

```
void setup (void)
{
    Serial.begin(115200);

    // init can bus : baudrate = 500k

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");
    else
        Serial.println("USB started ok");

    delay( 200 );

    while (CAN_OK != CAN.begin(CAN_500KBPS)) {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(10000);
    }

    Serial.println("CANbus ready");
}

```

It seems to have something to do with the registers available for write by the CAN bus library whenever the USB board is or isn't present. The write fails when the USB board is there. Any thoughts as to why or other things to try would be greatly appreciated.

# Answer
There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.

Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.
> 1 votes

---
Tags: arduino-uno, shields, spi, can-bus, icsp
---


# Question
Title: Where do I put the cables from my soldered l293d onto the arduino uno/arduino pro mini? (Drone)
I am trying to create a drone but I am struggeling a bit with the components and the schematic. I have 4 small drone motors from hubsan x107 and i have soldered their wires on a l293d driver like this below:

As you can see i have also soldered jumper cables on the l293d as well and I now look to put them on the arduino uno or a arduino mini pro (i have both at home) but I am not sure where to put these cables in order to make this work. I have typed them out as you can see on the picture and named them: Jumper cable 1, 2, 3, 4, 5, 6, 7 and 8.

This is the hardware I use:

Motor: http://www.banggood.com/Hubsan-H107C-X4-RC-Quadcopter-Spare-Parts-Motor-H107-a23-p-87563.html

Arduino uno

L293D

Cables

Would a setup like this work if I put the jumper cables on the correct pins on the arduino? And if so where on the arduino do i need to connect each wire?

Thanks a lot!!

# Answer
> 0 votes
simulate this circuit – Schematic created using CircuitLab

The battery needs to be the right voltage for your motors. There are no specifications on the page you linked to at all, so your job now is to find out what your motors are and what voltage they run from.

---
Tags: motor, drone
---


title: Building a GPS-controlled Camera

text:
# Question
Title: Building a GPS-controlled Camera
I've been trying to build an Arduino UNO controlled Camera using two servo motors that points in the direction of an object with a certain tag.

Here's an Example: A camera is on the sideline of a gym, and the players are running around. One player has a portable GPS piece attached to him, and the camera should point in the player's direction in order to capture the player's movements along with his background.

A few questions: Would I use two different compasses in order to both record the direction and point the camera in this direction? Or would I use a GPS for the player and somehow convert the streaming data into compass direction(in which the camera will point)?

In a way, what combination (Player-Camera) would I use (if I need a combination), a GPS-GPS, GPS-compass, or compass-compass?

Do I actually need two location devices or just one?

Thanks, Mark

# Answer
> 0 votes
Take a look at the uTube site of "iforce2d". Chris has a couple of GPS projects, which use a GPS and nRF24L01 transceivers to implement a "GPS tag" and he has a model car follow the tag. He also has a ground station with a pan and tilt and a camera following his quadcopter (drone). Lots of useful stuff there.

---
Tags: arduino-uno, bluetooth, gps, tinygps
---


# Question
Title: Hardware damage from executing tight polling loop over extended periods of time?
I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous. But I LOVE IT! (It's a mouse that I control over the web)

EDIT Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!

I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:

```
do
{

} while (digitalRead(pin#) == 0); //wait for pin to go high

```

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -\> 100kHz Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"

Thanks in advance for any interest given to this question.

# Answer
> 1 votes
There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.

You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.

Update:

> "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -\> 100kHz Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is *well* within its specs.

# Answer
> 0 votes
For many applications within the realm of Arduino software & hardware development, the only practical concern is to limit the need to write to non-volatile types of memory. Non-volatile types of memory, such as that which stores the Arduino program, do have a finite number of write cycles. However, it is in the 10s (perhaps 100s) of thousands of writes. So is not a concern to most developers.

Running code, however, does put a load on the processor's power source. First we need to understand that a switch in a modern processor require only a minuscule amount of current if left alone. But if asked to change from a 0 to a 1 or 1 to 0, the current spikes. In processors pushed to their limits with 100s of thousands of switches, this extra current turns into heat which must be mitigated less damage is done.

Fortunately, most processors used in Arduinos are not pushed to their limits. So this is rarely a concern. To be clear, the processor chip used on most Arduinos will mostly likely not need a heat sink or fan.

However, even for an Arduino not pushed to its limits, this extra power demand is devastating to the long term life of portable battery operated devices. Programming an Arduino to extend battery life is by no means a trivial task. And certain processors (Arduinos can be made with many different processors) are orders of magnitude better at this then others. But, since most Arduino applications are powered from mains, this too is of little concern.

---
Tags: timers, electronics, teensy, timing, raspberrypi
---


# Question
Title: Arduino Due: ADC gain adjustment problem
I want to increase gain of the ADC channel. To achieve this I'm using `adc_set_channel_input_gain` function from **adc.h**. Here is the entire sketch:

```
const byte aPin = A6;

void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);
  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}

void loop() {
  int analog = analogRead(aPin);
  Serial.println(analog);
  delay(500);
}

```

The problem is that output values are not depending on the gain value.

# Answer
Well, the solution was very simple. We just need to call `adc_enable_anch()` before changing gain or offset of the ADC. I improved my setup and the sketch works as expected now:

```
void setup() {
  analogReadResolution(12);

  // Configure ADC gain
  // Arduino/hardware/arduino/sam/system/libsam/include/adc.h
  adc_channel_num_t ch = (adc_channel_num_t)(g_APinDescription[aPin].ulADCChannelNumber);
  adc_enable_anch(ADC);
  adc_set_channel_input_gain(ADC, ch, ADC_GAINVALUE_3);

  Serial.begin(9600);

  // Delay for serial stabilization
  Serial.println("Begin.");
  delay(2000);
}

```
> 0 votes

---
Tags: programming, arduino-due, analogread, adc, sam3x
---


title: While doesn't the loop terminate?

text:
# Question
Title: While doesn't the loop terminate?
I have a have project of Up Down counter using Arduino with seven segments, in which when I continuously press the push button, the counter moves upward from 0 to 99. When I release the push button, the counter moves downwards from the previous value.

For example: I continuously press the button counter from 0 to 58, then when I release the button, the counter moves backward from 58 to 0.

The problem is that when I simulate the code in Proteus software, the counter starts from 99 because the button is not pressed. But when I press the button the counter moves upward not accurately.

Also the other big issue is that when the button is released, the counter does not move backwards although the counter moves upwards continuously and the button is not working (whether the button is pressed or not).

Here my code and Proteus simulator circuit image.

```
int num_array_1[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9
int num_array_2[10][7] =
  { { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }}; // 9

const int button = 35;
const int alarm = 50;

//function header
void Num_Write_1(int);
void Num_Write_2(int);

void setup() {
  // set pin modes for Display 1
  pinMode(22, OUTPUT);
  pinMode(23, OUTPUT);
  pinMode(24, OUTPUT);
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(28, OUTPUT);
  // set pin modes for Display 2
  pinMode(40, OUTPUT);
  pinMode(41, OUTPUT);
  pinMode(42, OUTPUT);
  pinMode(43, OUTPUT);
  pinMode(44, OUTPUT);
  pinMode(45, OUTPUT);
  pinMode(46, OUTPUT);
  // set pin for alarm indication
  pinMode(alarm,OUTPUT);
  // set pin for button input
  pinMode(button,INPUT);
  int i = 1;
  int j = 1;
  int counter_1 = 0; // for counter 1
  int counter_2 = 0; // for counter 2
}

void loop() {
  int counter_1; // for counter 1
  int counter_2; // for counter 2
  int button_state = digitalRead(button);
  // check the button state
  //counter loop
  if (button_state == HIGH) {
    // if button is pressed , counter moves Upward(0,1,2,3,....,99)
    boolean start = true;
    while (start) {
      // when button pressed , loop is continuously running
      if (counter_1 == 10) {
        // if counter 1 is value 10
        counter_1 = 0; // reset counter1 to 0
        counter_2 = counter_2 + 1; // counter2 is starting now
        Num_Write_1(counter_1); // display value of counter1
        Num_Write_2(counter_2); // display value of counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == LOW) {
          // if low then condition of while is false
          // button is released, button_state is low
          start = !start; // toggle the while condition true to false
          // which terminate the while loop
        }
      } else {
        counter_1 = counter_1 + 1; // incr. 1 by 1
        Num_Write_1(counter_1); // display value of counter1
        delay(200);
      }
      button_state = digitalRead(button);
      // again check the button state
      // button is released, button_state is low
      while (button_state == LOW) {
        // if low then condition of while is false
        start = !start;
      }
    }
  } else {
    //if button is release , counter moves Downward(56,55,54,...,0)
    Num_Write_1(counter_1); // show previous values on both counters
    Num_Write_2(counter_2); // b/c decr. starts from incremented values
    boolean start = true;
    while (start) {
      // when button release , loop is continuously running
      if (counter_1 == 0) {
        //if counter 1 is value 0
        counter_1 = 9; // reset counter1 to 9
        counter_2 = counter_2 - 1; // counter2 is starting now
        Num_Write_1(counter_1); // display on counter1
        Num_Write_2(counter_2); // display on counter2
        button_state = digitalRead(button); // check the button state
        if (button_state == HIGH) {
          // if high then condition of while is false
          // button is pressed, button_state is high
          start = !start; //toggle the condition
        }
      } else {
        counter_1 = counter_1 - 1; // decr. 1 by 1
        Num_Write_1(counter_1); // display on counter1
        delay(200);
      }
      button_state = digitalRead(button); // again check the button_state
      // if button pressed , button_state goes high
      if (button_state == HIGH) {
        start = !start;
        // toggle the while condition true to false
        // which terminate the while loop
      }
    }
  }
}
// this functions writes values to the sev seg pins for counter1
void Num_Write_1(int number) {
  int pin= 22;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_1[number][j]);
    pin++;
  }
}
// this functions writes values to the sev seg pins for counter2
void Num_Write_2(int number) {
  int pin= 40;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array_2[number][j]);
    pin++;
  }
}

```

If button pressed ----------\> logic goes HIGH If button release ----------\> logic goes LOW

Please resolve my problem. I have tried for 2 weeks solving this problem but still I'm stuck. Any little advice will be important for me.

# Answer
I'd throw that code away and start over from scratch; it's overly verbose and needlessly repetitious, which may account for the kinds of errors you are seeing.

A few notes:

• The contents of `num_array_1` look identical to those of `num_array_2`. Ordinarily there is no need to have two copies of the same constant array, so get rid of one or the other.

• It doesn't make sense to use four different lengthy sections of code that do about the same trivial things, incrementing or decrementing a counter, displaying its value, and then doing some kind of switch check. Instead, use one section of code that handles all the cases. See example 1 below.

• In three of those four different sections of code just referred to, in effect you say
`if (button_state == LOW) { start = !start; }` and in one of them, you say
`while (button_state == LOW) { start = !start; }`. That statement loops forever if encountered when `button_state` is `LOW`.

`int counter_1` and `int counter_2` declared in `setup()` are not the same variables as the ones of the same name declared in `loop()`. If you want them to be the same, declare them at global scope before `setup()`, and don't declare them within either of `setup()` or `loop()`.

• As declared in `loop()`, `counter_1` and `_2` are automatic local variables, uninitialized and technically of undefined value. See discussion in an answer to “local variable initialized to zero in C” on stackoverflow.

• It doesn't make sense to use two different display-a-digit functions that do about the same thing. Instead, use one function to handle both cases. See example 2 below.

• You can save 126 bytes each of RAM and Flash by storing the ones and zeroes of `num_array_1` or `_2` packed into bytes. See example 3 below.

---

*Example 1:* First, declare `int dir`, which will be 1 when counting up, and -1 when counting down. To change direction, say `dir = -dir;`. To step the count, say:

```
count += dir;
if (dir<0)  dir = 0;
if (dir>99) dir = 99;
showDigit(count/10, 40); // Hi digit ports are 40...46
showDigit(count%10, 22); // Lo digit ports are 22...28

```

After stepping the counter and showing its digits, you can do your check some kind of switch thing, once in one place instead of spread out in four different places. Note, you could (and should) create symbolic constants that stand for 40 and 22, via an `enum` like the following, and then use the symbols instead of hardcoded numbers in the `showDigit()` calls.

```
enum { hiDigitAt=40, loDigitAt=22};
...
showDigit(count/10, hiDigitAt);
showDigit(count%10, loDigitAt);

```

---

*Example 2:* Your `Num_Write_1()` and `_2` functions are identical except that one says `int pin= 22;` and the other `int pin= 40;`. To combine them, you can add a parameter specifying the starting pin number:

```
void showDigit(byte value, byte basePin) {
  for (byte j=0; j < 7; ++j) {
    digitalWrite(basePin+j, num_array_1[value][j]);
}

```

---

*Example 3:* Instead of using 14 bytes of RAM and 14 bytes of Flash for each entry in your digit-segments-pattern arrays, you can pack the seven ones and zeroes that represent one digit into a single byte. For example, `{ 0,1,1,0,0,0,0 }, // 1` converts to `0b0110000, // 1`. Then use shifts to unpack the bits, as below.

```
byte digitPats[10] =
     { 0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
       0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1110011
     };
...
void showDigit(byte value, byte basePin) {
  byte pattern = digitPats[value], bitj;
  for (byte j=0; j < 7; ++j) {
    bitj = (pattern & 64)>>6;
    digitalWrite(basePin+j, bitj);
    pattern *= 2;  // Shift the pattern one bit left
}

```
> 2 votes

# Answer
Your counter variables only have scope within the methods they are declared in. So initializing them in the setup() method will have no effect in other methods.

Instead, declare these variables as global or at least with "file" scope as you did with your array variables.
> 1 votes

---
Tags: arduino-mega, programming, arduino-ide, coding-standards
---


title: Why doesn't this code work?

text:
# Question
Title: Why doesn't this code work?
I'm having trouble programming an Arduino Uno with this sketch, the sketch compiles and I get full serial output and an IP address, but no web browser can connect to it.

I've tried this Arduino example (https://www.arduino.cc/en/Tutorial/WebServer) and it works right out of the box, I don't understand why my code therefore doesn't work.

My code is below:

```
#include <SPI.h>
#include <Ethernet.h>

// Bootup millisecond counter
const unsigned long started     = millis();

// Serial settings
const int SERIAL_BAUDRATE       = 9600;

// Non-DHCP ethernet settings:
// Device MAC address: DE:AD:BE:EF:FE:ED
const byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(
  192, 168, 1, 177
);

// Pins
const int P_RELAY               = 7;
const int P_ON_LED              = 8;
const int P_OFF_LED             = 9;
const int P_SW_MAN              = 10;

// Relay power states
const char B_RELAY_ON           = HIGH;
const char B_RELAY_OFF          = LOW;

// Relay switching state
boolean RELAY_STATE             = false;

// Network/web data
EthernetServer server(80);
String readString;
String localIp;

// Testing switches
const boolean connectToEthernet = true;
const boolean hostWebServer     = true;
const boolean useDHCP           = false;
const boolean testRelay         = false;

// Testing settings
const int testRelayDelay        = 500;

// Formats an IPAddress nicely as a string for printing
String displayAddress(IPAddress address) {
  return String(address[0]) + "." +
         String(address[1]) + "." +
         String(address[2]) + "." +
         String(address[3]);
}

void setup() {
  const unsigned long started = millis();
  delay(50); // allow some time (50 ms) after powerup and sketch start, for the Wiznet W5100 Reset IC to release and come out of reset.
  Serial.begin(SERIAL_BAUDRATE);
  Serial.println("HTTP Web Remote Power-Point Controller.");
  Serial.println();
  if (connectToEthernet) {
    Serial.println("Connecting to Ethernet...");
    if (useDHCP) {
      Ethernet.begin(mac);
      Serial.println("Obtaining IP address...");
      localIp = displayAddress(Ethernet.localIP());
    } else {
      Ethernet.begin(mac, ip);
      localIp = displayAddress(ip);
    }
    if (localIp != "0.0.0.0") {
      Serial.println("Connected. IP: " + localIp);
      if (hostWebServer) {
        Serial.println("Starting Ethernet server...");
        server.begin();
        Serial.println("Started.");
      }
    } else {
      Serial.println("Error: No address provided via DHCP.");
      Serial.println("Please check your network connection and settings, and try again.");
      while (1);
    }
  }
  Serial.println("Configuring pins...");
  pinMode(P_RELAY, OUTPUT);
  pinMode(P_ON_LED, OUTPUT);
  pinMode(P_OFF_LED, OUTPUT);
  pinMode(P_SW_MAN, INPUT_PULLUP);
  Serial.println("Pins configured.");
  Serial.println("Pin Information: \n            Relay: " + String(P_RELAY) +
                                  "\n           On LED: " + String(P_ON_LED) +
                                  "\n          Off LED: " + String(P_OFF_LED) +
                                  "\n    Manual Switch: " + String(P_SW_MAN));
  if (hostWebServer && connectToEthernet) {
    Serial.println("Remote controller interface is running at http://" + localIp + "/");
  }
  if (testRelay) {
    Serial.println("Testing relay mode enabled.");
    Serial.println("Toggling relay every " + String(testRelayDelay) + " milliseconds...");
  }
  const unsigned long starttime = (millis() - started);
  Serial.println("Startup took " + String(starttime) + " milliseconds.");
}

void loop() {
  if (testRelay) {
    delay(testRelayDelay);
    if (RELAY_STATE) {
      toggleRelay(false);
    } else {
      toggleRelay(true);
    }
  }
  if (useDHCP) {
    byte dhcpRenew = Ethernet.maintain();
    if (dhcpRenew == 1) {
      Serial.println("Dynamic DHCP lease renewal failed.");
    } else if (dhcpRenew == 2) {
      Serial.println("Dynamic DHCP lease was renewed.");
    } else if (dhcpRenew == 3) {
      Serial.println("Dynamic DHCP lease rebind failed.");
    } else if (dhcpRenew == 4) {
      Serial.println("Dynamic DHCP lease was rebound.");
    }
  }
  EthernetClient client = server.available();
  if (client) {
    Serial.println("Client connected to web server.");
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }

        if (String(c) == "\n") {
          Serial.println("Data received from HTTP client: " + String(readString));

          // HTTP header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();

          // HTTP body
          if (readString.indexOf("?state") > 0) {
            if (RELAY_STATE) {
              client.print("1");
            } else {
              client.print("0");
            }
          } else {
            client.println("<!DOCTYPE HTML>");
            client.println("<html lang=\"en\">");
            client.println("<head>");
            client.println("<title>Power-Point Controller</title>");
            client.println("</head>");
            client.println("<body>");
            client.println("<h1>hello world</h1>");
            client.println("</body>");
            client.println("</html>");
          }

          delay(10);

          client.stop();
          Serial.println("Client disconnected from web server.");

          if (readString.indexOf("?relay=1") > 0) {
            toggleRelay(true);
          } else if (readString.indexOf("?relay=0") > 0) {
            toggleRelay(false);
          }

          readString = "";
        }
      }
    }
  }
}

void toggleRelay(bool state) {
  if (state == true) {
    digitalWrite(P_OFF_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_ON);
    digitalWrite(P_ON_LED, HIGH);
    RELAY_STATE = true;
    Serial.println("Relay State: ON");
  } else if (state == false) {
    digitalWrite(P_ON_LED, LOW);
    digitalWrite(P_RELAY, B_RELAY_OFF);
    digitalWrite(P_OFF_LED, HIGH);
    RELAY_STATE = false;
    Serial.println("Relay State: OFF");
  }
}

```

# Answer
> I don't understand why my code therefore doesn't work.

Without any in-depth analysis of your code I would suspect that you have simply run out of memory. It is easy to forget that the Arduino Uno is a very small machine with limited resources.

Here are some steps forward:

1. Check memory status (compile and run-time).
2. Use the F() macro to force string literals to be stored in program memory.
3. Reduce String class operators especially on print statements. Simply replace with multiple print statements.

Cheers!
> 2 votes

---
Tags: arduino-uno, web-server
---


title: Long Distance Shift Register

text:
# Question
Title: Long Distance Shift Register
I am using a Mega to control some relay boards. I have a 16 relay board near the mega, and I want to put an 8 relay board about 40 ft. away. So I figured I could use a shift register - instead of running 9 wires (8 relays and gnd) I could just run 4 (gnd, latch, clock, and data). I had some cat5e cable so I ran that from the Mega to the shift register. (I have an external 5V power supply so that does not come from the mega).

Problem is that is works, but inconsistently. I wrote a test program to turn on the relays in sequence. Sometimes it goes in order as it should but other times it skips relays or goes out of order.

I think there might be 4 sources of the problem:

1 The cat5e cable is too thin. Would a bigger wire help? Will twisting one pair together and using it like it was one wire help?

2 The shift\_out code timing is off. I tried inserting some `delay` statments and that seemed to help a little. But I'm not sure where to insert them.

```
 void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

```

`DigitalWrite` is my own function that manipulates the PORTn bits instead of using Arduino's `digitalWrite()`.

3 The shift register is very close to some 110V wires. Maybe interference?

4 The 5V power supply isn't powerful enough to power the relay board and the shift register?

Any suggestions welcome.

Edit: here's a pic of what I've built. The Cat5 cable runs directly back to the Arduino.

# Answer
SPI is supposed to be used for things in close proximity to each other. See Wikipedia - Serial Peripheral Interface Bus.

> The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for *short distance communication*, primarily in embedded systems.

(My emphasis).

At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.

See my page about SPI \- you can use SPI to transfer to a 595 register (as described here).

*(I'm assuming you are talking about a 74HC595 shift register)*

I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) `SPI_CLOCK_DIV128`.

---

> The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a page describing that.

---

> The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

---

Also see How do you use SPI on an Arduino?
> 1 votes

# Answer
If nothing else works, consider a RS485 link. Nick Gammons forum has a useful and in depth tutorial on the subject. There is a bit of a hardware penalty - an additional Arduino or some other avr and a couple of RS485 driver chips, which is why I council "if nothing else works" in this case.
> 0 votes

# Answer
A good debugging tool in this case is a logic analyzer. It could help understand the timing characteristics for your code (and wiring).

```
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

```

For instance, how long is the clock pulse? Does the data signal raise/fall correctly before the clock signal? What is the clock pulse frequency? How is it affected by the RC factor of the wiring.

Given that the signals are within limits you can add micro-second delays to compensate for propagation.

```
void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, (bits & (1 << i)));
         delayMicroseconds(T1);
         DigitalWrite(clock_pin, HIGH);
         delayMicroseconds(T2);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

```

Cheers!
> 0 votes

---
Tags: shift-register
---