title: How to read data from an NI DAQ?

text:
# Question
Title: How to read data from an NI DAQ?
I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are other sensors for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?

Some other points:

1. I also have Arduino Ethernet Shield, if required.
2. The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
3. If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices. Is it possible to install this driver on Arduino?
4. I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

# Answer
Unlikely.

First you would need a USB shield to be able to plug it in.

Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.
> 1 votes

# Answer
The main answer for your question is already given by Majenko, and is "no". These protocols are much more complicated than you can think, so no way.

However, if I correctly interpret your point 2 (which is The final goal is to have logged data synced so out of the box solutions are also acceptable for me), you don't need to do this. Just use your PC (or raspberry) to collect all the data and make a synchronization inside it. For instance, connect the arduino to the PC via bluetooth, add a serial connection in the labview program and then send all the data the arduino records to the serial peripheral; you will get all the infos in the labview program.

If for any reason this is not possible, you can use a common signal to sync the acquisitions. For instance, when you start the measurements you let the DAQ generate a long pulse (let's say 100ms), then every second or minute it will generate a shorter pulse (let's say 10ms); the arduino also records this signal, so you will have a way to sync acquisitions. Or you can do the opposite: the arduino generates and the DAQ records.

To sum up, the arduino is not capable of doing what you request, but maybe what you need is not what you asked for...
> 1 votes

---
Tags: sensors, datalogging
---


title: CH340 3.3v stability

text:
# Question
Title: CH340 3.3v stability
I want to use the 3.3v on a cheap Arduino Nano clone as my ADC analog reference voltage. The 3.3v comes from a regulator inside the CH340 USB serial chip.

I've measured the voltages (My DMM is NOT calibrated) on seven different Nanos and the voltages vary (2.96-3.38v).

I'm happy to calibrate each board to this voltage, but are there any figures available on how stable this 3.3v supply is? Long term and temperature wise?

# Answer
> 1 votes
Using the VCC as voltage reference is ok only if

1. you accept poor performances or
2. you need to measure a ratiometric output.

Case 2 is because the output depends on VCC (so you compensate). For instance, if you want to get the value of position in a potentiometer, you have that the voltage you see is `Vo = Vcc * X` (where 0\<=X\<=1 is the position), then the result you have on your ADC is `Y = Vi / Vcc * k = X * k` (where k is the maximum value of the ADC reading - e.g. 1023). So you actually compensate the Vcc deviation.

If you want to measure an absolute voltage, however (case 1) you will have a lot of uncertainties. For instance, if your current varies during the time (for instance you turn on the LED), the Vcc voltage can vary quite a lot. This is why for precise measurements you always must use a voltage reference.

In your case, you can

1. Use the internal reference - for the Atmega328 it is nominally 1.1V, but it can range from 1.0V to 1.2V
2. Use an external reference

You have to keep in mind that the voltage reference is the maximum value you can read. For instance, if you use the internal reference and then try to measure a 2.3V, you will not be able to do it (you will read the maximum value of 1.1V)

In order to fix this, you can use a trick: use Vcc as reference, and then use a voltage reference to get a precise calibration every time you need to measure something. For instance, if you have to read values from ADC1 and ADC3, you can

1. Read the value of the internal/external reference
2. Read ADC1
3. Read ADC3
4. Use the reading in point 1 to be able to guess what ADC1 and ADC3 readings were

This way you compensate for variations in the supply.

Just note that, even if the internal reference is not very precise (it has a 10% deviation from the standard value), it is indeed stable, while the VCC varies (a lot) during time. So if you have to calibrate, calibrate against the internal reference and not the Vcc.

If you can afford an external voltage reference, these are usually very stable and have very little deviation from sample to sample, so you may assume their value is "fixed"

---
Tags: voltage, ch340
---


title: Error with pointer in array

text:
# Question
Title: Error with pointer in array
I am currently learning pointers. I am following a book (Says Teach Yourself "Arduino Programming") in which there is an exemple about pointer and array.

```
void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);

  char string1[] = "This is my test string";
  char string2[]="This is another string test";
  char *ptr2 = string2;
  char *ptr1 = string1;

  while (*ptr1 != '\0') { // not "\0"
    *prt2 = *prt1;
    ptr1++;
    prt2++;
  }
  Serial.println(string1);
  Serial.println(string2);
}

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

}

```

I get an error "ptr2 was not declare in this scope."

I don't know what is wrong...

That for your help.

# Answer
> 1 votes
"ptr2" != "prt2"

You have a typo there.

---
Tags: pointer, compilation-errors
---


title: Arduino GSM shield code help

text:
# Question
Title: Arduino GSM shield code help
Trying to run the below code but getting the following error message:

> exit status 1 expected unqualified-id before '==' token

Code is as follows:

```
==============================================
= Arduino SOS CAll sim900 shield Project =
= with Arduino =
= http://www.mrmodder.com =
==============================================
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "call.h"

#define ACTIVE LOW

const int ledPin = 13; // the number of the LED pin

CallGSM call;
boolean started=false;
int buttonState = 1;
const int buttonPin = 7; // the number of the pushbutton pin
boolean calling = false;

void setup()
{

Serial.begin(9600);
pinMode(ledPin,OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin,HIGH);
if (gsm.begin(9600))
{
Serial.println("\nstatus=READY");
started=true;
}
else
Serial.println("\nstatus=IDLE");
}

void loop()
{
buttonState = digitalRead(buttonPin);
if (buttonState == ACTIVE) {
if(calling)
{
digitalWrite(ledPin,LOW);
calling = false;
call.HangUp();
delay(1000);
}else
{
calling = true;
digitalWrite(ledPin, HIGH);
delay(1000);
call.Call("+300000000000"); //Insert telephone number here

}

```

https://mrmodder.com/make-a-call-using-gsm-module-arduino/

Have a GSM shield and trying to call a preset number using the above tutorial but I cant get the code to run properly

# Answer
> 0 votes
**This is where the problem is:**

==============================================

= Arduino SOS CAll sim900 shield Project =

= with Arduino =

= http://www.mrmodder.com =

==============================================

**COMMENT THIS WHOLE TEXT using**

**/\* \[insert text here\] \*/**

---
Tags: arduino-uno, compilation-errors
---


# Question
Title: How to only detect the opening and closing of door sensor once
im quite new to Arduino coding. Currently im trying to create an alarm and when the alarm ring, the user will just need to remove the door sensor once to stop the alarm and listen for the next alarm. What i have is Real Time clock module to keep track of the time.

So i have tried to code on my own but failed and here's the outcome: After the alarm ring, and i remove the door sensor from each other, it stopped buzzing (Which is correct partly) but once i put it back together, it continued to ring for the alarm duration (Which was set as 1 min)

Here's the code i had:

```
#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
DS3231  rtc(SDA, SCL);
Time  t;
#define buz 11      //This is Buzzer that is plug into pin 11 (Change it accordingly to what you will be putting it in the arduino)
int Hor;            // This is declaring the alarm in Hours
int Min;            // This is declaring the alarm in Minutes
int Sec;            // This is declaring the alarm in Seconds
const int sensor = 10;    // Door sensor connected to Pin 10
int state; // 0 close - 1 open switch

void setup()
{
  Wire.begin();
  rtc.begin();
  Serial.begin(9600);
  pinMode(buz, OUTPUT);
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Alarm");
  lcd.setCursor(0,1);
  lcd.print("Test");
  // The following lines can be uncommented to set the date and time
  //rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
  delay(2000);
  pinMode(sensor, INPUT_PULLUP);
}

void loop()
{
  t = rtc.getTime();
  Hor = t.hour;
  Min = t.min;
  Sec = t.sec;
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(rtc.getDateStr());

  alarm1();
  alarm2();
  delay(1000);
}

void Buzzer()
{
  digitalWrite(buz,HIGH);
  delay(500);
  digitalWrite(buz, LOW);
  delay(500);
}

void alarm1() //E.g. This is the first alarm for the medicine
{
  state = digitalRead(sensor);
  if( Hor == 20 && (Min == 11 || Min == 12) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else if ( Hor == 20 && (Min == 11 || Min == 12) && state == 1)
  {
    noTone(buz);
  }
  delay(200);
}

void alarm2()
{
  if( Hor == 19 && (Min == 48 || Min == 49) && state == 0) //Comparing the current time with the Alarm time
  {
      Buzzer();
      lcd.clear();
      lcd.print("1st Alarm ON");
      lcd.setCursor(0,1);
      lcd.print("Morning Medicine");
     }
  else
  {         //Once user open the door sensor, the alarm will stop buzzing
    noTone(buz);
    alarm1();
  }
  delay(200);
}

```

Just to clarify that the variable state i took from

http://www.instructables.com/id/How-to-Use-a-Magnetic-Door-Switch-Sensor-With-Ardu/

So to summarised my problem, i am trying to get the system to read the opening of the door sensor **once** so that the alarm will stop and listen to the next alarm regardless if i put it back the door sensor or not Really hope someone can help me thanks for you kind attention

# Answer
> 1 votes
As often, the answer to this question is “Implement a ‘Finite State Machine.’”. In this instance, you need at least three distinct states:

* `ARMED`: the buzzer is not active, but it is only a matter of time...
* `ON`: bzzzz... bzzzz... bzzzz...
* `STOPPED`: the user has stopped the alarm.

Each of your alarms should have a start time and a stop time (say, two minutes after the start time). Then, the possible state transitions are:

* `ARMED``ON`: when we hit the `start` time of an alarm
* `ON``STOPPED`: when the user stops the alarm
* `ON``ARMED`: when we hit the `stop` time of the alarm
* `STOPPED``ARMED`: when we hit the `stop` time of the alarm

Notice that, once the user stops the alarm, the only way for the buzzer to start buzzing again is by going through the transitions `STOPPED``ARMED``ON`. The first transition happens at the alarm's stop time, whereas the second one happens at the next alarm's start time.

You did use a kind of state variable in your code, but the problem is you failed to realize that `ARMED` and `STOPPED` should be distinct states. If you fuse these states together then, when the user stops actively “stopping” the alarm, and if it's still `start` time, the system transitions immediately back to the `ON` state.

---
Tags: arduino-uno, arduino-ide, code-review, ds3231-alarms
---


# Question
Title: Analog input draws current when Arduino is turned off
I am using a Arduino Pro Micro from SparkFun (similar to Arduino Leonardo, cpu: Atmega 32u4). It has a analog input: A0, which I use to keep track of the battery voltage in my battery powered project (via analogRead).

I found out that the red LED on the board lights up, even if there is no supply voltage on the usual inputs (micro-USB or Vcc). If I use a multimeter to measure the current between the battery and A0, I see that the analog input is drawing about **30mA** if the Arduino is not powered.

Is this the normal behaviour? Can I fix this via hardware?

# Answer
Yes, it is normal behaviour, and it's called *back-powering*.

The current is flowing into the input pin and then flowing up through the ESD protection diode inside the chip to VCC. It's bad, because the ESD protection diode can't take much current and is easy to damage.

simulate this circuit – Schematic created using CircuitLab

You can prevent it from happening by adding some isolation into the input:

simulate this circuit

MOSFET M1 will be ON when VCC has power, but off when it doesn't. The 100kΩ resistor pulls the gate to ground when VCC is off so it doesn't float. The diode is the body diode of the MOSFET added for clarity. You don't need to add a diode there.
> 3 votes

# Answer
That's probably due to the clamping diodes. To protect the chip against ESD, there are diodes between the pins and Vcc and ground. This is to make sure that when charge builds up on a pin, it can flow to Vcc (when it's higher than the supply voltage) or to ground (when it's lower than ground level).

If you supply a voltage to a pin without a voltage on Vcc, current will flow through the pin to the supply line, powering the circuit.

You could probably solve this by adding a relatively large resistor in series with the pin.
> 0 votes

# Answer
This is normal, if you *abuse* the chip in this fashion.

But you must take into consideration that it is strictly prohibited to apply a voltage to any I/O pin when the chip itself is unpowered.

This is because the protection diodes are not rated to supply power to the chip, and relying on them to do so may cause damage.

The literal statement of this rule is in the data sheet as

> Voltage on any Pin except RESET with respect to Ground . . . . . . . . . .-0.5V to VCC+0.5V

If VCC is 0v, then the maximum voltage you may apply to any I/O is half a volt which is approximately (or just below) the point where a protection diode would begin to meaningfully divert current from the I/O to trying to lift the Vcc net of the chip, and likely the entire board.
> 0 votes

---
Tags: power, led, analogread, atmega32u4, faq
---


# Question
Title: Arduino ESP8266 direct/fast control of the digital pins
How does one control a digital pin directly avoiding the slow digitalWrite or digitalRead?

# Answer
After a weekend of searching and trying, here is what I was looking for:

It is slightly different than for the AVR chips. There is one register for setting the pins to HIGH and another one to set the pins to low.

Setting the pin HIGH:

```
GPOS = (1 << PIN_OUT);

```

Setting the pin LOW:

```
GPOC = (1 << PIN_OUT);

```

using this, I managed to speed up my code by a factor of three. It is not as dramatic as for the AVR chips, since the digitalWrite function is much more simple for the ESP8266.

**Edit Further experiments show it is 10x faster**: 910nsec for `digitalWrite` vs. 88nsec using `GPOC` or `GPOS`!
> 10 votes

# Answer
Unfortunately, Ratchet Freak's answer is specific to AVR, and isn't how the ESP8266 works.

It looks like the ESP8266 does indeed have registers for doing exactly this, which would let you set all 16 GPIO pins (GPIO0 through GPIO15, 16 is a different thing entirely) with a single operation. There's also a SET register, which sets the pins corresponding to 1 bits, and ignores pins corresponding to 0 bits, and a CLEAR register, which is the other way around.

Something I found on a forum said a user went from ~800KHz to ~5.7MHz toggling pins using these direct registers, that sounds about right.

One version of this is found in `eagle_soc.h`. The relevant bits from the header to get you started:

```
#define GPIO_REG_READ(reg)                         READ_PERI_REG(PERIPHS_GPIO_BASEADDR + reg)
#define GPIO_REG_WRITE(reg, val)                 WRITE_PERI_REG(PERIPHS_GPIO_BASEADDR + reg, val)
#define GPIO_OUT_ADDRESS                         0x00
#define GPIO_OUT_W1TS_ADDRESS             0x04
#define GPIO_OUT_W1TC_ADDRESS             0x08

```

So, if I've understood this correctly (and I haven't done any real testing, just going off the spec sheet and the header and posts elsewhere):

```
GPIO_REG_WRITE(GPIO_OUT_ADDRESS, 0xF0F0);

```

would set GPIO 4-7 and 12-15 to high, and 0-3 and 8-11 to low. In one operation. But there's more! Look at those `W1TS` and `W1TC` names. Those are set and clear registers. Which means you *don't* have to mask things. Instead of grabbing the current value, masking a bit in or out, and then writing it back, you can use those:

```
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, 0x1);

```

This will set GPIO0 high, and not affect any other bits.

This is also offered in a cleaner/simpler (??) form in `esp8266_peri.h`, which simplifies it to:

```
GPOS = 0x1;

```

for setting a bit. This is what's actually called by the arduino library's digitalWrite (for pins other than GPIO16):

```
extern void ICACHE_RAM_ATTR __digitalWrite(uint8_t pin, uint8_t val) {
  pwm_stop_pin(pin);
  if(pin < 16){
    if(val) GPOS = (1 << pin);
    else GPOC = (1 << pin);
[...]

```

But definitely be aware of this if you're doing anything fast, because writing multiple pins with a single operation is going to be *way* faster than multiple function calls. Without this, this chip can't even toggle bits as fast as a 16MHz Arduino.
> 5 votes

# Answer
In the spec sheet you will find the details for your device but most of the time it's pretty simple.

There will be global variables to control them, each will control various aspects of the pins.

For example you will have a register to control whether it's input or output, a register to control the output state, ... Again read the spec for your device to know what is what.

After the pin has been set up the instruction to set a pin high is:

```
PORTA |= PINx_MASK;

```

where Pinx\_MASK is a bit mask with a single bit set according to the pin it represents.

To set the pin low it's similar:

```
PORTA &= ~PINx_MASK;

```

To set multiple pins on the port to different values you can do the following:

```
PORTA = (PORTA & ~pinsMask) | pinValues;

```

where pinsMask is a bitmask where all the pins you want to change are set and pinValues is the bitmask of which pins should be set high.

It pays to know how to manipulate bits in bitmasks but that's out of scope for this answer.

The SDK will be doing direct port manipulation itself, if you follow the definitions you should be able to figure it out.
> -1 votes

---
Tags: esp8266
---


# Question
Title: ESP8266 Send data to Firebase using Arduino Uno error
Good day everyone! I have a project, in which the data from a button (number of clicks) will be sent to a real-time Firebase database. Every time the button is clicked the counter increases and will be updated in the firebase database.

**Wifi Module: Esp8266 Esp-01 + Esp-01 Adapter**

In my understanding, there are 2 ways to use this wifi module.

1. Upload the code to the Arduino Uno and use AT commands in the module to send data to the web.
2. Upload the code inside the WiFi Module itself and after that it can be a standalone SOC and does not need the Arduino anymore after the code has been uploaded.

I have tried the second way, but I got confused and stuck. So far I have successfully plugged the adapter in a breadboard and tested some AT commands.

Since I will be using the second way I won't be using these. So I tried this code:

```
 #include <ESP8266WiFi.h>
 #include <FirebaseArduino.h>

 #define FIREBASE_HOST "https://duck-917ba.firebaseio.com/"
 #define FIREBASE_AUTH "r3jNQCsxN2Y2dcfawimRlzjLjdBSXLjstwGeyB0oMK"

 #define WIFI_SSID "mywifi"
 #define WIFI_PASSWORD "621533515"

const int  buttonPin = 8;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setInt("clicks",0);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
      Firebase.setInt("clicks", buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(100);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;
}

```

**So I have plugged my 4-pin adapter to the following:**

* ARD(TX)-ADAPTER(TX)
* ARD(RX)-ADAPTER(RX)
* ARD(5V)-ADAPTER(VCC)
* ARD(GND)-ADAPTER(GND)

I have set the Generic ESP8266 Module Board.

**Problems Encountered:**

I am supposed to select the port of the ESP8266 but I only see the Arduino UNO port in the port list. When I compile the code I get this error:

I am now confused on what the error is all about. I thought since I am using an adapter I can use the **PROGRAMMING MODE** of the module easily. But it seems like my adapter is not doing its job. According to some of my research I have to use TTL or FTDI USB-to-serial dedicated module / Ground some wires while compiling which is very confusing for a beginner like me.

**So here are my final thoughts:**

1. Can I input/flash code in my module using my Arduino and adapter?
2. Since the button is plugged in the Arduino's pin 8, does that mean that the code in the module will be successfully inserted? I will still need the Arduino to be plugged in the buttons?
3. What could be the reason why the module won't appear in the Port List and generates the errors?

I know this is quite a long and boring topic but I know a lot of aspiring IOT developers out there are having the same issues about this wifi module. I hope we can solve it together. Thanks!

# Answer
> 1 votes
> 1.) Can I input/flash code in my module using my arduino and adapter?

Yes

> 2.) Since the button is plugged in the pin 8 of arduino. Does that mean If the code in the module will be successfully inserted. I will still need the arduino to be plugged in the buttons?

The ESP8266 cannot magically know about the Arduino and the Arduino cannot magically know about the buttons. If you have buttons connected to the Arduino then the Arduino needs telling about them. If the Arduino and ESP8266 need to work together then they both need programming to work together. If, and only if, you connect the buttons to the ESP8266 and not the Arduino do you not need the Arduino.

> 3.) What could be the reason why the module won't appear in the Port List and generates the errors?

The Arduino is getting in the way. Connect Arduino RESET to Arduino GND to disable the ATMega328p chip which is also trying to use TX and RX and conflicting with the ESP8266. Or better still get a cheap USB to UART cable (just a couple of dollars on eBay) and connect the adaptor direct to your PC without the Arduino.

# Answer
> 0 votes
Connect GP00 to ground This is required to flash ESP8266

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


title: Use an L293D with Arduino

text:
# Question
Title: Use an L293D with Arduino
I am making a 2-wheeled Arduino car controlled by T.V. remote for a science fair tomorrow. I have found a tutorial for the IR part. I brought this L293D motor driver to control a 2-wheeled car. I am facing a problem. I know where to connect the motors (because there are indications stating M1 and M2) but I don't know where to connect the motor driver to the Arduino and to the batteries.

I checked over the net but couldn't find any tutorial for this kind of board. Also I have no experience in all this so I don't want to risk it. I don't want any code or anything, just where to connect what.

Any help is appreciated.

# Answer
All the inputs are clearly marked.

The battery connects to +12V and GND The Arduino's 5V and GND connect to 5V and GND.

The control signals connect to the header of control signals. ENx is the PWM signal for the speed for motor X. IN1/IN2 are the direction/brake controls for motor 1, and IN3/IN4 are the direction/brake controls for motor 2.

The signal labels are exactly the same as the pin names for the chip and match up precisely with every single tutorial on the net for using the L293D with the Arduino.
> 0 votes

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


# Question
Title: Speed measurement from lidar sensor for automatic braking system
For a school project I have been working on a system that will automatically brake when there is danger. Only the requirements are more strict (safety) than just using a ping sensor and detecting a fixed distance. I am going to implement the speed of an incoming object a swell.

On the internet I found this awesome 100Hz sample Lidar module that's very cheap. It uses UART with 2 header frames (0x59), after that a data Lowbyte and a data Highbyte.

So I've started inputting coffee and outputting code (in C) on the atmega328P (Arduino). Only I'm stuck for a few days now.

As you can see here I've set up the code to read the sensor and process the data. The problem is that it gives back weird readings, like a distance difference when I'm moving further away AND when moving closer even though I stated it not to.

Does anyone have experience using this module? Or maybe I misread something of the datasheet.

```
//Includes
//============================================================================================//
#include <avr/io.h>
#include <avr/interrupt.h>
#include <math.h>
//============================================================================================//

//Defines
//============================================================================================//
#define F_CPU 16000000                                          //CPU frequency
#define Baudrate 115200                                         //UART Baudrate
#define UBRR_VALUE (((F_CPU / (Baudrate * 8))) - 1)             //UART Baudrate set in Arduino
// #define SafetyRating 8
// #define sampleTime 0x65                                          //Time between 2 samples in 10^-4. This value comes from testing (its 1,01ms)
//============================================================================================//

//Enums
//============================================================================================//
enum {Safe, Warning, Danger}State;                              //Possible States
//============================================================================================//

//Global variables
//============================================================================================//
uint8_t distanceL;                                              //Distance (low value) data taken from the UART buffer coming from Lidar
uint8_t distanceH;                                              //Distance (high value) data taken from the UART buffer coming from Lidar
uint16_t Distance;                                              //Distance combined
uint8_t frameByteCount = 0;                                     //To count which byte in the frame is current
uint16_t Speed;                                                 //Speed variable
//volatile uint8_t DangerLevel;                                 //Danger indicator

//Function prototypes
//============================================================================================//
void calcSpeed(uint16_t Measurement);                       //Function to calculate the speed out of distance readings
void UART_Transmit(uint8_t data);                               //Funtion to send data via uart
//============================================================================================//

//Interrupts
//============================================================================================//
/*UART receive complete interrupt*/
ISR(USART_RX_vect)                                              //Data taken from the UART buffer
{
    uint8_t sample;

    sample = UDR0;                                              //Read a sample from the receiver buffer

    if(frameByteCount == 3)                                     //If its the 4th byte of the frame
    {
        frameByteCount = 0;                                     //Reset the counter
        distanceH = sample;                                     //Read the distance data high byte
        Distance = (8 << distanceH);                            //Combine the data low and data high
        Distance |= distanceL;

        calcSpeed(Distance);                                //Send the data to laptop for debugging purposes

    }

    if(frameByteCount == 2)                                     //If its the 3rd byte in the frame read the distance data low byte
    {
        distanceL = sample;
        frameByteCount++;                                       //Increment the counter
    }

    if (sample == 0x59)                                         //If a sample is a header increment a counter
    {
        frameByteCount++;
    }
    else if (frameByteCount != 2 && frameByteCount != 3)        //If its not a header or distance data byte reset counter
    {
        frameByteCount = 0;
    }
}
//============================================================================================//

//Timers and Counters
//============================================================================================//
/*Timer0 Counter, this decreases the danger level periodically so a really slow approach will not keep incrementing the danger level*/
ISR(TIMER0_OVF_vect)
{
//  if (DangerLevel > 0)
//  {
//      DangerLevel--;
//  }
}
//============================================================================================//

//Main
//============================================================================================//
int main(void)
{
    DDRB    |=      0x02;                                       //For debugging purposes LED pin PB1 (pin 9) as output

    UBRR0H = (UBRR_VALUE >> 8);                                 //Setting the Baudrate register high value
    UBRR0L =  UBRR_VALUE;                                       //Setting the Baudrate register low value
    UCSR0A |= (1<<U2X0);                                        //Setting the data sample to double speed to make Baudrate error less
    UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00);                        //Initializing UART, setting frame to 8 data bits
    UCSR0B |= (1<<RXCIE0) | (1<<TXEN0) | (1<<RXEN0);            //Setting receiver interrupt enable, transmitter enable and receiver enable... Transmitter for debugging purposes

    TCCR0A = 0x00;                                              //Timer0 Setup
    TCCR0B |= 0x05;                                             //Timer0 clock prescaler to 1024
    TIMSK0 |= 0x01;                                             //Timer0 overflow interrupt enable

    sei();                                                      //Set interrupts

    State = Safe;                                               //Set state to safe

    while (1)
    {
        //checkState(DangerLevel);
    }
}
//============================================================================================//

//Functions
//============================================================================================//
/*Calculate the danger level out of distance readings*/
void calcSpeed(uint16_t Measurement)
{
    static uint8_t samplenumber = 0;                                //Sample tracker
    static uint16_t value0 = 0;                                         //First sample
    static uint16_t value1 = 0;                                         //Second sample

    switch(samplenumber)                                            //To store the measurements alternately
    {
        case 0:
            value0 = Measurement;                                   //Store first measurement
            samplenumber = 1;                                       //So next measurement goes to a different variable
        break;
        case 1:
            value1 = Measurement;                                   //Store 2nd measurement
            samplenumber = 0;                                       //So next measurement goes to a different variable
        break;
        default:
        break;
    }

    if (samplenumber == 0 && value1 < value0)                       //When value0 is first and value1 is second and the object is closing in
    {
        Speed = value0 - value1;
    }
    else if (samplenumber == 1 && value0 < value1)                  //When value1 is first and value0 is second and the object is closing in
    {
        Speed = value1 - value0;
    }
    else
    {
        Speed = 0;
    }
    UART_Transmit(Speed);       //I think sending an uint16_t over uint8_t uart is possible because 'Speed' is never greater than 255 when i'm testing it
}

/*Send data over UART when buffer is empty*/
void UART_Transmit(uint8_t data)
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) )
    ;
    /* Put data into buffer, sends the data */
    UDR0 = data;
}
//============================================================================================//

```

The datasheet for the module: Datasheet Lidar module

# Answer
I found it! Can't believe I was stuck for two days on this.

```
Distance = (8 << distanceH);                            //Combine the data low and data high
Distance |= distanceL;

```

Should be:

```
Distance = (distanceH << 8);                            //Combine the data low and data high
Distance |= distanceL;

```

Thanks all for taking the effort, and i'm definately going to do the experiment above to test the accuracy.
> 1 votes

# Answer
I think you are either getting interference that is corrupting the serial data or reflections from the scattering of the light off the object.

If you are certain that your code is right, which it seems to be, then I think you need to ascertain if the unit is giving you constant readings or not. Can you set up a test that puts the unit at a fixed distance from a reflector and get readings for a minute. The raw readings should all be identical, absolutely no variation. They won't be they will waver around a tiny amount so work out what the percentage variation is for this distance.

Now repeat the test but at double the distance, you should get the same accuracy. Now again at double the distance again and you should have the same level of accuracy.

If the accuracy is varying "significantly" then you will need to generate a calibration table. 'At distance x the accuracy is y', etc.

Reflections will give you intermittent wildly inaccurate results. To combat this you might want to filter the data to remove any data that is more than n times the accuracy away from the previous reading. n has to be a value large enough to cover the maximum distance the reflector (car) can cover in the time between samples. I would guess assuming a maximum speed of 300MPH would be enough for most cases.
> 0 votes

---
Tags: sensors, c, code-review, uart, speed
---


title: Strings from serial are not equal

text:
# Question
Title: Strings from serial are not equal
In my code I have that string:`String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017` It means that `code = "034000017"`. But if I run `if (code.equals("034000017")) Serial.println("OK");` There is nothing in serial monitor. Here is full code:

```
String code, rs1, rs2, rs3, readString;
void setup() {
    Serial.begin(9600);
    Serial.println("Serial ready!");
}

void loop() {
    if (Serial.available()) {
        while (Serial.available()) {
          delay(10);
          if (Serial.available() >0) {
            char c = Serial.read();
            readString += c;
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
          }
        }
    }
}

```

# Answer
> 2 votes
Lots of errors in your code. Mine is basically the same that @frarugi87's answer.

I only have to add: when reading serial, wait for the end of line ('\r' and/or '\n') to know when you have all your data, so you don't depend on length (which can be corrupted).

**Edit (on Majeko's comment)**

```
String code, rs1, rs2, rs3, readString;
void setup()
{
  Serial.begin(9600);
  Serial.println("Serial ready!");
}

void loop()
{
  static bool inData = true;

  while (Serial.available()) {
    char c = (char) Serial.read();

    if (c != '\r' && c != '\n') {
      readString += c;
      inData = true;
    }
    else {
      if (inData) {
        rs1 = readString.substring(0, 3); //034
        rs2 = readString.substring(3, 6); //000
        rs3 = readString.substring(6, 9); //017
        code = rs1 + rs2 + rs3;
        Serial.println(code);

        if (code.equals("034000017")) {
          Serial.println("OK");
        }
        readString = "";
        inData = false;
      }
    }
  }
}

```

This code works for any configuration of line ending ('\r', '\n' or '\r\n').

It doesn't test for length (or validity or timeout); it's left as an exercise to the reader :-)

I hope it shows how code grows when making it robust in all scenarios.

# Answer
> 1 votes
In your code there is a trivial error and a conceptual error.

The trivial error is in line 16, you wrote

```
rs2 = readString.substring(6, 9); //017

```

but it should have been

```
rs3 = readString.substring(6, 9); //017

```

(3 instead of 2)

The conceptual one is that you do not have to check the string every time; if you know that the string must be 9 chars long, check for it:

```
void loop() {
    while (Serial.available()) {
        readString += (char)Serial.read();
        if (readString.length() >= 9) {
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
            readString = "";
        }
    }
}

```

Note that in this code I cleaned up a bit your code, and MOST IMPORTANT I reset the readstring to nothing after the check (otherwise only the first string is accepted)

I left a lot of things as they were (for instance in my opinion using a string in this case is pointless - better use a byte array; or splitting the string in three for joining it again later), since I think this is part of a larger program

---
Tags: serial, string, code-review
---


# Question
Title: How can I make a rotary encoder change between neopixel programs?
I am making a program to use a rotary encoder instead of a button in the buttoncycler example in the Adafruit NeoPixel library.
I am using the US Digital S1-256-250-IE-B-D. Datasheet can be found here:
https://cdn.usdigital.com/assets/datasheets/S1\_datasheet.pdf?k=636466553771569761

```
#include < RotaryEncoder.h >
void setup() {
}
void loop() {
  static int change =  0;
  static int pos = 0;
  static int oldPos = 0;
  //Read the Encoder's state
  encoder.tick();
  int enc = encoder.getPosition();
  pos = abs(enc) % 2;
  change = oldPos-pos;
  if (change != 0) {

    switch (pos) {
      case 0:
      //do a program that lasts 5 seconds
      break;
      case 1:
      //do a program that lasts 5 seconds
      break;
    }
    oldPos = pos;
    change = 0;
  }
}

```

I was wondering if there is a way to change the program immediately after turning the rotary encoder, instead of having to wait for the program to complete.

# Answer
> I was wondering if there is a way to change the program immediately after turning the rotary encoder, instead of having to wait for the program to complete.

There is, but it's not completely trivial. The reason it is not trivial is each animation is implemented as a function that takes a while to execute. For doing what you ask, each of these animations should be modified, with a way to exit early if needed.

One approach would be to manage the rotary encoder using an interrupt. I let you investigate how to do that: you probably can find examples on the Web. Once the encoder reading is interrupt-based, you would need to do the following changes in your program:

At global scope, add

```
volatile bool stop_now = false;

```

This will be a sort of “flag” intended to inform the currently running animation that it should return ASAP.

Then, inside the interrupt handler, add

```
stop_now = true;

```

In loop(), just after `if (change != 0) {`, add

```
stop_now = false;

```

In *each* animation, replace `delay(wait)` with:

```
uint32_t start_time = millis();
while (millis() - start_time < wait) {
    if (stop_now)
        return;
}

```
> 1 votes

# Answer
Your code (if it worked) is right. All you need to do is turn the comments into function calls:

```
#include <RotaryEncoder.h>

// Define global variables
int pos = 0;
int oldPos = 0;

void setup() {
// Do stuff
}

void loop() {
  //Read the Encoder's state
  encoder.tick();
  pos = encoder.getPosition();
  const int change = (oldPos - abs(pos)) % 2;
  switch (change)
  {
      case 0:
        programOne();
        break;
      case 1:
        programTwo()
        break;
    }
    oldPos = pos;
  }
}

void programOne()
{
//Do Stuff
}
void programTwo()
{
// Do stuff
}

```
> 0 votes

---
Tags: neopixel, rotary-encoder
---


# Question
Title: How to pass JsonObject from ArduinoJson to ESP8266WebServer object?
I am learning the `ArduinoJson.h` library and creating jsonOject:

```
JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  JsonObject& root = jsonBuffer.createObject();
  JsonArray& tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray& humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray& dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray& EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);
  return root;
}

```

As per the example given here. However since I am using an `ESP8266WebServer` to create a server object from `ESP8266WebServer.h`, I cannot pass a JsonObject to `server.send(.....)`.

> no matching function for call to 'ESP8266WebServer::send(int, const char \[10\], ArduinoJson::JsonObject&)'

```
void outputJson() {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& json = prepareResponse(jsonBuffer);
  writeResponse(client, json);
  server.send ( 200, "text/json", json );
}

void writeResponse(WiFiClient& clnt, JsonObject& json) {
  clnt.println("HTTP/1.1 200 OK");
  clnt.println("Content-Type: application/json");
  clnt.println("Access-Control-Allow-Origin: *");
  clnt.println("Connection: close");
  clnt.println();
  json.prettyPrintTo(clnt);
}

```

# Answer
As far as I know, the only way is to serialize the `JsonObject` to a `String`:

```
String createJsonResponse() {
  StaticJsonBuffer<500> jsonBuffer;

  JsonObject &root = jsonBuffer.createObject();
  JsonArray &tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray &humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray &dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray &EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);

  String json;
  root.prettyPrintTo(json);
  return json;
}

void outputJson() {
    server.send(200, "text/json", createJsonResponse());
}

```

By the way, I recommend that you use the ArduinoJson Assistant to compute the size of the `JsonBuffer`.
> 1 votes

---
Tags: esp8266, web-server, esp32, json
---


title: Arduino : LCD / POT

text:
# Question
Title: Arduino : LCD / POT
how can I make the repetitions stop at 10 ? Also how can I get the lcd to reset when its off/low ?

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(12,11,5,4,3,2);
const int tiltSensor = 8;
int reps = 0;
int switchState = HIGH;
int prevSwitchState = LOW;

void setup() {
  lcd.begin(16,2); // type of lcd(16 columns and 2 rows)
  pinMode(tiltSensor,INPUT);
  lcd.clear();
  lcd.setCursor(0,0); // the cursor is where on the
  lcd the characters will be placed
  lcd.print("Workout Time"); // print is the characters on the screen
  lcd.setCursor(0,1);
  lcd.print("Lets GO ! ");
}

void loop() {
  switchState = digitalRead(tiltSensor);
  if (switchState != prevSwitchState) {
    if (switchState == LOW) {
      reps = reps + 1;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Reps:");
      lcd.setCursor(0,1);
      lcd.print(reps/10);
    }
  }
  prevSwitchState = switchState;
}

```

# Answer
> 0 votes
> how can I make the repetitions stop at 10 ?

use a loop counter:

```
  if (loop_cnt++ < 10) do_mything();

```

---
Tags: programming
---


title: How to write modular code for arduino?

text:
# Question
Title: How to write modular code for arduino?
I would like to create a program with separated modules, is this this possible using Arduino IDE?

# Answer
> 3 votes
While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.

Specifically, in the Arduino IDE create a new tab with some name `foo.h`, and in your main tab, add `#include "foo.h"` at the top of your code. What this does is essentially copy paste the code from `foo.h` into your code during the build process. While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.

You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."

And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as `delay()` or `Serial` unless you add `#include "Arduino.h"`. However, for IDE versions less than 1.0, use `#include "WProgram.h"`. This will give you access to those functions.

# Answer
> 2 votes
Arduino sketches can include Libraries (see https://www.arduino.cc/en/Guide/Libraries).

In order to work with the Arduino IDE, such a library is required to adhere to a certain folder structure and naming convention (as described in the above guide).

Other than that, it's similar to modularized code in any other language. The canonical language in Arduino libraries is C++.

Since a regular Arduino IDE installation already comes preinstalled with a multitude of libraries, you can take a look and go from there.

I recommend that you look through the example sketches (from the "Examples" menu option). Whenever you see an #include statement at the top of the sketch, you have a hint where to look next in order to gain a better understanding about the inner works.

# Answer
> 0 votes
The sketch code can be easily split into several files by creating a **new tab** (file) **without file name extension or .ino** (source). No need for `#include`s as the Arduino IDE combines these files for the build process.

For proper modularisation make a Library or see the link above for further information on using .h/.c/.cpp as modules.

# Answer
> 0 votes
> I would like to create a program with separated modules, is this this possible using Arduino IDE?

the answer depends on your code.

writing modular code is mostly a thought process:

1) you have to design your code to a logic model: rather than setting an led on pin 2, you design your code to set a pin, use that code to set a pin specified as LED\_PIN, and then define LED\_PIN to be pin 2. With this approach, you can simply redefine LED\_PIN in your new project to use the same code.

2) you have to design your code top-down: rather than start writing your code right away, break it down to logic blocks, design the input and output of each block so that they work together cohesively. this is the toughest part of writing modular code.

after that, breaking the code down to .c/.h files is a piece of cake.

# Answer
> 0 votes
Well.... The answers are interessting but depend on what JuanV is thinking about when he say "separated modules"... For me, as an "old timer software dev", "separated modules" mean I build a central bloc of code (a nutshell) and the user download module which are automaticly "plugged" to the nutshell, expanding the feature. A bit like a printer driver you add to your system, and which add feature for all software. When I look at my past dev using this, I must admit I've some problems thinking of that on Arduino. If you are looking for that you must think about various problems:

1) how to update? Maybe with an Android App getting the code from the Web and sending these data to the Arduino via Bluetooth. You can also think of adding a Wifi interface on the Arduino

2) where to store the new piece of code... It's seem you can write on flash "on the fly" but seems to be complicated

Due to this second point, maybe the easiest way would be to create a nutshell which will "interpret" data (so which read a kind of small script) and then you'll have just to send the data. I suggest to have a look at the CNC made with Arduino. In most cases they use a GCode interpreter. GCode is a descriptif langage for CNC machine. So the interpreter read the code and according to the code, send "orders" to the machine. Maybe such a thing would be a good starting point.

On the other way, if what you call "modular approach" is just the way of building lib and re-use them, Lord Gonk answer is the way :)

---
Tags: arduino-ide
---


# Question
Title: How can I have 2 differents frequency on the 2 DAC outputs on an Arduino Due?
I would like to blink, using specific waveforms, 2 LED controlled by the 2 DAC output of the Arduino Due.

I wrote this :

```
    #include "Waveforms.h"

    int i = 0;
    int sample;

    void setup()
{
      analogWriteResolution(12);
}

    void test(float fq, int wave1, int wave2)
{

      sample = ((1/fq)*1000000)/120;

      analogWrite(DAC0, waveformsTable[wave1][i]);
      analogWrite(DAC1, waveformsTable[wave2][i]);

      i++;

      if(i == maxSamplesNum)
          {
            i = 0;
          }

      delayMicroseconds(sample);

}

    void loop() {
    // 10 Hz, 0 is a sine wave on DAC0, 3 is a square wave on DAC1

      test(10, 0, 3);

```

I would like to be able to change the frequency of each output (1Hz - 100 Hz) using differents waveforms. Changing waveforms is ok and it works, but is it possible to also change the frequency so to have two differents output frequency on each DAC output ?

The goal is to have, for example, simultaneously :

* 1 Hz, sine wave on DAC0.
* 10Hz, square wave on DAC1.

Thanks a lot.

# Answer
> 0 votes
I don't have experience with this, but what you can do is:

* If the frequency of DAC1 is x times faster than DAC2 to calculate the delay time based on the fastest and for DAC1 changing in every loop, while changing DAC2 only every DAC1/DAC2 times.
* Vice versa if DAC2 is x times faster than DAC1
* However, if there is not a simple ratio between DAC1 and DAC2 than you have to use the fastest speed of the two and use for the slowest an approximation...
* Or use a higher significant fixed speed for i use a simple linear approximation between two points of the wavetable.

E.g. assume the speed is 10 times too fast for DAC1. Suppose i = 100.. you should use the following points in the waveform: wave\[100/10\] and wave\[100/10 + 1\], so two consecutive points. Assume the first is 10.0 and the second is 20.0... for the 10 increases of i (because i is running 10 times too fast) you can calculate for values of

```
 i     : 10.0 +   0% of (20.0 - 10.0)
 i + 1 : 10.0 +  10% of (20.0 - 10.0)
 ...
 i + 10: 10.0 + 100% of (20.0 - 10.0)

```

etc.

Note this is called linear interpolation.

You would have to check how many numbers per wave form table you need to get good values for different frequencies/speeds and what 'fixed' frequency you need to use for the delay.

---
Tags: arduino-due
---


title: Hall effect sensor and water sensor

text:
# Question
Title: Hall effect sensor and water sensor
I'm working on a project based on the two sensor above but I keep getting this error:

'liquid\_level does not name a type'

This is my sketch:

```
/*
YF‐ S201 Water Flow Sensor
Water Flow Sensor output processed to read in litres/hour
Adaptation Courtesy: www.hobbytronics.co.uk
*/
const int sensorPin= 0; //sensor pin connected to analog pin A0
int liquid_level;
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;
void flow () // Interrupt function
{
   flow_frequency++;
}
void setup()
{

   pinMode(flowsensor, INPUT);
   pinMode(sensorPin, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}
void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
      Serial.print(l_hour, DEC); // Print litres/hour
      Serial.println(" L/hour");

   }
}

liquid_level= analogRead(sensorPin); //arduino reads the value from the liquid level sensor
Serial.println(liquid_level);//prints out liquid level sensor reading
delay(100);//delays 100ms
}

```

# Answer
> 2 votes
The last 4 lines are outside any function. They aren’t in the `loop()` function. You can’t put plain statements outside of any function. Check your brackets.

---
Tags: arduino-uno, compilation-errors
---


title: No data in text file

text:
# Question
Title: No data in text file
Data can be seen in the console but the data is not being written in the text file. The file is created but there is no data in it.

Here is my code in Processing,

```
import processing.serial.*;
Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port
PrintWriter output;
void setup()
{

   String portName = Serial.list()[0];
   myPort = new Serial(this, portName, 9600);
   output = createWriter( "my.txt" );
}
void draw()
{
    if ( myPort.available() > 0)
     {  // If data is available,
         val = myPort.readStringUntil('\n');
       output.print( val );
     }
    println(val); //print it out in the console

 }

```

and in Arduino,

```
  int potPin = 0; // initialize analog pin 0 for LM35 temperature sensor
  void setup()
  {
     Serial.begin(9600);// set baud rate at”9600”
  }
  void loop()
  {
     int val;// define variable
     int dat;// define variable
     val=analogRead(0);
     dat=(125*val)>>8;// temperature calculation formula
     Serial.print("Tep:");//
     Serial.print(dat);// output and display value of dat
     Serial.println("C");// display “C” characters
     delay(500);// wait for 0.5 second
   }

```

Any answers are appreciated. Thank you!

# Answer
> 2 votes
createWriter description says:

> "For the file to be made correctly, it should be flushed and must be closed with its flush() and close() methods"

Source: https://processing.org/reference/createWriter\_.html
This question is not about Arduino, but Processing language.

---
Tags: arduino-uno, arduino-ide, sketch, processing-lang, arduino-makefile
---


# Question
Title: Why do I have to open Serial Monitor to display what is in loop function?
Why do I have to open Serial Monitor to display non-NaN values retrieved from DHT22,
what am I doing wrong in the code below?

```
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
// OLED display TWI address
#define OLED_ADDR   0x3C
// reset pin not used on 4-pin OLED module
Adafruit_SSD1306 display(-1);  // -1 = no reset pin
// 128 x 64 pixel display
#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif
#define DHTPIN D3
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {

Serial.begin(115200);
delay(100);
  dht.begin();
  pinMode (DHTPIN, OUTPUT);
  /// initialize and clear display
  display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR);
  display.clearDisplay();
  //  display.drawRect(1, 1, display.width()-1, display.height()-1, WHITE);   // draws the outer rectangular boundary on the screen
  display.display();
  // display a pixel in each corner of the screen
  display.drawPixel(0, 0, WHITE);
  display.drawPixel(127, 0, WHITE);
  display.drawPixel(0, 63, WHITE);
  display.drawPixel(127, 63, WHITE);
  // display a line of text
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(20, 18);
  display.print("Welcome");
  display.setCursor(25, 40);
  display.print("San");

  // update display with all of the above graphics
  display.display();
}
void loop() {
  // put your main code here, to run repeatedly:
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 1);
  display.print("Showing Temperature");
  // display Temperature
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1, 18);
  display.print("T : ");
  display.print(t);
  display.setTextSize(1);
  display.print((char)247);
  display.setTextSize(2);
  display.print("C");
  display.setCursor(1, 40);
  display.print("H : ");
  display.print(h);
  display.print(" %");
  // update display with all of the above graphics
  display.display();
}

```

After uploading code it does will display NaN but when I open serial monitor it works fine displaying actual values from DHT22 :o

below is the fritzing of the hookup, I do not have witty cloud in fritzing, so I have used wemos D1Mini instead. on wemos d1 mini 3v3 is VCC on witty cloud dev board.

It looks like loop function doesn't execute by itself unless I open the serial monitor, why is it so? please help

# Answer
> 0 votes
Hard to tell from your fritzing which actual ESP8266 pin you are using, but you require a pull up resistor on the data line of the DHT22.

My guess is that you are using one of the serial UART pins for the data connection, and opening the serial monitor activates the output of the onboard UART chip which then acts as your missing pullup resistor.

# Answer
> 0 votes
Serial monitor sends a RESET signal during its initialization - maybe this is the problem. Sometimes these Witty boards need an implicit RESET after power up / programming.

---
Tags: serial, esp8266, lcd, code-review, nodemcu
---


title: Yellow LED got burned, green LED didn't

text:
# Question
Title: Yellow LED got burned, green LED didn't
> I'm not talking about the onboard LED at the Arduino board here. What those LED's mean, is the LED's we usually plug at the breadboard.

I plugged in a yellow LED and a green LED onto a breadboard. I wired it up, and noticed something. Green LED lights up at its full brightness, while yellow LED didn't emit any light. Tried in another yellow LED, and it seems like it's smoking, which means it's burned.

I'm not using a 220 Ohm resistor or any kind of resistor that time. I also have no idea why the green LED didn't burn itself, when you plug it directly on 5V and GND. I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

# Answer
> I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

> When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

> I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.

Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.
> 2 votes

# Answer
Majenko already mentioned the reason. Maybe it's good to add that different colored LEDs (and even each type/model) should have its 'calculated' resistor.

Find the forward voltage of the LED (differs per type/color), and use the following formula :

```
V - Vfv = I * R  <=> R = (V - Vfv) / I

```

E.g. if the forward voltage is 2V and you use a 5V Arduino and want 20 mA:

```
R = (5 - 2) / 0.02 = 150 ohm

```

The maximum mA you can find also in the data sheet of the LED.
> 1 votes

# Answer
> I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

LEDs get burned from excessive heat that is the result of excessive current. Green LEDs have higher forward voltage than yellow LEDs so, if everything else is equal, the "excessive" current through the green LED is smaller than the one through the yellow LED, thus causing the yellow LED to warm up faster and thus burn out faster.

Other factors may still attribute to the yellow's burn-out.
> 0 votes

---
Tags: led
---


title: connecting 4 wire camera to esp8266

text:
# Question
Title: connecting 4 wire camera to esp8266
I am looking for the arduino code to stream video to a webpage using the ESP8266. here is the 4 wire camera I have: https://www.ebay.com/itm/172272466793

The other tutorials I'm finding online are all for a different cameras or are not using the ESP8266 for webpage streaming.

Any help or pointers would be most appreciated.

* As a side note I have LiFePo 3.3v batteries that I plan to use to power both the ESP8266 and the 5v camera (by wiring them in series). The thing I am completely lost on is how to wire the video and audio to ports and access them with arduino code.

# Answer
No. Your link is to an *analog* NTSC camera. Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.

It is simply not compatible to use this with a small embedded system.

If you really want a camera for a resource constrained embedded system, seek a *still* camera with a serial or SPI output.

Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.
> 0 votes

---
Tags: esp8266, arduino-ide, electronics
---


# Question
Title: How can I use PWM in power saving mode (ATmega328)?
I fail to use PWM in power saving mode. The output behaves erratically. This should be possible, I guess. The following is a minimal working example:

```
/* MWE: Cannot use PWM in any power saving mode.

   A minimal working example (MWE) demonstrating my trouble in using
   PWM while saving power.

   Intention: Control one load to be on or off for longer periods of
   time (hours, that is).  The brightness of the load is set by PWM.

   Wiring:

                                              +5V
                                               |
           +------------------+                |
     +5V---|Vin               |                |
           |     Arduino      |                C
           |     Pro Mini    9|-----/\/\/----B|<  PN2222
           |     compatible   |      1k        E
           |     (ATmega328)  |                |
     GND---|GND               |                | +
           +------------------+               LED
                                               | -
                                               |
                                               >
                                               < 1k
                                               >
                                               |
                                               |
                                              GND

   Implementation:

     * Set watchdog to cause an interrupt in regular intervals (in
       this MWE: 2s).  Count down `cycles` (MWE: 2 or 3) on each
       watchdog interrupt.

     * If `cycles` is 0, toggle the output, set new `cycles` value.
       The real program uses 7200 8s cycles for 16h before the next
       toggle.

     * Go to SLEEP_MODE_PWR_DOWN.

   Expected: attached load is on for 4s, dimmed at 32/256.  Then off
             for 6s.  Then repeat.

   Observed: In most cases, there's no output in sleep mode, the LED
             only blinks before sleeping.  But sometimes it is on, so
             PWM seems to be possible while sleeping!

   The real program (from which this MWE is derived) uses adjustable
   brightness, wakes up from sleep by external interrupts, stores
   brightnes to EEPROM, ...
*/

/* Setting the following to 0 uses `digitalWrite` instead of
   `analogWrite` to demonstrate that the watchdog and interrupt logic
   do actually work. */
#define USE_PWM 1

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

#define outputPin 9    // where the PWM load is connected
#define onCycles 2     // num of watchdog cycles to stay on
#define offCycles 3    // num of watchdog cycles to stay off

int brightness = 32;  // PWM duty cycle in 1/256, if the load is on
int toggle = 1; // current on/off state of PWM load

/* Number watchdog cycles until next toggle.  This will be modified in
   the watchdog interrupt handler. */
volatile unsigned long wdt_cycles = onCycles;

/* Watchdog interrupt handler called when watchdog expires, count down
   remaining cycles.  Does not underflow. */
ISR(WDT_vect) {
    if (wdt_cycles > 0)
        wdt_cycles--;
}

void setup(void) {

    /* Setup watchdog.  See [1] p54, [2] */
    cli(); // BEGIN disable interrupts

    MCUSR &= ~(1<<WDRF); // no system reset on watchdog timeout

    WDTCSR |= 1<<WDCE | 1<<WDE; // allow watchdog configuration

    WDTCSR
        = 1<<WDIE // enable interrupts
        | 1<<WDP2 | 1<<WDP1 | 1<<WDP0 // 2.0 seconds
        ;

    wdt_reset(); // reset timer

    sei(); // END disable interrupts

    /* Setup output pins */

    pinMode(outputPin, OUTPUT);

#if USE_PWM
    analogWrite(outputPin, brightness);
#else
    digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif

}

void loop(void) {

    if (wdt_cycles < 1) {
        toggle = !toggle;
        wdt_cycles = toggle ? onCycles : offCycles;
#if USE_PWM
        analogWrite(outputPin, toggle ? brightness : 0);
#else
        digitalWrite(outputPin, toggle ? HIGH : LOW);
#endif
    }

    /* Heartbeat: Short blink of builtin led.  This verifies that we
       are actually sleeping and waking up. */
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    digitalWrite(LED_BUILTIN, LOW);

    /* Got to sleep, see [3].  I want `SLEEP_MODE_PWR_DOWN`, but also
       none of the others works. */
    set_sleep_mode(
                   //SLEEP_MODE_IDLE
                   //SLEEP_MODE_ADC
                   //SLEEP_MODE_PWR_SAVE
                   //SLEEP_MODE_STANDBY
                   SLEEP_MODE_PWR_DOWN
                   );
    sleep_mode();
}

/* References
   [1] https://cdn.sparkfun.com/datasheets/Kits/doc8161.pdf
   [2] https://forum.arduino.cc/index.php?topic=63651.0
   [3] https://playground.arduino.cc/Learning/ArduinoSleepCode
 */

```

# Answer
> 2 votes
The timers are disabled during SLEEP\_MODE\_PWR\_DOWN, so PWM doesn't work during SLEEP\_MODE\_PWR\_DOWN. You could instead use `SLEEP_MODE_IDLE`, but that only saves a bit of current.

When you put the MCU to sleep, the led will keep the state it was in during PWM. So around 12.5% if the time the leds will be on, and the other times it will be off (during those 2s PWM periods).

# Answer
> 1 votes
Just as a complement to Gerben's answer:

1. You could use `SLEEP_MODE_PWR_DOWN` during the off period, but `SLEEP_MODE_IDLE` is the only way to do PWM while sleeping.
2. When in `SLEEP_MODE_IDLE`, you can use the `power_*_disable()` function defined in `<avr/power.h>` in order to further reduce the power consumption.

---
Tags: pwm, atmega328, arduino-pro-mini, sleep
---


# Question
Title: Feather MO: How would I change my code to have my txt file data be in columns rather than be staggered?
First of all, I am using the Feather MO Adalogger from Adafruit with the Ultimate GPS Feather hat to collect some GPS data: time stamp (millisec), GPS Coordinates (latitude & longitude), speed (knots), and altitude (meters). The GPS data is stored on a micro SD card and I have the GPS portion of the code working. The data I want is being stored on the micro SD card. My only problem is that I can't get the data to be appropriately put in columns under their respective "headers". I used .print("\t") after each data type in attempt to tab the data into columns. This worked for the "headers" but not for the data itself. Screenshots and code are below. Thanks in advance!

My txt file: Headers

My text file: working GPS data

Code for Headers

Code for data

# Answer
> 2 votes
Change the `println()`s to `print()`s. Put one `println()` at the end of the list of data prints. You want each row of data to not take up more than one line in the text file. A `println()` starts a new row after printing.

Also, you’ll want to open the text file in a tabular program like Excel or similar. A plain text editor likely won’t utilize tab characters in the way you like.

---
Tags: gps
---


# Question
Title: Is it possible to read-write the memory of a Gikfun ISD1820 voice recording module?
I just got a Gikfun ISD1820 voice recording module for an Arduino project that I'm working on. I want to be able to record a few seconds message and then send the message over wifi to another Arduino Mega 2560, which will then play back the message.

The ISD1820 module can record and play back short messages and can be controlled from the Arduino, but I want to know if it is possible to access the memory / read-write the memory of the ISD1820 module to accomplish my goal. And how would I do it?

If it is impossible, what hardware should I get instead? Do I need a wave shield with a SD card or a wifi shield with an SD card?

Thanks!

# Answer
No. You can't. That module can only record and play.

The only possible thing you could do is record onto the chip then play it back recording it on to the Arduino (at ridiculously low quality) - in which case, what would the point of the chip be?

If you want some quality to your recordings you need a powerful microcontroller with an I2S interface and a CODEC chip. However any powerful MCU (such as the ARM chip on the Due, or the Teensy, or the PIC32 chip on the chipKIT boards) can sample at a reasonable quality through the ADC inputs.

The Arduino Uno can record very short bursts at very low quality (due to lack of memory) without any external hardware (except a suitable microphone preamplifier). The Mega can record slightly more, but the quality will still be very low.
> 2 votes

---
Tags: arduino-mega, wifi, audio, memory, speaker
---


title: Is this a fake pulse sensor?

text:
# Question
Title: Is this a fake pulse sensor?
A couple of days ago, I purchased a pulse sensor online for a project. Before actually doing anything with it, I wanted to capture and view its analogue waveform output. One while placing my finger on it and one when in the default state, so that I can see the trend or difference in the two waveforms. But when I captured the output, it seems like there is not much difference. Just some random noise I guess. Also, I checked the company website who may have made this one and it all looks good to me.

1. The image below shows the waveform captured when no finger is placed on the sensor.
2. The image below shows the waveform captured when my index finger is placed on the sensor.
3. This is my setup for the sensor for measuring pulses.
4. This image shows the face of the sensor.

I need some insights from folks here regarding this sensor. Is it showing some junk output? or my understanding is wrong and there's a better way to figure this out/ work with this sensor.

# Answer
> 1 votes
The second trace looks like a pulse to me. With that kind of sensor you don't get the PQRST traces of an ECG - just a slight bump when you get a pulse.

---
Tags: sensors
---


title: Arduino nano and wemos sd shield

text:
# Question
Title: Arduino nano and wemos sd shield
Is it possible use Arduino nano with wemos sd shield? If I can, how to I connect sd shield to arduino and what modification I need to do on library setting?

# Answer
No, you can't. The WeMos boards operate at 3.3V, and so does the SD card. If you want to use a 5V Arduino with a 3.3V SD card, you'll need voltage level shifters.

The schematic of the WeMos SD shield will tell you what SD connections go to what pins. Then just google how to use an SD card with Arduino to connect those pins to the correct Arduino pins.
> 1 votes

---
Tags: arduino-nano, sd-card
---


# Question
Title: How to get code to respond to a certain time from the DS3231 RTC?
I am trying to make a program that runs when it gets to five in the afternoon, so 17:00:00.

I am using this DS3231 library, but I can't figure out a way to get it to send "Woooopp" to the serial monitor at the specified time.

On the DS3231, the pin labeled SCL is connected to A5 on the Arduino and the pin labeled SDA is connected to A4 on the Arduino.

SCL -\> A5 SDA -\> A4

My code:

```
#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc (SDA, SCL);

void setup() {
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(19, 48, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop() {
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)

  if (rtc.getTimeStr() == "19:58:12") {
    Serial.println("Woooopp");
  }
  delay (1000);
}

```

No errors are thrown, however, the code simply does not work.

Any help would be greatly appreciated!

# Answer
> How to get code to respond to a certain time from the DS3231 RTC?

the easiest is to set up the alarm in rtc.

alternatively, keep reading the rtc until the desired time has passed. not terribly efficient.
> -1 votes

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


title: interrupt not triggered correctly

text:
# Question
Title: interrupt not triggered correctly
I have an arduino uno and want to react to three sensors, which should trigger an ISR.

I wrote the following program, and for sensor 3 it works, however the other two sensor don't seem to trigger an interrupt. I checked the sensors by connected each one to pin A5, and every sensor worked.

Is there a better way to check which pin caused the interrupt than digitalRead()? Is this maybe even my problem?

```
#define pinDrehen 12
#define pinRevDrehen 13

volatile boolean triggeredAngleSensor1 = false;
volatile boolean triggeredAngleSensor2 = false;
volatile boolean triggeredAngleSensor3 = false;
volatile unsigned int triggeredTimeAngleSensor1;
volatile unsigned int triggeredTimeAngleSensor2;
volatile unsigned int triggeredTimeAngleSensor3;

ISR (PCINT1_vect) // handle pin change interrupt for for A0 to A6 and reset [only A3 to A5 are enabled]
{
  if (digitalRead(A3)){//angle sensor 1
    triggeredAngleSensor1 = true;
    triggeredTimeAngleSensor1 = millis();
  }
  if(digitalRead(A4)){//angle sensor 2
    triggeredAngleSensor2 = true;
    triggeredTimeAngleSensor2 = millis();
  }
  if(digitalRead(A5)){//angle sensor 3
    triggeredAngleSensor3 = true;
    triggeredTimeAngleSensor3 = millis();
  }
}

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

  // pin change interrupt
  PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3
  PCIFR  |= bit (PCIF1);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);    // enable pin change interrupts for A0 to A6 and reset

  pinMode(pinDrehen, OUTPUT);
  pinMode(pinRevDrehen, OUTPUT);

  //start turning machine:
  digitalWrite(pinDrehen, HIGH);
  digitalWrite(pinRevDrehen, HIGH);
}

void loop() {
  if(triggeredAngleSensor1){
    triggeredAngleSensor1=false;
    Serial.print("Sensor 1 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor1);
  }
  if(triggeredAngleSensor2){
    triggeredAngleSensor2=false;
    Serial.print("Sensor 2 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor2);
  }
  if(triggeredAngleSensor3){
    triggeredAngleSensor3=false;
    Serial.print("Sensor 3 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor3);
  }
  delay(5);
}

```

# Answer
This line:

```
PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3

```

is probably not what you want.

Let's break it down and look at just what you have there.

```
bit (PCINT13)

```

The `bit` function returns the bitmask for a specific bit. So if you pass it `3` you get a value with the third (counting from 0) bit enabled (`1 << 3`, or `0b1000`, or `0x08`).

`PCINT13` is 5. So you have `1 << 5`, or 0x20.

So far so good. Now you OR that with:

```
bit (PCINT12 | bit (PCINT11))

```

And this is the bit that's wrong. Inside is `bit (PCINT11)` which, with `PCINT11` being 3, results in `0x08`. That is then ORed with `PCINT12`, which is 4. The result is 8+4. That's 12. The value 12 is then fed through another `bit()` function, which gives you `1<<12`. That, of course, overflows outside of an 8-bit value, so you end up with `0`.

The final result is ORed together with the `0x20` from before, which of course remains as `0x20`.

What you probably wanted (and intended) is to have:

```
PCMSK1 |= bit (PCINT13) | bit (PCINT12) | bit (PCINT11);  // want pin A5 or A4 or A3

```
> 0 votes

# Answer
the logic in the isr is incorrect.

generally, you want to set up the pcint pins so that they respond to an edge.

in the isr (with multiple pin changes), you will need to either 1) preserve and maintain the previous state so to determine which pins have experienced a state change; or 2) use pin change flags.

what you have there can lead to false determination of triggers.
> 0 votes

---
Tags: sensors, interrupt, atmega328, code-review
---


title: Getting boot mode 1.6 error

text:
# Question
Title: Getting boot mode 1.6 error
When I try to upload my script I get this in my serial monitor:

> ets Jan 8 2013,rst cause:4, boot mode:(1,6)
>
> wdt reset

The board I am using is Uno + Wifi

And this is my sketch:

```
/*
* Arduino Smart Thermometer
*
*/
#include <LiquidCrystal.h> // includes the LiquidCrystal Library
#include <Button.h>
#include <SteinhartHart.h>

//LCD constants
const int rs = 2, en = 3, d4 = 8, d5 = 9, d6 = 10, d7 = 11;

//Thermsistor variables
int ThermistorPin = 0;
boolean degreeChanged = false;
double temp = 0.0;

//Buttons
int decreaseDegreePin = 12;
int increaseDegreePin = 13;
int backlightSwitch = 7;

#define PULLUP false        //To keep things simple, we use the Arduino's internal pullup resistor.
#define INVERT false        //Since the pullup resistor will keep the pin high unless the
                           //switch is closed, this is negative logic, i.e. a high state
                           //means the button is NOT pressed. (Assuming a normally open switch.)
#define DEBOUNCE_MS 50     //A debounce time of 20 milliseconds usually works well for tactile button switches.

Button decreaseDegreeButton(decreaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button increaseDegreeButton(increaseDegreePin, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button
Button backlightSwitchButton(backlightSwitch, PULLUP, INVERT, DEBOUNCE_MS);    //Declare the button

//Variables
int wantedDegree = 20;
int backlight = 255;
int switchPin = 4;
double curTemp;

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers
unsigned long previousDegreeUpdateTime = 0;
unsigned long degreeUpdateDelay = 3000;

//Libraries
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
SteinhartHart thermsistor(ThermistorPin);

void setup() {
  //Initialize backlight
  analogWrite(5,backlight);

  pinMode(switchPin,OUTPUT);

  //Initialize display
  lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }

  //First display
  updateDegree();
  displayCurrentStatus();
}
void loop() {
  switchHeather();

  //Initialize backlight
  analogWrite(5,backlight);

  //Recalculate degree
  updateDegree();

  //Buttons initialization
  changeDegreeWithButtons();

  //If degree is updated, update display
  unsigned long currentDegreeUpdateTime = millis();
  if(degreeChanged){
    if((currentDegreeUpdateTime - previousDegreeUpdateTime) > degreeUpdateDelay){
      previousDegreeUpdateTime = currentDegreeUpdateTime;
      displayCurrentStatus();
    }
  }

}

void switchHeather(){
  if(wantedDegree > curTemp){
    digitalWrite(switchPin, HIGH);
  }
  else{
    digitalWrite(switchPin, LOW);
  }
}

void updateDegree(){

  curTemp = thermsistor.getTempCelsius();

  if(temp != curTemp)
  {
    temp = curTemp;
    degreeChanged = true;
  }
  else{
    degreeChanged = false;
  }
}

void displayCurrentStatus(){
    //Print degrees to LCD
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print(temp);
    lcd.print(char(223));
    lcd.print(" Celcius");
}

void changeDegreeWithButtons(){
  //Read buttons
  decreaseDegreeButton.read();
  increaseDegreeButton.read();
  backlightSwitchButton.read();

  if (increaseDegreeButton.wasReleased()) {
    wantedDegree++;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omhoog naar: ");
    lcd.print(wantedDegree);
  }

  if (decreaseDegreeButton.wasReleased()) {
    wantedDegree--;
    lcd.clear();
    lcd.print("Temperatuur:");
    lcd.setCursor(0,1); // Sets the location at which subsequent text written to the LCD will be displayed
    lcd.print("Omlaag naar: ");
    lcd.print(wantedDegree);
  }

  //Backlight switch
  if (backlightSwitchButton.wasReleased()) {
    if(backlight == 255){
      lcd.clear();
      lcd.print("Backlight: Off");
      backlight = 0;
    }
    else{
      lcd.clear();
      lcd.print("Backlight: On");
      backlight = 255;
    }
  }
}

```

Why does this happen and how can I fix it? When I use the same script on my Arduin Uno board it does work. The board Uno + Wifi however doesn't.

Also what I used is:

* An LCD Screen
* 3 buttons with resistors
* A thermsistor with resistor
* A relay (only connected to arduino
* External power source

# Answer
> 2 votes
This message indicates that you currently have the ESP8266 rather than the ATmega connected to the USB interface.

In order to upload Arduino sketches to the ATmega, you need to follow the instructions on the sale page to change the dip switches to `USB<>ATmega328` mode.

The table is probably sufficient, if not you can puzzle out the German explanatory text or try machine translation.

It's possible you could also install ESP8266 support in your Arduino IDE and run your sketches on the ESP8266 part of the board instead of the ATmega part, however chances are mot of the Arduino headers go to the ATmega, so you would be limited in what peripherals you could connect.

---
Tags: arduino-uno, bootloader
---


title: Arduino Nano v3.0 with ESP8266

text:
# Question
Title: Arduino Nano v3.0 with ESP8266
I am attempting to connect and use an ESP8266 board with my Arduino nano v3.0 and I am not have much luck.

I have read a bunch of tutorials and articles, the most recent is http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html

Any help would be greatly appreciated.

I have connected it like below and am using some simple code to try and get it working.

Code:

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

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

  Serial.flush();

  esp8266.print("AT+RST\r\n"); // reset for esp8266
  delay(500);
  esp8266.flush();//clear serial1
  // Check AT
  esp8266.print("AT"); // reset for esp8266
  esp8266.print("AT+CIFSR\r\n");// learn the ip which token for esp8266
  delay(500);
  if (esp8266.find("ready"))
  {
    esp8266.flush();
    esp8266.print("AT+CIFSR\r\n");
    delay(500);
    Serial.println("CIHAZ IP ADRESI:" + esp8266.readString()); // print esp8266 ip

  }
  else
  {
    Serial.println("there is no internet connection");
  }
  esp8266.print("AT+CIPMUX=1\r\n");//ser mux 1 so we want to connect as multiple users
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("Mux ok");
  }
  else
  {
    Serial.println("MUX failed");
  }
  esp8266.print("AT+CIPSERVER=1,23\r\n");// set esp8266 as server
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("SERVER started");
  }
  else
  {
    Serial.println("SERVER failed");
  }

}
void loop()
{

  if (esp8266.available())
  {
    Serial.print(esp8266.readString()); // get message which comes from clients.
  }
}

```

# Answer
> 3 votes
The Esp8266 module has different firmware, the old one was running at 9600 and the new one is running at 115200.

Try to upload this code on your arduino Nano and send AT commands over the Serial monitor of the Arduino.

If you send AT it should returns "OK", if not, try to swap RX to TX and try to play around with the baudrate 9600, 57600, 115200.

It might be that your Wifi module doesnt have any firmware loaded which might need to be done.

```
#include <SoftwareSerial.h>

SoftwareSerial wifi(10,11); // RX, TX

void setup()
{
Serial.begin(9600); // FTDI
wifi.begin(9600); // GPS; 9600 first time, 38400 second time
}

void loop()
{
if (Serial.available())
wifi.write(Serial.read());
if (wifi.available())
Serial.write(wifi.read());

}

```

# Answer
> 3 votes
Do not Connect your ESP8266 Module Directly to an Arduino Board, Always try your best to use Divider resistors for better communication. you need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of writing At Commands in Source Code. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.

Download Simple Source Code and List of Necessary AT Commands

# Answer
> 2 votes
Remember that ESP8266 Uses 3.3v logic and arduino 5v. So use a voltage divider to get 3.3v at esp8266 rx pin. Also esp8266 must be connected rx-\>rx tx-\>tx to communicate with pc and rx-\>tx tx-\>rx to communicate with arduino.

---
Tags: arduino-ide, arduino-nano, esp8266
---


# Question
Title: Linux IDE 1.0.6 & Nano: Problem with if statement
This is a basic battery monitor for a solar-powered control box. It keeps the solar panels tracking the sun.

The Arduino monitors the voltage on the battery and turns on an AC-powered battery charger if the voltage drops too low.

It works, but there is an odd quirk.

* Actual code is posted here. Too long to post and it does a bunch of other stuff that can be distracting.

One simple `if` statement isn't executing, as described below and shown on the plot.

---

**HERE IS THE KEY CODE SEGMENT WHERE THE FAILURE OCCURS:**

```
if (vind < vTriggerOn) {    // Batt low, turn on charger
  digitalWrite(powerPin,LOW);
  digitalWrite(powerPin2,LOW);
  vAC=17.0;
  }
if (vind > vTriggerOff) {   // Solar panels on, turn off charger
  digitalWrite(powerPin,HIGH);
  digitalWrite(powerPin2,HIGH);
  }

//  HERE IS THE PROBLEM :  THIS ONE DOESN'T EXECUTE
if (vind > 15.5) {vind=15.48; vin=15.48;}

```

This is followed by yet another `if` statement that works.

**Problem: That `if` statement in question is supposed to keep it from going off-scale above the top of the plot. Yet it is not executing.**

**The two gray lines show that it is detecting the on and off triggers, but the voltage is going off the top. This should be impossible.**

**The first two `if` statements are executing but the third one is not.**

---

Considered the fact that I hadn't upgraded the Arduino IDE since first installation. It is "Arduino 2:1.0.6:dpsg2-4"

Tried this:

```
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install arduino

```

and it told me I had the latest version.

---

**Question: How can I make it execute that third `if` statement?**

# Answer
> 1 votes
This a new answer, upon the complete, original sketch as posted here by OP.

I deleted all the code that doesn't affect `vind` directly. Also, I replaced the `value=analogRead(A2)` with worst case scenario `value=1023`. Also tested with 781 and 782, which produces values for `vind` around 15.5.

**Reduced sketch**

```
const float R1 = 147000.0;
const float R2 =  47000.0;
const float constADC = 5.0;
const float offsetADC = -0.25; //
const float convADC = constADC / 1024.0;
const float numReadings = 10.0;
const float vTrigAlertLow = 12.1;

float nReadings = 0.0;
float tReadings = 0.0;

int value = 0;
float vout, vin, vind;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println("");
}

void loop() {
  int value = 1023;
  vout = value * convADC;
  vin = vout / (R2 / (R1 + R2));
  vind = vin + offsetADC;
  tReadings = tReadings + vind;
  nReadings = nReadings + 1.0;

  Serial.print(nReadings); Serial.print(" "); Serial.print(tReadings); Serial.print(" ");   Serial.println(vind);

  if (nReadings >= numReadings) {
    vind = tReadings / numReadings;
    tReadings = 0.0;
    nReadings = 0;

    Serial.print("Before "); Serial.print(vind);
    if (vind > 15.5) vind = 15.48; // <----  PROBLEM - not executing
    Serial.print(" After "); Serial.println(vind);

    if (vind > vTrigAlertLow) { // Normal, otherwise below vTrigAlertLow it will send alerts in the 'else' below
      Serial.println(vind);
    }
    else {
      Serial.println("LOW VOLTAGE");  // send Texts
    }
    Serial.println("----");
  }
}

```

The output is

```
1 20.37 20.37
2 40.74 20.37
3 61.10 20.37
4 81.47 20.37
5 101.84 20.37
6 122.21 20.37
7 142.58 20.37
8 162.95 20.37
9 183.31 20.37
10 203.68 20.37
Before=20.37 After=15.48
Send to PI 15.48
----

```

The `if` works as intended. It must be something else.

---
Tags: programming, arduino-ide, arduino-nano
---


# Question
Title: Problem with PWM function on RGB LED and IR
I'm having an issue in controlling a RGB LED with Arduino and a remote control. When including the library IRRemote.h (version 2.2.3), the blue channel only works in on/off logic instead of PWM. If I remove the library, the PWM logic of the blue channel works normally and it does accept the whole range (0-255). I'm using an Arduino/Elegoo Uno R3 board. What could be causing the issue?

Below the code:

```
#include "IRremote.h"

int pinRic = 9; // Signal Pin of IR receiver to Arduino Digital Pin 11
IRrecv ricevitore(pinRic);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define BLUE 3
#define GREEN 5
#define RED 6
#define IR_BPlus  0xFF3AC5  //
#define IR_BMinus 0xFFBA45  //
#define IR_ON     0xFF827D  //
#define IR_OFF    0xFF02FD  //
#define IR_R    0xFF1AE5  //
#define IR_G    0xFF9A65  //
#define IR_B      0xFFA25D  //
#define IR_W    0xFF22DD  //
#define IR_B1   0xFF2AD5  //
#define IR_B2   0xFFAA55  //
#define IR_B3   0xFF926D  //
#define IR_B4   0xFF12ED  //
#define IR_B5   0xFF0AF5  //
#define IR_B6   0xFF8A75  //
#define IR_B7   0xFFB24D  //
#define IR_B8   0xFF32CD  //
#define IR_B9   0xFF38C7  //
#define IR_B10    0xFFB847  //
#define IR_B11    0xFF7887  //
#define IR_B12    0xFFF807  //
#define IR_B13    0xFF18E7  //
#define IR_B14    0xFF9867  //
#define IR_B15    0xFF58A7  //
#define IR_B16    0xFFD827  //
#define IR_UPR    0xFF28D7  //
#define IR_UPG    0xFFA857  //
#define IR_UPB    0xFF6897  //
#define IR_QUICK  0xFFE817  //
#define IR_DOWNR  0xFF08F7  //
#define IR_DOWNG  0xFF8877  //
#define IR_DOWNB  0xFF48B7  //
#define IR_SLOW   0xFFC837  //
#define IR_DIY1   0xFF30CF  //
#define IR_DIY2   0xFFB04F  //
#define IR_DIY3   0xFF708F  //
#define IR_AUTO   0xFFF00F  //
#define IR_DIY4   0xFF10EF  //
#define IR_DIY5   0xFF906F  //
#define IR_DIY6   0xFF50AF  //
#define IR_FLASH  0xFFD02F  //
#define IR_JUMP3  0xFF20DF  //
#define IR_JUMP7  0xFFA05F  //
#define IR_FADE3  0xFF609F  //
#define IR_FADE7  0xFFE01F  //
#define incFact 30
int  brightFact = 0;
int lv[3];

void fade7()
{
#define delayTime 10 // fading time between colors

  lv[0] = 255; // choose a value between 1 and 255 to change the color.
  lv[1] = 0;
  lv[2] = 0;

  for (int i = 0; i < 255; i += 1) // fades out R bring G full when i=255
  {
    lv[0] -= 1;
    lv[1] += 1;

    analogWrite(RED, lv[0]);
    analogWrite(GREEN, lv[1]);
    delay(delayTime);
  }

  lv[0] = 0;
  lv[1] = 255;
  lv[2] = 0;

  for (int i = 0; i < 255; i += 1) // fades out G bring B full when i=255
  {
    lv[1] -= 1;
    lv[2] += 1;

    analogWrite(GREEN, lv[1]);
    analogWrite(BLUE, lv[2]);
    delay(delayTime);
  }

  lv[0] = 0;
  lv[1] = 0;
  lv[2] = 255;

  for (int i = 0; i < 255; i += 1) // fades out B bring R full when i=255
  {
    lv[2] -= 1;
    lv[0] += 1;

    analogWrite(BLUE, lv[2]);
    analogWrite(RED, lv[0]);
    delay(delayTime);
  }
}

void setColor(int r, int g, int b)
{
  Serial.println("About to write:");
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void  translateIR() // takes action based on IR code received
{
// describing Remote IR codes
  Serial.println(results.value, HEX);
  switch (results.value)
  {
    //case IR_BPlus: setBright(true);break;
    //case IR_BMinus: setBright(false);break;
    case IR_OFF: setColor(0, 0, 0); break;
    //COLORS
    case IR_R: setColor(255, 0, 0); break;
    case IR_G: setColor(0, 255, 0); break;
    case IR_B: setColor(0, 0, 255); break;
    case IR_W: setColor(255, 255, 255); break;
    case IR_B1: setColor(255, 20, 0); break;
    case IR_B2: setColor(0, 255, 20); break;
    case IR_B3: setColor(20, 0, 255); break;
    case IR_B4: setColor(255, 20, 255); break;
    case IR_B5: setColor(255, 90, 0); break;
    case IR_B6: setColor(0, 255, 90); break;
    case IR_B7: setColor(90, 0, 255); break;
    case IR_B8: setColor(255, 150, 255 ); break;
    case IR_B9: setColor(255, 191, 0); break;
    case IR_B10: setColor(0, 255, 191); break;
    case IR_B11: setColor(191, 0, 255); break;
    case IR_B12: setColor(120, 255, 255); break;
    case IR_B13: setColor(255, 255, 0); break;
    case IR_B14: setColor(0, 255, 255); break;
    case IR_B15: setColor(255, 0, 255); break;
    case IR_B16: setColor(150, 255, 255); break;

    //END COLORS
    case IR_FADE7: fade7();
  }// End Case

  delay(100); // Do not get immediate repeat
} //END translateIR

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  ricevitore.enableIRIn(); // Start the receiver*/

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (ricevitore.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    ricevitore.resume(); // receive the next value*/
  }
} /*--(end main loop )-- */

```

# Answer
By default, the IRremote library uses Timer 2 on an ATmega328P. (Library documentation) This timer is also used for PWM on pins 3 and 11.
This means that you will have to use a different PWM pin for your blue LED (e.g. 9 or 10, controlled by Timer 1). Alternatively, you could edit the IRremote library to use Timer 1.
> 2 votes

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


# Question
Title: How will Arduino sketch and Android app communicate over GPS?
How will I make Arduino with GPS communicate with an Android app? I just need this for my school project.

# Answer
> 2 votes
> How will i make arduino with gps to communicate with android app? i just need this for my school project.

as gps is one-way communication, you will have to either launch your own birds capable of two way communications, or pick a different school.

---
Tags: gps, android
---