# Question
Title: Hiding WLAN password when pushing to GitHub
I have started to use GitHub to store Arduino code. However some of my code uses the SSID and password for my WLAN which I don’t want published.

A common way of handling this in non-embedded programming is to use a configuration file, but that doesn’t seem to be a viable approach in programming the Arduino. I’m currently just commenting out the sensitive information before pushing it to GitHub, but one day I’m sure I’ll forget.

Is there another – better - way of handling this?

# Answer
Sure you can use a config file. It's called a "header" file, and you just `#include` it in your sketch.

```
[config.h (not pushed)]

const char *password = "DOD982yp398fhgpwbn09tupf0p04";

[sketch.ino (pushed)]

#include "config.h"

// Now you can use the password variable.

```

Another method, which is better if you have multiple files in your sketch, is to use `#define` instead of variables in your header file:

```
[config.h]

#define WIFI_PASSWORD "348r0yp80ytwp85tpj8yjp98y97t8t"

[sketch.ino]

#include "config.h"

const char *password = WIFI_PASSWORD;

```
> 5 votes

# Answer
You could commit the following file into your project, named credentials.h:

```
// Replace with your actual SSID and password:

#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

```

Near the beginning of your sketch, you add:

```
#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char password[] = WIFI_PASSWD;

```

Now, you can edit credentials.h to add your real SSID and password, and go on with your normal git workflow, with one exception: never `git add credentials.h` again, nor `git commit -a`.

Now, git will always remind you that credentials.h has been modified and is not staged for commit. It will do so even if you add the file to your .gitignore. If you always review your changes before committing, this is only a minor inconvenience. If, on the other hand, you tend to `git commit -a` without reviewing what you are committing, then this solution is likely not for you.

---

**Edit**: An idea I got from reading Chris Stratton's comments. **If** you use a Makefile in your own workflow (this has already been discussed in this site a few times), you could commit this credentials.h to your repo:

```
#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

```

Make a copy of this file named true-credentials.h and put the real credentials there (but do not rename the include guard). Then add to your Makefile

```
CFLAGS += -include true-credentials.h

```

Keep true-credentials.h and the Makefile out of the repo. You can add them to your .gitignore or, better yet, to .git/info/exclude.

Now you have a compilable version with dummy credentials in the repository, you have the true credentials when you compile on your own machine, and git does not bother you about credentials.h being changed.
> 7 votes

# Answer
Building upon the shoulders of giants I took Edger Bonet's answer and used a slightly different twist. I went this route because I don't use a makefile and found this solution works well for me in my project.

I created a placeholder credentials.h file with the following info (Edger's answer).

```
#ifndef CREDENTIALS_H
#define CREDENTIALS_H

// Replace with your actual SSID and password:
#define WIFI_SSID "Your SSID here"
#define WIFI_PASSWD "WLAN AP password here"

#endif

```

I further added the reference to this new file in the .ino file.

```
#include "credentials.h"

const char ssid[] = WIFI_SSID;
const char pass[] = WIFI_PASSWD;

```

Now the twist.. I excluded the file from being checked for changes using the --assume-unchanged command.

> git update-index --assume-unchanged credentials.h

You can then modify the credentials.h file and wont be prompted to add it to github.

Note, to re-check the file use --no-assume-unchanged.
> 5 votes

---
Tags: programming, arduino-ide, version-control
---


title: Passing a reference as a variable

text:
# Question
Title: Passing a reference as a variable
I have a function for manually jogging a stepper motor using the AccelStepper library. At the beginning of the function I would like the motor in question to be selected until told to stop.

Here is what I imagine it would look like:

```
AccelStepper X_Axis(AccelStepper::DRIVER, 3, 2);
AccelStepper Y_Axis(AccelStepper::DRIVER, 5, 4);
AccelStepper Z_Axis(AccelStepper::DRIVER, 7, 6);

void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  if (Dir == 0){i = 1;}else{i =- 1;}
  setSpeed(i * Spd);
  switch(axis)
    {
      case 1:
      axis = X_Axis;
      break;

      case 2:
      axis = Y_Axis;

      case 3:
      axis = Z_Axis
    }
  while (!Serial.available()){

      axis.runSpeed();
    }
  }

```

The axis variable should map to whichever axis is called and so control the desired stepper.

How can I achieve this?

Note: I submitted this to StackOverflow with no response. Any help would be appreciated

# Answer
How about using an array?

```
const int x = 0;
const int y = 1;
const int z = 2;

AccelStepper axis[] = { {AccelStepper::DRIVER, 3, 2}, ... };

void ManualJog(int Dir, int Spd, int axisIdx)
{
   axis[axisIdx].runSpeed();
}

```
> 0 votes

# Answer
To do it in the form you have, you would want to use a *pointer*.

```
void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  AccellStepper *thisAxis = NULL;

  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  switch(axis)
  {
    case 1:
      thisAxis = &X_Axis;
      break;

    case 2:
      thisAxis = &Y_Axis;
      break;

    case 3:
      thisAxis = &Z_Axis
      break
  }

  if (thisAxis != NULL) {
    while (!Serial.available()) {
      thisAxis->runSpeed();
    }
  }
}

```

Briefly: the `&` before the name of a variable in assignment means "Give me the address of this variable". A `*` before a variable when declaring that variable means "Make this variable hold the address of another variable of this type". You then have the address variable hold the address of your chosen axel, and then "dereference" that with the "poiner dereference operator" `->` (instead of using `.`).

A check is added to see if `thisAxis` has actually been assigned anything or not, although you could use the `default:` case in your switch to abort on an invalid axis number instead.

Depending on how the rest of your program works, though, it may be possible to not use the "axis" integer at all, but pass a reference to the correct stepper to the function:

```
void ManualJog(int Dir, int Spd, AccelStepper &axis) {
  int i;
  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  while (!Serial.available()) {
    axis.runSpeed();
  }
}

```

In this example the `&` before the `axis` variable in the function prototype means "Pass me the address of the variable", and a new variable is created located in the same memory space. This is the *pass by reference* operator in C++.
> 1 votes

---
Tags: arduino-uno, stepper
---


# Question
Title: How come my switch is triggering with out pushing the button?
New here, sorry If my formatting is bad.

```
int button = 2;
int relay = 3;
int speaker = 4;

void setup()
{

  pinMode(button, INPUT_PULLUP);
  pinMode(relay, OUTPUT);
  pinMode(speaker, OUTPUT);

}

void loop()
{
  if(digitalRead(button) == 0)
  {
    digitalWrite(relay, HIGH);
    tone (speaker, 100, 300);
    delay (3000);
  }
  else
  {
    digitalWrite(relay, LOW);
  }
}

```

I want the relay to trigger and stay open only while the button is pressed. However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

If i remove the `tone (speaker, 100, 300);` it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

# Answer
> 0 votes
> I want the relay to trigger and stay open only while the button is pressed. However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.

> If i remove the tone (speaker, 100, 300); it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.

---
Tags: arduino-uno
---


title: Detect a non-human moving object

text:
# Question
Title: Detect a non-human moving object
I would like to design a system in which I am able to make a light flash when a motion sensor detects a movement of a non human object such as a car.

(The goal here being that when a car is moving behind me in my blind spot around the corner of a wall in my parking spot I don't back into it.)

I have looked into a few tutorials using arduinos to detect this motion but so far I have only read about the PIR (which only detects humans and animals).

http://www.instructables.com/id/DIY-Arduino-Motion-Sensor-Lighting-Control/?ALLSTEPS

What sensor would be best for this situation or do I need to rethink my system?

(I have no intention of harming anyone or anything :) )

# Answer
If your car is moving at the time, then relative to your car *everything* is moving.

Automotive companies have spent billions of dollars working on this problem. There is no "sensor" that can differentiate one moving object from a background that is also moving.

All existing automotive systems that perform this task use cameras and computers, with software such as OpenCV. This is not something that any Arduino could even come close to doing.

The closest you could get is "is there something in this area that is within a certain distance of me" which you may be able to do with an ultrasound "Ping" sensor. It won't differentiate between a moving car or a bollard or a child or just the wall you are reversing towards.
> 2 votes

# Answer
I would try the PIR sensor before writing it off. It detects changes in infrared radiation from an initial baseline that it reads, so whenever the ambient heat that it sees changes by some threshold, it notifies you. They might be sensitive enough to see a car coming through, as suggested by others.

A more robust solution could be the ultrasonic proximity sensor, like Majenko mentioned. Here's one as a starting point: ultrasonic distance sensor. This will be best if you know that the car will be passing in front of where you point the sensor. If it's hard to point the sensor to a point where you're sure the car will be coming through, then that's where a PIR would have advantages, as it "sees" a wider area.
> 2 votes

# Answer
I hate to be the wet blanket here but maybe the job is too simple for this much technology. Wouldn't a suitably placed curved mirror give you the information you need?

Or put a PIR sensor around the corner where it can see the car, and put the flashing light where you can see it while backing.
> 1 votes

# Answer
I am not sure why no one has suggested a Microwave Doppler sensor. I am not sure how it would work in an outdoor environment but it is designed to detect motion regardless of whether it is a human. This link has some information about using a cheap Microwave sensor with an Arduino.
> 1 votes

# Answer
I would use an ultrasonic distance sensor. They are quite accurate, and are common to use for this kind of problem. You will get all kinds of noise in your data, from all the different surfaces that the ultrasonic sound will bounce off from.

Another option would be infrared distance sensor. Make sure you find one with a long enough range, because the 'usual' one used with arduino examples goes to about 30cm. They are less precise, but very easy to use with arduino. And if I remember correctly they have less problems of getting interference if you have a bunch of them together.

Pir sensors are made to detect the difference in infrared heat coming off a human skin (comparing to when the person is not there). So I would not recommend that.
> 0 votes

# Answer
You can use the servo motor to rotate the ultrasonic sensor 180°:

* In the `setup()` function of your code, store the distance for every 180° in an array;
* In the `loop()` function, read the distance of each degree and compare with the one in the array.

If the value changes that means that the object has been moved
> 0 votes

---
Tags: arduino-uno, accelerometer
---


title: How to convert a string to long int?

text:
# Question
Title: How to convert a string to long int?
I'm new to Arduino and my first project is an RFID reader. since I need a lot of known tags list , i have a problem with not enough memory. for that reason I want to convert strings like : "426d9244", "1265dd39"... to a long int. I know it's been asked but as a new programer I find it hard to understand. an example would be very appreciated also.

# Answer
> 1 votes
It's a bit unclear what you want to do with the 'd'or 'dd'in between.

You can check some functions:

1. strtok: which can split a string based on delimiters (in your case probably 'd'). Than you get an array of strings (e.g. for the first: { "426", "9244"}.
2. For each string ("426" and "9244") you use function atol to convert it into a long integer.

# Answer
> 1 votes
If all those are known tags, you can put them in the source code as 32 bit integers. No need to convert. Or rather, let the compiler do the conversion:

```
const uint32_t ID_num[ARRAYSIZE] PROGMEM = {
    Oxbcc0f1c3, Ox821a7d39, Ox4924887c, ...
};

```

When you read a tag number in hex, in order to compare it with the known tags, you convert it to the same type using `strtoul()` from avr-libc:

```
uint32_t tag_id = strtoul(tag_string, NULL, 10);

```

---
Tags: programming
---


title: Looking to blink entire led strip

text:
# Question
Title: Looking to blink entire led strip
I am fairly new to FASTLED programming and am looking to make my entire LED strip blink at the same time. Similar to the Example Sketch "Blink" however all 30 of my LEDS. I might just be having a temporary mind derp right now but I cant figure it out.

# Answer
> 1 votes
FastLED has a function called `fill_solid()` which will change the color of an indicated range of LEDs in a strip.

From https://github.com/FastLED/FastLED/wiki/Controlling-leds#set-rgb-color

> use new 'fill\_solid', telling it to fill just one led. (v2) Note that this is a pretty silly way to set one pixel, but it lets us illustrate the existence of fill\_solid, a new convenience function the library provides.
>
> ```
> fill_solid( &(leds[i]), 1 /*number of leds*/, CRGB( 255, 68, 221) )
>
> ```

For your case, you want to change the color of all LEDS, so you would call:

```
fill_solid(leds, NUM_OF_LEDS, CRGB::Red);

```

To turn them back off, you would change the color to `CRGB::Black`

---
Tags: led, rgb-led
---


title: Making an H-bridge with transistors

text:
# Question
Title: Making an H-bridge with transistors
I am trying to make an H-bridge with two NPN and two PNP transistors to drive a motor which works fine on the 5 V Arduino. I have a schematic in the picture. When I use a simple code to have pin 9 HIGH and pin 8 LOW, the motor doesn't do anything. The transistor which I circled green is getting very hot. Is there something wrong with the schematic or code? Or is it my wiring?

I know people use diodes as well, but in my case the motor doesn't work, so the diodes aren't the problem.

This is my code:

```
     void setup()
    {

    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);

    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);
    }

```

# Answer
There is a few possible scenarios to create a H-bridge:

* with NPN transistors only or PNP
* mix of PNP and NPN

You have to be careful to not mix the types and inputs. See pictures below:
> 2 votes

---
Tags: motor, transistor, h-bridge
---


title: For loop broken?

text:
# Question
Title: For loop broken?
This is a pseudo code from my LED cube project

```
void loop(){
  //switch( map(constrain(analogRead(pt),10,1020),10,1020,1,4));  - for select pattern
  //show(1);
 for(lp=128;lp>=1;lp = lp/2){
  runfor(1000,lp,1,0,0,0,0);
  //Serial.println("HI");
 }
}

void runfor(short mills,byte a,byte b,byte c,byte d,byte e,byte f){
  timer = millis();
  Serial.println(a);
  while((millis()-timer)<=mills){
    light_L1(a,b);
    //light_L2(c,d);
    //light_L3(e,f);
  }
}

```

the variable 'lp' here never changes its value and remains 128

Why is this?

# Answer
> 1 votes
**Don't ever use a global variable for `for` loop.**

You use the same variable in functions `for` loops which count down to zero. If `lp` is zero `for` loop in `loop()` ends and new `loop()` starts.

# Answer
> 2 votes
When I ran your code as you presented it in the chat, lp stayed at 128. When I commented-out the "light\_L1()" call in "runfor()", lp decremented by 1/2 its value per step as you would expect. The issue is that lp is global and therefore, accessible by any other function. One of your lower functions is resetting it.

---
Tags: debugging, loop
---


title: Two nRF24L01 radios per Arduino

text:
# Question
Title: Two nRF24L01 radios per Arduino
Due to the results of my previous post (Slower nRF24L01 round trip delay than expected) I found out that it will be quite difficult to reach my latency requirements.

I am thinking about using my own protocol (instead of the 6-1 Multiceiver protocol), but that would involve getting some kind of 'clocked' receive and send times for devices, which will not make it simple probably. The time to change from reading to writing is less than expected (startListening takes max 350 us and stopListening 450 us). However, if I need to do this ever 5 ms and making sure no devices are reading/sending to others, that's quite a bit of downtime.

So I was thinking, would it be a good (or stupid) idea to use TWO nRF24L01's per Arduino, one by default in reading mode, the other on writing mode (thus having bidirectional communication) and using two different channels. This means I never have to switch between reading and writing and can read/write simultaneously without message colliding.

(note: later I want to use multiple Arduinos and one STM32 device).

Does anyone see problems in this idea?

Requirement goals:

* Latency: less than 10 ms to send it from device A to B, process it (excluded, takes a few ms) and send back from B to A (or in some cases B to C). Less than 10 ms is better.
* Amount of messages: can be theoretically hundreds per second, in practice max 100 (from various devices, but all go through a processor-device).
* Payload per message: 16 bytes probably, most are shorter, some are longer but I can split or combine them if needed.
* Range: about 10 meters max, but in a music/band stage environments
* Channels: I will not use the WIFI channels, but a range of others, also (professional) wireless mics do not work on 2.4 GHz, so I don't expect too many problems.

About channels: I don't expect any problems. I should have enough channels between 2.484 and 2.525 GHz. This gives me about 40 channels for 1 mbps or 20channels for 2 mbps to chose from.

# Answer
> 1 votes
At 2 Mbps, a 32-byte packet (40 bytes with preamble, addresses, CRC) will be approx 160 microseconds long. The round-trip time is likely to be much longer, since the microcontroller or radio will need additional time delays for auto-retry, sending and receiving the response packet, PLL lock, reading the data registers, etc. In my experience a 2 ms round trip is possible, and the best way to do that is make use of the nRF built-in features:

-- IRQ interrupt: interrupts = fast

-- Enhanced Shockburst: this automatically handles lost packets and failed transmissions. You can't get that capability any faster via the microcontroller coding.

On top of this, there is scope to use fast SPI libraries (or use SPDR/SPCR registers directly) to transfer data to and from the radio module. If speed is your goal, don't rely on plug-and-play libraries that others have written. Read the data sheets carefully and minimize unnecessary delays within the Arduino code.

---
Tags: nrf24l01+, rf, latency
---


title: NodeMCU 12E V2 Power Saving

text:
# Question
Title: NodeMCU 12E V2 Power Saving
I'm powering a NodeMCU with 4 x AA batteries (6v, ~9,600mAh). I am running ESP.deepSleep(\[milliseconds\]) to minimize power consumption. Even with deepSleep I am seeing a precipitous drop off in battery voltage. I've gone from 6.00v to 5.62 in 28 hours. Does this make sense? I was expecting the board to consume SIGNIFICANTLY less power and I'm at a loss.

I have the reset/wakeup pins (D0, D3, and D4) set connected to 3.3v with resistors and I've jumped the reset pin to D0 to make the wakeup call. Nothing else is connected! Does this power draw make any sense??

As far as the operation goes, it's waking up and posting data just fine.

I've researched various power saving techniques and the best description I've found is here. I really don't want to start hacking up ESPs though. That is time consuming and presents a real opportunity (ahem...guarantee) for me to destroy a lot of boards!

My questions:
1.) Are there other SW-based methods for improving power use on the NodeMCU 12E?
2.) Where do I probe a 12E to read current draw with a multimeter
3.) Are there "dumber" ESP8266 modules that have a reset pin, a few? GIPOs and a VIN capable of handling a 6v input with either a 5v and/or 3.3v output? Product recommendation...I know...I'm hard up though and need some guidance.

I'll make these separate questions if necessary.

I am going to by an in-line current reader. I need to stick with a multimeter for now.

# Answer
If you can't do anything about the hardware you're using (lower powered USB interface, etc) then the top thing you can do is run the wifi radio as little as possible. The radio uses a lot of power, so the less time it's on for and the less network traffic you send, the less power you'll use.

When the board comes out of deep sleep and reconnects on wifi again, it performs a DHCP exchange to find out its IP address. Configuring a static IP address, network mask and router address will avoid this and let the radio stay on for less time.

The ESP8266 SDK also automatically saves wifi credentials to flash every time you call `WiFi.begin()`. This is probably not what you want. Disabling this will also help save power.

The new wifi connect code would look something like this:

```
IPAddress ip( 192, 168, 0, 1 );
IPAddress gateway( 192, 168, 0, 254 );
IPAddress subnet( 255, 255, 255, 0 );

WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.mode( WIFI_STA );
WiFi.config( ip, gateway, subnet );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

```

You'd need to replace the specific IP address, gateway (router) address and subnet mask with ones that work for your network. And you'll need to allocate a static IP address either from a range that your router sets aside, or you'll need to configure your router to permanently allocate the address - how you do this totally depends on the router you're using.

The other way to save wifi-related power is to use as lightweight a protocol as possible and do as little work while wifi is on as possible.

For instance, suppose you need to compute a complicated piece of data that you're transmitting over wifi. Maybe it's a chunk of XML or a JSON string. Or you need to read a slow sensor. Do all that work *before* you enable wifi, and have the data ready to transmit.

Or if you're receiving data, if at all possible, finish receiving the data and turn off wifi before you do any work with the data.

If you have any choice in the matter, use as simple a protocol to transmit the data as possible. UDP is ideal - you can transmit a single packet (but you won't know if it's been received). TCP requires several packets of handshake at connection startup and shutdown. If you use a secure (SSL) connection over TCP that's even more data and computation.

If your very top priority is battery life, UDP is ideal though it's not reliable and not secure.

There's a great series of articles on power saving at

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-1/

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-2/

https://www.bakke.online/index.php/2017/05/22/reducing-wifi-power-consumption-on-esp8266-part-3/

Part 1 is about measuring power use; part 2 is about switching the wifi radio on and off and part 3 gets partly into the stuff I talked about above.
> 2 votes

---
Tags: esp8266, nodemcu, sleep
---


# Question
Title: Why the MPU6050 gyroscope read write register value is 0x08 for a full scale of 500 degrees per second?
I am trying to connect a gyroscope MPU6050 to arduino ATmega2560 and read its raw values from its 6DOF (gyro and acc).

I found the following code:

```
//Activate the MPU-6050
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x6B);                                                    //Send the requested starting register
  Wire.write(0x00);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the accelerometer (+/-8g)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1C);                                                    //Send the requested starting register
  Wire.write(0x10);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission
  //Configure the gyro (500dps full scale)
  Wire.beginTransmission(0x68);                                        //Start communicating with the MPU-6050
  Wire.write(0x1B);                                                    //Send the requested starting register
  Wire.write(0x08);                                                    //Set the requested starting register
  Wire.endTransmission();                                              //End the transmission

```

I am trying to break it line by line, to understand what is going on during the setup of the gyroscope.

According to MPU6050 datasheet, the I2C is at the register `0x68`. The I2C helps us to access all registers and communicate with the master connected to. Which gives the following 3 lines:

```
Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0x00);

```

According the the sheet, the `0x6B` is the register designed to enable and disable the gyroscope:

> This register allows the user to configure the power mode and clock source. It also provides a bit for resetting the entire device, and a bit for disabling the temperature sensor. By setting SLEEP to 1, the MPU-60X0 can be put into low power sleep mode. When CYCLE is set to 1 while SLEEP is disabled, the MPU-60X0 will be put into Cycle Mode. In Cycle Mode, the device cycles between sleep mode and waking up to take a single sample of data from accelerometer at a rate determined by LP\_WAKE\_CTRL (register 108). To configure the wake frequency, use LP\_WAKE\_CTRL within the Power Management 2 register (Register 108). An internal 8MHz oscillator, gyroscope based clock, or external sources can be selected as the MPU-60X0 clock source. When the internal 8 MHz oscillator or an external source is chosen as the clock source, the MPU-60X0 can operate in low power modes with the gyroscopes disabled. Upon power up, the MPU-60X0 clock source defaults to the internal oscillator. However, it is highly recommended that the device be configured to use one of the gyroscopes (or an external clock source) as the clock reference for improved stability. The clock source can be selected according to the following table.

So why we set its value to `0x00` ?

And the same for setting up the gyroscope at register `0x1B` where datasheets specify the full scale ranges as:

The code is setting the range of `500 dps`, so why the coder set the register to `0x08` and not `0x01` where the `FS_SEL[1:0]` should contain decimals from 0 to 3 right ?

# Answer
The i2c address is 0x68 or 0x69. Some modules with the MPU6050 have indeed 0x69, but most have 0x68.

When searching the datasheet for the word "sleep", this sentence is easy to find: "Note: The device will come up in sleep mode upon power-up".

When the MPU6050 powers up, the SLEEP bit is 1 and the sensor is in sleep mode. Therefor writing a 0 is to get it out of sleep mode. After that you can set the sensor as you want.

The FS\_SEL\[1:0\] is a notation that is used a lot in datasheets. It is an indication that only two bits are used. It is not the bit-position in the register. Those bits are located at Bit3 and Bit4. To turn on the lower bit of FS\_SEL, Bit3 has to be set to 1, thus a value of 0x08 is needed for the register.
> 0 votes

---
Tags: arduino-mega, programming, mpu6050, gyroscope
---


# Question
Title: GPS Module Outputting Question Marks in Serial Window
I've got a uBlox Neo 7N GPS Module and configured it so if theres is no incoming data print `no location` but if there is print the latitude and longitude. However it's printing `?,?`.

So I'm assuming it's wired correctly as I'm getting an output however maybe my code is preventing it from printing the two long numbers hence converting it to a `?` instead.

```
  char buf[128];
  if (gps.location.isValid()) {
    snprintf(buf, sizeof(buf), "%lf,%lf", gps.location.lat(), gps.location.lng());
    Serial.println(buf);
  }

```

EDIT I know that Im getting a read as I set two variables of type double lat and long to equal gps.location.lat() and gps.location.lng() respectively and I'm getting a number. How do I fix up this snprintf line so it prints properly?

# Answer
> 3 votes
**No floating point for sprintf, it prints a '?'**.

The functions `sprintf`, `sscanf` and the alike functions (`snprintf` and others) do not have floating point support for avr microcontrollers.

**History**

One of the first Arduino boards used the Atmega8 microcontroller with only 8k flash and 1k sram. It was important to be very memory efficient.
The gcc compiler did not automatically include the floating point support libraries for the `sprintf` functions, however it was easy to include them. Arduino decided not to include those extra libraries because they use extra memory.

Arduino has a preprocessor, compiler and linker that tries to only use code that is actually used. The `sprintf` does not know at compile time if floating point will be used, so it would have to include those extra floating point support libraries whether they were used or not.

Now it is 2018 and it is sadly still not included.

**Workaround**

* The `Serial.println` functions can print floating point variables. They can however not print the output in scientific notation. It rounds the value that is printed to the nearest number.
* The `dtostrf()` and `dtostre()` convert a `float` variable to text. The `dtostre()` is for scientific notation.
* A variable of the `float` type can be cast to a integer.
* The Arduino String object can handle a `float`.

**Only `float` for avr microcontrollers, no `double`.**

The avr microcontrollers are 8-bit microcontrollers. There is no floating point library for 64-bit `double` variables, only a library for 32-bit `float` variables.
That library is according to the IEEE standard and is extremely fast and optimized.

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


# Question
Title: output not declaired.anyone please help me to fix this problem
output not declaired.anyone please help me to fix this problem

```
int const trigpin=10;
int const echopin=9;
int const buzzpin=2;
void setup()
{
  {
  Serial.begin(9600);
 }
  pinmode(trigpin,output);
  pinmode(echopin,input);
  pinmode(buzzpin,output);
}
void loop()
{
  long int duration,distance;
  digitalwrite(trigpin,high);
  delaymicroseconds(1000);
  digitalwrite(trigpin,low);
  duration=pulsein(echopin,high);
  distance=(duration/2)/29.1;
  Serial.print(distance);
  Serial.println("CH");
  if(distance<=50)
   {
    digitalwrite(buzzpin,high);
   }
   else if(distance>50)
   {
    digitalwrite(buzzpin,low);
   }
   delay(60);
}

```

# Answer
To be used in the pinMode function (note capital M), it needs to be all capitals, ie OUTPUT.

From a quick scan, you might also need the following changes:

output ==\> OUTPUT

input ==\> INPUT

pinmode ==\> pinMode

digitalwrite ==\> digitalWrite

delaymicroseconds ==\> delayMicroseconds

Make sure your code matches the case (uppercase/lowercase) of the examples/tutorials etc.
> 4 votes

---
Tags: arduino-uno
---


# Question
Title: FSR wiring using internal pullup resistors?
What are the disadvantages to using Arduino's internal pullups with a force force sensitive resistor (FSR) sensor?

All the wiring examples I see for FSRs place the sensor on the high side and use a 10k pulldown resistor. Searching Google, I can find virtually no one who places the FSR on the low side and uses the internal pullup. Since this would reduce complexity by using one less wire and resistor, I have to assume there's some big downside I'm not seeing. Why shouldn't you use the internal pullup?

I've worked with conventional potentiometers in the 100k ohm range, and I've found that with values that high, the Arduino's ADC finds a lot of noise, resulting in a sensor value that jitters and drifts. I found that the only reliable way to get a stable ADC value is to use a potentiometer with a maximum value of 10k or less. Since the FSR's range is up to 1M ohms, I'm worried I won't be able to get a stable reading. Does wiring it via the high side or low side effect this? What can I do to minimize noise from the FSR, other than shielding the sensor cable or adding a capacitor between the signal a and ground wire?

# Answer
There is probably no practical difference concerning high side vs low side (except the Arduino Uno only has a pullup, and no pulldown).

The issue would be the accuracy of the pullup (graphs in the datasheet show variations of 10% with temperature) vs the accuracy of the resistor (1% is now commonplace).

The pullup is usually a current source, not a specific resistor value. Even if the supply voltage is not known, the maths involved with solving a known resistor is series with an unknown resistor is quite straightforward.

Short answer, using the pullups would probably work, but you would have to confirm accuracy, calibration and even repeatability, while this is already well known for a resistor.

Datasheet, see graphs on p412:

http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P\_Datasheet.pdf
> 2 votes

---
Tags: sensors, pull-up
---


# Question
Title: Stabilitiy Problem for Interrupts Code related to Flow sensor
There is a problem with code related in link Interrupts Problem with Flow sensor. Code is working but when I stop the pumps, flow value on lcd is frozen until I reset the arduino. And when I start the pumps, flowmeter shows firstly 0.54 value, then begin to show real values. But always 0.54 down or up ( if flow is 5 lt/min, lcd show sometimes 5 lt/min, 5+0.54 lt/min or 5-0.54 lt/min ). When there are no oil flow into flow sensor, value of flow have fixed value that last readings. Could you help me ?

```
 #include <Wire.h> //I2C lib
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
 // LCD lib
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

const int pot_pin = A0;
const int pump_pwm = 3;

const int resetButton = 11;
byte press_pin = A1;

//flowmeter parameters
int flowPin = 2;  // input pin on arduino D2

volatile double flowRate;   // value intented to calculate
volatile double flowR; // flow value in lt
volatile double totalFlow; // total output of flow from system

byte sensorInterrupt = 0; // interrupt 0 on D2 pin Arduino Nano

volatile int count; ////integer needs to be set as volatile to ensure it updates correctly during the interrupt process.

int pot_init= 0;
int pump_init= 0;
int percentValue =0;

unsigned long previous_read;
void setup() {

  pinMode(resetButton, INPUT);
  digitalWrite(resetButton, HIGH);

  lcd.begin(20,4);  // A4 - A5 connection SDA - SCL
  lcd.backlight();
  Serial.begin(9600);

  pinMode( flowPin,INPUT); // Set D2 pin as an input

  attachInterrupt(sensorInterrupt,Flow,RISING); // Configures interrupt 0 ( pin D2 on Arduino Nano ) to run function "Flow"
}
void flow_control(void) {

  // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(int(flowRate));  // Print the integer part of the variable
    Serial.print("L/min");
    Serial.print("\t");       // Print tab space

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalFlow/1000);
    Serial.println("L");

 if(digitalRead(resetButton) == LOW)
  {
    totalFlow = 0;
    lcd.setCursor(0, 3);
    lcd.print("Resetting....        ");

}

else {
 lcd.setCursor(0,3);
  lcd.print("Total: ");
  lcd.setCursor(7,3);
  lcd.print(totalFlow/1000);
  lcd.print(" lt");

}
  lcd.setCursor(0,2);
  lcd.print("Flow: ");
    lcd.setCursor(6,2);
  lcd.print(flowRate);
  lcd.print(" lt/min");

}

void Flow(void)
{
  count++; // every time this function is called, increment  "count" by 1

  if(millis() -  previous_read > 1000){
    noInterrupts(); // disable interrupts on arduino nano
    int local_count = count;
    count=0;
    interrupts(); // enables interrupts on arduino nano
    previous_read += 1000;

  flowR = (local_count*8.93);   // 112 pulse/lt 423.84 pulse /gallon
  flowRate= flowR*60;     // convert seconds to minutes, new unit is ml/minutes
  flowRate= flowRate/1000; // convert ml to liters, new unit is lt/minutes

  totalFlow += flowR;
 //process flowrate based on local_count

  //calculation for flowmeter

  }
}

void loop() {

  pressure_cal();
  pump_control();
  flow_control();

}

void pressure_cal(void) {

  float sensorVoltage = analogRead(press_pin);   // sensor voltage A0
  float psi = ((sensorVoltage-102)/204)*25;  // Offset    0 PSI= 0.5V=102 unit, 50 PSI= 2.5, 100 PSI= 4.5V, 1 PSI= 0.04V

  // calibration
  float bar = psi*(0.0689475729);           // Conversion PSI to BAR

  lcd.setCursor (0,1);
  lcd.print (psi);
  lcd.print (" PSI");

  lcd.setCursor ( 10,1);
  lcd.print(bar);
  lcd.print( " BAR");

  //lcd.setCursor(17,1);
  //lcd.print(sensorVoltage);

  Serial.print("\t Sensor Value = ");
  Serial.print(sensorVoltage);
  Serial.print("\t Bar = ");
  Serial.print(bar);
  Serial.print("\t PSI = ");
  Serial.println(psi);

  delay (100);
}

void pump_control(void)

{

  // read the analog in value:
  pot_init = analogRead(pot_pin);
  // map it to the range of the analog out:
  pump_init = map(pot_init, 0, 1023, 50, 230);  //  duty cycle between %20 - %90: speed control , duty cycle between %0 - %20: turned off  , duty cycle between %90 - %100: full speed
  // map pump speed percent of full scale
  percentValue = map (pump_init, 50, 230,0,100);
  // change the analog out value:
  analogWrite(pump_pwm, pump_init);

  // print the results to the Serial Monitor:
  Serial.print("\t Speed Input = ");
  Serial.print(pot_init);
  Serial.print("\t Speed Output = ");
  Serial.print(pump_init);
  Serial.print("\t Pump Speed Percentage = ");
  Serial.println(percentValue);

  lcd.setCursor(2,0);
  lcd.print("Speed: ");
  lcd.setCursor(8,0);
  lcd.print("%");
  lcd.setCursor(9,0);
  lcd.print(percentValue);
  lcd.print("     ");

 //  delay after the last reading:
  delay(10);

}

```

# Answer
> `if (millis() - previous_read > 1000) { [...] previous_read += 1000; [...] }`

The code inside this block is obviously meant to be executed every second. However, since this belongs to the interrupt handler, it only has a chance to execute when the flow-meter sends interrupts. If the flow is zero or very weak, this will not execute often enough.

> flowmeter shows firstly 0.54 value

It is no coincidence that 0.54 is what you get when `count == 1`.

The piece of code above should be moved to the main `loop()`, or to a function called from `loop()`. This way it will execute consistently irrespective of whether there is some flow or not, which is the only way to reliably read a zero flow. Note that for better timing consistency you should avoid doing something like...

> `delay(100);`

Don't do this. Instead, use the same trick as above:

```
if (millis() -  previous_pressure_print > 100) {
    previous_pressure_print += 100;
    pressure_cal();
}

```
> 1 votes

---
Tags: arduino-uno, sensors, i2c, lcd, interrupt
---


# Question
Title: ESP8266 - does it really have terrible wifi range by default?
ESP8266 - does it really have terrible WiFi range by default??

First time to try this module out and we're disappointed with the range.. as per our testing we can only get max 5m WiFi range line of sight (LOS) to our regular WiFi router (TPlink and other routers we tried)

LOS Distance (Test results based on RSSI):

* at 6 meters NO CONNECTION
* at 5 meters -77
* at 4 meters -70
* at 1 meter -56
* at 3 meters -59

We also tried using different WiFi Channel from 1-11
We also tried removing wifi password (no password) and WEP password
We tried also using different modes B G N

NO change ..

Are we doing something wrong here? Or is this module just that bad?

Any solution not requiring hardware change? (because we already bought a lot)

here's our little module

Interestingly, I saw these guys test the module and it seemed to work well .. Could we have a fake chip?

https://www.youtube.com/watch?v=7BYdZ\_24yg0

We have really hit a stumbling block. hope you guys can help

# Answer
> 9 votes
The very first thing I notice is that your WiFi antenna is shielded by the PCB. That is the antenna is placed right over the top of the ground plane of the PCB and your range is going to be severely limited.

You will notice on the NodeMCU design below that they have placed a PCB cutout where the antenna is located. In other pictures you can also see that the ground plane does not go past where the antenna starts.

On other boards the antenna sits proud of the main PCB such as this one from Tronixlabs:

If money is tight and new hardware is out, you could try cutting a cutout where the antenna sits using your Dremel (or other rotary tool). **If there are any traces underneath the antenna you will need to fix them up with wire worms.** Of course it is best to remove the ESP module first.

Alternatively, you could redesign the PCB and send it out for another manufacturing run. I use PCBShopper.com to find the best price for the bare PCBs.

Edit:
Something else you could do is to unsolder the ESP and mount it 90 degrees to the PCB. You would need to solder wires from the base PCB to the terminals of the ESP. This should work and you won't need to cut the base PCB.

---
Tags: esp8266, wifi, pcb-design
---


title: Cannot get Serial working

text:
# Question
Title: Cannot get Serial working
I've bought a module which should communicate via serial RX/TX. The module and code are described here: https://www.dfrobot.com/wiki/index.php/Weather\_Station\_with\_Anemometer/Wind\_vane/Rain\_bucket\_SKU:SEN0186.

I've hooked up everything as described (using an Arduino Nano instead of an Uno, but the rest is the same) and now trying to get things to work. I could not get any decent output. So I decided to switch to a bare-minimum program to read stuff from the serial port in order to see whats going on. I found the following sample: https://gist.github.com/Protoneer/96db95bfb87c3befe46e and implemented this code (only this).

Now what I see is the following: \- With RX/TX connected **the wrong way**, when I reset the nano, the serial monitor shows me one instance of the string I'm looking for (as described in the module documentation). When connected the right way, the text is not there but that's to be expected as the nano should receive it (and not the serial monitor). This does however prove that the module is actually sending data. \- `Serial.available` seems to evaluate to 0 all the time, indicating there is no data to be read from the serial line.

So why would `Serial.available` return 0 even though there seems to be data being sent to serial, as the monitor does show the string I'm looking for with the pins crossed. I have also tried disconnecting the RX line on the module to prevent statements being sent over serial to interfere with the module. The documentation does not state the need to send anything to the module in order to trigger the response. In fact, if you look at the sample code the first interaction with serial (after `Serial.begin(9600)`) is `Serial.available()`.

Is there anything else I can do from a debug perspective? As you might notice I'm no expert in this stuff.

# Answer
It seems you have the module connected to the Nano pins 0 and 1, and are also trying to communicate with the PC via the `Serial` object and serial monitor?

There is a USB/serial converter chip on the Nano that is likely conflicting with your module. You can try SoftwareSerial to get a bit-banged serial port for communicating with the module on some other pins.
> 1 votes

---
Tags: serial, arduino-nano
---


# Question
Title: Using Arduino wireless SD Shield to save data to sd card and send to PC over wireless network
I'm using an Arduino Mega to monitor the current & voltage input to four different sensors. This works fine - the sensors work as expected and I can view the results via the Serial Monitor or Parallax DAQ for Excel.

**SETUP**

I also have an Arduino wireless SD shield (now retired) with an XBee module (shown in the below image):

1. Arduino Shield page
2. XBee module page

I would like to do the following:

1. Save the current/voltage sensors' output locally to the SD card
2. Send the data over a wifi connection for plotting using plotly API (see example here)

I've seen a bunch of tutorials on how to get the shield to work but can't seem to figure it out:

1. Arduino WiFi shield example
2. Instructables
3. Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee

Here's my code (removed the current/voltage sensor code for brevity):

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

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  SPI.begin();

  Serial.println("Checking WiFi status:");
  Serial.print("\tWiFi Status: ");
  Serial.println(WiFi.status());

  if(WiFi.status() == WL_NO_SHIELD){
    Serial.println("\tNo Shield present.\n");
  }else{
    Serial.println("\tShield found.\n");
  }

  Serial.println("Initializing SD card:");
  if (!SD.begin(53)) {
    Serial.println("\tSD card initialization failed.\n");
    return;
  }else{
    Serial.println("\tSD card initialization successful.\n");
  }

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi:");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(5000);
  // scan for existing networks:
  Serial.println("Scanning available networks:");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("\tMAC: ");

  for(int i = 0; i < 5; i++){
    Serial.print(mac[5-i],HEX);
    if(i != 5){
      Serial.print(":");
    }
  }
  Serial.println(" ");
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

```

**OUTPUT**

```
Checking WiFi status:
    WiFi Status: 255
    No Shield present.

Initializing SD card:
    SD card initialization successful.

Initializing Wifi:
    MAC: 0:0:0:0:0:
Scanning available networks...
** Scan Networks **
number of available networks:0

```

Not sure what is going on here.

# Answer
> 1 votes
"Arduino Wireless SD shield" is not "Arduino WiFi shield".

The code you have is for the Arduino WiFi shield. But you have Arduino Wireless SD shield for a XBee module. XBee is not WiFi. Zigbee protocol is different protocol than WiFi.

You can save data to SD card with the SD library. Install the library in Library Manager and try the examples.

Arduino WiFi shield:  Note: the Arduino WiFi library is only for this shield and clones

---
Tags: arduino-mega, wifi, sd-card, xbee
---


title: Making simple on/off IR servo movement.

text:
# Question
Title: Making simple on/off IR servo movement.
I'm new to Arduinos and programming. I'm getting into a project and one of my tasks was to learn how to incorporate servos into Arduino and learn about sensors. I wanted to combine both, but I'm having some problems in my syntax. Can I get some help?

This is my code:

```
// servo test
#include <Servo.h>
#include <IRremote.h>
#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

int servopin1 = 13; // first servo
int servopin2 = 12; // second servo

int pos = 0;

int receiver_pin = 4; // output pin
int vcc = 5; // vcc ir sensor
int gnd = 6; // gnd for ir sensor
IRrecv receiver(receiver_pin);
decode_results output;
Servo Servo1;
Servo Servo2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  receiver.enableIRIn();
  pinMode(vcc, OUTPUT);
  pinMode(gnd, OUTPUT);
  digitalWrite(vcc, HIGH);

  Servo1.attach(servopin1);
  Servo2.attach(servopin2);
}

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

    if (receiver.decode(&output)) {
    unsigned int value = output.value;
    switch(value) {
      case START_BUTTON:
        if (pos <= 180){
           Servo1.write(pos);
           delay(500);
           pos = pos + 30;}
        else {
           pos=0;
             }
        if (pos <= 180){
          Servo2.write(pos);
          delay(500);
          pos = pos + 30;}
        else {
            pos=0;}
      break;
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }
     }
  }

  //^servo 2 positions and delays
}

```

I'm trying to figure out why I'm getting a the following error:

```
C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
In function 'void loop()':

Servo_test2Library:38: error: expected primary-expression before ':' token

       case START_BUTTON:

                        ^

Servo_test2Library:53: error: expected primary-expression before ':' token

       case STOP_BUTTON:

                       ^

C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
At global scope:

Servo_test2Library:64: error: expected declaration before '}' token

 }

 ^

Multiple libraries were found for "IRremote.h"
 Used: C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
 Not used: C:\Users\Alex\Documents\Arduino\libraries\Arduino-IRremote-master
Using library Servo at version 1.1.2 in folder: C:\Program Files
(x86)\Arduino\libraries\Servo
Using library IRremote-2.2.3 at version 2.2.3 in folder:
C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
exit status 1
expected primary-expression before ':' token

```

# Answer
> 4 votes
Up at the top of your code, you have:

```
#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

```

A `#define` needs 2 parts after it. The first is the new name being created, and the 2nd is the definition of the new name.

You should put the value that you expect for the `START_BUTTON` condition after the name, such as:

```
#define START_BUTTON 0x48
#define STOP_BUTTON 0x49

```

Or whatever your IR remote is sending.

Also, you have one too many closing braces (`}`) at the end.

```
      [...]
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }  // THIS CLOSES THE SWITCH
     }  // THIS CLOSES THE IF STATEMENT
  }  // THIS CLOSES loop()

  //^servo 2 positions and delays
} // THIS IS NOT CLOSING ANYTHING THAT WAS OPENED

```

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


# Question
Title: Is two modules using Serial Interface on one Arduino Uno possible?
I was wondering if I have both a Bluetooth HC-05 module and a GPS module (uBlox 7N) is it possible both for both to be using the serial interface?

I'm aware they cant be operating simultaneously with one another but if I using the RX TX pins for the GPS module, can I receive a location, store it in a variable then terminate the GPS serial usage and using software serial with 2 pins of my choice transmit data via the Bluetooth module which also requires the serial pins?

# Answer
You are right, that you need one Serial interface for each module. The Uno has only 1 hardware serial interface (hardware means, that the Arduinos hardware will do the communication work in the background and you can let it do other things in the meantime). But you can add more serial interfaces, on other pins, that work purely through software. For this the `SoftwareSerial` library is meant.

`SoftwareSerial` comes with some limitation, since the load of communication has to be done in software instead of hardware. For example it becomes unstable at high baudrates. Especially for the HC-05 you should not use baudrates of 115200 baud and higher. Also - since it uses pin change interrupts to work - you can only listen at one SoftwareSerial at any given time.

Since you only have 2 modules, it should be easily possible, to utilize SoftwareSerial and access both of them with the Uno. If you at some time want to use more serial modules, you can still change to a bigger board like the Mega.

Note: Be sure to disconnect the module from the hardware serial, before programming the Uno over the Serial interface (USB), or the programming will fail.
> 1 votes

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


# Question
Title: Stepper Motor - Limit Switch for Position
I'm following this guide https://howtomechatronics.com/tutorials/arduino/diy-motorized-camera-slider-pan-tilt-head-project/

My question is with the following piece of code used to calibrate the position values.

```
  // Move the slider to the initial position - homing
  while (digitalRead(limitSwitch) != 0) {
    stepper1.setSpeed(3000);
    stepper1.runSpeed();
    stepper1.setCurrentPosition(0); // When limit switch pressed set position to 0 steps
  }
  delay(20);
  // Move 200 steps back from the limit switch
  while (stepper1.currentPosition() != -200) {
    stepper1.setSpeed(-3000);
    stepper1.run();
  }
}

```

I understand the first while loop is to to get a zeroth position for calibration. **But why move it 200 steps back and then set speed to -3000?\[Q1\]** I don't understand that part.

And then later on in loop(), there is

```
// Limiting the movement - Do nothing if limit switch pressed or distance traveled in other direction greater then 80cm
  while (digitalRead(limitSwitch) == 0 || stepper1.currentPosition() < -64800) {}

```

I understand the first condition but why is second one there? **Is it because 80cm is the max length of the slider/track and you don't want the stepper to move more than that? \[Q2\]** **Also how does 64800 = 80cm? \[Q3\]**

Full Code: \[Not mine - from link above\]

```
/*
  DIY Camera Slider with Pan and Tilt Head
  by Dejan Nedelkovski
  www.HowToMechatronics.com

  Library - AccelStepper by Mike McCauley:
  http://www.airspayce.com/mikem/arduino/AccelStepper/index.html

*/

#include <AccelStepper.h>
#include <MultiStepper.h>

#define JoyX A0       // Joystick X pin
#define JoyY A1       // Joystick Y pin
#define slider A2     // Slider potentiometer
#define inOutPot A3   // In and Out speed potentiometer
#define JoySwitch 10  // Joystick switch connected
#define InOutSet 12   // Set Button
#define limitSwitch 11
#define inLED 8
#define outLED 9

// Define the stepper motors and the pins the will use
AccelStepper stepper1(1, 7, 6); // (Type:driver, STEP, DIR)
AccelStepper stepper2(1, 5, 4);
AccelStepper stepper3(1, 3, 2);

MultiStepper StepperControl;  // Create instance of MultiStepper

long gotoposition[3]; // An array to store the In or Out position for each stepper motor

int JoyXPos = 0;
int JoyYPos = 0;
int sliderPos = 0;
int currentSpeed = 100;
int inOutSpeed = 100;

int XInPoint = 0;
int YInPoint = 0;
int ZInPoint = 0;
int XOutPoint = 0;
int YOutPoint = 0;
int ZOutPoint = 0;
int InandOut = 0;

void setup() {
  // Set initial seed values for the steppers
  stepper1.setMaxSpeed(3000);
  stepper1.setSpeed(200);
  stepper2.setMaxSpeed(3000);
  stepper2.setSpeed(200);
  stepper3.setMaxSpeed(3000);
  stepper3.setSpeed(200);
  pinMode(JoySwitch, INPUT_PULLUP);
  pinMode(InOutSet, INPUT_PULLUP);
  pinMode(limitSwitch, INPUT_PULLUP);
  pinMode(inLED, OUTPUT);
  pinMode(outLED, OUTPUT);

  // Create instances for MultiStepper - Adding the 3 steppers to the StepperControl instance for multi control
  StepperControl.addStepper(stepper1);
  StepperControl.addStepper(stepper2);
  StepperControl.addStepper(stepper3);

  // Move the slider to the initial position - homing
  while (digitalRead(limitSwitch) != 0) {
    stepper1.setSpeed(3000);
    stepper1.runSpeed();
    stepper1.setCurrentPosition(0); // When limit switch pressed set position to 0 steps
  }
  delay(20);
  // Move 200 steps back from the limit switch
  while (stepper1.currentPosition() != -200) {
    stepper1.setSpeed(-3000);
    stepper1.run();
  }

}

void loop() {
  // Limiting the movement - Do nothing if limit switch pressed or distance traveled in other direction greater then 80cm
  while (digitalRead(limitSwitch) == 0 || stepper1.currentPosition() < -64800) {}

  // If Joystick pressed increase the Pan and Tilt speeds
  if (digitalRead(JoySwitch) == 0) {
    currentSpeed = currentSpeed + 50;
    delay(200);
  }
  // If Set button is pressed - toggle between the switch cases
  if (digitalRead(InOutSet) == 0) {
    delay(500);
    // If we hold set button pressed longer then half a second, reset the in and out positions
    if (digitalRead(InOutSet) == 0) {
      InandOut = 4;
    }
    switch (InandOut) {
      case 0:   // Set IN position
        InandOut = 1;
        XInPoint = stepper1.currentPosition(); // Set the IN position for steppers 1
        YInPoint = stepper2.currentPosition(); // Set the IN position for steppers 2
        ZInPoint = stepper3.currentPosition(); // Set the IN position for steppers 3
        digitalWrite(inLED, HIGH); // Light up inLed
        break;

      case 1: // Set OUT position
        InandOut = 2;
        XOutPoint = stepper1.currentPosition(); //  Set the OUT Points for both steppers
        YOutPoint = stepper2.currentPosition();
        ZOutPoint = stepper3.currentPosition();
        digitalWrite(outLED, HIGH);
        break;

      case 2: // Move to IN position / go to case 3
        InandOut = 3;
        inOutSpeed = analogRead(inOutPot); // Auto speed potentiometer
        // Place the IN position into the Array
        gotoposition[0] = XInPoint;
        gotoposition[1] = YInPoint;
        gotoposition[2] = ZInPoint;
        stepper1.setMaxSpeed(inOutSpeed);
        stepper2.setMaxSpeed(inOutSpeed);
        stepper3.setMaxSpeed(inOutSpeed);
        StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
        StepperControl.runSpeedToPosition(); // Blocks until all steppers are in position
        delay(200);
        break;

      case 3: // Move to OUT position / go back to case 2
        InandOut = 2;
        inOutSpeed = analogRead(inOutPot);
        // Place the OUT position into the Array
        gotoposition[0] = XOutPoint;
        gotoposition[1] = YOutPoint;
        gotoposition[2] = ZOutPoint;
        stepper1.setMaxSpeed(inOutSpeed);
        stepper2.setMaxSpeed(inOutSpeed);
        stepper3.setMaxSpeed(inOutSpeed);
        StepperControl.moveTo(gotoposition); // Calculates the required speed for all motors
        StepperControl.runSpeedToPosition(); // Blocks until all are in position
        delay(200);
        break;

      case 4: // If Set button is held longer then half a second go back to case 0
        InandOut = 0;
        digitalWrite(inLED, LOW);
        digitalWrite(outLED, LOW);
        delay(1000);
        break;
    }
  }

  // Joystick X - Pan movement
  JoyXPos = analogRead(JoyX);
  // if Joystick is moved left, move stepper 2 or pan to left
  if (JoyXPos > 600) {
    stepper2.setSpeed(currentSpeed);
  }
  // if Joystick is moved right, move stepper 2 or pan to right
  else if (JoyXPos < 400) {
    stepper2.setSpeed(-currentSpeed);
  }
  // if Joystick stays in middle, no movement
  else {
    stepper2.setSpeed(0);
  }

  //Joystick Y - Tilt movement
  JoyYPos = analogRead(JoyY);
  if (JoyYPos > 600) {
    stepper3.setSpeed(currentSpeed);
  }
  else if (JoyYPos < 400) {
    stepper3.setSpeed(-currentSpeed);
  }
  else {
    stepper3.setSpeed(0);
  }

  // Slider potentiometer
  sliderPos = analogRead(slider);
  // If potentiometer is turned left, move slider left
  if (sliderPos > 600) {
    sliderPos = map(sliderPos, 600, 1024, 0, 3000);
    stepper1.setSpeed(sliderPos); // Increase speed as turning
  }
  // If potentiometer is turned right, move slider right
  else if (sliderPos < 400 ) {
    sliderPos = map(sliderPos, 400, 0, 0, 3000);
    stepper1.setSpeed(-sliderPos); // Increase speed as turning
  }
  // If potentiometer in middle, no movement
  else {
    stepper1.setSpeed(0);
  }
  // Execute the above commands - run the stepper motors
  stepper1.runSpeed();
  stepper2.runSpeed();
  stepper3.runSpeed();
}

```

# Answer
Q1: It is a common practice to move the stepper a bit away from the limit switch after a calibration, so that it can again be activated, if the stepper is moved into that direction. In most cases the limit switch marks a point very near or at a physical limitation, where the stepper cannot proceed and will hit some kind of wall. The limit switch can turn the motor off, before that happens. And your causal chain is incorrect. The code doesn't move to -200 and THEN set speed to -3000. Instead it checks in a while loop, if the position -200 is reached, and when not will set the speed and run the motor. When the position is finally reached due to the motor being run, the while loops exits.

Q2: The 80cm are used as a soft limit, meaning that the slider at this point will not hit a physical limit or a limit switch, only the software stops the slider to go further and finally hit a wall. This is often used to save limit switches in a physically confined situation and also not hit any physical walls, since a collusion is mostly undesirable (due to possible harm to people and the machine). The 80cm are known here (because the rail for the slider is no longer, than that).

Q3: The Stepper does not count in length (cm), but in the number of steps, that he has taken. Depending on the used stepper motor, 1 steps corresponds to a specific angle, that the motor will spin. And the mechanics determine, what angle of rotation corresponds to what distance on the rail. Most likely the author of the guide had calculated this for his specific build. You can calculated this yourself, so that you can use the correct conversion from steps to distance:

```
distance for 1 step = circumfence of the driving wheel / number of steps per revolution of the driving wheel

```

Or shorter:

```
d1 = C / N

```

Then you can calculate the steps for a specific distance `d` by

```
Nd = d / d1

```
> 0 votes

---
Tags: stepper
---


# Question
Title: What value of resistance to put between the output of a 74hc595 and the LEDs?
I'm going to start a project to make an array of LEDs using the shift registers **74HC595**, I've seen many tutorials and it's not really difficult using the Arduino plataform.

The situation is as follows: in the tutorials they put a resistance between the outputs of the **74HC595** (*Qx*) and the **LEDs** , but in each tutorial the resistance varies (*between **200** and **575** Ohms*).

Then the question would be: if feed with **5V** to **74HC595** (the same power as the Arduino) and the resistance that I put between its **outputs (Qx)** and the **LEDs** is lower (let's say **200 Ohms**), the LEDs will light brighter than if I do it with resistors with higher values (let's say **500 Ohms**)?

# Answer
> 3 votes
You are correct that a lower resistance would offer higher brightness. The more current through the LED, the brighter it will be. The current is calculated by dividing the voltage across the resistor by resistance value. The voltage across the resistor would be your 5V - the voltage drop across the LED. this often varies by color. A RED LED might have a 1.2V drop, and GREEN or BLUE would be higher. So to get the same relative brightness in different color LEDS, you will often see a lower resistance used, to get the same current.

Lets say you have a 20mA Red LED, with a 1.2V drop. So (5 - 1.2)/.020 = 190 ohms. If the LED required 10mA, that would be 380 ohms.

Now you DO need to look at the data sheet for the chip driving the LED, and make sure it is up to the task. Can a pin source or sink 10mA? 20mA?

---
Tags: led, shift-register
---


title: Relay Module for water pump

text:
# Question
Title: Relay Module for water pump
I want to switch on/off my water pump by using arduino nano, I have 2 channel relay module. Is this module safe for controlling pump? Specifications pump: power = 746 watt (1HP) single phase, voltage = 220V

Specifications relay: 5VDC 10A 250 VAC, 15A 125 VAC this model actually ( tongling jqc-3ff-s-z )

# Answer
Well you'll need to know the true maximum current for the pump. It may say 1HP (746 watts), which you'd like to think came out to a simple 3.5 amps. But there are a few other factors to consider, such as motor efficiency and power factor to name a few. You can see where if the efficiency were only 50%, you'd need to consume 2X the power to get that 1HP. Also, if the power factor were 60%, it would mean the 746 watts become 1243 VA (volt-amps), which would put you above 5 amps, and that's before efficiency concerns. Then there is the initial surge... how much current is drawn for the short interval during startup.

So what you need to do is really examine the name plate data on that pump. I've actually just done something like this (controlling a water pump for a pool), and I looked at some of those relay modules too. I personally like to see relay contacts that are at least 3X the expected run-time current when controlling a motor. And in the end those modules just did not offer enough extra safety margin for me. But you can make your own analysis.

What I ended up using were some low cost OMRON LY4F-DC12 relays. They have 4 10 amp contacts, and I had a conversation with an OMRON engineer about using the contacts in parallel to create one 40 amp relay, and he confirmed it was a workable solution. Here's one at Mouser Electronics, shown with a mounting socket. You can safely drive this relay forever with a cheap 2N2222 transistor and a 12V supply, provided you put a revers blocking diode across the relay coil. then, put about a 1K resistor between the 1000 the arduino pin and the transistor's BASE pin. You need the transistor (or a MOSFET) because the relay needs about 100mA to operate, and because the coil needs 12V. I know you didn't count one a separate supply, but you can only push the arduino's 5V supply so far. And 12V switching supplied, good to 300mA, are small and can be had for a couple of bucks. Those supplies can also be powered with anything from about 90VAC to about 250VAC, with no mods.

Here's a piece of a schematic from my own project. It's ugly, but you get the idea. The bottom line is that with my motor, which i expected draw a maximum of 12 amps (mine is 125VAC), I can sleep easy knowing this relay will probably outlast the motor!
> 1 votes

---
Tags: arduino-nano, motor, relay
---


# Question
Title: Data is not sending to Thingspeak using SIM900 with an interrupt in the code
I'm currently working in a weather station with online recording on Thingspeak. When I send a set of parameters (T, Pressure, Humidity, light), I don't have any problem with sending data. But when I add to the code the rain parameter, the code doesn't send the data. The rain parameter is calculated based on an interrupt, so could this affect my data sending? It is any trick that I can use to solve it?

The code:

```
#include <Wire.h>
#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial Sim900Serial(9,11);//Configarión de los pines serial por software: RX, TX

Weather myHumidity;//Create an instance of the humidity sensor

const byte RAIN = 2;

volatile int pulse_counter_ISR;
float mm;
volatile unsigned long raintime, rainlast, raininterval, rain;

float humidity = 0; // [%]

void setup() {
  Serial.begin(19200);
  Sim900Serial.begin(19200);//Arduino se comunica con el SIM900 a una velocidad de 19200bps
  Sim900Serial.println("AT+IPR=19200");    // Tell the SIM900 not to autobaud

  Wire.begin();

  pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
  digitalWrite(RAIN, HIGH);

  myHumidity.begin();

  // attach external interrupt pins to IRQ functions
  attachInterrupt(0, interrupt_handler, FALLING);

  // turn on interrupts
  interrupts();

}

void loop() {
 calcWeather();
 comandosAT();
 delay(600000);
}

void calcWeather()
{
//Calc humidity
humidity = myHumidity.getRH();

//Calculate amount of rainfall for the last 10 minutes
mm = pulse_counter_ISR*0.2794;
pulse_counter_ISR = 0;

}

void comandosAT(){
Sim900Serial.println("AT+CIPSTATUS");//Consultar el estado actual de la conexión
delay(2000);
Sim900Serial.println("AT+CIPMUX=0");//comando configura el dispositivo para    una conexión IP única o múltiple 0=única
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CSTT=\"internet.simple\"");
delay(1000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIICR");//REALIZAR UNA CONEXIÓN INALÁMBRICA CON GPRS O CSD
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIFSR");// Obtenemos nuestra IP local
delay(2000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSPRT=0");//Establece un indicador '>' al enviar datos
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//Indicamos el tipo de conexión, url o dirección IP y puerto al que realizamos la conexión
delay(6000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSEND");//ENVÍA DATOS A TRAVÉS DE una CONEXIÓN TCP O UDP
delay(4000);
mostrarDatosSeriales();
String datos="GET https://api.thingspeak.com/update?api_key=MYAPIKEY&field1=0" + String(humidity) + "&field2=0" + String(mm);
Sim900Serial.println(datos);//Envía datos al servidor remoto
delay(4000);
mostrarDatosSeriales();
Sim900Serial.println((char)26);
delay(5000);//Ahora esperaremos una respuesta pero esto va a depender de las condiones de la red y este valor quizá debamos modificarlo dependiendo de las condiciones de la red
Sim900Serial.println();
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSHUT");//Cierra la conexión(Desactiva el contexto GPRS PDP)
delay(5000);
mostrarDatosSeriales();
}

void mostrarDatosSeriales()//Muestra los datos que va entregando el sim900
{
while(Sim900Serial.available()!=0)
Serial.write(Sim900Serial.read());
}

void interrupt_handler()
{
  pulse_counter_ISR = pulse_counter_ISR + 1;
}

```

# Answer
> 0 votes
Finally I split the comands in two functions (comandosAT\_1 and comandosAT\_2) with different variables. The first one do not works and the socond one works fine. Here are the code

```
void comandosAT_1(){
Sim900Serial.println("AT+CIPSTATUS");//Consultar el estado actual de la conexión
delay(2000);
Sim900Serial.println("AT+CIPMUX=0");//comando configura el dispositivo para una conexión IP única o múltiple 0=única
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CSTT=\"internet.simple\"");//comando configura el APN, nombre de usuario y contraseña."gprs.movistar.com.ar","wap","wap"->Movistar Arg.
delay(1000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIICR");//REALIZAR UNA CONEXIÓN INALÁMBRICA CON GPRS O CSD
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIFSR");// Obtenemos nuestra IP local
delay(2000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSPRT=0");//Establece un indicador '>' al enviar datos
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//Indicamos el tipo de conexión, url o dirección IP y puerto al que realizamos la conexión
delay(6000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSEND");//ENVÍA DATOS A TRAVÉS DE una CONEXIÓN TCP O UDP
delay(4000);
mostrarDatosSeriales();
String datos="GET https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0" + String(tempC) + "&field2=0" + String(humidity) + "&field3=0" + String(pressure);
Sim900Serial.println(datos);//Envía datos al servidor remoto
delay(4000);
mostrarDatosSeriales();
Sim900Serial.println((char)26);
delay(5000);//Ahora esperaremos una respuesta pero esto va a depender de las condiones de la red y este valor quizá debamos modificarlo dependiendo de las condiciones de la red
Sim900Serial.println();
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSHUT");//Cierra la conexión(Desactiva el contexto GPRS PDP)
delay(5000);
mostrarDatosSeriales();
}

void comandosAT_2(){
Sim900Serial.println("AT+CIPSTATUS");//Consultar el estado actual de la conexión
delay(2000);
Sim900Serial.println("AT+CIPMUX=0");//comando configura el dispositivo para una conexión IP única o múltiple 0=única
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CSTT=\"internet.simple\"");//comando configura el APN, nombre de usuario y contraseña."gprs.movistar.com.ar","wap","wap"->Movistar Arg.
delay(1000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIICR");//REALIZAR UNA CONEXIÓN INALÁMBRICA CON GPRS O CSD
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIFSR");// Obtenemos nuestra IP local
delay(2000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSPRT=0");//Establece un indicador '>' al enviar datos
delay(3000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//Indicamos el tipo de conexión, url o dirección IP y puerto al que realizamos la conexión
delay(6000);
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSEND");//ENVÍA DATOS A TRAVÉS DE una CONEXIÓN TCP O UDP
delay(4000);
mostrarDatosSeriales();
String datos="GET https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field4=0" +  String(light_lvl) + "&field5=0" + String(mm) + "&field6=0" + String(windspeed_KMH);
Sim900Serial.println(datos);//Envía datos al servidor remoto
delay(4000);
mostrarDatosSeriales();
Sim900Serial.println((char)26);
delay(5000);//Ahora esperaremos una respuesta pero esto va a depender de las condiones de la red y este valor quizá debamos modificarlo dependiendo de las condiciones de la red
Sim900Serial.println();
mostrarDatosSeriales();
Sim900Serial.println("AT+CIPSHUT");//Cierra la conexión(Desactiva el contexto GPRS PDP)
delay(5000);
mostrarDatosSeriales();
}

```

And the first answer of the serial monitor is the following:

OK AT+CIPSTATUS

OK

STATE: IP INITIAL AT+AT+CSTT="internet.simple"

OK AT+CIICR

OK AT+CIFSR

10.254.14.23 AT+CIPSPRT=0

OK AT+CIPSTART="TCP","api.thingspeak.com","80"

OK

CONNECT OKAT+CIPSEND

SEND OK

AT+CIPSHUT

SHUT OK

And the socond one is (that works)

AT+CIPSTATUS

OK

STATE: IP INITIAL AT+CIPMUX=0

OK AT+CSTT="internet.simple"

OK AT+CIICR

OK AT+CIFSR

10.110.2.23 AT+CIPSPRT=0

OK AT+CIPSTART="TCP","api.thingspeak.com","80"

OK

CONNECT OKAT+CIPSEND GET https://api.thingspeak.com/update?api\_key=XXXXXXXXXXXXXXXXX&

SEND OK 381 AT+CIPSHUT

SHUT OK

You can see that after the AT+CIPSEND command, the SIM answer "GET https://api.thingspeak.com/update?api\_key=XXXXXXXXXXXXXXXXX&" , then "SEND OK" and finally the number of the entry (381).

Any idea or suggestion?

---
Tags: interrupt, gsm, thingspeak
---


# Question
Title: everything works independitly but not together. Piezo not generating a tone
My goal with the code is simple. Let the Piezo buzz when temperature reaches 25 degrees. My piezo is hooked up correctly, because It makes a buzz when the arduino boots or when I put this line of code anywhere else in my code.

I also checked if the If statement was called. And yes it is! So the if statements is happening yet I don't hear a buzz.

I am aware that I am breaking my seven segmented screen by using the delay. But I don't mind the screen working when the buzzer is.

```
void loop()
{
  //local vars
  if (millis() % 5000 <= 10) {
      float lm35TempC = lm35.getTempC();
      sevseg.setNumber(lm35TempC, 2);
      if (lm35TempC > 25.00) {
        tone(1,500,1000);
        delay(3000);  <------- WHERE IT PROBABLY GOES WRONG
      }
      if (lm35TempC < 25.00) {
        noTone(1);
      }
  }
  sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
}

```

To conclude: The If-statement is working yet I don't hear a buzz. How does this happen?

Thanks in Advance!

# Answer
> 4 votes
You connected the piezo to pin 1? Chose other pin. Pin 1 is Serial TX. You 'pump' PWM to USB.

tone() function will make sound no matter if you have a delay there. You set 1 sec with 1000 as third parameter. It will sound 1 sec and the turn of. **You do not need the delay() and noTone()**.

500 is low frequency. If it sounds only one second, can you catch it?

try `tone(TONE_PIN, 4500, 500)`. with speaker it is a nice beeeep

---
Tags: arduino-uno, piezo, buzzer
---


title: Parse UNIX-time from char[]

text:
# Question
Title: Parse UNIX-time from char[]
I want to parse a large number to sync time on my arduino. For this i send it a string with the current time in Unix time format wich looks somethink like this:

> 1535441277

For this I just call a php script wich echos the `time()` function.

But with `string.toInt()`I'm unable to parse it. I suppose the number is too large for an int or a long. But I can't put it directly into the `setEpoch()` method from the RTCzero libary because it accepts as input datatype only `uint32_t`. So how can I parse large numbers on a system where double isn't implemented. And I don't just try to parse the entire HTTP-Response. I iterate thru the response and at the relevant line I write all the chars into a char-Array. I also have removed the \r and \n chars.

# Answer
> 1 votes
On 32 bit systems, `uint32_t` is usually the same as `unsigned int` and `unsigned long`. You should be able to parse the number using `strtoul()`, which is quite standard and returns an `unsigned long`.

# Answer
> 0 votes
Thanks for the quick response. I also found another solution: Before echoing the time remove a large chuck of the time by just removing the current timestamp on the server-side. Later on I add the exact same amount when using the `setEpoch()` function. I know that's not very elegant but it works for me.

---
Tags: time, mkr1000, web-service
---


title: Arduino: command not found

text:
# Question
Title: Arduino: command not found
After installing the Arduino IDE on MacOS (1.8.5), I am trying to run some commands in the terminal to flash the firmware on an Uno R3.

I have successfully connected and uploaded through the GUI, but would like to use the command line for the `johnny-five` API (https://github.com/rwaldron/johnny-five/wiki/Getting-Started).

However, when running

```
arduino --install-library "Firmata,Servo"

```

I get the following error:

> -bash: command not found

How do I install the command line interface?

# Answer
Instructions to installing and binding the Arduino CLI can be found at

https://github.com/arduino/arduino-cli#getting-started

Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as `/usr/local/bin/`).

Note: You may have to rename the binary to `arduino-cli`.
> 3 votes

---
Tags: arduino-uno, command-line, johnny-five
---


title: How to give an analog output of 0-5V

text:
# Question
Title: How to give an analog output of 0-5V
I'm trying to program an Arduino to control a motor at different intensities by giving a 0-5V reference value from the board. I have some programming experience, but have very little knowledge of manipulating an Arduino or about electricity. As I understand from reading this, I need to call the AnalogWrite function to output the signal, but how do I do this? How can I control when the voltage (and by extension, the motor intensity) is increased or decreased. Is it possible to do this without additional hardware?

Any help is much appreciated, it doesn't have to be code. I mostly want to understand how to use the Arduino, but code would also help a lot with that. I'm using an Arduino Due, which as I understand, has true analog out.

# Answer
You would indeed need to use analogWrite to send a PWM signal to the motor. PWM will turn on and off the power to the pin really fast. In effect powering the motor with pulses. The length of these pulses will determine how much power the motor receives.

The DUE also has a true analog output, but you don't want to use that for motors. The use of the word `analogWrite` is a bit misleading when it's used for generating a PWM signal.

analogWrite will ask for a value between 0 and 255 to indicate the pulse length. 0 is OFF, 255 is full ON, 127 is ON for 50% of the time.

Also note that most motors require more current that the Arduino pins can provide, so you need to use a transistor/mosfet to "amplify" the signal to a higher current.
> 1 votes

# Answer
You can't do it without additional hardware because Due output is max 3.3 V. You need to amplify PWM or the analog output. PWM can be amplified using a MOSFET. If you are new to electronics I would recommend Grove MOSFET module. I use it to amplify PWM of M0 to 5 V.

It is normal to use PWM for regulation. True analog output is used for sound and similar waves. If you really need true analog value to 5 V with Due, you must use a voltage converter like in the tutorial linked by Majenko in comments.

The Arduino core handles the DAC of the SAMD boards with `analogWrite()` too.

Quote from the analogWrite reference:

> The Arduino DUE supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.

And you can set the resolution with `analogWriteResolution()`:

> By setting the write resolution to 12, you can use analogWrite() with values between 0 and 4095 to exploit the full DAC resolution.
> 0 votes

---
Tags: arduino-due, hardware
---


title: Two HC05 Bluetooth Bind problem

text:
# Question
Title: Two HC05 Bluetooth Bind problem
I succeeded in giving an AT command. My two BL MAC addresses are `21, 13, A03B` and `21, 13, A3E2`.

When I want to connect one to the other I use `AT+BIND=21,13,A3E2`. But then I see `Error(7)`. If I use another BL address from the Internet, it works.

So, why won't my 2 HC05 bind?

# Answer
The solution is

```
AT+BIND=0021,13,00A03B

```

NB: Here I just added `00` left side and right side digits
> 1 votes

# Answer
I think that this is an error caused by a difference of firmware versions. Now BT is on version 3.0-20170601 and I think that this version does not accept these `link` or `bind` commands.
> -1 votes

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Burning the Bootloader on Adafruit Feather 32u4
So, the default bootloader in Arduino is oddly set to erase EEPROM with every reboot, rendering the EEPROM, well, useless.

I found where the fuses are set in the boards.txt file, but getting this configuration change into the chip requires burning an updated booloader.

In the Arduino IDE, there is an option to "Burn Bootloader", but that would be way too easy, and of course, doesn't seem to work.

I can't find any clue on the Internet about how to actually get the bootloader updated in these devices.

So, is it possible to reprogram the bootloader on the Adafruit Feather 32u4 devices?

If so, what's the trick to do it?

# Answer
"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.

You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (`MOSI`, `MISO`, `SCK`, `RESET`, `VCC`, `GND`). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an Arduino as ISP.

The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.

**EDIT:**

This AVR USB Bootloader Datasheet states on page 3:

> • Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so that the Reset Vector points to the Boot Flash section start address after reset. Once the user code is loaded, a bootloader command (“start application”) can start executing the application code. Note that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse is programmed, the Reset Vector will always point to the Bootloader Reset and **the fuse can only be changed through the serial or parallel programming interface.** The BOOTRST fuse is not active in the default factory configuration.

That document also references AVR282: “USB Firmware Upgrade for AT90USB” (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.

This doc has a FAQ section which states:

> 3. Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the `32u4`. If that's not the case, I'm sure the site would welcome the new info.
> 3 votes

# Answer
In my case the 32u4 (Lora32u4II) failed after uploading big firmware. Not responsive.

Fortunately I have the buspirate 4 with firmware 7.0. And during this time I discovered that the BusPirate is not able to power the board to reflash the firmware. But if I connect the board over USB and then the cabling as described:

```
BUS PIRATE - LORA32U4II
MISO              MISO
MOSI               MOSI
CLK                SCK
GND                GND
CS                 RST

```

And I use arduino ide to upload a new bootloader it starts to work again. So. I wonder why the firmware update locked the board while there's enough space. And why powering over 5v doesn't get it to work on buspirate + arduino ide.

I leave info for others that have same problem.

I discovered that using this method, even if slower, I can skip bootloader, leaving more room for my firmware...
> 0 votes

---
Tags: arduino-ide, adafruit, atmega32u4
---


title: what is wrong with my code for buttons

text:
# Question
Title: what is wrong with my code for buttons
```
int "buttons"[6];

int "buttons"[0] = 2;

```

When i upload the code to the board it says:

```
exit status 1
expected unqualified-id before string constant

```

# Answer
1. `"buttons"` is not a valid identifier (i.e., not a valid variable name) because it does not start with a letter or underscore.
2. You should not repeat the type when you want to refer to the already-declared variable.

You declare the variable like:

```
int buttons[6];  // A 6-element array of integers

```

And if you want to refer to a specific element in the array:

```
buttons[0] = 2; // Let the first element of the array be the value 2.

```
> 2 votes

---
Tags: arduino-uno
---


title: What's wrong with my code

text:
# Question
Title: What's wrong with my code
I use a mega as a master and a nano as a slave.
Both should convey texts. However, I get the master always only the answer that I send.
The text from the slave does not arrive.

Master:

```
#include <SPI.h>
volatile boolean senden;
volatile char Paket_vom_Slave;
volatile char Paket_zum_Slave;
char buf [100];
volatile byte pos;
String Paket = "";
char x;

void setup (void)

{
  Serial.begin(9600);
  pinMode(53, OUTPUT);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);  //SS Pin auf HIGH setzten
  SPI.begin ();  //Verbindung starten
  SPI.setClockDivider(SPI_CLOCK_DIV8);  //Geschwindigkeit verlangsamen
}

void loop (void)
{
  //Text_erstellen();

  digitalWrite(SS, LOW);    //starten der Kommunikation mit Slave

  for (const char * p = "TxT v Master\n" ; Paket_zum_Slave = *p; p++)
  {
    //Text_erstellen();
    Paket_vom_Slave = SPI.transfer(Paket_zum_Slave); //senden von Text
    Text_erstellen();
    delayMicroseconds (500);
    Serial.print("sent: ");
    Serial.print(Paket_zum_Slave);
    Serial.print("\t empfangen: ");
    //Serial.println(Paket_vom_Slave);
    Serial.println(Paket);
    delay(200);
  }
  digitalWrite(SS, HIGH);  //beenden der Kommunikation
  delay (1000);  //kurze pause

}

void Text_erstellen()
{
  char c = Paket_vom_Slave;  //kopieren der Daten von SPI Buffer
  if (pos < sizeof buf)
  {
    buf [pos++] = c;  //hinzufuegen des naechsten Zeichens
    if (c == '\n')
      senden = true;
  }
  if (senden)
  {
    buf[pos] = 0;
    Paket = (buf);
    x = buf;
    Paket.trim();
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (("empfangen :--->") + (Paket));
    pos = 0;
    senden = false;

  }
}

```

Slave:

```
#include <SPI.h>
volatile boolean senden;
volatile boolean versandbereit;
//volatile byte Paket_Master,Sendung_Slave;
volatile char Paket_Master;
volatile char Sendung_Slave;
String Paket = "";
String Sendung = "";
int i = -1;
char buf[20];
char buf1[20];
volatile byte pos;
volatile byte pos1;

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

 pinMode(12, OUTPUT);
  pinMode(MISO, OUTPUT);
 SPCR |= _BV(SPE);         // turn on SPI in slave mode

  //SPCR |= bit (SPE);
  senden = false;
  SPCR |= _BV(SPIE);   // turn on interrupts
  SPI.attachInterrupt();
}

void loop(void)
{

  if ((versandbereit) == false);
  {
    Paket_Text();
  }

  if (senden)
  {
    i = i + 1;

    buf[pos] = 0;
    Paket = (buf);
    buf1[pos] = 0;
    Sendung = (buf1);

    if (i == 12)
    {
      SPDR = "\n";
    }
    else
    {
      SPDR = (buf1[i]);
    }
    Paket.trim();
    Sendung.trim();
    Serial.println (("empfangen :--->") + (Paket));
    Serial.println (buf1[i]);
    Serial.println (i);
    Serial.println (("gesendet  :--->") + (Sendung));

    pos = 0;
    senden = false;
  }

  if (i == 12) i = -1;
}

ISR(SPI_STC_vect)
{

  byte c = SPDR;  //kopieren der Daten von SPI Buffer
  if (pos < sizeof buf)
  {
    buf[pos++] = c;  //hinzufuegen des naechsten Zeichens
    if (c == '\n')
      senden = true;
  }
}

void Paket_Text()
{
  if (pos1 < sizeof buf1)
    for (const char * p = "Paket--Slave\n" ; char c = *p; p++)
    {
      buf1[pos1++] = c;
                            Serial.println (buf1);
      if (c == '\n')
        versandbereit = true;
    }
}

```

I've updated the code above.
The slave now sends bitwise the same text length as it should, but another text like the master sent.
Unfortunately, the master always receives what he sends, not what comes from the slave.

---

I'm getting on slowly :-)

But I currently have a problem with the data transfer. I hand over at startup: char package\_to\_master \[50\] = "Start from the slave."; and change SPI interrupt routine content with "new text" but is sent "starting from the slave." How should I change that?

```
// Slave
char Paket_zum_Master[50] = "Starten vom Slave.";
volatile int pos;
volatile bool active;
String Send_Paket;
ISR (SPI_STC_vect)    // SPI interrupt routine
{
  Send_Paket = "neuer Text";
  char Sendung = ((Send_Paket + "\n").c_str());
  Paket_zum_Master[50] = Sendung;
  byte c = SPDR;
  if (c == 1)  // starting new sequence?
  {
    active = true;
    pos = 0;
    SPDR = Paket_zum_Master[pos++];   // sendet erste byte
    return;
  }
  if (!active)
  {
    SPDR = 0;
    return;
  }
  SPDR = Paket_zum_Master[pos];
  if (Paket_zum_Master[pos] == 0 || ++pos >= sizeof(Paket_zum_Master))
    //wenn pos=0 oder größer 1
    active = false;
}  // end

```

# Answer
You do not have `pinMode(SS, OUTPUT);` in `setup()` of the master.
> 1 votes

# Answer
I've tried it on with Arduino Pro Micro as a master and Arduino Uno as a slave. It is working.

In the 'Note about Slave Select (SS) pin on AVR based boards' https://www.arduino.cc/en/Reference/SPI, it is notified that the SS pin should be set always as OUTPUT, even though you use another one to select the device.

The answer contains the text inside the SPI data register, you have to change it inside isr https://www.avrfreaks.net/forum/how-fast-can-spi-slave-reply, else it is the same text as that received

```
const char *p = "Reponse Uno\n" ;
ISR(SPI_STC_vect)
{
  byte c = SPDR;  //kopieren der Daten von SPI Buffer
  buf[pos++] = c;  //hinzufuegen des naechsten Zeichens

  if (pos < 13)
    SPDR = p[pos-1];
  else
    SPDR = 0;

  if (c=='\n') {
    for (int i=0;i<pos;i++)
        bufi[i]=buf[i];
    posi = pos;
    pos = 0;
    senden = true;
  }
}

```

The result is

By the way, it is another issue to make it work with Arduino Pro Micro as a slave ...
> 0 votes

---
Tags: spi
---


# Question
Title: Secure HTTPS request fails 90% of the time
I'm using a NodeMCU, which is connected to an enterprise network at a school. The information given in the GET requests that the ESP8266 sends is sensitive, so naturally we want to make it secure and encrypted - enter SSL. We do the request like so;

`HTTPClient http.begin(url, thumbprint)`

However, on the network at the school, doing this request fails 90% of the time, so I did a few tests - 100 requests to the exact same IP and certificate, noting how many went through;

* **School network**
    + HTTP**S** requests: 10/100 successful **\[10%\]**
    + HTTP requests: 100/100 successful **\[100%\]**
* **Private home network**
    + HTTP**S** requests: 100/100 successful **\[100%\]**
    + HTTP requests: 100/100 successful **\[100%\]**

We have also tried using the `WiFiClient` class, and while 100% of the requests went through, each one took 15 seconds which is too long.

My question is; what would the problem be, and what can we do to fix it? Can I do something in the code, or on the network?

# Answer
> 2 votes
Increase the timeout for your request with `HTTPClient.setTimeout()`. Note the timeout is in milliseconds.

```
HTTPClient http;
http.setTimeout(15000); // 15 Seconds
http.begin(url, thumbprint);

```

---
Tags: esp8266, nodemcu, networking
---


# Question
Title: Monitoring the state of AC relay, design considerations
I want to use a sensor and relay as a safety device to allow/deny power to an AC mains-powered electrical unit. If the wall power is disconnected I loose the state of the relay which is stored in a variable on my Pro Mini. My Arduino is powered from an AC-DC voltage regulator that is between the AC mains and the Power On switch of the electrical unit. Apart from powering the Arduino with a battery/supercap, are there any circuit design tricks I'm missing?

# Answer
> 1 votes
When you change the state of the relay, save it to the EEPROM. In setup() read the value from EEPROM and apply it.

# Answer
> 1 votes
I have run into a similar situation on a few occasions. Maybe my scheme will help. What I do is sense power loss early, so I can save a structure full of all my program states to EEPROM when the power is going away. Conversely, the first thing the program does on power up is restore the memory structure from EEPROM. Provided you save your relay state whenever it changes, this scheme should help you recover. You don't need a super cap. I use a circuit like this...

In this circuit, I use a diode to isolate a large (but not super) capacitor from the supply, and that circuit point also feeds my VIN (This is a NANO board). Then, that capacitor voltage is further isolated from a voltage divider, with another diode. The voltage divider brings down the 12V (only 11V after the diodes) to pretty near 5V. there's also a small (100nF) capacitor there to filter any noise.

If power is lost, that 2200uF capacitor will keep my NANO, a bunch of LEDs, an LCD display, and even a transistor driver and relay circuit(not shown) alive for nearly a second. But the voltage at the digital input (D2 in my case) will drop within milliseconds! So if you are polling that pin regularly, you'll have plenty of time to react by saving your states. If you doubt whether you can poll that fast, pin D2 can easily be tied to an interrupt. (that's overkill.. easier to just create you're owe version of millis(), so that whenever you have a timer wait, you can continually test the power detect pin, and react within a millisecond).

Now if for some reason you would like to ensure that the arduino doesn't lose power at all during short power line disturbances, you can add another diode to the 2200uF capacitor, and connect it to a battery pack. It the battery voltage is a little lower than the main supply, no current will flow out of it until its really needed.

# Answer
> 1 votes
You power your device and your controller from same AC source. You loose that AC source and they both will go off line. You get your AC source back - restart controller and check the current state of your device /relay.

What did I missed ?

---
Tags: relay
---