title: Arduino core structure and timer usage

text:
# Question
Title: Arduino core structure and timer usage
I needed to use TC1 for input capture, but also analogWrite() and an approximate 1 ms interrupt to poll the user interface (encoder, button).

The Arduino Nano's ATmega328p (datasheet, beware: a lot of bit symbol typos) has three timers:

1. TC0
2. TC1
3. TC2

It is not easy to find information on the "Arduino core" structure and it's use of peripherals. The Arduino Reference does not seem to refer to any information. Nor does Arduino Hacking.

Some info can be found on

https://arduino-info.wikispaces.com/Timers-Arduino

but I am not sure it's up to date. For instance, I find disabling TC2 also disables the `analogWrite()` PWM. Trying to use TC0 results in an error, as `TIMER0_OVF_vect` is already being used ("multiple definition of \`\__vector\_16'").

How can I use the timers (and their interrupts) that are already used for the core?

# Answer
Here is a summary of all this. On an ATmega328P (Arduino Uno, Nano, etc.), the Arduino core library uses the timers as follows:

* Timer 0
    + timing and delay functions, using the `TIMER0_OVF` interrupt
    + “fast” PWM at 980 Hz on pins 5 and 6 (PD5 and PD6)
* Timer 1
    + “phase-correct” PWM at 490 Hz on pins 9 and 10 (PB1 and PB2)
* Timer 2
    + “phase-correct” PWM at 490 Hz on pins 3 and 11 (PD3 and PB3)

All three timers have their prescalers set to 64. `TIMER0_OVF` is the only timer interrupt enabled by default.

Note that libraries can use the timers for their own purposes. `Servo` for instance uses Timer 1 for doing interrupt-based PWM.
> 3 votes

# Answer
"Reimplementing" the interrupt handlers to free Timer/Counter resources would require changes to the Arduino core firmware. But there may be a workaround:

The source code shows how `init()` and `loop()` are used:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp

and the basic timer initialization is here:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L45

and `init()` is there as well, which also configures all the other timers for *phase-correct PWM*...

`analogWrite()` is in https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring\_analog.c

I thought that at just 490/980 Hz it might use software-PWM, but in fact it selects the corresponding timer *output compare* pin (that also means the CPU can be powered down while the PWM still is being generated).

It does that via a runtime lookup in the board header's `digital_pin_to_timer_PGM`, e.g. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/standard/pins\_arduino.h

which seems to be a (conditional) list of all pins.

So there is a limited, indirect choice on which timer is being used for PWM:
PD5 and PD6 are served by TC0, so using one of these as `analogWrite()` output pin frees TC2 for my purposes (~1 kHz polling).

Works for me!
> 2 votes

---
Tags: interrupt, pwm, atmega328, timers, core-libraries
---


title: Multiple if statement conditions

text:
# Question
Title: Multiple if statement conditions
I would like to make this code using the Arduino Uno. I am using three on/off switches and based on the truth table would like to turn on one of 8 LEDs. When I use `digitalWrite()`, I get an error code saying that there are too few arguments.

Here is the code

```
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
}

void loop() {

  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
    digitalWrite (ledPin1 = HIGH);
    digitalWrite (ledPin2 = LOW);
    digitalWrite (ledPin3 = LOW);
    digitalWrite (ledPin4 = LOW);
    digitalWrite (ledPin5 = LOW);
    digitalWrite (ledPin6 = LOW);
    digitalWrite (ledPin7 = LOW);
    digitalWrite (ledPin8 = LOW);
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
    ledPin1 = LOW;
    ledPin2 = HIGH;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = HIGH;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = HIGH;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = HIGH;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = HIGH;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = HIGH;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = HIGH;
  }
}

```

# Answer
`digitalWrite (ledPin1 = HIGH);` should be `digitalWrite (ledPin1, HIGH);`

PS `if ( (x = LOW) && (y = LOW) && (z = LOW))` should be `if ( (x == LOW) && (y == LOW) && (z == LOW))`. `=` is for assignment, `==` is for comparison.
> 4 votes

# Answer
> void loop() {
>
> ```
>  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
>  {
>
> ```

Apart from the issue of needing `==` instead of `=` you are never *reading* those pins. In fact you are comparing the pin *numbers* (which will never change), not the data on those pins.

You need:

void loop() {

```
  if ( (digitalRead (x) == LOW) &&
       (digitalRead (y) == LOW) &&
       (digitalRead (z) == LOW))              //condition 1
    {

```

... and so on.

---

This is wrong too, I'm surprised it compiled:

> ```
>    digitalWrite (ledPin1 = HIGH);
>    digitalWrite (ledPin2 = LOW);
>    digitalWrite (ledPin3 = LOW);
>    digitalWrite (ledPin4 = LOW);
>    digitalWrite (ledPin5 = LOW);
>    digitalWrite (ledPin6 = LOW);
>    digitalWrite (ledPin7 = LOW);
>    digitalWrite (ledPin8 = LOW);
>
> ```

It should be:

```
  digitalWrite (ledPin1, HIGH);
  digitalWrite (ledPin2, LOW);
  digitalWrite (ledPin3, LOW);
  digitalWrite (ledPin4, LOW);
  digitalWrite (ledPin5, LOW);
  digitalWrite (ledPin6, LOW);
  digitalWrite (ledPin7, LOW);
  digitalWrite (ledPin8, LOW);

```

> when i use digital write i get an error code saying that there are too few arguments. ... I just dont know why the simulation program is still not lighting the LED

Oh I see, it did *not* compile. No wonder the LEDs didn't turn on.
> 4 votes

# Answer
Here's a little tip for you (it has nothing to do with your problem, it's just a good programming method). This will massively reduce the size of your program.

You have three boolean state variables, and you are comparing the state of all combinations - that's 8 combinations. If you take each boolean value as 1 bit of a value between 0 and 7 - that is values (as binary) 000, 001, 010, 011, 100, 101, 110, and 111 - then you can use much simpler methods for controlling your LEDs.

For instance, this (untested) code will turn three digital reads into a single number between 0 and 7:

```
uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);

```

`x` is the least significant bit, and `z` is the most significant. So `value` will now be a value between 0 and 7 representing the state of those three pins.

Now you can use that `value` variable to decide which pin to turn on. Here's another trick: Store you LED pins as an array. That means, instead of having `ledPin1`, `ledPin2`, etc, you just have a list of pin numbers known as `ledPin[x]`:

```
const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

```

Now you can use a `for` loop to iterate though that list and turn on the LED you want:

```
for (uint8_t i = 0; i < 8; i++) {
    if (i == value) {
        digitalWrite(ledPin[i], HIGH);
    } else {
        digitalWrite(ledPin[i], LOW);
    }
}

```

In fact, that can be further compressed, since HIGH and LOW are basically truth values (HIGH is 1, or true, and LOW is 0, or false):

```
for (uint8_t i = 0; i < 8; i++) {
    digitalWrite(ledPin[i], i == value);
}

```

So your whole program could look like this:

```
const uint8_t x = A3;    // select the input pin for the switch
const uint8_t y = A4;
const uint8_t z = A5;

const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

void setup() {
    for (uint8_t i = 0; i < 8; i++) {
        pinMode(ledPin[i], OUTPUT);
    }
    pinMode(x, INPUT);
    pinMode(y, INPUT);
    pinMode(z, INPUT);
}

void loop() {
    uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);
    for (uint8_t i = 0; i < 8; i++) {
        digitalWrite(ledPin[i], i == value);
    }
}

```

Saves a huge amount of typing and also ends up using considerably less Flash memory.
> 2 votes

# Answer
Since you mentioned you are new to programming, I am posting your own solution modified to work with right things; this code can be optimize to a great extent if you get good at programming; For your benefit, I will post both your approach and a slightly better approach

**Your approach:**

```
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

    // declare the ledPin as an OUTPUT:
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(ledPin4, OUTPUT);
    pinMode(ledPin5, OUTPUT);
    pinMode(ledPin6, OUTPUT);
    pinMode(ledPin7, OUTPUT);
    pinMode(ledPin8, OUTPUT);

    pinMode(x, INPUT);
    pinMode(y, INPUT);
    pinMode(z, INPUT);
}

void loop() {

    if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
    {
        digitalWrite (ledPin1, HIGH);
        digitalWrite (ledPin2, LOW);
        digitalWrite (ledPin3, LOW);
        digitalWrite (ledPin4, LOW);
        digitalWrite (ledPin5, LOW);
        digitalWrite (ledPin6, LOW);
        digitalWrite (ledPin7, LOW);
        digitalWrite (ledPin8, LOW);
    }

    if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, HIGH);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, HIGH);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, HIGH);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, HIGH);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, HIGH);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, HIGH);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, HIGH);
    }
}

```

---

**Slightly better approach:**(better programmers may be able to write even more optimized code)

```
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
}

void loop() {
  int pinToTurnHigh = 2; // just making sure its a valid pin
  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
    pinToTurnHigh = ledPin1;
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
    pinToTurnHigh = ledPin2;
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
    pinToTurnHigh = ledPin3;
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
    pinToTurnHigh = ledPin4;
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
    pinToTurnHigh = ledPin5;
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
    pinToTurnHigh = ledPin6;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
    pinToTurnHigh = ledPin7;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
    pinToTurnHigh = ledPin8;
  }
  resetAllLEDs();
  digitalWrite(pinToTurnHigh, HIGH);
}

void resetAllLEDs()
{
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);
  digitalWrite(ledPin3, LOW);
  digitalWrite(ledPin4, LOW);
  digitalWrite(ledPin5, LOW);
  digitalWrite(ledPin6, LOW);
  digitalWrite(ledPin7, LOW);
  digitalWrite(ledPin8, LOW);
}

```
> 1 votes

# Answer
The sole error in digitalWrites is that digitalWrite (ledPin1 = HIGH); should be **digitalWrite (ledPin1, HIGH);** same for other digitalWrite calls;

**"too few arguments to function"** clearly implies that the number of arguments you are passing are less than expected by the function;

***by the way your code will also work fine if you update your assignments to digitalWrite statements in your code in all the if/else blocks;***

you can read more about the digitalWrite function in the link below https://www.arduino.cc/en/Reference/DigitalWrite
> 0 votes

---
Tags: arduino-uno, led
---


title: String to unsigned long conversion

text:
# Question
Title: String to unsigned long conversion
I'm trying to use `strtoul()` to convert an Arduino **S**tring to an unsigned long *(like the return of `millis();`)* using the following code snippet:

```
unsigned long foo (String time)
{
  unsigned long mili;
  char Tim[9]="";
  uint16_t timsize = time.length()+1;
  char TIM[timsize];
  time.toCharArray(TIM,timsize);
  mili=strtoul(TIM,timsize,10);
  return mili;
}

```

The code seems to work. However, I'm getting the following warning:

> invalid conversion from 'uint16\_t {aka unsigned int}' to 'char\**' \[-fpermissive\] `mili=strtoul(TIM,timsize,10);`

---

My question is twofold:

1. Is there a better way to convert a **S**tring to unsigned long without first converting to a C string?
2. If not, how can I eliminate this error?

# Answer
Arduino `String` class provides method `c_str()`. So you don't have to convert it to C string, as it's already stored as a C string internally.

And as mentioned in comments, the second parameter of `strtoul` is:

> **endptr**
> Reference to an object of type `char*`, whose value is set by the function to the next character in str after the numerical value.
> This parameter can also be a null pointer, in which case it is not used.

Basically you can reduce whole foo to the: `return strtoul(time.c_str(), NULL, 10);`
> 5 votes

---
Tags: arduino-mega, data-type, convert
---


# Question
Title: How to have code/sketch that's easily toggleable to work on different nodes
i have a question about best practice to achieve what i want to do. I would like to have a sketch setup, and then to be able to deploy to different devices of the same type, but each device/node will have a few different parameters, like ip address and mqtt topic etc,

What would be the quickest way to be able to upload new changes to all of my nodes without having to track my changes and update each seperate sketch for each node?

I was thinking about using some IFDEF statements if i can figure out how to? would that be the best way to go or is there something better?

Thx in advance

# Answer
You can put the per-node parameters in a external EEPROM and load them during `setup()`. For example the IP address is the first 16 bytes of the eeprom (IPv6), the next bytes would the the topic, etc..

That way every node has exactly the same sketch and the customization is in the eeprom that you could put in a socket and possibly have a separate programmer for them.

EEPROMs with I2C interface are easy enough to get and can store 64kB. Which should be more than enough for most things.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: Arduino Uno Sensor DHT11 Failed to read from DHT sensor
I get this error every time. I used the DHT tester file from this library. Which gives me an error.

And then I realized that in my code Arduino recognizes only the `readTemperature` function, not `readHumidity`, but it doesn't give any compile error. Also, when I read the sensor, this is the output:

> Humidity Sensor Test
> Temp: 0C, Humidity: 0%
> Temp: 0C, Humidity: 0%
> Temp: 0C, Humidity: 0%

My code is here:

```
//DHT11 Sensor:
#include "DHT.h"
#define DHTPIN 5 // which digital pin we're connected to
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  delay(300);
  lcd.begin(16,2);
  Serial.println("Humidity Sensor Test");
  dht.begin();
  delay(300);
}

void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  int h = dht.readHumidity();
  int t = dht.readTemperature();

  // set the cursor to (0,0):
  lcd.setCursor(0, 0);
  // print from 0 to 9:

  lcd.print("Temp: ");
  lcd.print(t);
  lcd.print("C");

  // set the cursor to (16,1):
  lcd.setCursor(0,1);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.print("%");

  Serial.print("Temp: ");
  Serial.print(t);
  Serial.print("C, Humidity: ");
  Serial.print(h);
  Serial.println("%");
  delay(2500);
}

```

Also I have the 10k resistor between data and Vcc pins. Data is connected to digital pin 5. Has anyone had this problem before?

# Answer
> 1 votes
There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Here is a simple sketch to test the sensor with the output going to the serial monitor.

```
// 5k ohm pull up resistor is used on the data line.
// Sensor operates at 5VDC.
// Data line connects to Arduino Uno pin 3.

#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 3

// Sensor calibration. Start with 0 for each.
const int HumidityCorrection = -10;          // -10 worked with my sensor.
const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

// Update the serial display every 60 seconds.
const float UpdateSerialDisplay = 60000;

// Celsius to Fahrenheit conversion.
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

void setup(){
  Serial.begin(9600);
  // Minimum wait for good data recommended is 1 second.
  delay(2000);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
}

void loop(){
  Serial.println("");
  int chk = DHT11.read(DHT11PIN);
  switch(chk){
    case DHTLIB_OK:
      //Serial.println("OK");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.println("Read sensor: Checksum error");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.println("Read sensor: Time out error");
      break;
    default:
      Serial.println("Read sensor: Unknown error");
      break;
  }

  Serial.print("Humidity: ");
  Serial.print("\t");
  Serial.print(DHT11.humidity + HumidityCorrection);
  Serial.println(" %");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
  Serial.println(" C");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
  Serial.println(" F");

  delay(UpdateSerialDisplay);
}

```

Once you get this working you can add the LCD code to it. Here is a link to the DHT 11 Humidity & Temperature Sensor manual / data sheet: http://www.micropik.com/PDF/dht11.pdf

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


title: Break loop/restart program at any time

text:
# Question
Title: Break loop/restart program at any time
maybe my problem is just that my thinking is wrong. I hope you can help me. First of all I will point out what I think in general, then I show you some code to work with.

In general my problem is to wrap me head around a push-button (or any other input) that stops (or better restarts) a running program at **any** time. If i use the digitalRead(pin-whatsoever)-statement don't I have to tackle the exact mili/microsecond my MC is working on that specific line of code? I don't want to use an interrupt either, i want to restart the program, not to interrupt it.

My project is some kind of turn-indicators for a bicycle. The lights shall "run" from right to left on left-turns and vice versa. But i want to stop the sequence at any point (or at least after one loop-run) if I push the corresponding button again. After that the MC shall wait for another button-push to run the indicator either till the for-loop is finished or i press the same button earlier.

Another (general) question: Is there a way to get rid of delay-statements and achieve similar results?

Thank You so far.

```
   // Var-Setup
  const int mtime = 120; // Time between lights lighting up
  const int ftime = 100; // Time between lights turning out

void setup() {
  // put your setup code here, to run once:
  // Pin-Setup
    // LED-Pins
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);

    // Button-Pins
  pinMode(12, INPUT);
  pinMode(13, INPUT);

}

void right(){
  for(int i=0; i<5; i++){
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
      delay(mtime);
      digitalWrite(10, HIGH);
      delay(mtime);
      digitalWrite(9, HIGH);
      delay(mtime);
      digitalWrite(8, HIGH);
      delay(mtime);
      digitalWrite(7, HIGH);
      delay(mtime);
      delay(mtime);

      // Fade
      digitalWrite(11, LOW);
      delay(ftime);
      digitalWrite(10, LOW);
      delay(ftime);
      digitalWrite(9, LOW);
      delay(ftime);
      digitalWrite(8, LOW);
      delay(ftime);
      digitalWrite(7, LOW);
      delay(250);
    }
}

void left (){
  for(int i=0; i<5; i++){
    // Indicator left with running light
    // Rise
    digitalWrite(2, HIGH);
    delay(mtime);
    digitalWrite(3, HIGH);
    delay(mtime);
    digitalWrite(4, HIGH);
    delay(mtime);
    digitalWrite(5, HIGH);
    delay(mtime);
    digitalWrite(6, HIGH);
    delay(mtime);
    delay(mtime);

    // Fade
    digitalWrite(2, LOW);
    delay(ftime);
    digitalWrite(3, LOW);
    delay(ftime);
    digitalWrite(4, LOW);
    delay(ftime);
    digitalWrite(5, LOW);
    delay(ftime);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorL = digitalRead(12);
  int sensorR = digitalRead(13);
  if(sensorL == HIGH){
    left();
  }else if(sensorR == HIGH){
    right();
  }
}

```

# Answer
replace each delay chain with a switch statement where each delay is replaced by saving the current millis counter, a increment of the state, a case label for the new state and a `if(millis()-timestamp < timeout) return;`

```
switch(state){
case 0;
      // Indicator right with running light (like a "half-knight-rider" ;) )
      // Rise
      digitalWrite(11, HIGH);
  timestamp = millis();
  state++;
case 1:
   if(millis()-timestamp  < mtime) return;

      digitalWrite(10, HIGH);
  timestamp = millis();
  state++;
case 2:
      digitalWrite(9, HIGH);
//etc.

```

The for loop around the entire thing will need to be replaced. Make `i` global and incrementing it in the last state and resetting it as needed. When i has been incremented to beyond 5 you always return.

This means that the `left` and `right` functions only do a few things: set the led, check a timestamp against the current time, and increment a state before returning.

This means that they will take very little time to execute and that you can check the button in the main loop() body and if pressed initiate the statemachine or end it (and putting out the LED when needed).
> 1 votes

---
Tags: arduino-uno, programming, interrupt, hardware
---


# Question
Title: Arduino Uno simple LED example with pointers
I am new to Arduino and I have recently started off by trying to turn on an LED connected to pin 13 on my Arduino Uno using pointers.

I opted to do this with pointers because this would give me a better understanding on what really goes behind when I use predefined Arduino functions.

My simple code looks like this,

```
uint8_t *data = (uint8_t *) 0x05; //PortB data register ptr (Since pin 13 is PB6)
uint8_t *dir = (uint8_t *) 0x04;  //PortB dir register ptr (Since pin 13 is PB6)

void setup() {
    *dir = 0x40;  //PB6 direction set to O/P
    *data = 0x40; //PB6 data set to 1 to turn on the LED
}

void loop() {
  *data = 0x40;
}

```

I tried the same program using pinMode(13, OUTPUT) and digitalWrite(13, LOW) functions and it works fine. But I do not understand what could be wrong with my pointers. If you find anything wrong, kindly let me know.

# Answer
> 2 votes
You made two small mistakes:

1. The addresses of the I/O registers are `0x24` for `DDRB` and `0x25` for `PORTB`. The numbers you used are I/O port numbers, but since pointers are supposed to point to memory, you have to use the memory-mapped addresses instead.
2. Pin 13 is `PB5`, not `PB6`.

With these two mistakes fixed, your code works as expected. There are still two issues however:

1. Under some circumstances, the compiler can optimize away some writes to these registers. You have to qualify the pointers as “pointer to `volatile` data” in order to avoid this. Even if your simple example does not show this problem, it is always safer to use the qualifier.
2. The compiler generates inefficient code. Not as inefficient as `digitalWrite()`, but still... It knows how to optimize, but it is prevented to do so by the fact that your pointers are modifiable. You should qualify them as `const` if you want to benefit from compiler optimizations.

With those fixes, your pointer definitions would look like:

```
volatile uint8_t * const data = (uint8_t *) 0x25;
volatile uint8_t * const dir  = (uint8_t *) 0x24;

```

and access to them gets compiled into efficient `in` ans `out` assembly instructions.

That being said, if you want to do direct port access, I would recommend doing it the avr-libc way:

```
void setup() {
    DDRB  = _BV(PB5);
    PORTB = _BV(PB5);
}

void loop() {
    PORTB = _BV(PB5);
}

```

The way the AVR-libc defines the I/O registers is roughly equivalent to

```
#define PORTB (* (volatile uint8_t *) 0x25)

```

# Answer
> 1 votes
Port definitions in AVR-Libc are done via black magic. Don't attempt to replicate them as a beginner. That being said...

"How do I pass an IO port as a parameter to a function?"

```
volatile uint8_t *data = &PORTB;
volatile uint8_t *dir = &DDRB;

```

---
Tags: arduino-uno, led, pins
---


title: Get a LED to fade out

text:
# Question
Title: Get a LED to fade out
I want to light an LED in a sketch and then have it fade out. I tried to use analogWrite and have it decrease from a value of 255 to 0 using a for() loop, but I can't seem to get it to work. Using digitalWrite I can turn it on and off but cant get it to fade out. Can anyone help please.

```
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 9;
int j = 0;

void setup() {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
}

void loop() {
    j = 255;
    delay(1000);
    if (j >= 5);
    {
        analogWrite(ledPin3,j);
        delay(10);
        j = j - 5;
    }
    delay(1000);
}

```

# Answer
Not all output pins are able to perform PWM ("AnalogWrite").

> On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

https://www.arduino.cc/en/Reference/AnalogWrite

Note that the PWM-enabled ports are marked by a "~" on the board.

If you try analogWrite, e.g., on port 4, you'll get your observed switch behaviour.
> 2 votes

# Answer
Problems noted in comments:

```
void loop() {
    j = 255;             // Resets j EVERYTIME
    delay(1000);
    if (j >= 5);         // Semi-colon here makes this a null statement
    {
        analogWrite(ledPin3,j);  // j is always 255 (see line 1)
        delay(10);
        j = j - 5;       // No effect as j is reset in line 1
    }
    delay(1000);
}

```

Here's a simple fix:

```
int j = 255;   // Start at 255

void loop() {
    analogWrite(ledPin3, j);   // Set the brightness
    delay(10);
    j -= 5;
    if (j <= 0) j = 255;       // Reset j?
}

```
> 2 votes

---
Tags: led, pwm
---


title: USB or external power

text:
# Question
Title: USB or external power
I have an arduino mega that i am using as a clock. I would like it to detect if it is connected to a USB or external power supply (e.g. a battery). I then want to set a variable to different values depending on the result, so i can display it on an OLED.

# Answer
Use a simple transistor where the Vin (external power) is connected to the base, which switches the transistor. Than connect the collector to +5V, and the emitter to a GPIO input pin and read the status with the Arduino. If it receives a HIGH you know external power (via Vin) is used.

See the useful 'good' answer as comment of Majenko below ... I will leave the answer above as is, to keep his remarks clear.
> 1 votes

---
Tags: arduino-mega, power, usb
---


# Question
Title: Two data outputs to be displayed on one 16x1 lcd display
Before pursuing this very far, I would like to know if I can get two different data outputs (one on the left 8 and the other data on the right 8). And if so, are there any requirements on the display or any other thing that might be needed. I'm thinking that as far as the proper Arduino platform being the Mega 2560. My idea is to put together an FSX navigation radio for my flight simulator.

# Answer
> 2 votes
You can use

```
lcd.setCursor(x, y);

```

To set the cursor.

Than you can output text with

```
lcd.print("Text");

```

Make sure you add spaces in case there is already text written to overwrite older text.

You can also use

```
lcd.clear();

```

to clear the display, but this might result in flickering if you do it too often.

Another possibility is to create a 16 character string

```
char lcdText[16];

```

and write characters in this string and set it at once with:

```
lcd.setCursor(0, 0);
lcd.print(lcdText);

```

---
Tags: display, data
---


# Question
Title: Having a problem where the previous letter flashes after a space
im currently working on a stranger things letter board with an arduino and ws2811 leds and im having an issue where ever there is a space, the previous letter will be displayed. Ive tried going in and finding where it makes this duplicate, but i am rather inexperienced. Heres my code:

```
#include <FastLED.h>

#include <HashMap.h>

#define DATA_PIN 6 //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin

#define NUM_LEDS 50 //change this for the number of LEDs in the strip

#define COLOR_ORDER RGB

CRGB leds[NUM_LEDS];

CRGB colors[5];

int myleds[25];

int last_letter = 0;

CRGB white = CRGB(255, 255, 255);

CRGB red = CRGB (255, 0, 0);

CRGB green = CRGB (0, 255, 0);

CRGB blue = CRGB(0, 0, 255);

CRGB off = CRGB(0, 0, 0);

const byte HASH_SIZE = 28;

HashType<char, int> hashRawArray[HASH_SIZE];

HashMap<char, int> charToLed = HashMap<char, int>( hashRawArray , HASH_SIZE );

void setup() {

  FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); //setting up the FastLED

  randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

  myleds[0] = 47;//A

  charToLed[0]('a', 47);

  myleds[1] = 45;//B

  charToLed[1]('b', 45);

  myleds[2] = 43;//C

  charToLed[2]('c', 43);

  myleds[3] = 42;//D

  charToLed[3]('d', 42);

  myleds[4] = 40;//E

  charToLed[4]('e', 40);

  myleds[5] = 38;//F

  charToLed[5]('f', 38);

  myleds[6] = 37;//G

  charToLed[6]('g', 37);

  myleds[7] = 34;//H

  charToLed[7]('h', 34);

  myleds[8] = 32;//I

  charToLed[8]('i', 32);

  myleds[9] = 16;//J

  charToLed[9]('j', 16);

  myleds[10] = 18;//K

  charToLed[10]('k', 18);

  myleds[11] = 20;//L

  charToLed[11]('l', 20);

  myleds[12] = 22;//M

  charToLed[12]('m', 22);

  myleds[13] = 24;//N

  charToLed[13]('n', 24);

  myleds[14] = 26;//O

  charToLed[14]('o', 26);

  myleds[15] = 28;//P

  charToLed[15]('p', 28);

  myleds[16] = 29;//Q

  charToLed[16]('q', 29);

  myleds[17] = 31;//R

  charToLed[17]('r', 31);

  myleds[18] = 15;//S

  charToLed[18]('s', 15);

  myleds[19] = 13;//T

  charToLed[19]('t', 13);

  myleds[20] = 11;//U

  charToLed[20]('u', 11);

  myleds[21] = 9;//V

  charToLed[21]('v', 9);

  myleds[22] = 7;//W

  charToLed[22]('w', 7);

  myleds[23] = 4;//X

  charToLed[23]('x', 4);

  myleds[24] = 2;//Y

  charToLed[24]('y', 2);

  myleds[25] = 0;//Z

  charToLed[25]('z', 0);

  colors[0] = white;

  colors[1] = red;

  colors[2] = green;

  colors[3] = blue;

  colors[4] = off;

  reset();

  abcs();

}

void loop() {

  type("My world would be upsidedown if i went to homecoming without you");
  delay(3000);
  type("andificant");
  delay(100);
  jog();

}

void beforejog() {
  FastLED.clear();
  leds[0] = CRGB (0, 255, 255); //aqua
  leds[10] = CRGB (0, 255, 255); //aqua
  leds[20] = CRGB (0, 255, 255); //aqua
  leds[30] = CRGB (0, 255, 255); //aqua
  leds[40] = CRGB (0, 255, 255); //aqua
  leds[1] = CRGB (153, 50, 204); //dark orchid
  leds[11] = CRGB (153, 50, 204); //dark orchid
  leds[21] = CRGB (153, 50, 204); //dark orchid
  leds[31] = CRGB (153, 50, 204); //dark orchid
  leds[41] = CRGB (153, 50, 204); //dark orchid
  leds[2] = CRGB (255, 255, 0); //yellow
  leds[12] = CRGB (255, 255, 0); //yellow
  leds[22] = CRGB (255, 255, 0); //yellow
  leds[32] = CRGB (255, 255, 0); //yellow
  leds[42] = CRGB (255, 255, 0); //yellow
  leds[3] = CRGB (0, 255, 127); //spring green
  leds[13] = CRGB (0, 255, 127); //spring green
  leds[23] = CRGB (0, 255, 127); //spring green
  leds[33] = CRGB (0, 255, 127); //spring green
  leds[43] = CRGB (0, 255, 127); //spring green
  leds[4] = CRGB (255, 165, 0); //orange
  leds[14] = CRGB (255, 165, 0); //orange
  leds[24] = CRGB (255, 165, 0); //orange
  leds[34] = CRGB (255, 165, 0); //orange
  leds[44] = CRGB (255, 165, 0); //orange
  leds[5] = CRGB (65, 105, 255); //royal blue
  leds[15] = CRGB (65, 105, 255); //royal blue
  leds[25] = CRGB (65, 105, 255); //royal blue
  leds[35] = CRGB (65, 105, 255); //royal blue
  leds[45] = CRGB (65, 105, 255); //royal blue
  leds[6] = CRGB (76, 0, 153); //dark purple
  leds[16] = CRGB (76, 0, 153); //dark purple
  leds[26] = CRGB (76, 0, 153); //dark purple
  leds[36] = CRGB (76, 0, 153); //dark purple
  leds[46] = CRGB (76, 0, 153); //dark purple
  leds[7] = CRGB (255, 105, 180); //hot pink
  leds[17] = CRGB (255, 105, 180); //hot pink
  leds[27] = CRGB (255, 105, 180); //hot pink
  leds[37] = CRGB (255, 105, 180); //hot pink
  leds[47] = CRGB (255, 105, 180); //hot pink
  leds[8] = CRGB (0, 128, 0); //dark green
  leds[18] = CRGB (0, 128, 0); //dark green
  leds[28] = CRGB (0, 128, 0); //dark green
  leds[38] = CRGB (0, 128, 0); //dark green
  leds[48] = CRGB (0, 128, 0); //dark green
  leds[9] = CRGB (255, 0, 0); //red
  leds[19] = CRGB (255, 0, 0); //red
  leds[29] = CRGB (255, 0, 0); //red
  leds[39] = CRGB (255, 0, 0); //red
  leds[49] = CRGB (255, 0, 0); //red
  FastLED.show();
  delay(50);
  FastLED.clear();
}

void jog() {
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  beforejog();
  delay(100);
  BLACKOUT();
  leds[31] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
  leds[11] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
  leds[24] = CRGB (255, 0, 0);
  FastLED.show();
  delay(2000);
  FastLED.clear();
}

void abcs() {

  for (int i = 0; i < 25; i++) {

    int t = myleds[i];

    leds[t] = white;

    FastLED.show();

    delay(250);

  }

  delay(10);

}

CRGB randomColor() {

  int t = random(4);

  return colors[t];

}

void reset() {

  for (int x = 0; x < NUM_LEDS; x++) {

    leds[x] = off;

  }

  FastLED.show();

  last_letter = 0;

}

void displayLetter(char letter) {

  if (isWhitespace(letter)) {

    last_letter = 0;

    delay(2000);

  }

  int lednum = charToLed.getValueOf(letter);

  if (lednum >= 0 && lednum <= 50) {

    if (last_letter == lednum) {

      delay(2000);
    }

    leds[lednum] = white;

    FastLED.show();

    last_letter = lednum;

    delay(2000);

    leds[lednum] = off;

    FastLED.show();

  }

}

void type(String message) {

  reset();

  message.toLowerCase();

  for (int i = 0; i < message.length(); i++) {

    displayLetter(message[i]);

  }

  reset();

}
void BLACKOUT() {
  int r = 0;
  int b = 0;
  int g = 0;

  for (int x = 0; x < NUM_LEDS; x++) {
    leds[x] = CRGB(r, g, b);
  }

  FastLED.show();
  delay(100);

}

```

Any help is appreciated. thanks.

# Answer
> 1 votes
This will not fix your problem!

You said you were inexperienced, so I have taken you code and with no knowledge of what it does (that mean I may have made mistakes) I have refactored it slightly.

```
#include <FastLED.h>

#define DATA_PIN (6) //this is the data pin connected to the LED strip. If using WS2801 you also need a clock pin
#define NUM_LEDS (50) //change this for the number of LEDs in the strip
#define COLOR_ORDER RGB
#define HASH_SIZE (28)

CRGB Leds[NUM_LEDS];

int last_letter = 0;

enum ColourNames {White, Red, Green, Blue, Off};
const CRGB Colours[] = { CRGB(255, 255, 255), CRGB(255, 0, 0), CRGB(0, 255, 0), CRGB(0, 0, 255), CRGB(0, 0, 0) };

struct LED
{
    int myled;
    int led;
    char letter;
    LED(const int& m = 0, const int& l = 0, const char& let = 0)
        : myled(m)
        , led(l)
        , letter(let)
    {}
};
LED LedData[HASH_SIZE];

void setup()
{
    FastLED.addLeds<WS2811, DATA_PIN, COLOR_ORDER>(Leds, NUM_LEDS); //setting up the FastLED
    randomSeed(analogRead(0)); //seeding my random numbers to make it more random.

    LedData[ 0] = LED(47, 47, 'a');
    LedData[ 1] = LED(45, 45, 'b');
    LedData[ 2] = LED(43, 43, 'c');
    LedData[ 3] = LED(42, 42, 'd');
    LedData[ 4] = LED(40, 40, 'e');
    LedData[ 5] = LED(38, 38, 'f');
    LedData[ 6] = LED(37, 37, 'g');
    LedData[ 7] = LED(34, 34, 'h');
    LedData[ 8] = LED(32, 32, 'i');
    LedData[ 9] = LED(16, 16, 'j');
    LedData[10] = LED(18, 18, 'k');
    LedData[11] = LED(20, 20, 'l');
    LedData[12] = LED(22, 22, 'm');
    LedData[13] = LED(24, 24, 'n');
    LedData[14] = LED(26, 26, 'o');
    LedData[15] = LED(28, 28, 'p');
    LedData[16] = LED(29, 29, 'q');
    LedData[17] = LED(31, 31, 'r');
    LedData[18] = LED(15, 15, 's');
    LedData[19] = LED(13, 13, 't');
    LedData[20] = LED(11, 11, 'u');
    LedData[21] = LED( 9,  9, 'v');
    LedData[22] = LED( 7,  7, 'w');
    LedData[23] = LED( 4,  4, 'x');
    LedData[24] = LED( 2,  2, 'y');
    LedData[25] = LED( 0,  0, 'z');
    LedData[26] = LED();
    LedData[25] = LED();

    reset();
    abcs();
}

void loop()
{
    type("My world would be upsidedown if i went to homecoming without you");
    delay(3000);
    type("andificant");
    delay(100);
    jog();
}

void beforejog()
{
    static const int MaxColours = 10;
    const CRGB colours[MaxColours] =
    {
          CRGB(0, 255, 255)         //aqua
        , CRGB(153, 50, 204)        //dark orchid
        , CRGB(255, 255, 0)         //yellow
        , CRGB(0, 255, 127)         //spring green
        , CRGB(255, 165, 0)         //orange
        , CRGB(65, 105, 255)        //royal blue
        , CRGB(76, 0, 153)          //dark purple
        , CRGB(255, 105, 180)       //hot pink
        , CRGB(0, 128, 0)           //dark green
        , CRGB(255, 0, 0)           //red
    };

    FastLED.clear();
    for (int col = 0; col < MaxColours; ++col)
    {
        for (int r = col; r < NUM_LEDS; r += MaxColours)
        {
            Leds[r] = colours[col];
        }
    }

    FastLED.show();
    delay(50);
    FastLED.clear();
}

void jog()
{
    for (int l = 0; l < 7; ++l)
    {
        beforejog();
        delay(100);
        Blackout();
        delay(100);
    }

    static const MaxLights = 3;
    const int lights[MaxLights] = { 31, 11, 24 };
    for (int l = 0; l < MaxLights; ++l)
    {
        Leds[lights[l]] = Colours[Red];
        FastLED.show();
        delay(2000);
        FastLED.clear();
    }
}

void abcs()
{
    for (int i = 0; i < 25; i++)
    {
        Leds[LedData[i].myled] = Colours[White];
        FastLED.show();
        delay(250);
    }
    delay(10);
}

CRGB randomColor()
{
    const int t = random(4);
    return Colours[t];
}

void reset()
{
    Blackout();
    last_letter = 0;
}

void displayLetter(char letter)
{
    if (isWhitespace(letter))
    {
        last_letter = 0;
        delay(2000);
    }
    const int lednum = charToLed.getValueOf(letter);
    if (lednum >= 0 && lednum <= 50)
    {
        if (last_letter == lednum)
        {
            delay(2000);
        }
        Leds[lednum] = Colours[White];
        FastLED.show();
        last_letter = lednum;
        delay(2000);
        Leds[lednum] = Colours[Off];
        FastLED.show();
    }
}

void type(String message)
{
    reset();
    message.toLowerCase();
    for (int i = 0; i < message.length(); i++)
    {
        displayLetter(message[i]);
    }
    reset();
}

void Blackout()
{
    for (int x = 0; x < NUM_LEDS; x++)
    {
        Leds[x] = Colours[Off];
    }
    FastLED.show();
}

```

What I have tried to do is group similar variables into arrays (`Colour`). I have also created a structure to hold your LED data, it makes it easier to read if it all appears on a single line. I have added loops to some of the functions to reduce the line count. And if you aren't changing a variable make it const, it will make no difference to the compiler, but its easier to read and understand.

I haven't compiled this, so there is probably a howler in there, but hopefully it will give you a different perspective on your code and a different (not better) way of doing things. Oh and it should still have the problem you are asking about, which I think is you need to add an else into that function.

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


# Question
Title: LCD library and timer2 CTC interrupt not working together
I want to set up real time counter along with lcd functions from LiquidCrystal library. But they don't work together. However, they work fine separately.
The code is working by itself, but by implementing counter function, LCD just freezes with other functionality.
Part of code:

```
    #include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7, 8, 9, 13, 12, 10);

volatile boolean timerFlag = false;
volatile unsigned long int tmr2Count = 0;

void setup(){

    timer2Init();
}
void loop(){
    checkState();

}
//everything works by commenting out ISR and timer2Init
//===================================================
ISR (TIMER2_COMPA_vect){
  if (timerFlag)
    tmr2Count++;
}
void timerStart(void){
  if ( !timerFlag )
    timerFlag = true;
}
void timerReset(void){
  timerFlag = false;
  tmr2Count = 0;
}
void timer2Init(void){
    //Timer 2 interrupt service routine CTC settings, 1 uS:

    TCCR2A = 0;
    TCCR2B = 0;

    //set CTC mode
    TCCR2A |= (1 << WGM21);
    //prescaler 1 for timer2
    TCCR2B |= (1 << CS20);

    // prescaler for 1 uS.
    OCR2A = 15;
    //set compare match for register OCRA
    TIMSK2 |= ( 1 << OCIE2A);
}
//========================================================

// menu
void checkState(void)
{
  // if button is pressed without menu being displayed
  if (userSettings.currentState == STATE_IDLE && encButton == true){
    userSettings.currentState = MENU_CHOICE;
    lcd.clear();
    lcd.setCursor(3,1);
    lcd.print("<Settings>");
    encButton = false;
  }

  int menuState = userSettings.currentState;

  switch(menuState)
  {
    case STATE_IDLE:
      timeDisplay();
      dateDisplay();
      break;

    case MENU_CHOICE:
      menuSettingDisplay();
      break;

    case MENU_CONTRAST:
      contrastSetting();
      break;

    case MENU_TIME:
      timeSetting();
      break;

    case MENU_DATE:
      setDate();
      break;

    case TIME_DISPLAY:
      timeDisplayOnOff();
      break;

    case DATE_DISPLAY:
      dateDisplay();
      break;

    default:
      break;
  }
}

```

I digged in LiquidCrystal.cpp and found that there is DelayMicroseconds function, I'm thinking that it could be the cause. If it's not, what can be done otherwise ?

# Answer
> 1 votes
You're getting interrupt every 16th CPU clock cycle. The `ISR` handler might be even longer than that and your code and lower priority ISRs suffers by "starvation" as MCU can't do anything else than processing ISR.

If you use prescaler value 8, then you have `1/2us` resolution of `TCNT2` and overflow interrupt (in normal mode) occurs every `128us`, so there will be enough time to do something else. However, if you want atomic value of `TCNT2` and counted value from `ISR` handler, you'll have to stop Timer2 for a while.

---
Tags: lcd, interrupt, atmega328
---


# Question
Title: How to jump outside the loop? in below Programme how to use goto or any other Jump related Programme
```
const int analogPin1 = A1;
const int analogPin2 = A2;
const int analogPin3 = A3;
const int ledPin = 13;
const int ledPin2 = 7;
const int thresold = 400;
unsigned int x1, x2, x3, fault = 0;
void setup()
{
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}
void Config()
{
    delay(1000);
    Serial.print("ATE0r");
    Response();
    Serial.print("ATr");
    Response();
    Serial.print("AT+CMGF=1r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0r");
    Response();
}
void Response()
{
    int count = 0;
    Serial.println();
    while (1) {
        if (Serial.available()) {
            char data = Serial.read();
            if (data == 'K') {
                Serial.println("OK");
                break;
            }
            if (data == 'R') {
                Serial.println("GSM Not Working");
                break;
            }
        }
        count++;
        delay(10);
        if (count == 1000) {
            Serial.println("GSM not Found");
            break;
        }
    }
}
void loop()
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);

    if (analogValue1 < thresold) {
        x1 = 1;
        fault = x1;
    }
    if (analogValue2 < thresold) {
        x2 = x1 + 3;
        fault = x2;
    }
    if (analogValue3 < thresold) {
        x3 = x1 + x2 + 5;
        fault = x3;
    }

    switch (fault) {
    case 1:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("PHASE 1 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 3:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 4:
        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("1 AND 2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 5:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("AT+CNMI=2,2,0,0,0");
        goto nsr;
        break;

    case 6:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("1 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 8:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("2 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    case 10:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919\"\r");
        delay(1000);
        Serial.print("ALL 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        goto nsr;
        break;

    default:
        x1, x2, x3, fault = 0;
        digitalWrite(ledPin, LOW);
        break;
    }

    x1, x2, x3, fault = 0;
    digitalWrite(ledPin, LOW);
    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while (analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold);
}

do {
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);
} while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
}

nsr : if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
{

    digitalWrite(ledPin, HIGH);
    Serial.begin(9600);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);

    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
}

```

# Answer
> 2 votes
You want to create separate function `nsr` and use it instead of goto.

```
void nsr(void){
  if ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
  {

    digitalWrite(ledPin, HIGH);
    Serial.begin(9600);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    Serial.print("AT+CMGS=\"+919\"\r");
    delay(1000);
    Serial.print("ALL 3 Phase Restored");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);

    do {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    } while ((analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
  }
}

```

# Answer
> 1 votes
Instead of using

```
goto nsr

```

Use a boolean to skip parts you do not want to execute. It is (almost) never a good idea to use goto.

Due to the misalignment of { and } I do not know what you exactly want to execute.

---
Tags: arduino-uno, interrupt, gsm
---


# Question
Title: How to get elapsed seconds since Jan 1, 1970?
I am building a time-critical system using Arduino. Is there any way to get the **elapsed seconds** like `time.h` of **C** in Arduino? I tried `time(NULL)` but it returns `0`. Then moved forward to use `now()` in `Time.h`. But the result persists.

How can I get the elapsed seconds since Jan 1, 1970 until now?

# Answer
The accepted answer is not the only (nor best) answer. It depends what you have in hand. The Time library will allow your arduino to keep the current time, it just need to be set the time periodically (because of clock shifting issues) There are several ways you can get the current time:

* Use a GPS module
* Get time from NTP server if you have network access to one, using an Ethernet shield or may be wifi
* Use a custom Serial interface
* Use a GSM service
* Use a RTC module, may be the most popular and standalone, like the DS3231. However these kind of module will also require some adjustment in the long term, and they require a backup battery (often a coin like CR2032) to keep time when module is not externally powered.
* Use a few push buttons and LCD to have the user manually input it.
* Use a light sensor to see when it is the brightest time of the day and using azimuth calculation determine the hour of the day (ok, I might be going to far here, but consider a solar powered device in the middle of nowhere)

I sorted them in the order I would choose it if I have several options available. Those are a few ways that come to my mind
> 1 votes

# Answer
An arduino does not have a real time clock (RTC) built in. Every time it restarts it will reset the millis counter.

You will need to add a RTC peripheral that you can poll to find the current date and time.
> 5 votes

# Answer
You must use an RTC module like DS3231 or DS1307 for such purposes and there are good libraries available for these modules;

Unlike the standard return value of milli seconds elapsed since Jan 1 1970 00:00 on a computer, **the millis() function on arduino just returns the number of milliseconds since the board began running the current program** and this number will overflow (go back to zero), after approximately 50 days as per the official documentation at https://www.arduino.cc/en/Reference/Millis

While millis() can be used for very basic time controlled operations, its not really reliable to be used for time critical operations;
> 3 votes

# Answer
There is an 1307 RTC module emulator for Arduino: DS1307Emulator. You can set this emulator running and save seconds to `struct tm *timeStructure` and afterwards converting the structure to a `time_t` variable using time.h functions

```
DS1307Emulator.init(13);
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00); // set address 0
DS1307Emulator.writeToRTC(0x00); // start the RTC issuing the clock run command at address 0
DS1307Emulator.setUserData();

```

Adresses are as follows:

* 0x00 - seconds
* 0x01 - minutes
* 0x02 - hours

If you want to use weekdays, date, year etc. refer to the DS1307 datasheet or check examples on the link I provided.

For reading seconds:

```
DS1307Emulator.bufferUserData();
DS1307Emulator.writeToRTC(0x00);
temp = DS1307Emulator.readUserData();

```

`temp` now holds seconds in binary format, you may want to convert them to dec.

Check out examples in the link I gave for full operation.
> 0 votes

---
Tags: programming, c++, c, time
---


# Question
Title: Controlling 10+x 5m led strips with 10+ individual analog floor switches
I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.

The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.

I have a number of questions:

1. How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)
2. How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:
3. How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.

Thank you!

# Answer
> 2 votes
I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.

Maybe this can be slightly overkill, but you can think of using a MAX7313.

This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.

This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.

Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...

This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.

Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).

Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).

Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you

# Answer
> 1 votes
Unless you want to do fancy things with the LED strips you really don't need an Arduino to accomplish this task. You can just switch each strip with a powerful enough MOSFET and control the gate with the sensor:

simulate this circuit – Schematic created using CircuitLab

If you really want the Arduino (for example to add effects like delays, fading, blinking patterns, etc) it would basically go into the circuit at point `A` in the circuit. The sensor into an input and the MOSFET into an output.

Since these are just presence sensors (not pressure sensors, they don't sense pressure, only presence) you don't need an analog input to read them - a digital one will suffice and also make your programming simpler.

You can use shift registers or IO expanders to increase the number of input and output pins you have, or you can use a larger Arduino with more pins.

# Answer
> -1 votes
> I have a number of questions:

use a transistor to turn on / off each leds. size the transistor based on the leds' voltage / current requirement.

make sure that your arduino has sufficient number of pins for the sensors + leds. if not, you can split the tasks among multiple arduinos.

---
Tags: led, switch, project
---


title: Blink a LED between servo pulses

text:
# Question
Title: Blink a LED between servo pulses
Apparently using delay() commands locks the Arduino during the delay period and there are better ways to control a servo that free the Arduino to do other things at the same time as running the servo.

At this point my code consists of a servo going forwards and backwards like this:

```
void setup()
{
  pinMode(1, OUTPUT); // makes pin 1 an output
}
void loop()
{
for(int i = 0; i<31; ++i) { //keeps in this position for about 400ms
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}

for(int i = 0; i<31; ++i) { // keeps in this position for about 400ms
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}}

```

Where and how will I add some code that will allow the arduino to carry out another task for example blinking an led light during the approximately 20ms between servo pulses.

NOTE: The arduino is using the ATtiny 85 Processor.

# Answer
> 2 votes
Before and after the delay of 19 ms?

In setup add:

```
pinMode(2, OUTPUT); // LED pin output

```

Than changen in both cases:

```
  delay(19);

```

into

```
  digitalWrite(2, HIGH); // LED on
  delay(19);
  digitalWrite(2, LOW); // LED off

```

# Answer
> 2 votes
Short answer: don't use `delay()` if you want to do anything other than waiting, so rewrite your code without that call.

Long answer follows.

Instead of asking the Arduino to go to *sleep* (1) until a certain amount of time has passed, you should write your code to run continuously and do certain things whenever enough time has passed since the last time they have been executed. If the previous statement makes sense to you, then the following piece of code translates to C language what I just stated in English:

```
unsigned long time; // stores the time when the last motor movement happened, in ms
boolean clockwise; // stores the wanted direction: true CW, false CCW
unsigned byte counter; // stores how many time the wanted movement has occurred so far

unsigned long ledTimer; // stores the last time we changed the LED state
boolean ledIsOn; // stores the current LED state
void setup() {
  pinMode(1, OUTPUT); // makes pin 1 an output
  pinMode(13, OUTPUT); // makes pin 13 (onboard LED pin) an output
}

void loop() {
  if (time - millis() >= 19) { // has enough time passed since the last time we executed a step motor movement?
    time = millis(); // reset the timer for next pass
    if (counter < 31) { // have we moved in the same direction enough?
      if (clockwise) {
        moveCW();
      } else {
        moveCCW();
      }
      counter++;
    } else { // we moved enough times in the same direction: reset the counter and switch direction
      counter = 0;
      clockwise = !clockwise;
    }
  }
  // do anything else, but don't use delay()!!!
  // the following does the same as above, but on the LED
  // blinking at 1Hz (500 ms on, 500ms off)
  if (millis() - ledTimer >= 500) {
    if (ledIsOn) {
      digitalWrite(13, LOW);
    } else {
      digitalWrite(13, HIGH);
    }
    ledIsOn = !ledIsOn;
    ledTimer = millis();
  }

  // need to do something more? go ahead and try
  // but remember not to use delay() and not to waste too much time
  // in complex calcs or the loop will take too long to wrap
}

void moveCW() {
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
}

void moveCCW() {
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
}

```

There is a beautiful library called `elapsedMillis` (reference) which can reduce a bit the boilerplate code regarding subtracting `millis()` and all that stuff, but the code above is practically the same and, probably, more straightforward to begin with.

<sub> (1) The term *sleep* it's incorrect as it implies some sort of power reduction. Instead `sleep()` is just wasting time at full power. </sub>

# Answer
> 1 votes
*I'm not sure exactly what you mean with "between servo pulses" but I am assuming it means you want to blink the led while the servo is turning.*

Use the Arduino Timer library: https://playground.arduino.cc/Code/Timer

Add this at top of the sketch:

```
#include "Timer.h"

Timer t;
#define BLINK_TIME 20

```

in setup, add:

```
t.oscillate(LED_PIN, BLINK_TIME, HIGH);

```

inside the two for-loops, add:

```
t.update();

```

This will make the led on LED\_PIN turn on and off every 20 milliseconds.

---
Tags: arduino-uno, led, servo, attiny
---


# Question
Title: ESP8266 Blink sketch - does not blink / or stays constant
I uploaded the Blink sketch (from the ESP8266 examples, in the Arduino IDE) successfully.

Depending on which wire configuration I am using two different things happen:

`wiring 1`:

```
CH_PD -> 3.3V
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

```

`wiring 2`:

```
VCC -> 3.3V
RST -> GND
GPI02 -> LED
GND -> GND

```

There are TX/RX lines in the picture from when I was flashing - they aren't being used for running the sketch.

With `wiring 1` the LED stays on (doesn't blink) - I was wondering if this was because I still had the VCC -\> 3.3V connected. So I disconnected that, which gives way to `wiring 2`.

With `wiring 2` the LED doesn't come on at all, it is the same as `wiring 1` except without VCC -\> 3.3V.

Why is it constant when 3.3V is going to VCC, and constantly off when I disconnect it? Why doesn't it blink using `wiring 2`?

**UPDATE**

A diagram as requested, sorry it was my first time doing this:

Code:

```
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

```

# Answer
You should connect Vcc to 3.3V, because that's how the ESP8266 is powered. RST is active-low reset and should be pulled to 3.3V
> 3 votes

# Answer
I can't comment as my karma is too low so if I am wrong please just someone let me know and I'll simply delete.

I thought that the RST pin being pulled to ground resets the chip, if this is the case surely in your setup you are constantly reseting your chip, so it won't do anything. My understanding is that you should have the reset pin pulled up to 3.3V with a 10K resistor.
> 1 votes

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


title: How to connect DRV-8835 to arduino

text:
# Question
Title: How to connect DRV-8835 to arduino
I try to connect arduino with motor using DRV-8835. The problem I have - simply nothing happens. I used tutorial from http://www.instructables.com/id/The-SnapMobile-Start-Your-Physical-Computing-Engin/step6/Building-the-Prototype-Wiring-Up-the-Arduino-the-D/

Code for arduino:

```
void setup() {
    pinMode(7, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
  analogWrite(5, 255);
}

```

Maybe someone has scheme how to connect wires to motor. Now I'm not sure if I made a mistake or motor driver is broken.

# Answer
Try this code:

```
void setup() {
    pinMode(8, OUTPUT);//MODE
    pinMode(5, OUTPUT);//AENBL
    pinMode(7, OUTPUT);//APHASE
}

void loop() {
  pinMode(7, HIGH);//APHASE
  pinMode(8, HIGH);//MODE
  pinMode(5, HIGH);//AENBL
  delay(200);
  pinMode(5, LOW);//AENBL
}

```

Here is a description of the breakout board, this shows a requirement of PWM on AENBL for speed control. Try different delays.
> 1 votes

# Answer
Setting AENBL HIGH should drive the motor at full speed - it has the same effect as analogWrite(5, 255). Dropping it from high to low should stop the motor.

Are you sure the DRV8835 is working properly? You can in theory diagnose it with a logic analyzer, but a scope will work better as the motor outputs aren't really logic. My test setup (yeah, I had one die on me) watched PHASE (just make sure it would toggle), MODE (should be HIGH), and AENBL (should show a square wave for the PWM duty cycle) as logic inputs, then watched the motor outputs on the scope to verify that one of them is the inverse of AENBL and the other is HIGH. Which follows AENBL and which is HIGH depends on PHASE, so you can toggle it if you can only check one output.
> 0 votes

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


# Question
Title: Conncet Bluetoth module HC-05 to Arduino Uno Using UART Usb to enter in AT command
I have connected Arduino Rx(pin 0) to Bluetooth module Rx pin. Tx od Arduino to Tx of Bluetooth . I am able to send command to Bluetooth module using Serial Monitor of Arduino on my PC.

I have uploaded the empty code in Arduino.

I want to know why we connected Tx to Tx and Rx to Rx i.e one to one connection?

If I send command "AT" from my PC using serial Monitor of Arduino , How is it flowing to Bluetooth module.

Why not we connect Rx to Tx pin in AT Mode of Bluetooth module?

Pls explain using diagram.

# Answer
By using SoftSerial you can connect the HC-05 module to another pin than D0 and D1. Example connect HC-05 to D2 and D3 and define SoftSerial to use D2 and D3.

```
---------                        -----------                        ------
| HC-05 +---(SoftSerial)---(D2/3)+ Arduino +(D0/1)---(Serial USB)---+ PC |
---------                        -----------                        ------

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to get response of issued AT command for ES266 on Arduino programatically?
I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.

**Goal:** After issuing AT commands programatically, knowing whether these run successfully or not.

**Microcontroller:** Arduino Uno

```
#include<string.h>
#include<SoftwareSerial.h>

#define OK "OK"
#define SERVER_PORT 1234
#define RX_PIN 2
#define TX_PIN 3

SoftwareSerial ESP(RX_PIN, TX_PIN);

void setup() {
  Serial.begin(115200);
  Serial.println("First serial");
  while(!Serial);
  ESP.begin(115200);
  Serial.println("Second serial");
  while(!ESP);
  //Enabling multiple connections
  ESP.println("AT+CIPMUX=1\r\n");
  while (!ESP.available());
  String muxResponse = ESP.readString();
  Serial.print("muxR:");
  Serial.println(muxResponse);
}

void loop() {
  if (ESP.available()) {
    String val = ESP.readString();
    Serial.println(val);
  }
}

```

After running the above code I get the response in the Serial Monitor like:

```
muxR:AT+CIPMUX=1

busy p../

OK

```

I'm getting special characters too.

# Answer
change

```
AT+CIPMUX=1\r\n

```

to

```
AT+CIPMUX=1

```
> 1 votes

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


# Question
Title: Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega
I am trying to follow Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?

Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;

```
void analogWrite25k(int value)
{
    OCR4A = value;
    OCR4B = value;
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4A1)
           | _BV(COM4B1)
           | _BV(COM4C1)
           | _BV(WGM11);
    TCCR4B = _BV(WGM13)
           | _BV(CS10);
    TCCR4C = _BV(WGM13)
           | _BV(CS10);
    ICR4   = 320;

    // Set the PWM pins as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

```

edit2:

Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;

```
TCCR4A = 0;
TCCR4B = 0;
TCNT4  = 0;
TCCR4A = _BV(COM4C1)
      | _BV(WGM41);
TCCR4B = _BV(WGM43)
     | _BV(CS40);
ICR4   = 320;         // TOP = 320

```

# Answer
Found a properly working answer for the question finally; Thanks to KIV's answer on Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega to control speed of a 4-wire cpu fan an additional usful thing he has added is to allow setting of duty cycle from serial monitor input for convenience while testing;

```
void analogWrite25k(int value)
{
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCNT4  = 0;

    // Mode 10: phase correct PWM with ICR4 as Top (= F_CPU/2/25000)
    // OC4C as Non-Inverted PWM output
    ICR4   = (F_CPU/25000)/2;
    OCR4C  = ICR4/2;                    // default: about 50:50
    TCCR4A = _BV(COM4C1) | _BV(WGM41);
    TCCR4B = _BV(WGM43) | _BV(CS40);

    Serial.begin(115200);

    // Set the PWM pin as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    int w = Serial.parseInt();
    if (w>0) {
        analogWrite25k(w);
        Serial.println(w);
    }
}

```
> 2 votes

# Answer
easy.

1. find a copy of the datasheet for your mcu;
2. go to the section about your timer;
3. figure out a prescaler setting that yields the maximum roll-over count;
4. pick the timer mode that supports the roll-over count;
5. write your own analogWrite() function;
6. \[optional\] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.
7. done.

edit: i decided to give it a try.

the following code:

```
void setup() {
  // put your setup code here, to run once:
  pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);       //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  analogWrite(9, 20);                           //dc = 20/80=25%
  analogWrite(10, 40);                          //dc = 40/80=50%
}

void loop() {
  // put your main code here, to run repeatedly:
}

```

produced the following output on an ATMega328p's TIMER1.

i'm reasonably sure that the output is indeed 25Khz.

the code itself however is capable of generating pwm at other frequencies.

edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

code used for that is as follows:

```
  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  //DC on Pin 6 = 20/80 = 25,
  //DC on Pin 7 = 40/80 = 50,
  //DC on Pin 8 = 60/80 = 75,
  pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

```

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.
> 3 votes

---
Tags: pwm
---


# Question
Title: Sim800l gsm module cannot connect gprs data
I am a rookie to arduino. I am trying to access MQTT server using Sim800l coreboard GSM module with Adafruit Fona/Tinygsm library but failed.So I decided to check http GET/POST request with AT command first.In AT commands all the basic commands following www.exploreembedded.com/wiki/Setting\_up\_GPRS\_with\_SIM800L works fine but whenever I make a GET request by "AT+CIPSTART=" module restart itself.I also tried seeduino library GPRS\_HTTP example, it gives me "error:CIPSTART" and restarts module.Though this code worked one time only,this is the code

```
#include <gprs.h>
#include <SoftwareSerial.h>

char http_cmd[] = "GET /media/uploads/mbed_official/hello.txt
HTTP/1.0\r\n\r\n";
char buffer[512];

GPRS gprs;

void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("GPRS - HTTP Connection Test...");
gprs.preInit();
while(0 != gprs.init()) {
 delay(1000);
 Serial.println("init error");
}
while(!gprs.join("gpinternet")) {  //change "cmnet" to your own APN
  Serial.println("gprs join network error");
  delay(2000);
}
// successful DHCP
Serial.print("IP Address is ");
Serial.println(gprs.getIPAddress());

Serial.println("Init success, start to connect mbed.org...");

if(0 == gprs.connectTCP("mbed.org", 80)) {
  Serial.println("connect mbed.org success");
}else{
  Serial.println("connect error");
  while(1);
}

Serial.println("waiting to fetch...");
if(0 == gprs.sendTCPData(http_cmd))
{
gprs.serialDebug();
}

//  gprs.closeTCP();
//  gprs.shutTCP();
//  Serial.println("close");
}

void loop() {

}

```

also tried this commands and module got restarted after AT+HTTPACTION=0 this last command

module power and sim configure are fine as far I know,please help me find out what am I doing wrong?Sorry for making this long.please ask me if I couldn't make the question clear.TIA

# Answer
> 2 votes
I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks

---
Tags: arduino-uno, gsm, http
---


title: LED matrix question light up H or 4

text:
# Question
Title: LED matrix question light up H or 4
Just a basic query;

On my understanding of LED Matrix's, The following would light up 4 LEDs.

But what if I only wanted to light up just 3 of those LEDs? The circuit still needs the same inputs, since power will continue across all columns/rows

Thanks

Tom

# Answer
> 3 votes
Multiplexing is the answer.

If you want to, as an example, light up only LEDS 1, 3 and 4, you will:

* activate line A
* activate line X
* de-activate line X
* de-activate lines A and B (yes, B was not active)
* activate line A and B
* activate line Y
* de-activate line Y
* de-activate lines A and B
* start again from top

Do this so that the loop takes less than 10 milliseconds and you are actually refreshing the entire matrix at 100Hz, fast enough to trick the eyes of any human being as if the LEDs 1,3 and 4 are lighted up at the same time: *persistence of vision* is your friend.

# Answer
> 0 votes
This is very simple. You can turn on each LED one at a time and repeat this over and over again. The easiest way of achieving this is to put this code in the loop section.

> Persistence of vision is defined as "the retention of a visual image for a short period of time after the removal of the stimulus that produced it" - dictionary.com

Even though the LED is on for only 1/3 of the time, it is fast enough that the human eye will not be able to tell that each LED turns off. Hence the viewer sees 3 LEDs on at the same time.

This allows any combination of LED patterns in your LED matrix.

7-segment displays also use this technique. You probably have some in a microwave or DVD player that you never realized that they were cycling through each digit, using persistence of vision.

**Resources:**
http://www.circuitstoday.com/interfacing-8x8-led-matrix-with-arduino (recommended) http://tronixstuff.com/2013/10/11/tutorial-arduino-max7219-led-display-driver-ic/
https://playground.arduino.cc/Main/LEDMatrix
http://forum.hobbycomponents.com/viewtopic.php?f=43&t=1489

---
Tags: led
---


# Question
Title: How important is the INT pin of the MPU6050 (GY-521)?
I want to wire multiple MPU6050 (at least 16 of them) to an arduino UNO for development (then nano for production). So I first started wiring one MPU6050 to an arduino like shown on the diyhacking website or in the picture below:  as you can see in the picture above the INT pin is used. I then wearched for a way to wire multiple MPU6050 to an arduino using a multiplexer and I found a way on horizonlab's website or see the picture below:  As you can see in the second picture the INT isn't used at all. I'd like to know how important it is and what I'm missing out by not using it.

# Answer
> 5 votes
The `INT` is the interrupt signal, usually open-drain output and you can connect many of them to the single `MCU` interrupt line (but you have to check all devices which ones are ready). The `LOW` level from `MPU` device signalize that data are ready (conversion was finished). So you don't have to periodically read status register to find it out (no polling is necessary).

In short, using `INT` is optional.

---
Tags: mpu6050, multiplexer
---


title: Referencing Serial output

text:
# Question
Title: Referencing Serial output
I'm confused with what I'm reading.

I have Serial communicating with my PC (USB) and SoftwareSerial over RS485 to a remote PC. I don't want to duplicate all of my print statements to be able to send output to either (or both) terminals. What I want to do is have a single set of print statements (think of a list of error messages) and then be able to output a message to either Serial or SSerial depending on which needs it. Does this make sense?

# Answer
Almost all of those things you do which involve functions like print, println, and write all derive from the Print class. You could have an array of Print objects and print to whichever you like.

```
Print* outs[] = {&Serial, &Serial1, &mySoftSerial};

//  Later somewhere in code:

outs[0]->println("This prints to Serial");
outs[1]->println("This prints to Serial1");
outs[2]->println("This prints to mySoftSerial");

for(int i = 0; i < 3; i++){
  outs[i]->println("This prints to all 3.  You could even make this bit a function");
}

```
> 1 votes

---
Tags: serial, softwareserial
---


# Question
Title: Temperature Controlled fan using arduino project regarding - LCD not displaying anything
I have connected the circuit as per the diagram below and I have got the LCD to display boxes and nothing else. What could be wrong here? Please help!

Circuit diagram below -

Code as follows -

```
#include<DHT11.h>
#include<LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
#define dht11pin 12
dht11 DHT11;
#define pwm 9
byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};
void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Our Project ");
  delay(2000);
}

void loop()
{
  DHT11.read(dht11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF  ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

```

I used the default LiquidCrystal.h library for this project. Is that wrong?

# Answer
> 2 votes
Your constructor doesn't match your wiring:

```
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

```

You have:

```
RS = 7
E = 6
D4 = 5
D5 = 4
D6 = 3
D7 = 2

```

Yet your wiring has:

```
RS = 2
E = 3
D4 = 4
D5 = 5
D6 = 6
D7 = 7

```

I.e., completely backwards.

The constructor prototype is:

```
LiquidCrystal(rs, enable, d4, d5, d6, d7)

```

Yet you seem to have chosen to ignore (or misunderstand) that.

Instead you need to specify your pins *correctly*:

```
LiquidCrystal(2, 3, 4, 5, 6, 7);

```

Also, as a side note, you don't have a ground connection to that little 9V circuit off to one side - so you will never be able to control it. Read this.

---
Tags: lcd
---


# Question
Title: serial data transfer on gps shield duinopeak
I'm using an arduino uno r3 with a gps shield duinopeak.

The shield is configured using RX pin 3 and Tx pin 2, as image below:

I'm using the TinyGPSPlus library to read NMEA data. This is my code:

```
/******************************************************************************
  This example uses SoftwareSerial to communicate with the GPS module on
  pins 8 and 9, then communicates over SPI to log that data to a uSD card.

  It uses the TinyGPS++ library to parse the NMEA strings sent by the GPS module,
  and prints interesting GPS information - comma separated - to a newly created
  file on the SD card.

  Resources:
  TinyGPS++ Library  - https://github.com/mikalhart/TinyGPSPlus/releases
  SD Library (Built-in)
  SoftwareSerial Library (Built-in)

  Development/hardware environment specifics:
  Arduino IDE 1.6.7
  GPS Logger Shield v2.0 - Make sure the UART switch is set to SW-UART
  Arduino Uno, RedBoard, Pro, Mega, etc.
******************************************************************************/

#include <SPI.h>
#include <SD.h>
#include <TinyGPS++.h>

#define ARDUINO_USD_CS 8 // uSD card CS pin (pin 8 on Duinopeak GPS Logger Shield)

/////////////////////////
// Log File Defintions //
/////////////////////////
// Keep in mind, the SD library has max file name lengths of 8.3 - 8 char prefix,
// and a 3 char suffix.
// Our log files are called "gpslogXX.csv, so "gpslog99.csv" is our max file.
#define LOG_FILE_PREFIX "gpslog" // Name of the log file.
#define MAX_LOG_FILES 100 // Number of log files that can be made
#define LOG_FILE_SUFFIX "csv" // Suffix of the log file
char logFileName[13]; // Char string to store the log file name
// Data to be logged:
#define LOG_COLUMN_COUNT 8
char * log_col_names[LOG_COLUMN_COUNT] = {
  "longitude", "latitude", "altitude", "speed", "course", "date", "time", "satellites"
}; // log_col_names is printed at the top of the file.

//////////////////////
// Log Rate Control //
//////////////////////
#define LOG_RATE 5000 // Log every 5 seconds
unsigned long lastLog = 0; // Global var to keep of last time we logged

/////////////////////////
// TinyGPS Definitions //
/////////////////////////
TinyGPSPlus tinyGPS; // tinyGPSPlus object to be used throughout
#define GPS_BAUD 9600 // GPS module's default baud rate

////////////////////////////////////////////////
// Arduino GPS Shield Serial Port Definitions //
////////////////////////////////////////////////
// If you're using an Arduino Uno, Mega, RedBoard, or any board that uses the
// 0/1 UART for programming/Serial monitor-ing, use SoftwareSerial:
#include <SoftwareSerial.h>
#define ARDUINO_GPS_RX 3 // GPS TX, Arduino RX pin
#define ARDUINO_GPS_TX 2 // GPS RX, Arduino TX pin
SoftwareSerial ssGPS(ARDUINO_GPS_TX, ARDUINO_GPS_RX); // Create a SoftwareSerial

// Set gpsPort to either ssGPS if using SoftwareSerial or Serial1 if using an
// Arduino with a dedicated hardware serial port
#define gpsPort ssGPS  // Alternatively, use Serial1 on the Leonardo

// Define the serial monitor port. On the Uno, Mega, and Leonardo this is 'Serial'
//  on other boards this may be 'SerialUSB'
#define SerialMonitor Serial

void setup()
{
  SerialMonitor.begin(9600);
  gpsPort.begin(GPS_BAUD);

  SerialMonitor.println("Setting up SD card.");
  // see if the card is present and can be initialized:
  if (!SD.begin(ARDUINO_USD_CS))
  {
    SerialMonitor.println("Error initializing SD card.");
  }
  updateFileName(); // Each time we start, create a new file, increment the number
  printHeader(); // Print a header at the top of the new file
}

void loop()
{
  if ((lastLog + LOG_RATE) <= millis())
  { // If it's been LOG_RATE milliseconds since the last log:
    if (tinyGPS.location.isUpdated()) // If the GPS data is vaild
    {
      if (logGPSData()) // Log the GPS data
      {
        SerialMonitor.println("GPS logged."); // Print a debug message
        lastLog = millis(); // Update the lastLog variable
      }
      else // If we failed to log GPS
      { // Print an error, don't update lastLog
        SerialMonitor.println("Failed to log new GPS data.");
      }
    }
    else // If GPS data isn't valid
    {
      // Print a debug message. Maybe we don't have enough satellites yet.
      SerialMonitor.print("No GPS data. Sats: ");
      SerialMonitor.println(tinyGPS.satellites.value());
    }
  }

  // If we're not logging, continue to "feed" the tinyGPS object:
  while (gpsPort.available())
    tinyGPS.encode(gpsPort.read());
}

byte logGPSData()
{
  File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

  if (logFile)
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.
    logFile.print(tinyGPS.location.lng(), 6);
    logFile.print(',');
    logFile.print(tinyGPS.location.lat(), 6);
    logFile.print(',');
    logFile.print(tinyGPS.altitude.feet(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.speed.mph(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.course.deg(), 1);
    logFile.print(',');
    logFile.print(tinyGPS.date.value());
    logFile.print(',');
    logFile.print(tinyGPS.time.value());
    logFile.print(',');
    logFile.print(tinyGPS.satellites.value());
    logFile.println();
    logFile.close();

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

// printHeader() - prints our eight column names to the top of our log file
void printHeader()
{
  File logFile = SD.open(logFileName, FILE_WRITE); // Open the log file

  if (logFile) // If the log file opened, print our column names to the file
  {
    int i = 0;
    for (; i < LOG_COLUMN_COUNT; i++)
    {
      logFile.print(log_col_names[i]);
      if (i < LOG_COLUMN_COUNT - 1) // If it's anything but the last column
        logFile.print(','); // print a comma
      else // If it's the last column
        logFile.println(); // print a new line
    }
    logFile.close(); // close the file
  }
}

// updateFileName() - Looks through the log files already present on a card,
// and creates a new file with an incremented file index.
void updateFileName()
{
  int i = 0;
  for (; i < MAX_LOG_FILES; i++)
  {
    memset(logFileName, 0, strlen(logFileName)); // Clear logFileName string
    // Set logFileName to "gpslogXX.csv":
    sprintf(logFileName, "%s%d.%s", LOG_FILE_PREFIX, i, LOG_FILE_SUFFIX);
    if (!SD.exists(logFileName)) // If a file doesn't exist
    {
      break; // Break out of this loop. We found our index
    }
    else // Otherwise:
    {
      SerialMonitor.print(logFileName);
      SerialMonitor.println(" exists"); // Print a debug statement
    }
  }
  SerialMonitor.print("File name: ");
  SerialMonitor.println(logFileName); // Debug print the file name
}

```

Basically the code get the values os lat, long, alt, etc and log into csv file on sdcard. Unfortunately I'm always get no gps data. What's wrong with my code?

**Update:**

Test serial connection with this code:

```
#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor to open
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
  altSerial.println("Hello World");
}

void loop() {
  char c;

  if (Serial.available()) {
    c = Serial.read();
    altSerial.print(c);
  }
  if (altSerial.available()) {
    c = altSerial.read();
    Serial.print(c);
  }
}

```

I just receive the menssage "AltSoftSerial Test Begin", so the problem may be the serial port?

# Answer
> 1 votes
The comments in the AltSoftSerial Test say that you have to connect the GPS to pins 8 (RX for GPS TX) and 9 (TX for GPS RX). Your shield does not have jumpers for those pins, but you could use a jumper wire to connect any of the TX pins (0-7) to Arduino pin 8 (on the edge of the shield).

I would also recommend looking at my NeoGPS library. It's smaller, faster, more accurate and more reliable than all other GPS libraries. Even if you don't use it, there are lots of tips on the Troubleshooting page.

Be sure to read about choosing a serial port for the GPS device. That's especially important. In your case, you could use pins 0 and 1. `SoftwareSerial` is the worst choice and is NOT recommended.

There is also an NMEASDlog example. Unlike examples from other libraries, the NeoGPS examples will reliably work at high update rates and with slow SD cards.

NeoGPS is also available from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.

---
Tags: arduino-uno, serial, softwareserial, gps, tinygps
---