# Question
Title: No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor
I have a Wemos d1 mini, and when I upload nothing or anything to it, the built-in LED always lights up and the serial monitor gets a lot of garbage at every baudrate. I have supplied it with 4 AA batteries and the board has a built in voltage regulator of 3.3V at the 5V pin.

The Wemos d1 mini contains the esp8266 chip.

Please help me! I have searched everywhere. This just happened all of a sudden, the board was working perfectly fine before too.

# Answer
> 1 votes
Three words. "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked. I've been there and found out that you should never use these devices on breadboards and with funky power sources. There is this chip within the module called **eFuse**, which is basically an electronic fuse that's really easy to destroy. Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.

I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor. In that case, your module's death sentence is officially sealed.

Congrats. :(

---
Tags: arduino-ide, esp8266, wifi, electronics, serial-data
---


# Question
Title: Using TMRpcm object, why is the SD Card failing to be found by arduino?
I am using this micro-sd card reader, and my wiring configuration is as follows (double and triple checked):

```
3.3v goes to 3.3v on the Arduino UNO
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 4 on Arduino UNO

```

When I run the 'basic' example from the TMRpcm library, everything compiles and uploads properly with no warnings. Looking at the Serial Monitor, I get "SD Fail", which, according to the comments, means that the SD card failed to initialize. The card is present, and works in my computer. Do I have something wired wrong, or is there another issue?

**EDIT**

I have tried using a different pin for D3, and changed the code as needed. Still no luck.

# Answer
See https://github.com/greiman/SdFat

Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.
> 1 votes

# Answer
Check if the reader is plugged in correctly. This will give a PEBKAC error.
> -1 votes

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


title: Communicating with I2C DAC (LTC2631)

text:
# Question
Title: Communicating with I2C DAC (LTC2631)
Firstly, let me say that I'm new to using I2C devices, especially with Arduino. I have an 8-bit DAC (LTC2631) that I'm trying to control with an Arduino Uno. I thought I would be able to use the standard Wire library protocol to talk to it, but I'm not getting any response. Here's what I've tried:

```
#include <Wire.h>

void setup() {

    Wire.begin();
}

void loop() {
    Wire.beginTransmission(0x11); //specify device's address

    Wire.write(150); //send a test value

    Wire.endTransmission();
}

```

Am I missing something obvious? Or are not all I2C devices compatible with Wire?

# Answer
Software: Wire should be fine. Of course, you usually will want libraries for each device. This particular ADC is designed for automotive use and I could not find a specific library for it so you are correct that you will need to speak with it directly. Here is the DATASHEET

I2C Hardware: On the Arduino Uno, SDA is A4 and SCL is A5.

One thing you almost always have to do with I2C is to provide a 10K pull-up to +5 on each pin (SDA and SCL) - I use a small breadboard whenever I use I2C, so I have power, ground, A4 and A5 available for pullups and multiple devices.

The reason for this is that the I2C bus is active-low. It signals by pulling the pins low in sequence to communicate.

If you already had the DS3231 RTC module on the same bus, which apparently you do not or you would not be asking this question, then you do not need your own pull-ups because the RTC includes them internally.

---

It might be easier for you to use a different I2C ADC such as the ADS1115.

Here is a generic search that shows the module:

https://smile.amazon.com/s/ref=nb\_sb\_noss\_2?url=search-alias%3Daps&field-keywords=i2c+adc

Here is a generic search which shows the software side:

https://www.google.com/search?q=arduino+ads1115+ADC+library+download
> 0 votes

---
Tags: i2c, wire-library, digital-analog-conversion
---


title: How to create a library from scratch?

text:
# Question
Title: How to create a library from scratch?
Good morning. I have a problem that I hope you understand. I'm trying to create a library from scratch. I've read and watched most videos and documentation that are on the internet. I can not understand and I'm not able to make one.

I hope someone can help me create a library that only shows a message that says "Hello World" in the serial port and give me the code if they are so kind. Also, it would be good if they could explain it to me.

I insist I know of many programming languages and realize this has made me a problem. I just need the code of the 3 parts so I can analyze it and understand it. I wait for your help.

# Answer
A simple example...

Create a folder named My\_Library, and place it in the Arduino/libraries folder

Create a sketch named My\_Library.h and add the following:

```
#ifndef __My_Library_H__
#define __My_Library_H__
#include "Arduino.h"

//example 1
#define myhello1() ( { \
   Serial.println(F("Hello World"); \
Serial.println(F("Hello World again"); \
} )

//example2
void myhello2() {
 Serial.println(F("another Hello World");
Serial.println(F("another Hello World again");
}

#endif

```

Place the the sketch in the "My\_Library" folder

In the beginning of your sketch, add

```
#include <My_Library.h>

```

Then, wherever you want, add the following:

```
//example 1
myhello1();

//example2
myhello2();

```

I have not tested the above, but it should work fine. Regardless, this gives you a reasonable starting point.

For your last question concerning word colour, research "Arduino Libraries" regarding the "keywords.txt" file.
> 0 votes

---
Tags: arduino-uno
---


title: Compilation issues on Arduino Due

text:
# Question
Title: Compilation issues on Arduino Due
I wrote an code on Arduino and I getting compilation errors. I am using Arduino Due . I wrote the following code :

```
void setup() {
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit

}

void loop() {

  // code
}

```

But compiler gave me the following errors :

```
'analogReadResolution’ was not declared in this scope
‘analogWriteResolution’ was not declared in this scope
‘DAC0’ was not declared in this scope

```

I'm using Arduino 2:1.0.5 (on Linux). The board list doesn't show Arduino Due (USB programmable).And I don't have Board Manager option. How do I install Arduino SAM Board to compile the program ?

# Answer
According to the Arduino - ReleaseNotes,

> ARDUINO 1.5 BETA - 2012.10.22
>
> * First release for the unified IDE for both AVR 8-bit and ARM 32-bit (SAM3 CPUs) architectures.
> * This release include the SAM Arduino Core used in the Arduino Due Board.

So your 1.0.5 version does not allow for Due compilation. Download the most up-to-date version and you will be fine (you will be able to install SAM support).

Then you will be able to at least compile. If you have other problems with your code, please open another question here (in order to keep the one-question-per-post behavior of this website).

Don't install arduino from the debian repository, since that version is not updated regularly. Use the website version
> 2 votes

---
Tags: arduino-due, pwm, input
---


title: Transistor switching problem

text:
# Question
Title: Transistor switching problem
With my team we constructed a circuit using Arduino. The circuit works on the Proteus simulator. It worked fine with LEDs connected directly to Arduino outputs.

However, when I used Arduino output to trigger a BC 337 transistor to try and actuate a 12 V DC coiled relay, it wouldn't trigger. I measured voltage across transistor collector and emitter, it reads 12 V, just like the source I gave... (The transistor is not switched on I guess).

Supply for the Arduino is a constant 5 V DC.

Where have I gone wrong? Picture as uploaded.

Furthermore, we are trying to build a controller for an ice making machine. The power circuit (12 V) is to be controlled by Arduino through the transistors.

I am uploading the codes we used and the full circuit diagram.

```
const int start = 13;
const int comp= 2;
const int cond=3;
const int hGas=4;
const int wbut=12;
const int watersol=5;
const int dumper=6;
const int iced=11;

int startButton=0;
int waterButton=0;
int dumperlimswitch=0;

void setup() {

  pinMode(start, INPUT);
  pinMode(comp, OUTPUT);
  pinMode(cond, OUTPUT);
  pinMode(hGas, OUTPUT);
  pinMode(wbut,INPUT);
  pinMode(watersol, OUTPUT);
  pinMode(dumper, OUTPUT);
  pinMode(iced, INPUT);
}

void loop() {

startButton = digitalRead(start);
waterButton = digitalRead(wbut);

 if (startButton == HIGH) {

    digitalWrite(comp, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
     delay(800);
    digitalWrite(hGas,HIGH);
    digitalWrite(cond, LOW);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(500);
    digitalWrite(hGas, LOW);
    digitalWrite(dumper, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(800);
    digitalWrite(dumper, LOW);
  }
else {
    digitalWrite(comp, LOW);
    digitalWrite(cond, LOW);
  }
}

```

# Answer
> 2 votes
**TL/DR:** Your LEDs without resistors are diverting all the current away from the transistors so they are unable to switch.

**In detail:**

Let's take a quick look at just one small portion of your circuit in more detail:

simulate this circuit – Schematic created using CircuitLab

I have added an extra resistor into the circuit - Rw - which represents the resistance of the wires and pins of the LED, and I have given it a nominal 0.1Ω value.

Now, let's say you set the GPIO HIGH, so it outputs 5V. The LED, D1, is a typical red LED with a forward voltage of, say, 2V. Let's calculate the current through the LED.

* I = (VCC \- VF)/R = (5 - 2) / 0.1 = 3 / 0.1 = 30A

30A?! But the GPIO can't provide more than 40mA *absolute maximum*. So all that *can* come from the GPIO is being sent straight through the LED leaving nothing (much) for the transistor.

Oh and yes, all that current demand is doing unspeakable damage to the Arduino's GPIO pin.

The transistor's Base-Emitter junction has about a 0.7V drop across it, and, if it weren't for the LED, with the 1kΩ resistor that gives (5-0.7)/1000 = 4.3mA. Which with a hFE of around 100, would give a collector current of around 430mA. And that should be fine for most small relays.

But with all the current being dumped through the LED what can get through to the transistor won't be enough to turn on the relay.

So increasing the resistance of the wire to the LED will decrease the current demands of the LED. And of course you do that by adding a resistor. So let's make that 1kΩ - a decent enough value for a simple indicator LED:

simulate this circuit

Now let's do the calculation for the LED's current:

* I = (VCC \- VF) / R = (5 - 2) / 1000 = 3 / 1000 = 3mA

Add that to the 4.3mA that wants to go through the transistor, and we have 7.3mA in total.

Now that is way below what the Arduino's GPIO can provide, so the IO pin is happy, the LED is happy and, most importantly, the transistor is happy.

# Answer
> 1 votes
This is not an answer but its too big to be a comment. I can't solve your problem, but hopefully I can point you in the right direction.

I think the first problem you have is you have talked this problem in one chunk. I think even some of the more experienced users would have a problem hitting this in one go. You need to break it down into simple units (Functional decomposition if you want to be posh).

The problem you are asking about is why your transistor doesn't work. You have used an LED and you think the correct signals are being sent.

So Phase one, take the transistor and test it in isolation, then you know its working. Secondly does it still work when the Uno is controlling it rather than just a battery?

Does the object you are powering via the transistor work on its own? Does it work when you add it to the uno and transistor?

You get the idea. To be honest I suspect it might be an issue with lack of power.

---
Tags: arduino-uno
---


# Question
Title: Differential voltage measurement with Arduino UNO
**EDITED:** I bought a very sensitive (and expensive) pressure sensor which requires differential analog measurement. I am an amateur hobbyst and a total beginner in Arduino so I would like to ask some advice on how to connect the device so nothing would be damaged.

In the figure below is the scheme which I've got form the manufacturer along with schematic on how I am going to connect that:

* the wire colours are as in the provided device,
* the symbols are as they were attached to the wires,
* the resistor was provided and connected by the manufacturer.

As far as I understood the sensor manual I should connect the device to analog pins as in the schematic below, and read the A0 and A1 and subtract the signal values. Is that fine? Should I connect the wire going to A1 to Arduino GND as well?

Or should I connect the GND instead of A0 line in the image below?

EDIT: Original connection scheme from the DS and link to the CL1A sensor www and link to the sensor datasheet (only in Polish) Yeah, possibly I misunderstood something.

# Answer
> 2 votes
According to the update, which shows the datasheet, you have one BIG mistake and one smaller mistake.

The big mistake is that you inverted the polarity! Look carefully. The +24V wire goes to the + pin of the supply, while the ground to the - pin.

Moreover the DAQ board has a differential one, but one of them is tied to ground.

So I suggest you to attach the wires in this way:

# Answer
> 2 votes
You do not need to do any kind of differential measurement here. The Arduino analog input measures voltages relative to ground. Then, as long as the Arduino and the power supply share a common ground, you should be fine.

On the other hand, you may need a voltage divider. I have seen a few sensors interfaced the same way (GND, +24V and signal), which output a voltage between 0 and +10 V. That could fry the Arduin, and maybe also the sensor. Check the datasheet to see the maximum voltage the sensor can output, and use a voltage divider to get that safely into the 0 – +5 V range.

# Answer
> 2 votes
The output of that sensor is an industry standard "4-20mA" (known as a *current loop*). That means that the current output from the `+S` wire varies between 4mA and 20mA depending on the pressure. You need to convert that current into a voltage so that the Arduino can sample it.

Note that your attempt at a schematic is completely backwards. You must connect the +24V pin to +24V on a power supply. GND must be connected to GND on the power supply, and also GND on the Arduino.

Now for the signal. Yes, a resistor is the simplest way of converting a current into a voltage. Simply pass the current through the resistor to ground and a voltage will be dropped across it.

According to Ohm's Law, V=IR. Or, to turn it around, R=V/I.

Your maximum current is 20mA (0.02A) and your desired maximum voltage is 5V. So you can put those values into Ohm's Law and get a resistance:

* R=V/I = 5/0.02 = 250Ω.

Now 250Ω resistors aren't that common, but 220Ω ones are. So what would that give us?

* V = IR = 0.02 * 220 = 4.4V

Perfect. And at the lower (4mA) end of the range?

* V = IR = 0.004 * 220 = 0.88V.

So with a 220Ω resistor you would get a voltage reading of between 0.88 and 4.4V on the Arduino.

(Note: the datasheet recommended 100Ω would be more suitable for a 3.3V Arduino - it would give between 0.4V and 2V).

For safety I would also include a small inline current limiting resistor and 5.1V zener diode. If the 220Ω resistor should fail or become disconnected you would get the full 24V (or somewhere about there) across the Arduino's A0 pin. It's limited to 20mA so may not be a problem, but you can't be sure, so best to add that to clamp the voltage to a maximum of 5.1V. After all, a zener diode is cheaper than a new Arduino.

And to clarify - the schematic:

simulate this circuit – Schematic created using CircuitLab

---
Tags: sensors, analogread
---


title: Arduino not detected

text:
# Question
Title: Arduino not detected
I took an Arduino from a friend yesterday but when I connect it to the laptop there is no light blinking from the Arduino and the laptop doesn't detect any device.

Is there a problem with the Arduino or is there a possibility that the USB has problems?

# Answer
> 0 votes
Are you sure your laptop doesn't detect any device? It is possible that you need to install right driver for your arduino. The problem could be with:

1. Cable: Try to replace it with a working cable
2. Drivers Issue: You need to install driver for your `Arduino`. Generally, your laptop will issue warnings if it didn't find any appropriate driver for it.
3. USB-To-UART Bridge: This is an IC in `arduino board`. It needs to be working for laptop to detect your board.
4. Microcontroller: Since, you told us that your board is blinking, then `microcontroller` will be working for sure.

Can you see any part getting hotter? Have you tried with other laptop and cable?

# Answer
> 0 votes
Adding on to abhiarora's answer, if there are no lights at all on the Arduino, and you verify your cable is outputting power, then you may have shorted the device and need to replace the USB port diode. On my Arduino Nano, this diode is directly under the USB-mini port, on the bottom of the board.

Picture of diode:

I replaced this on my Arduino Nano with the CDBW0520L-HF from Comchip Technology and the Arduino worked perfectly. (Link provided is from www.arrow.com).

And in case you have a Chinese Arduino Nano like me:

# Answer
> 0 votes
When you say Arduino, which product specifically are you referring to ? the Arduino UNO ?

Assuming it is the Arduino UNO (or Nano) you will need to first check if it is a genuine Arduino product or a clone (not that there is anything wrong with using a clone). Check your board for a CHIP near the USB port. See if it reads FTDI or CH340. If it reads CH340, then you have a clone. Not to worry, you can still use it as any normal Arduino, you will just need to install the appropriate drivers for the CH340 chip. A simple search for "CH340 driver" can fetch you the right results for your operating system.

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


# Question
Title: DHT11 not giving correct value if I attaching a servo motor
So I am using a servo motor and 2 DHT11s in my Uno, when I attach them separately it works well. But when I try to attach both, servo working correctly but DHT11 giving weird number(DHT11 was side by side, one gives 22oC and another gives 30oC sometimes -999).

I am powering both devices by using 5V and GND from arduino to a breadboard and then DHT11 and Servo power pin to the breadboard. All signal pin are direct from devices to arduino.

Am I power both devices wrong? or is there's a way to solve this?

Thanks

EDIT: this is the code

```
#include <Servo.h>
#include <dht.h>

dht DHT;

#define DHT11_PIN 7
#define DHT11_PIN2 6
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  int chk = DHT.read11(DHT11_PIN);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  int chk2 = DHT.read11(DHT11_PIN2);
  Serial.print("Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("Humidity = ");
  Serial.println(DHT.humidity);
  delay(1000);
}

```

For the servo, I used GWServo S03N STD.

# Answer
> 1 votes
Your code looks like there is no bug in there. You might want to look at using a library that lets you assign a pin in the constructor, so you don't need to read from a specific pin. There might be something internal going on that you don't know (or want to know) about. As for the movement of the servos do you realise you a rotating 181 degrees `int p = 0; p <= 180` is 181 degrees, drop the `=` if you wanted 180. Also `pos++` is the same as `pos += 1` but requires less of those tiring key presses :)

You say that the DHT11s work on their own. The servo works on its own. So it not a hardware fault. I assume its not a wiring fault, but please double check. That means it has to be something to do with the power. If you are powering the servo from a digital pin then this is unlikely to work, try powering it from the 5V output pin on the other side of the board.

However if you are powering it from the 5V output pin and it doesn't work then you need to power it from a external source, a mobile phone charger will do (if you have one you can chop the plug off). The problem with using external PSU is you must tie the grounds together. Doing this means the Arduino and the external device agree what zero volts is and things work. This is easily done by taking the gnd of the PSU and putting it in the GND connector of the Arduino and the taking the GND for the servo from the other GND on the Arduino.

I hope that all makes sense, if not tell me what you need clarifying.

---
Tags: servo
---


# Question
Title: Hardware interrupts for buttons not directly assigned to pins
The Adafruit LCD shield offers an LCD and access to 4 button, using only a two wire connection with the Arduino. This is achieved with the MCP23017 I2C port expander IC.

These buttons are not directly assigned to pins, since only two pins are required for the whole communication, via the I2C protocol.

Can i use a hardware interrupt with any of the 4 buttons? If not, is there any workaround to trigger an interrupt when one of these buttons is pressed?

PS: I am using Arduino Due

# Answer
The MCP23017 has two interrupt outputs. The Adafruit shield however doesn't bring out either of those two pins. You could solder a wire between one of these pins and one of the unused arduino-header pins.
> 1 votes

# Answer
No, you can not while keeping the shield intact but it's possible I think.

https://learn.adafruit.com/rgb-lcd-shield/downloads

Here if you see the schematic and fabrication print, you will see that buttons are connected to MCP23017 I/O port. Now if you can connect to the MCP23017 pin corresponding to button you may detect the voltage change. This can be used to trigger interrupt.
> 0 votes

---
Tags: i2c, arduino-due, lcd, interrupt, button
---


title: Simple 2 Servo Synch

text:
# Question
Title: Simple 2 Servo Synch
I have two servos connected to an Arduino, They work fine if i write to them one by one so the wiring is all correct. I have seen a lot of examples here but none are facing the same issue. I have a simple for loop with Servo.write() on two servos (Facing each other) one going clockwise and the other going counterclockwise. I just want them to rotate at the same time and i cannot connect them to the same signal line since their movement is opposite. My Code Is:

```
 for(int pos = 0; pos < 90; pos += 2)
 {
     delay(200);
     int pos7 = 90-pos;
     pos7 = pos7*(-1);
     myservo6.write(pos);
     myservo7.write(pos7);
 }

```

**What Is Happening** Both the servos go to the "same position" (if one is at 90 the other is at 0 etc.. ) Yet one goes there slow and the other goes super fast(not affected by delay). Even though my delay should affect both servos.

If i remove the delay they both go to the same position yet very fast. **What i need is for them to move together slowly to the position.**

# Answer
> 1 votes
The Arduino Servo class is intended to accept *positive* values only, in the range of 0-180.

In addition to reversing the values for one servo by subtracting from 90, your code is also negating the values by multiplying by negative one.

That results in an invalid argument to the Servo function. It's unclear exactly what happens, but likely possibilities include an invalid pulse, or no pulse at all.

At the end of your for loop, you subtract 90 from 90 producing zero, and invert it to still zero. Zero is a valid input to the Servo function, so a valid output is produced and the "reversed" servo finally has a position it can seek to.

---
Tags: arduino-uno, servo
---


title: Manual Arduino Due Installation

text:
# Question
Title: Manual Arduino Due Installation
Not sure if this is the right place to post this.

I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but it just says there is an error downloading the files.

Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

---

UPDATE

When I open the Boards Manager, I get :

`Error downloading http://downloads.arduino.cc/packages/package_index.json`

and when I try to install Due support, I get :

`Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2`

I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.

I have manually downloaded *sam-1.6.4.tar.bz2* and extracted the contents to *C:\Arduino\arduino-1.6.5\hardware\arduino\sam* (I had to manually create the *sam* folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :

`Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified`

Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.

---

UPDATE 2

Question has been answered: https://github.com/arduino/Arduino/issues/3358

Many thanks to Federico Fissore!

# Answer
I had the same problem described above. Error downloading http://downloads.arduino.cc/packages/package\_index.json

I solved the problem, just deleting the temporary file: "package\_index.json.tmp"
> 1 votes

---
Tags: arduino-ide, arduino-due
---


# Question
Title: Compiling source with Arduino.h with avr-g++
How should I include the Arduino libraries when I'm compiling from the the command line? I tried to do it like this:

```
avr-g++ -g -Os -Wall -mcall-prologues -mmcu=atmega328p -fno-exceptions -o blink.obj blink.cpp -L. -lutil -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" -I"D:\Projects\Arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores"

```

but it returns `undefined reference` to the function that I am trying to use.

*Arduino version: 1.8.2*

# Answer
> 1 votes
You need to do a whole lot more than just run the one command.

You need to compile each individual source file for the libraries you want (using `-c` to just compile and not link), then (ideally) archive them into a library file. Do the same for the core. Then you need to add paths to your sketch compilation command pointing to where the header files are for those libraries, and compile the sketch to an object file (again with `-c`). Finally you need to link everything together into an ELF file, and convert that to a HEX file.

TBH you're best off using an already-existing Makefile project, or arduino-builder.

---
Tags: compiler, avr-toolchain
---


# Question
Title: Reducing noise and finding sampling rate
I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using `for` loop for this purpose.

```
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int i = 0;
int sensorPin = A0;
int sensorValue = 0;
int highest=0;
int lowest=0;
float mean=0;

void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  lcd.print("Hello");

}

void loop()
{

  for(;;)
  {
    mean=0;
    for(i=0;i<8000;i++)
    {
       sensorValue = analogRead(sensorPin);
     highest=max(highest,sensorValue);
     lowest=min(lowest,sensorValue);
     mean = mean + (highest-lowest);
    }
    mean = mean/8000;
    delay(10);
    lcd.setCursor(0, 1);
    lcd.print(mean);
  }

```

Will this set sampling rate to 8000 samples/sec ?

Also I was receiving a lot of noise at *A0* which often led to the lowest value to be 0. In the image : The red wave is a constant dc voltage of 2.7 V from power supply.  How do I overcome this noise so that mean value is accurate and precise ?

# Answer
Just to as a complement to Majenko's answer (which I second), there are a couple of flaws in your program that may be related to your problem:

* `lowest` is always zero, as it is initialized to 0 and cannot increase
* your computation of the mean is incorrect: the mean is the sum of the readings divided by their number
* you fail to reset `lowest` and `highest` between consecutive runs of 8000 samples
* there is no point in putting all of `loop()` inside an infinite loop.

Assuming you really intend to print summary statistics on runs of 8000 samples, as your code suggests, I would write it like this:

```
const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
const uint32_t SAMPLE_PERIOD = 125;  // 125 us

void loop()
{
    long sum = 0;
    int lowest = INT_MAX, highest = 0;

    uint32_t lastTime = micros();
    for (int i = 0; i < SAMPLE_COUNT; i++) {

        // Wait until it's time.
        while (micros() - lastTime < SAMPLE_PERIOD) ;
        lastTime += SAMPLE_PERIOD;

        // Take and process the sample.
        int sensorValue = analogRead(SENSOR_PIN);
        sum += sensorValue;
        highest = max(highest, sensorValue);
        lowest = min(lowest, sensorValue);
    }
    float mean = (float) sum / SAMPLE_COUNT;
    Serial.print("mean: "); Serial.print(mean);
    Serial.print(", minimum: "); Serial.print(lowest);
    Serial.print(", maximum: "); Serial.println(highest);
    Serial.flush();
}

```

---

**Edit**: I changed the code in order to keep a roughly constant sampling rate of 8000 samp/s. The main change is that, before taking a reading, we wait until it's time to do so (until `micros() - lastTime >= SAMPLE_PERIOD`).

Note that `lastTime` could be updated with `lastTime = micros()`, in which case it would have hold the time we last took a sample. By updating it with `lastTime += SAMPLE_PERIOD` it instead holds the time we *shoud have taken* the last sample. This is the right choice for enforcing a given *average* sampling rate.

**Running on an Uno**: I have no experience with the Due, but here are some remarks that would apply to an Uno, or any other AVR-based Arduino:

* `analogRead()` takes about 110 µs, which means we cannot sample more than one channel, and we only have about 15 µs to process the sample. Here the processing is simple enough that the Arduino can do it in this limited time.
* There is some jitter in the sampling, because `micros()` has a limited resolution of 4 µs, because of the timer interrupt kicking in from time to time, and because the `while` loop takes a finite amount of time.

If I were to do something similar on an Uno, I would forgo `analogRead()`, configure the ADC to be triggered by a timer, and set the timer to trigger the DC every 125 µs. Not only would this get rid of the jitter, it would also allow the CPU to do its job in parallel with the ADC, instead of just sitting idle and waiting until the ADC is done. This would allow for more complex per-sample processing.

**About the Due**: As I said, I have no experience with this board. It has a more capable processor, but this tells you nothing about the speed of its ADC. I would expect to face the same issues as with the Uno, though maybe to a lesser degree. I *guess* it should be possible to trigger the ADC from a timer, but I have no idea how to do so.
> 2 votes

# Answer
> Will this set sampling rate to 8000 samples/sec ?

No, that will make it perform a block of 8000 samples as fast as it can. There's absolutely nothing in there that has anything to do with time, so how can "seconds" be included in the description of it?

> How do I overcome this noise so that mean value is accurate and precise ?

That depends on where the noise is coming from. Maybe if you slowed down your sampling you wouldn't get the noise. Maybe if you made a better connection to whatever it is you're sampling you'd get less noise. Maybe if you added some external filtering you'd get less noise. Maybe if you used a different mathematical model for determining what your average value is you'd not care about the noise.
> 0 votes

---
Tags: programming, arduino-ide, arduino-due, analog-sampling
---


# Question
Title: How do you balance an Arduino quadcopter using calculated gyro values?
I was working on an Arduino quadcopter project. I setup all my hardware and was having balancing problems with my software end. I am using an MPU-6050 gyro and accelerometer. I have calculated the angle of the quad in relation to the ground and was trying to implement these values by adjusting the output values to each of the four motors.

Here is some of my code:

```
    x=(-computedGyroAngleX-3.5)*10;
    y=(-computedGyroAngleY-2)*10;
    esc1.writeMicroseconds(rc_values[RC_CH1]+x-y);
    esc2.writeMicroseconds(rc_values[RC_CH1]+x+y);
    esc3.writeMicroseconds(rc_values[RC_CH1]-x-y);
    esc4.writeMicroseconds(rc_values[RC_CH1]-x+y);

```

If the quad is leaning forward I increase the power at the front of the quad and reduce it at the back. I do the same for the y axis. But I run into problems when I test out the quad. It flips over to the side or forward. How would I fix this?

# Answer
That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side. The center of gravity should be taken care of when the drone is not balancing properly.
> 1 votes

---
Tags: arduino-uno, drone, algorithm
---


# Question
Title: How do I connect through a HC-05 to PS4 Controller?
Searching for Arduino and PS4 on google, I find always the same construction using a USB host shield and a Bluetooth dongle.

But I'd like to connect a PS4 Controller to a HC-05 device. Is it possible? If not, why not?

# Answer
> 3 votes
The HC-05 uses the Bluetooth Serial Port profile (SPP). The PS4 controller doesn't.

Hence you need something that is capable of using the same profile that the PS4 controller uses (HID?). And to that end you need something a little more configurable than a simple HC-05. One option is, as most people use, a USB Host shield with a Bluetooth dongle that can then be configured to communicate using the right profile.

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


# Question
Title: New Microcontroller - programmer is not responding -
I got an Arduino and after I was playing with it, I noticed that its internal micro controller si removable and decided to buy another micro controller. After I got the new one (atmega328P) and replaced with the original which came with the Arduino, I started to upload a sketch but it does not work.

I get the following:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

```

If I use the Original MC which came with the Arduino works fine, but with the new one it does not.

Did I buyed a bad/wrong MC, or I need to make something else? Both have the same name :

```
ATMEGA328P-PU

```

The new micro controller has already a boot loader installed.

# Answer
> 1 votes
I managed to fix the problem by downloading the latest version of the Arduino IDE from their website and works fine now.

I use Linux mint 18 and installed Arduino via `apt` and I really do not know why I managed to install the boot loader, but failed with uploading the Sketches.

---
Tags: arduino-uno, atmega328
---


title: Searching for a good keypad

text:
# Question
Title: Searching for a good keypad
I'm wanting to make a keypad for my gragedoor. I found one like this but i don't think it is very waterproof.

Now i'm wondering if someone of you know a good keypad that can be used outdoors and can be connected to a arduino (preferably arduino nano).

Hope you can help.

Edit if found this keypad will i be able to program this one with a arduino? link

# Answer
> 2 votes
The membrane keyboard you have linked (first link) in your question should be water resistant, if not water proof.

We use something similar at my work. You can have the keypad stuck to the outside of the enclosure and then have a rubber seal (or silastic) sealing where the ribbon cable enters the enclosure.

You will notice that the ribbon cable pretty much exits the bottom of the keypad. The better ones to get, if you can find them, are the ones where the ribbon cable exits the keypad further away from the edge (see example image below). That way the adhesive backing of the keypad seals the cable entry into the enclosure.

As far as hooking it up to an Arduino - no problems at all. A 16 key matrix keyboard has 8 connections, 4 for each row and 4 for each column. Every time you press a key, the row and column are shorted together.

The way I would connect it up is to have the rows connected as inputs and the columns as outputs. One by one I would turn one of the columns on (HIGH) and see which input(s) are reading a HIGH. If it is I know that that key (row and column) is pressed. This method will handle multiple keys pressed at once.

There is an walk-through tutorial posted at instructables.com.

The more expensive keypad in your second link and this one both have the option of connecting by PS2. There is an Arduino page on connecting and controlling a PS2 keyboard here.

---
Tags: arduino-nano
---


title: Link Arduino Uno to Particle Photon

text:
# Question
Title: Link Arduino Uno to Particle Photon
I'm working on a prototype with a Particle Photon, but I've realized the required number of pins is bigger than the number of pins on my photon.

I thought I could have an Arduino Uno wired to some sensors, and link the Arduino to the photon via a Software Serial from the Arduino (as its serial pins will already be busy) to the Serial pins of the photon.

Is it possible, and is there a better way to solve my problem?

# Answer
If you just need to get more inputs you could use multiplexing. The multiplexing method is more robust than software serial will be. How to do this is explained here and datasheet for the commonly used cd4051 here

You don't specify what kind of sensors you will use. if the sensors are i2c or similar it is possible to daisychain (multiplex too) them.
> 1 votes

# Answer
Everything is possible, it is programming. People are doing software-only USB on AVRs.

I doubt that the effort is worth it, given how hard it is to debug such low-level code. Besides you can use on-board UART if you don't need the USB connectivity - just disable it.

Main question is - where is the main software run, aka "Who's the Brain"? If Photon, maybe you can use SPI? SPI is dead-simple to emulate in software.
> -1 votes

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


title: Air quality sensor reading meaning

text:
# Question
Title: Air quality sensor reading meaning
So I got this air quality sensor running, and it's outputting some numbers. I've read some tutorial online and it looks like the smaller the number the better the air quality. But I don't understand what is the meaning of those number. Like what is the unit of measurement? For example, the temperature sensor gives you numbers in Celcius degree.

http://wiki.seeed.cc/Grove-Air\_Quality\_Sensor\_v1.3/

# Answer
One of those MQ gas sensors ? They are electrochemical sensors. They can be calibrated more or less with a known concentration of a certain gas. But since the are often sensitive to a number of gasses, you do not know the concentration of that specific gas that was used for calibration.

A number that is going up and down is what you have. You can make a graph with it to show the value for each hour or each day.

The MQ gas sensors have a "preheat" or "burn-in" time. It is often 24 hours. Keep the sensor on for 24 hours to get more stable output values.

A temperature sensor is completely different, it contains electronics inside and has been calibrated at the factory. The MQ gas sensors are just a few wires, a heater and some chemicals.

\[**ADDED**\]
That is a module with the MP503 gas sensor. It just like the MQ sensors a electrochemical gas sensor. According to the datasheet it is sensitive for alcohol and smoke and the "preheat" or "burn-in" is called "aging time" and can be up to one week! The module has a amplifier.

The detection of gasses is according to a certain curve. To calculate the concentration of gasses a calculation is needed (and a calibrated sensor). I don't see that calculation in the supplied library. So all you have is numbers that change according to the air quality. That's all. And that is normal for these sensors.

Read the information and pdf files on that seeed page about this Grove module. It clearly says that you can't measure the concentration of gas (not "quantitatively"), you can only tell if the air quality gets better or worse (qualitative).
> 2 votes

---
Tags: arduino-uno
---


title: Change Word Color

text:
# Question
Title: Change Word Color
I tried to change the color of the words but nothing happens, I do not know what I'm doing wrong. I am using official Arduino editor of code with words.txt

```
#######################################
# Syntax Coloring Map For testing
#######################################

#######################################
# Datatypes (KEYWORD1)
#######################################

Test    KEYWORD1
Diego   KEYWORD1
Ulises  KEYWORD1
PALMA   KEYWORD1

#######################################
# Methods and Functions (KEYWORD2)
#######################################

doSomething KEYWORD2
Argentina   KEYWORD2
Brasil      KEYWORD2
Alemania    KEYWROD2
Chile       KEYWORD2

#######################################
# Instances (KEYWORD2)
#######################################

#######################################
# Constants (LITERAL1)
#######################################

```

# Answer
The question's reference to “official Arduino with words.txt” is rather ambiguous. So far there has not been any clarification whether the question refers to the usual *Arduino IDE* environment.

However, supposing the question intended to refer to the usual environment, note that the Library Tutorial document at arduino.cc says to do the following to set up a list of highlighted keywords:

> Create a file called **keywords.txt** in the \[library\] directory

Thus, renaming your *words.txt* to *keywords.txt* may solve the problem.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Error 400. The request has an invalid header name ESP8266 (HTTP-POST)
I'm trying to send a http post to my server from an esp8266-Wifi (I use the ESP8266 library)

I check all my http post format, and I guess is okay... but at the response, the monitor serial **answer** me like this:

```
Requesting POST: HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Sat, 10 Jun 2017 23:12:48 GMT
Connection: close
Content-Length: 339

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>

closing connection

```

and this is my code:

```
#include <ESP8266WiFi.h>
const char* ssid     = "Putostodosmenosyo";
const char* password = "CetriX.2016%Gdl";

const char* host = "187.201.44.110";

const String Cadenadatos = "info=Micanton|2017-06-09%2012:00|25" ;
//const String Tamano = String(Cadenadatos.length()) ;
const String postiu = "POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1\r\nHost:187.201.44.110:80\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length:144\r\n\r\n?info="+String(Cadenadatos)+"\n" ;
const String postam = String(postiu);

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

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

 while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  delay(2000) ;
}

void loop() {

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host,httpPort)) {
    Serial.println("Conexion fallida");
    return;
  }

 //String data = "pst=temperature>" + String(random(0,100)) +"||humidity>" + String(random(0,100)) + "||data>text";

   Serial.print("Requesting POST: ");
   // Send request to the server:
   //client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
   //client.println();
   //client.println("co2kelling.hopto.org") ;
   client.println("POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1");
   client.println("Host: co2kelling.hopto.org");
   client.println("Content-Type: application/x-www-form-urlencoded");
   client.print("Content-length: ");
   client.print(postiu.length());
   client.println();
   client.print(String(Cadenadatos));
   while(client.connected())
   {
    while(client.available())
    //String line = client.readStringUntil('\r') ;
    Serial.write(client.read()) ;
   }

   /*delay(500); // Can be changed
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }*/
  Serial.println();
  Serial.println("closing connection");
  delay(5000);
}

```

**NOTE**: this is my fixed url *http://187.201.44.110/wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino?info=Micanton|2017-06-09%2012:00|25*

**EDIT**

This is my Post format:

```
POST /wsCo2Keellingv1002/wsCo2Keelling.asmx/GuardaInfoArduino HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded
Content-Length: length
info=string

```

# Answer
You are lacking the required blank line between the headers and the content. Also your content length is wrong.

Change

```
client.print(postiu.length());

```

Into

```
client.println(Cadenadatos.length());

```
> 1 votes

---
Tags: arduino-uno, esp8266, web-server, networking, http
---


title: DHT22 and DS18B20 together

text:
# Question
Title: DHT22 and DS18B20 together
I am trying to get DHT22 and DS18B20 to work together. The code below is the one I am using:

```
#include <SD.h>
#include "SPI.h"
#include "DHT.h"
#include <RTClibExtended.h>
#include <Wire.h>
#include <LowPower.h>
#include <stdlib.h>
#include <avr/interrupt.h> // library for interrupts handling
#include <avr/sleep.h> // library for sleep
#include <avr/power.h> // library for power control
#include <OneWire.h>
#include <DallasTemperature.h>

#define DHTPIN 7 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22  (AM2302)
#define wakePin 2 //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ONE_WIRE_BUS 4  //DS18B20 is plugged into pin 4

RTC_DS3231 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
const int chipSelect = 10;
int interval_sec=0; //An alarm interval in seconds
int interval_min=5; //An alarm interval in minutes
int interval_hr=0; //An alarm interval in hours
char file_name[25]="Readings.csv"; //
DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature.

void setup () {
  Serial.begin(9600);
  delay(3000); // wait for console opening
  /**RTC**/
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

  /**INTERRUPT**/
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT_PULLUP);
  Wire.begin();
  //clear any pending alarms
  rtc.armAlarm(1, false);
  rtc.clearAlarm(1);
  rtc.alarmInterrupt(1, false);
  rtc.armAlarm(2, false);
  rtc.clearAlarm(2);
  rtc.alarmInterrupt(2, false);
  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to arduino D2 pin for wake-up
  rtc.writeSqwPinMode(DS3231_OFF);
  //Initialize DS18B20 libraries
  sensors.begin();
  /**SD CARD**/
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
  //Remove File from SD card and create a new one
  SD.remove(file_name);
  File dataFile = SD.open(file_name, FILE_WRITE);
  dataFile.println("Date,Hour,Minute,Air_Temp,Humidity,Surface_Temp");  //Write the header
  dataFile.close();
   Serial.println("Initialisation complete.");
  delay(100); //Allow for serial print to complete.
}

void loop () {
  DateTime now = rtc.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" (");
  Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  Serial.print(") ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  /**Temperature and Humidity**/
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  //float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  //if (isnan(h) || isnan(t) || isnan(f)) {
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
    // Compute heat index
    // Must send in temp in Fahrenheit!
    //float hi = dht.computeHeatIndex(f, h);
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.println(" *C\t");
    delay(3000); // wait for console
    /**DS18B20**/
    // call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus
    sensors.requestTemperatures(); // Send the command to get temperatures
    float surface_temp=sensors.getTempCByIndex(0);
    Serial.print("Temperature for the device 1 (index 0) is: ");
    Serial.println(surface_temp);
    delay(3000); // wait for console

    /**Store on SD**/
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open(file_name, FILE_WRITE);
    String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + surface_temp;
    //String dataString = now.day() + String("/") + now.month() + String("/") + now.year() + String(",") + now.hour() + String(",") + now.minute() + String(",") + t + String(",") + h + String(",") + String("surface_temp");
    //Serial.println(dataString);
    // if the file is available, write to it:
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      //Serial.println(dataString);
    }
    // if the file isn't open, pop up an error:
    else {
      Serial.println("error opening file to log data");
    }
    /**INTERRUPT Based sleep**/
    DateTime nextAlarm = now + TimeSpan(0, interval_hr, interval_min, interval_sec);
    //Format is TimeSpan(day,hour,min,sec). Either use interval_min or interval_sec
    Serial.print("Alarm at:");
    Serial.println(nextAlarm.hour());
    Serial.println(nextAlarm.minute());
    Serial.println(nextAlarm.second());
    rtc.setAlarm(ALM1_MATCH_HOURS, nextAlarm.second(), nextAlarm.minute(), nextAlarm.hour (), 1); //set wake-up time here
    rtc.alarmInterrupt(1, true);
    delay(3000); // wait for console
    attachInterrupt(0, wakeUp, LOW); //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    //Arduino enters sleep mode here
    detachInterrupt(0);
    //execution resumes from here after wake-up
    //When exiting the sleep mode we clear the alarm
    rtc.armAlarm(1, false);
    rtc.clearAlarm(1);
    rtc.alarmInterrupt(1, false);
    Serial.println();
    delay(3000);
}

void wakeUp() {
  // here the interrupt is handled after wakeup
}

```

The above code ideally should read and store the temperature from DS18B20, and temperature and humidity from DHT22 and then go to sleep for a pre-determined time (5mins now) and then wake up when an interrupt is generated from the RTC.

However, I am unable to get both DHT22 and DS18B20 to work together. The code above works as expected if I comment out the code for DS18B20. Similarly, if I just run the examples (named Single and Simple) for DS18B20 as provided by DallasTemperature on the same Arduino keeping all the connections intact (DHT, RTC, SD Card, along with DS18B20) the DS18B20 also work as expected. Hence, I think I can be certain that the connections are proper. However, if I run the code above which include both DHT22 and DS18B20, then the output I get is as follows:

```
Initializing SD card...card initialized.
Initialisation complete.
201Initializing SD card...card initialized.
Initialisation complete.
2⸮

```

I would appreciate if someone can point me to where I am going wrong.

P.S.: I have also successfully tried a simple program like the one below to ensure that there are no conflicts in libraries of DHT22 and DS18B20.

```
#include <DallasTemperature.h>
#include <OneWire.h>
#include <DHT.h>

#define ONE_WIRE_BUS 4
#define DHTPIN 7     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup(void) {
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  sensors.begin();
}

void loop(void) {
  sensors.requestTemperatures();
  Serial.print("Temperature1: ");
  Serial.print(dht.readTemperature());
  Serial.print(" Temperature 2 : ");
  Serial.println(sensors.getTempCByIndex(0));
}

```

# Answer
> 2 votes
My first thought was that sram is being overwritten. That seems to be the case, as you have confirmed.

The SD library uses a lot of sram memory, because it has to handle a table of the FAT data structure from the SD memory card.

You don't use the 'PSTR()' or the 'F()' macro and not the `PROGMEM`.
For example this code:
`Serial.println("Dallas Temperature IC Control Library Demo");`
creates that text in Flash memory and during startup that text is also copied to sram memory. You can avoid that by forcing that text to stay in flash memory only with the 'F()' macro:
`Serial.println(F("Dallas Temperature IC Control Library Demo"));`

Perhaps you have already seen sketches that use the 'F()' macro a lot.

The names of the days of the week can be placed in Flash code with PROGMEM. It requires special functions to read data from PROGMEM, since the AVR microcontrollers can not read data from flash directly.

\[**ADDED**\] The 'F()' macro, the 'PSTR()' and the PROGMEM are explained here: Nick Gammon about PROGMEM

---
Tags: arduino-uno, sd-card, temperature-sensor, rtc, ds18b20
---


# Question
Title: Raspberry Pi Outputting Signal to arduino
I have been trying to get my raspberry pi to output a signal of High or Low, which is then picked up by digital pin 4 on my arduino.

On the raspberry pi, I have connected the output to GPIO 24 and have set up a simple to circuit with an led and 220 ohm resistor in series to check if there was any output. I did manage to get the led to turn on and off due to typing commands into the console on the raspberry pi, so that can't be the problem.

For the raspberry pi side of things, I have installed the WiringPi library and typed these commands:

```
gpio -g mode 24 out

```

This set up the GPIO pin and then to turn them off, I used these independently.

```
gpio -g write 24 1
gpio -g write 24 0

```

For my code on my arduino, I have adapted a rtc with stepper motor piece of code that I am working on to go with this sub project.

```
#include <DS3231.h>
#include <Stepper.h>

//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32

//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  // 2048

// Init the stepper object with sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

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

const int raspiPin = 4;
int raspiSwitch = 0;

int  Steps2Take;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  pinMode(raspiPin, INPUT);

  // 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(22, 32, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop()
{
  // Read the state from the raspi
  raspiSwitch = digitalRead(raspiPin);

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

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

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

  // Declare variable for later testing against
  String myTime = rtc.getTimeStr();

  if (myTime == "17:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (myTime == "08:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (raspiSwitch == 1) {

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  }

  delay (1000);

}

```

When I use the else if statement to turn the stepper motor if there is a high signal from the raspiPin, the motor will turn even when the signal is low.

I used Serial.println to output the state of the raspiSwitch variable to the serial output and for some reason, it changes by itself between 1 and 0. I do not know why and would like to resolve this so I can move onto the next stage of connecting it to the internet on a php webpage.

If anyone could help, I would greatly appreciated it

# Answer
> 0 votes
The Arduino and the Raspberry pi should have a common ground. Connect the ground pin of the Arduino to the Raspberry pi. Both boards should be powered by the same power source and connect a pull-down resistor from the digital pin of the Arduino to ground. about 10Kohms might be enough.

---
Tags: arduino-uno, raspberrypi
---


# Question
Title: HMC5883L not working in continuous mode!
I'm just starting with the HMC5883L, I'm writing my code with C and also my own I2C library.

I noticed that the values on the Arduino IDE's serial monitor are constant.

Then I developed a function to read the mode register. So the value should be 0x00 for continuous mode.

But, what I get is that the device work in single mode which has the value 0x01 at first cycle of the program, then it goes to idle mode with the value 0x03.

So, why is that and what to do?

```
#include <I2C.h>

#define HMC5883L_read   0x3D
#define HMC5883L_write  0x3C

#define Configuration_Register_A    0x00  //Read/Write
#define Configuration_Register_B    0x01  //Read/Write
#define Mode_Register               0x02  //Read/Write
#define Data_Output_X_MSB_Register  0x03  //Read
#define Data_Output_X_LSB_Register  0x04  //Read
#define Data_Output_Z_MSB_Register  0x05  //Read
#define Data_Output_Z_LSB_Register  0x06  //Read
#define Data_Output_Y_MSB_Register  0x07  //Read
#define Data_Output_Y_LSB_Register  0x08  //Read
#define Status_Register             0x09  //Read
#define Identification_Register_A   0x10  //Read
#define Identification_Register_B   0x11  //Read
#define Identification_Register_C   0x12  //Read
#define declination_angle 3.46

void HMC5883L_init (void);
int16_t data_read (int16_t *results);
uint8_t HMC5883L_read_reg (uint8_t reg);

int16_t results[3];
float m_scale = 1.0;

void setup() {
  // put your setup code here, to run once:
  I2C_init();
  Serial.begin(9600);
  HMC5883L_init();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
}

void loop() {
  // put your main code here, to run repeatedly:
  data_read(results);
  Serial.print("x-axis = ");
  Serial.println(results[0]);
  Serial.print("z-axis = ");
  Serial.println(results[1]);
  Serial.print("y-axis = ");
  Serial.println(results[2]);
  Serial.println();
  Serial.print("mode register ");
  HMC5883L_read_reg(Mode_Register);
  Serial.println();
_delay_ms(500);
}

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;
  I2C_start(HMC5883L_write);
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_start(HMC5883L_read);

  msb = I2C_rx();
  lsb = I2C_rx();
  results[0] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[1] = msb << 8 | lsb;

  msb = I2C_rx();
  lsb = I2C_rx();
  results[2] = msb << 8 | lsb;

  I2C_stop();

  return status_of_process;
}

uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  Serial.println(reg_dat);
}

```

Regards,

# Answer
> 1 votes
The problem stems from this function:

```
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

```

The way I2C in most chips work, when writing, is that the first byte defines the register to write to. All subsequent bytes are the data to write into that register and successive registers.

> To minimize the communication between the master and this device, the address pointer updated automatically without master intervention. This automatic address pointer update has two additional features. First when address 12 or higher is accessed the pointer updates to address 00 and secondly when address 08 is reached, the pointer rolls back to address 03.

So you are actually writing:

```
REG  CONTENT
0x00 0x07
0x01 Configuration_Register_B (0x01)
0x02 0x01
0x03 Mode_Register (0x02)
0x04 0x00

```

You need to either start a new transaction for each register you want to set a value in (*explicit* setting) or rely on the address pointer increment to move to the right register for you (*implicit* setting).

So either:

```
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_B);
  I2C_tx(0x01);
  I2C_stop();

  I2C_start(HMC5883L_write);
  I2C_tx(Mode_Register);
  I2C_tx(0x00);
  I2C_stop();
}

```

Or, since the registers are in sequence in the address space:

```
void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x07);
  I2C_tx(0x01);
  I2C_tx(0x00);
  I2C_stop();
}

```

Oh, and don't forget to have an `I2C_stop()` after reading your register in:

```
uint8_t HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop(); // <----- MISSING
  Serial.println(reg_dat);
}

```

---
Tags: programming, arduino-nano, i2c, c, gyroscope
---


# Question
Title: Problem with using pure C code to program default UART (UART0) in Arduino Mega
Can I code default serial port in Arduino Mega (USART0, I assume) in pure C? I mean to set up it and configure directly by ATmega's registers?

I'm asking because I'm trying to do it and I have a problem. Below is code which I use and Arduino doesn't transfer anything...

```
#include <avr/io.h>

#define F_CPU 16000000
#define BAUD_RATE 9600
#define MY_UBRR (F_CPU+BAUD_RATE*8UL)/(16UL*BAUD_RATE)-1

void setup() {

    UART_Init(MY_UBRR);
}

void loop() {
    UART_Transmit('a');

 }

void UART_Init(unsigned char ubrr)
{
   UBRR0H = (unsigned char)(ubrr >> 8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (1<<USBS0) | (1<<UCSZ00);
}

 void UART_Transmit(unsigned char data)
 {
    while(!(UCSR0A & (1<<UDRE0)))
    UDR0 = data;
 }

```

That code I created following the datasheet for ATmega 2560. It has been compiled and programmed but doesn't work at all...

Please give me any advice. It's important for me use just C code in that case.

# Answer
I suggest to use existing code and copy that or use that.

This is the Arduino HardwareSerial : HardwareSerial.cpp
You can find more code at avrfreaks.net. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.

The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?
> 1 votes

# Answer
I tried your program on an Uno, and it worked as expected once I fixed three problems:

* Removed `#define F_CPU 16000000`. This is not a big issue, but it fixes a warning about that constant being already defined by the Arduino environment.
* Added the `UCSZ01` bit to `UCSR0C` in order to work in 8-bit mode instead of the uncommon 6-bit mode.
* Added the semicolon after `while(!(UCSR0A & (1<<UDRE0)))`.

Note also that there is no point in loading `UBRR0` in two steps. You can just `UBRR0 = ubrr` and trust the compiler to do the right thing.
> 1 votes

---
Tags: arduino-mega, c
---


title: Avoid overflowing of counter

text:
# Question
Title: Avoid overflowing of counter
I have a global uint32\_t that keep tracks of used Bytes:

```
uint32_t usedBytes;
int bytesWritten;

byteWritten = myFile.print(data, FILE_WRITE);

if (byteWritten > 0) {
  usedBytes += bytesWritten;
}

```

What happen if usedBytes is close to the maximum (0xFFFFFFFF)? Will incrementing it make it 0, or stuck at 0xFFFFFFFF?

# Answer
It will wrap around though 0.

```
0xFFFFFFFF + 1 = 0

```

You can add a higher order word to track more data:

```
if (byteWritten > 0) {
    uint32_t newUsed = usedBytes + byteWritten;
    if (newUsed < usedBytes) {
        fourGigsUsed ++;
    }
    usedBytes = newUsed;
}

```

Or you could use `uint64_t` to automate it - however none of the Arduino print routines cope with the `uint64_t` variable type.
> 1 votes

---
Tags: programming, c
---


title: ESP8266 failure to connect to router

text:
# Question
Title: ESP8266 failure to connect to router
I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH\_PD is connected to D8, /RST to D9):

```
void setup() {
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  delay(2000);
  // initialize both serial ports:
  Serial.begin(9600);
  Serial1.begin(115200);
  delay(10000);
  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
}

void loop() {
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.write(inByte);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.write(inByte);
  }
}

```

When launching, I see following output:

```
<"random" bytes>
Ai-Thinker Technology Co. Ltd.

invalid

```

Performing a reset shows more:

```
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ŒÂÕ�MEM CHECK FAIL!!!
äsl�‚rô
Ai-Thinker Technology Co. Ltd.

invalid

```

The mode is set to station:

```
AT+CWMODE?

+CWMODE:1

OK

```

Listing the access points works fine:

```
AT+CWLAP

+CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
+CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
+CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

OK

```

But logging in to my Fritzbox router fails (WPA2):

```
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

```

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in `AT+CWLAP`).

I've tried nearly everything, e.g. `AT+CWMODE=3`, `AT+RST`, `AT+RESTORE`). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.

Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?

Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

# Answer
> 5 votes
It looks like the ESP8266 could not obtain the IP address over DHCP (it was enabled in the ESP8266, but the Fritzbox was configured for a limited range only .200 - .209). When setting the IP explicitly:

```
AT+CIPSTA="192.168.92.82","192.168.92.254","255.255.255.0"

OK

```

and then trying to connect, it worked:

```
AT+CWJAP="ap-2","mypassword"
WIFI CONNECTED
WIFI GOT IP

OK

```

Pinging also works now: :)

```
AT+PING="arduino.stackexchange.com"

+39

OK

```

# Answer
> 11 votes
In my case when I try to connect to my router, I get the following output:

```
AT+CWJAP="myssid","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

```

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:

```
AT+CWDHCP=1,1

```

If that works, you will get this message:

```
OK
WIFI GOT IP

```

# Answer
> 2 votes
I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post.

I did a `AT+RESTORE` followed by `AT+UART_DEF=9600,8,1,0,0` since, as expected, my module expected communication on 115200 after the restore.

Then... as if by magic, everything works now...

```
AT+CWJAP="ssis","pwd"
WIFI CONNECTED
WIFI GOT IP

!

```

I really don't know what was wrong that the `RESTORE` fixed... I must have screwed up the module by experimenting with various commands somehow.

# Answer
> 1 votes
I had many headaches related with this CWJAP:1 error and few others like Ok in return for change IP number command but actually the IP number still the same as before !!! The solution: The AT+RESTORE command to bring the ESP8266 back to the factory defaults... When not logical things happens for unknow reason probably is due to some internal register has dirty values inside and only a AT+RESTORE can normalize them...

---
Tags: esp8266
---


# Question
Title: Corrupted characters with an OLED displaying thermocouple output
I'm super new to Arduinos but I'm learning as I go. I'm in the first stages of a small temperature control project and so far I've been able to display the output of a MAX31855 thermocouple breakout board on 124x64 spi OLED through my Arduino micro.

My problem is that the characters of the temperature are corrupted looking. As I think I understand it, the temperature is changing while it's being written to the display therefore you get overlapping values. I've attached an image of the display.

I've tried making the temp output an integer but that didn't work.

Any input would be greatly appreciated as I'm just banging my head against the wall.

Here's my code:

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MAX31855.h>
#include <U8glib.h>

//Constructor line for OLED

U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9, 8);  // D0=13, D1=11, CS=10, DC=9, Reset=8

// Default connection is using software SPI, but comment and uncomment one of
// the two examples below to switch between software SPI and hardware SPI:

// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO   3
#define MAXCS   4
#define MAXCLK  5

// initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);

// Example creating a thermocouple instance with hardware SPI
// on a given CS pin.
//#define MAXCS   10
//Adafruit_MAX31855 thermocouple(MAXCS);

void draw() {
  double c = thermocouple.readCelsius();
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void setup(void) {

}

void loop() {

  // picture loop
  u8g.firstPage();
  do {

    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

```

# Answer
> 0 votes
The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page"). Because you are taking a reading for each chunk, the temperature can change. Just pull the reading out of `draw` and do it once in `loop`:

```
double c; // a global variable used in draw and loop

void draw() {
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void loop() {

  c = thermocouple.readCelsius(); // set the global variable once

  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

```

---
Tags: arduino-uno
---


title: Converting array to char

text:
# Question
Title: Converting array to char
I'm trying to convert a char array to a char. i used this code

```
char code[4] = {'1','2','3','4'};

char strcode[4];

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

void loop()
{
    memcpy(strcode, code, 4);
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
}

```

But for some reason when i read my serial monitor i get this:

```
1234
done

```

Why are there 2 squares behind it? Am I doing it wrong?

EDIT: For some reason stackexchange doesn't show the 2 squares but there are 2 squares behind 1234

# Answer
> 3 votes
C strings need to be NUL-terminated.

```
char strcode[5];

 ...

 ...
     ...
    strcode[4] = '\0';
     ...

```

---
Tags: array, convert
---


# Question
Title: When I see the red RX LED flash I am wondering if it means there is an error?
Each time I press a particular button in my circuit the red RX light flashes briefly.

I have been having trouble with making this button perform the command it should, I and am wondering if the RX flash has something to do with that, or is at least reporting some sort of error?

# Answer
> 2 votes
The TX LED is there to show that some data or signal has been received on your Arduino. When you press the button on your circuit, it briefly sends a signal which then triggers the RX LED on your Arduino. Most often, the RX LED is used to troubleshoot whether you are receiving an input and, in your case, it seems you are.

Therefore, the RX LED is not an error and shouldn't be the source of your problem.

---
Tags: arduino-uno, rx-pin
---


# Question
Title: If statement comparing array to value list throws error
In my program I have the following lines of code:

```
if (invest == {0, 1, 0, 0})
   {
      //code
   }

```

However, upon attempting to compile the code, I receive the following error:

```
exit status 1
expected ';' before '}' token

```

"Invest" is a bool array originally defined with\`

```
bool invest[] = {0, 0, 0, 0};

```

How can I prevent this error from ocurring?

# Answer
You cannot compare like that... you have to do it one by one (and check the length of the array).

```
if ((sizeof(invest) / sizeof(bool) == 4) &&
    (invest[0] == 0) &&
    (invest[1] == 1) &&
    (invest[2] == 0) &&
    (invest[3] == 0))
{
     ...
}

```

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.

Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.
> 2 votes

# Answer
Unfortunately you cannot do that.

In addition to Michel Keijzers, another possible way is to use binary manipulation of an integer.

Your declaration of the variable would look like this:

```
unsigned int invest = 0x00;    // B0000 or 0 would be acceptable also

```

(See https://www.arduino.cc/en/Reference/IntegerConstants for notation reference.)
So your `if` statement would be very close to what you had originally wrote.

```
if (invest == B0100)
{
   //code
}

```

Using this method you cannot reference each bit in the same way as an array (ie `invest[3]`). Instead to **view** the 4th bit:

```
result = (invest && 0x08) >> 3;

```

To **set** the 4th bit you would need to write:

```
invest |= 0x08;    // ie. B1000

```

And to **clear** the 4th bit:

```
invest &= 0x07;    // ie. B0111

```
> 1 votes

# Answer
You have a syntax error in that code; in C99, you would need to declare the type of the anonymous array `{0, 1, 0, 0}`, for example via `(bool[]){0, 1, 0, 0}`. So the following code compiles ok in C:

```
int main() {
  char invest[] = {0, 1, 0, 0};
  if (invest == (char[]){0, 1, 0, 0})
    printf("Yes yes yes\n");
  else
    printf("No no no\n");
  return 0;
}

```

However, if you compile and run this code, it will output "No no no" rather than "Yes yes yes" because the logical test `invest == (char[]){0, 1, 0, 0}` says to compare the address of the `invest` array to the address of the anonymous array, and of course they differ.

Note, if you try to compile the above as a C++ program, the result will be “error: taking address of temporary array” due to different type checking.

---

All that said, the straightforward way to compare arrays of bytes or in some cases arrays in general is to use the `memcmp()` function. From its man page:

```
SYNOPSIS
   #include <string.h>
   ...
   int memcmp(const void *s1, const void *s2, size_t n);
DESCRIPTION
   The  memcmp()  function compares the first n bytes (each
   interpreted as unsigned char) of the memory areas s1 and s2.
RETURN VALUE
   The memcmp() function returns an integer less than, equal to,
   or greater  than zero  if  the  first  n  bytes of s1 is found,
   respectively, to be less than, to match, or be greater than
   the first n bytes of s2.

```

The following code compiles ok both in C99 and C++ and prints out "Yes yes yes.".

```
#include <stdio.h>
#include <string.h>
int main() {
  char invest[] = {0, 1, 0, 0};
  char others[] = {0, 1, 0, 0};
  if (memcmp(invest, others, sizeof invest)==0)
    printf("Yes yes yes.\n");
  else
    printf("No no no.\n");
  return 0;
}

```

Note, when compiling code like this in the Arduino IDE, you may be able to leave out one or both of the `#include` statements.
> 0 votes

---
Tags: arduino-uno, compile
---


title: Where are RX and TX pins on the GT2560?

text:
# Question
Title: Where are RX and TX pins on the GT2560?
I'm adding WiFi (ESP8266) to my GT2560 board. Does anyone know where on the board are the RX and TX pins and the best place to connect to them?

This is all, no more info on the board in the internet and forums: https://www.geeetech.com/Documents/Users%20Manual%20of%20GT2560.pdf

# Answer
> Does anyone know where on the board are the RX and TX pins

The serial Rx and Tx signals from the ATmega2560, go to the nearby FT232RQ USB-to-serial adapter. You can look at the part numbers on the ICs and find those two devices on the PCB.

> no more info on the board in the internet and forums

It's good news that there does seem to be more information available :-) After a few minutes with Google (searching for GT2560 schematics) I found this download link for the schematics on this forum page.

Although it would be possible to reverse-engineer the PCB (or at least the relevant part of it) the schematics are still helpful, since the white coating makes the actual copper traces harder to follow visually.

The schematic shows that two 1k resistors, R3 and R13, are in series with serial signals:

* R3 between ATmega Tx -\> FT232 Rx
* R13 between ATmega Rx \<- FT232 Tx

You may want to confirm that the linked schematic still applies to your specific PCB (since PCB and schematic versions could have changed). With the power disconnected, you could check with a multimeter that there is continuity between the appropriate ATmega pin and one end of each resistor R3 & R13, and between the other end of each resistor and the appropriate FT232 pin, as shown on the schematic.

I have put a red ring around those 2 resistors on the GT2560 top view below, to help you to find them:

<sub>(original image source)</sub>

> best place to connect to them

If you are going to drive those serial signals from an ESP8266, you must first *disconnect* them from the on-board FT232, to avoid contention and so the ESP8266 *replaces* the FT232. Removing those two resistors would make each resistor's (now vacant) pads leading to the ATmega serial port, an ideal place to connect the ESP8266. (Of course you could attach wires directly to the pins of the ATmega or FT232, but I don't see any advantage to doing that.)

One issue which you need to consider, is the voltage compatibility of the serial port signals. The ATmega2560 uses 5V signal levels, whereas the ESP8266 is a 3.3V device. There have been discussions on various websites (example) that suggest the ESP8266 is 5V-tolerant on I/O pins. You will need to satisfy yourself whether to use voltage translation, or to rely on information discussed on web pages like that one.
> 1 votes

# Answer
The GT2560 uses USB for communications and USB has a combined RX/TX and not individual pins.
> 0 votes

---
Tags: esp8266
---


# Question
Title: basic_insert with WAMP server doesn't connect with MySQL database
I'm trying to establish a connection with a MySQL database on a local server wirelessly using the following script:

The wireless connection with my router is successful but then connection with database results in

I'm using a WeMos D1 mini ESP8266, Windows 10, WAMP64, MySQL 5.7.14.

I get ping responses from MySQL at 127.0.0.1, and my host computer and also the ESP8266. I've disabled my Windows Firewall to test it temporarily. After the wifi connects with the ESP8266 and confirms the correct WiFi.localIP, 'Connection failed' error with additional text below.

I can manually enter data into the test\_arduino table so I think it's a connection issue with the database server. Maybe something to do with my router's handling of of Port 80.

I am able to send sensor data to remote sites such as ThingSpeak.

Any help would be appreciated.

```
// Created by: Dr. Charles A. Bell

#include "ESP8266WiFi.h"
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

IPAddress server_addr(192,168,0,10);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "PASSWORD";        // MySQL user login password

const char* SSID = "MYSSID";         // Your network SSID
const char* PASS = "MYPASSWORD";

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

WiFiClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect

  Serial.print("Connecting to "+*SSID);
  WiFi.begin(SSID, PASS);
  Serial.println("going into wl connect");

  while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to connect
    {
      delay(1000);
      Serial.print(".");
    }

  Serial.println("wl connected");
  Serial.println("");
  Serial.println("Credentials accepted! Connected to wifi\n ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);

  Serial.println("Recording data.");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

```

The following is the Serial COM4 readout:

```
Connected to wifi
 going into wl connect
.......wl connected

Credentials accepted! Connected to wifi

192.168.1.XX (intentionally deleted)

Connection failed.
Recording data.

Exception (3):
epc1=0x402050ea epc2=0x00000000 epc3=0x00000000 excvaddr=0x402315cc depc=0x00000000

ctx: cont
sp: 3ffef5a0 end: 3ffef7d0 offset: 01a0

>>>stack>>>
3ffef740:  0a00a8c0 00000001 3ffe8785 402050f4
3ffef750:  3ffee524 0000000e 3ffe850e 3ffee79c
3ffef760:  3fffdad0 00000000 3ffee770 402048fd
3ffef770:  402315cc 00000000 3ffee770 3ffee79c
3ffef780:  3fffdad0 00000000 3ffee770 40204945
3ffef790:  402010ae 00000000 3fff061c 4020292e
3ffef7a0:  3ffe8780 00000000 3fff061c 40201d3e
3ffef7b0:  3fffdad0 00000000 3ffee794 40204c34
3ffef7c0:  feefeffe feefeffe 3ffee7b0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

```

# Answer
> 0 votes
I figured it out. I needed to set up a User (IP server) in the database. In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266. In the sketch I changed the user from "root" to "esp".

---
Tags: esp8266
---


# Question
Title: 2.8 Touchscreen does not work with Proto Screw Shield
I am using the Arduino Mega and the 2.8 touch screen by Adafruit, and I can't get the screen to work on my Proto R3 Screw Shield

Here are the tools I am using:

When I put the touch screen onto the Arduino Mega, no wiring needed, and run the graphic test provided by the Adafruit\_ILI9341, everything works perfectly. The touch screen runs the animation, and my serial monitor outputs the information of my touch screen.

However, when I put the touch screen on the screw shield, which I place on the Arduino Mega, **the touch screen stays white**, no matter if I press either reset button, unplug and replug the Arduino, restart the IDE, take off and put everything back on.

I explicitly followed the instructions by Adafruit here that say how to get the screw shield working.

There is no contact between each soldered pin, and I cut and soldered the ICSP and MEGA jumpers on the bottom of the touch screen accordingly, as shown in the picture on the bottom right:

I tried using an SD card as a test to see if the proto R3 screw shield was not working at all, and reading an image off of the SD card. I got **proper, working results**, so everything worked fine with the screw shield then. This means that the screw shield still works with it's 5V pin.

What could be the cause of the touchscreen staying white? Thanks in advance!

# Answer
> 1 votes
You are set to use the ICSP header for communication with the screen. That is good, when you are directly connected to a Mega.

However that is bad when you are going via a shield that *doesn't have an ICSP header*.

The ICSP header is the 6-pin (3x2) header in the right of your picture. It has SPI signals that the screen needs. Your screw shield lacks those pins.

You need to pass those signals through. The simplest way would be to add a 3x2 stackable header (or two 3x1 stackable headers) upside down through the correct holes to line up with the ICSP header.

---
Tags: spi, display, tft
---


# Question
Title: How to get ip information of arouter/AP with ESP8266
i, I would like to get ip number, DHCP ip range subnet mask information of an external AP/router autonomusly through the ESP8266 sketch, so the ESP8266 code can determine a suitable static ip range to configure. Any example code or references would be appreciated.

# Answer
All you can do is get what DHCP gives you.

1. Connect to the AP
2. Use DHCP to get an IP address
3. Store the IP, netmask and gateway in variables
4. Use the netmask to determine the "fixed" bits in the IP address.
5. Replace the "unfixed" bits of the IP with your own chosen IP portion
6. Re-set the IP information with your static information.

What you *cannot* do is determine what the DHCP *range* is. Only the router knows that, and it doesn't broadcast it.

The proper way of handling it, though, is to get the router to provide a fixed DHCP IP address for the MAC address the ESP8266 has. Most routers have this functionality available.
> 3 votes

---
Tags: esp8266
---


# Question
Title: Arduino Leonardo as USB Keyboard with WiFi module
I have two PCs: the first is connected to the Arduino via WiFi, this will instruct the Arduino what keys to send, and the second PC is connected to the Arduino via USB that will act as a USB Keyboard for the PC to receive keystrokes. Is it possible to use Arduino Leonardo as a USB Keyboard connected to a PC with WiFi module connected to another PC? Do I need other components or modules for this to work?

I have searched the possibility of keystrokes and WiFi connection as separate projects but can't seem to find a project that has this scenario.

I also consider using Teensy with WiFi module if it is feasible. If this is not possible, are there any workarounds? Or other devices I can use? Thanks in advance.

EDIT: I am also checking Raspberry Pi Zero as an alternative. Is the project more probable with this or is it better to stick with Arduino?

# Answer
> 1 votes
Its always very unlikely that someone will have done exactly the same project as you, which is why you need to break it down.

1. You want to talk to an Arduino over Wifi.
2. You want he PC to send commands to the Arduino.
3. You want to make the Arduino act as a keyboard.

I know each of those three parts in on this site, so that should help answer a lot of questions on how to do it, but obviously some of the solutions may conflict so you'll have to discard them.

1. You can use an ESP8226 - the Arduino talks to it via serial (software serial).
2. You will need an application (c# will be easiest for Windows) that will send data to the Arduino. You need to design and implement a protocol, using REST may be a good idea.
3. I've never done it and don't know how, but I think I read there is a HID Library (Human Interface Device aka Keyboard or rat) and that makes thinks easier.

As to what hardware you could use there may well be performance constraints, that affect what hardware you can use. I suspect the lower spec Arduiano's may introduce a lag that may not be acceptable. Since you want to do it over Wi-Fi, you might want to have a look at the ESP8226, which can be programmed like an Arduino and has native Wi-Fi. I'm not sure if you can use it as a HID though.

# Answer
> 1 votes
Further to what @CodeGorilla says:

1. You don't need SoftwareSerial on the Leonardo - the UART pins 0 and 1 are independent of any other hardware and can be used directly without any interference.
2. The Arduino IDE has Keyboard examples for the Leonardo built in and full software support for the USB interface acting as HID is built in to the API. No need for any extra libraries on that front.
3. The ESP8266 has no USB interface. It *may* be able to bit-bang it, but I don't think anyone has written software to do that (it's a horrible thing to do anyway).

So you would use pins 0/1 to talk to an ESP8266 which would be your WiFi interface. The Leonardo can directly talk "keyboard" with the wired PC.

A better choice of host board may be the Pro Micro 3.3V since it runs at the same voltage as the ESP8266 so you don't have any issues of logic level translation. True, it runs at half the speed of the Leonardo, but you're hardly doing any intensive processing here.

---
Tags: wifi, arduino-leonardo, keyboard, raspberrypi
---