title: ATMega32u4 SLEEP instruction

text:
# Question
Title: ATMega32u4 SLEEP instruction
I was reading the ATMega34u2 datasheet and trying to figure out Sleep Mode. I know most people recommend using avr/sleep.h library. But I wanted to try out using the registers. I am fairly new to all this so sorry if this an easy question but I can't seem to really find anybody doing it like this.

When checking which registers to adjust it says this:

> The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.

Now I understand setting the bit but what exactly is the sleep instruction? How do I call it in my arduino program?

# Answer
> 2 votes
`SLEEP` is an assembly instruction. You can execute assembly with GCC's Inline Assembly facility.

In short:

```
asm volatile("SLEEP");

```

will do what you want.

The `avr/sleep.h` file has `sleep_cpu()` defined as:

```
#define sleep_cpu()                              \
do {                                             \
  __asm__ __volatile__ ( "sleep" "\n\t" :: );    \
} while(0)

```

Which is essentially the same thing - just wrapped in a block to isolate it from the rest of your code somewhat.

---
Tags: arduino-leonardo, sleep, atmega32u4
---


title: Smooth servo control library

text:
# Question
Title: Smooth servo control library
Is anyone aware of an Arduino library for smoothly controlling a servo?

I have an especially fast servo, which is trivial to control using Arduino's built-in Servo library. However, the library doesn't support proportional control. You specify a position, and the servo immediately goes to that position as fast as it can. With my servo, that creates incredibly fast jerky motion.

I've found some algorithms for interpolating a smooth servo motion by generating small incremental changes to the signal over time. I've been able to translate this to some Arduino code, and although the motion is much slower, it's still very jittery.

I've search for pure Arduino implementations, but I've not found anything. Does anyone know of an implementation? I find it hard to believe no one else has faced this type of servo control problem with an Arduino before.

# Answer
Infortunately, I did not find any library but I found that the method shown below could work quite well for small projects. By adding a small delay, it helps the servo run a little smoother. It is not really ideal but it should work if your goal is to minimize the roughness of the servo.

Also by adding a 100uF capacitor between 5V and GND, the capacitor will help calm the sudden rush you might get when the servo first starts to turn. That rush is caused by the servo asking for more current when the servo is not moving.

```
#include <Servo.h>   //servo library
Servo myservo;       //servo object
int previousAngle = 0;

const int potPin = A3; //sensor pin

void setup() {
  myservo.attach(9);  //data pin of the servo
  pinMode(potPin, INPUT); //sensor pin as an input
}

void loop() {
  int val = analogRead(potPin);
  int angle = map(val, 0, 1023, 0, 180);

  if(angle>previousAngle)
  {
    for(int i=previousAngle; i<=angle; i++)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  if(angle<previousAngle)
  {
    for(int i=previousAngle; i>=angle; i--)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  previousAngle = angle;
}

```
> 5 votes

# Answer
After searching via a different angle (using "easing" as a keyword), I found this excellent library. Apparently this task is more commonly known as "servo easing", not smoothing. I've tested it with a hobby servo, and it does exactly what I was looking for.
> 5 votes

# Answer
Searching the net for smooth servo movement I found this entry one year ago.

In the end I built a new library for this task called ServoEasing.
> 1 votes

---
Tags: servo
---


title: 24V LED Lights with Arduino

text:
# Question
Title: 24V LED Lights with Arduino
I need help on determining how I can control 24VDC Auer Stack lights with an Arduino. I intend to activate these lights with a RF control and monitor them via IoT; the latter is just something else, not my main concern right now. However, I don´t know if I need to use normal relays, solid state relays or MOSFETs such as an IRF520. The lights are 24V, consume around 22mA-33mA, they are pre-wired and only have the 4 wires (from the amount of lights I intend to use) and a common wire.

Thanks in advance!

---

Thank you for your quick response! I can see the IRF520 might be too much. What about the IRF520 arduino module, it has lower current and voltage rates, do you think it might work?

# Answer
All that differs between those LEDs and 12V LEDs is the voltage. You do exactly the same as you would do with 12V LEDs - you just make sure the components you use are rated for *at least* 24V.

The IRF520 is overkill for this application. It's rated for 100V and 9A - far more than you need. But that's not to say it won't work - it'll work just fine. But you don't *need* one as big or beefy.
> 0 votes

# Answer
I don't think the IRF520 is a logic level MOSFET. You need one that can be driven to satuation with 5V. I've used this one from Adafruit for several projects: https://www.adafruit.com/product/355

It worked fine. It's also overkill, but so what?

(It looks like that same part number, IRLB8721, is available from several other manufacturers for cheaper than the Adadfruit part.)

It's dirt simple to use. You can drive the gate directly from an Arduino digital pin. It will handle plenty of current and up to 60V, so it should meet your needs.
> 0 votes

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


# Question
Title: I get the following error while using esp32
> rst:0x1 (POWERON\_RESET),boot:0x13 (SPI\_FAST\_FLASH\_BOOT) configsip: 0, SPIWP:0xee clk\_drv:0x00,q\_drv:0x00,d\_drv:0x00,cs0\_drv:0x00,hd\_drv:0x00,wp\_drv:0x00 mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044 load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac
>
> \[E\]\[camera.c:1049\] camera\_probe(): Detected camera not supported. \[E\]\[camera.c:1249\] esp\_camera\_init(): Camera probe failed with error 0x20004

I tried all the troubleshooting methods found in other forums

# Answer
> 1 votes
Welcome to StackExchange!

I guess you flashed esp32-cam firmware to off-branded ESP32-CAM with different pinout assignments.

To fix this, maybe you should try around with different settings.

Your code should have something similar to this:

```
// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
//#define CAMERA_MODEL_AI_THINKER

```

Now try to comment out the third line, and uncomment the last one. Probably it would help.

# Answer
> 0 votes
Whatever code you have on the ESP32 is looking for a camera. That camera can't be found - is it attached? Did you install the code? Did it come with the code pre-installed? If you installed the code, what code is it? If you didn't install the code yourself, maybe you want to write some new code to get the ESP32 to do what you want it to do.

---
Tags: arduino-uno, esp32
---


# Question
Title: What is the correct folder structure for including local headers in my Arduino project?
I am designing a "project" with 5 Arduino's (each with separate codes), communicating with each other using NRF24. All the 5 codes are different except they share a common header "MyHeader.h". The Arduino IDE forces the .ino filename to be same as the folder-name it is in. I currently have the following structure:

```
[parentfolder]
    MyHeader.h
    [arduino1]
          arduino1.ino
    [arduino2]
          arduino2.ino
    [arduino3]
          arduino3.ino
    [arduino4]
          arduino4.ino
    [arduino5]
          arduino5.ino

```

Now, if I use the following, I get an error that the IDE cannot find the header file:

```
#include "../MyHeader.h"

```

I am forced to use the above structure due to the IDE folder naming restrictions, whereas I would definitely like to have a structure like the following:

```
[parentfolder]
    MyHeader.h
    arduino1.ino
    arduino2.ino
    arduino3.ino
    arduino4.ino
    arduino5.ino

```

How should I organize my project so that I can include my header (without obviously duplicating the file inside every folder)? Thanks.

# Answer
> 1 votes
The reason why you can't reference the parent folder of your sketch when compiling is because the Arduino IDE doesn't compile your sketch in that folder. Instead it writes out the files from the IDE itself into temporary files in a "build" folder and compiles them in there - so the parent folder then does not contain your header file because the IDE has no clue about that.

So you need to put your header file somewhere that the IDE *does* know about - and the simplest place is where the libraries are.

A library is nothing more than a header file in a folder (both named the same) with optional source and other header files. If you place your header in a folder in your libraries folder the IDE will see it as a library and you can include it into any sketch.

So you would have:

```
Documents/
    Arduino/
        libraries/
            MyHeader/
                MyHeader.h
    MyFancyProject/
        NodeOne/
            NodeOne.ino
        NodeTwo/
            NodeTwo.ino
        NodeThree/
            NodeThree.ino

```

---
Tags: arduino-ide, project
---


# Question
Title: Need Help to Select Microcontroller ?? Help
i am doing a project which has to run in side a garage to control water levels in sump pit as well as in overhead tank . also schedule running of pumps.

i have to run 5 pumps (two for ground water to sump pit , three for sump pit to over head tank) check two levels also need to check when pump goes on the water is flowing or not if not try another pump

the micro controller should last at least two years .

the temperature inside garage where micro controller board will be kept will go to 47 centigrade in summer to 15 centigrade in winter .

i see many options :

1.arduino uno

2.arduino uno from sparfu and adafruit

3.Sparkfun Arduino Fio

4.SparkFun Arduino Pro Mini 328

5.Adafruit Metro Mini 328

6.Adafruit METRO 328

7.Particle Photon

what whould i use ?

# Answer
We cannot say, what single board you need to use. There are many boards, that are fitting to your requirements. You yourself have to choose.

Most of your listed boards use the same microcontroller (as Juraj wrote in his comment): The Arduino Uno (doesn't matter where you buy it, it's the same) and all the boards with a `328` at the end use the Atmega238P. The Sparkfun Arduino Fio uses an Atmega32U4, which is different from the 328P, but not a very big jump (though it implements native USB support). These are all AVR based microcontrollers. The Particle Photon is not an Arduino. It uses an ARM processor and has wifi.

To choose from the big amount of boards on the market, you should look into your requirements: \- How many outputs do I need? Only simple digital outputs or also PWM? If the latter, how many individual PWM pins do I need? \- How many inputs do I need? Only digital or also analog? \- What extra devices do I need? Relays for motors/high loads? Special boards? And how do they need to be connected (what interfaces they use)? \- What interfaces do I need to the outside world? LCD Display + Buttons? Bluetooth? Wifi? Or nothing? \- How computationtime- and memory-consuming are the calculation tasks, that I need to perform (resources)? \- What environment will the project be in?

Based on the answers, you can choose a board, that fit's all the requirements and still leaves a bit headroom for further development. To help you I will write some examples for your project, that might be fitting for you.

* **Outputs:** I guess your pumps are using mains power or similar (Be VERY carefully with mains power. It can easily kill you!). You need a relay to control these. It would be easiest to use a complete relay board, that includes all the needed extra circuitry. Then you just need to use one digital output pin per controlled pump, which results in 5 pins needed.
* **Inputs:** This depends on what level sensors you have. If they have a digital signal (like a simple switch, that triggers, when it is covered by water), you just need to tie one digital input pin to each level sensor. With 2 level sensors per tank and 2 tanks we need 4 digital input pins for level sensing.

If the level sensors work with an analog voltage, you need to use 4 analog input pins. Their usage is a bit different, since their voltage has to be converted to a number value by the ADC (Analog Digital Converter) inside the microcontroller.
* **Interfaces:** This is mostly up to you, since you didn't specify anything. You can just build the device with any outside interfaces, if you don't need them. Then you also can use a board without wifi. If you think, that adding wifi in the future would be a great idea, you can use a wifi capable board and just disabling wifi, until you need it. (Thinking a bit in the future, what future development might get interesting for this project)
* **Resources:** Controlling motors (pumps are only motors for the microcontroller) based on some simple inputs is somewhat the standard task for a simple microcontroller. It doesn't need much computation power, neither much memory.
* **Environment:** The temperature is not a problem for you. Basically all microcontrollers can operate in temperatures up to 80°C und down to -35°C (the exact values can be found in the datasheet of the corresponding microcontroller). The humidity is more of a problem. You need to build a water resistant casing for the electronics of your project, so that no water can get on the electronic parts. Also - to be sure - you should put one or two of these little silica bags into the casing, which sometimes come with electronic devices or such. The silica bags will bind the water in the air inside the casing and will keep the electronics even more dry.

So you need a simple microcontroller with 5 digital outputs and 4 inputs (digital or analog depending on your sensors), so in total 9 free fitting pins. An Uno or some of it's variants are fitting for this. If you want it smaller, that the Uno, you might want to use the Nano, which is the same as the Uno, just smaller. If you want wifi capabilities, you can go with an ESP variant like the NodeMCU.

This is just an example. There are many ways to build such a project, so there is no definitive answer. Any microcontroller, that fit's your requirements, is ok for the job.
> 0 votes

---
Tags: adafruit
---


title: Using Serial.begin() twice

text:
# Question
Title: Using Serial.begin() twice
I'm training kids programming Arduino. We're gonna use `Serial` for debugging purposes, so we started with a simple HelloWorld program. I let them try various stuff, including changing the speed.

Now, one of the outcomes was as simple as

```
void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.begin(9600);
  Serial.println("world");
}

```

My expectation was, that the Arduino does exactly as written, but the serial monitor of the Arduino IDE will become a bit consufed. When the monitor is set to 115200 baud, I expected to see

```
Hello
world
_#&%$"    < some garbage
world
_#&%$"    < garbage again
...

```

However, the real output is only one line

```
H⸮⸮⸮⸮C

```

Why is that? Is it impossible to change the baud rate in between?

The official documentation does not say we can use `Serial.begin()` only once.

I'm using Arduino Uno and Arduino IDE 1.8.9

# Answer
> 3 votes
This is because the output of the serial is buffered. It's still sending the first bit of data while you change the baud rate - and from then on it's just a complete mess.

You need to force it to finish sending before you can change the baud rate by using `Serial.flush()`:

```
void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.flush();
  Serial.begin(9600);
  Serial.println("world");
  Serial.flush();
}

```

That will wait after each print until all the data is sent out "onto the wire" before changing the baud rate for the next print.

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


# Question
Title: What kind of antenna should i use for my esp8266 module?
I have an esp8266 module and i want to increase its range by adding an antenna to it. What kind of antena should i use. Can i use an antenna from a RC car remote?

# Answer
> 4 votes
You must use a WiFi (2.4 GHz) antenna. From the picture in your post, you have one of the esp8266 modules with a "built-in" antenna implemented via traces on the PCB. You cannot add an external antenna without removing the old one first, and even that will be very dodgy - you'll likely render your esp8266 useless for any purpose.

Instead, you could get an esp8266 that is made for connecting an external WiFi antenna. See the Wikipedia article for details. It specifically mentions model # ESP-WROOM-02U as having a connector for an external antenna.

---
Tags: esp8266, wifi
---


title: Sparkfun Pro-Micro stuck on uploading

text:
# Question
Title: Sparkfun Pro-Micro stuck on uploading
I have read multiple posts on how to reset the sparkfun pro-micro when it gets stuck during upload, and this seems to work to get it back to a state where I can upload new code again - However, I am here to ask if it is possible that it is something in my code that is causing this issue? The reason I suspect it is my code is because I have tried:

* Different pro micro
* Different USB cable
* Downloaded latest IDE
* Downloaded latest AVR boards package
* Tried reverting back to an older AVR boards package as suggested in a different post

Not sure if this is a coincidence, but when I upload a simple blink sketch I don't have any trouble, but as soon as I upload my code (below), it gets stuck on uploading... I can get it to eventually upload after many attempts using the reset during upload trick, but it seems to be unstable. I say unstable because sometimes it will print out the values requested, and other times it will print nothing...

```
int clampVal = 0;

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

void ClampReading()
{
    const int numRead = 400; //amount of calibration values we will average
    double vals[numRead];      // the readings from the analog input
    int readIndex2 = 0;                 // the index of the current reading
    double total2 = 0;                  // the running total
    int calibration2 = 0;               // calibration incrementer

    for (int thisReading2 = 0; thisReading2 < numRead; thisReading2++) {
    vals[thisReading2] = 0;
    }
    while(calibration2<numRead)
    {
      int rawClamp = analogRead(A0);
      total2 = total2 - vals[readIndex2];
      vals[readIndex2] = rawClamp;
      total2 = total2 + vals[readIndex2];
      readIndex2 = readIndex2 + 1;
      if (readIndex2 >= numRead) {
        readIndex2 = 0;
     }
      clampVal = total2 / numRead;
      calibration2++;
    }

}

void loop() {
 ClampReading();
 Serial.println(clampVal);
}

```

EDIT: Once I reset and upload an EMPTY sketch, I can upload the empty sketch with no problems. I did it 5 times in a row with no issues. Then tried to upload the code above once, and it worked..but then tried to upload second time, and stuck in uploading again... it has to be the code, but I can't narrow down what it is.

# Answer
Uno's Mega's and so on have a separate MCU (u3) that contains the boot loader and is responsible for the USB connection and for driving the virtual serial port. Micros ( and also Leonardos and Esploras ) have built in USB support in the main MCU (u4). So if your program does something that breaks the USB part of the MCU the communication breaks also. This happens for instance if you disable the interrupts.

The only thing you use in your program that might cause a problem is the Serial connection. The blink example has no serial output.

If you add a `Serial.begin(115200)` and a `Serial.println("Hello")` to the blink example, I guess the problem occurs also.

The IDE establishes the programming connection by connection to the selected com port at 1200 Baud. The boot loader recognizes that, performs an auto reset and opens a second (programming port) from then the IDE has access to this port and uses it to communicate with the boot loader. On a UNO this is handled by the separate MCU and on the Micro the main CPU is responsible for that.

Perhaps it helps if you add a time delay, before the Serial.begin(). Then you will have more time to start the programmer.

There is also a trick to enlarge the time you can start the programming after a reset to 8 seconds. https://forum.arduino.cc/index.php?topic=224416.msg1643210#msg1643210

And one additional hint:

Your code is unnecessarily complicated. If you want, you can try the program below. I think it does the same as yours. I have no compiler and no micro at the moment so it's complete untested.

You used a calibration variable. I guessed that it is for skip the first calibration values. If you need the values you can store them in a separate array.

My prog. has a lower memory footprint because I store the integer values from the analog input into an integer array. You used a double array.

You also did a lot of unnecessary computations after you read an analog value. This can slow down the readings. Perhaps therefore you missed some values you expected to see.

```
//amount of calibration values we will average
const int valueCount = 400;
const int calibCount =   0;

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

void loop()
{
  // the readings from the analog input
  int vals[ valueCount ];

  for (int idx = 0; idx < valueCount + calibCount; idx++)
  {
    int rawValue = analogRead( A0 );
    if ( idx >= calibCount )
    {
      vals[ idx - calibCount ] = rawValue;
    }
  }

  double total = (double) 0.0;

  for (int idx = 0; idx < valueCount; idx++)
  {
    total += (double) vals[ idx ];
  }

  Serial.println( total / valueCount );
}

```
> 2 votes

---
Tags: arduino-ide, uploading, arduino-pro-micro
---


# Question
Title: FIXING BUG when Using Wire library to obtain compass heading
I am using the HMC-5983 magnetometer module to obtain the compass heading of a autonomous car I am building using the arduino platform.I'musing the Z axis and X axis to obtain the heading.

However when the headingFiltered variable is at 359 and the car turns to Zero,the headingFiltered becomes to 0 via all the values between 0 and 360 rather than just becoming 0.This causes my car be constantly steering side to side when heading in this relevant direction. Also if there is anyway that this function could be improved,I'm open to suggestions.

The function I'm using is as follows.

```
void chead() {

  //---- X-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX1 = Wire.read();
  }

  //---- Y-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY1 = Wire.read();
  }

  //---- Z-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ1 = Wire.read();
  }

  //---- X-Axis
  mX1=mX1<<8;
  mX_out =mX0+mX1; // Raw data
  // From the datasheet: 0.92 mG/digit
  Xm = mX_out*0.00092; // Gauss unit
  //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.

  //---- Y-Axis
  mY1=mY1<<8;
  mY_out =mY0+mY1;
  Ym = mY_out*0.00092;

  //---- Z-Axis
  mZ1=mZ1<<8;
  mZ_out =mZ0+mZ1;
  Zm = mZ_out*0.00092;
  // ==============================
  //Calculating Heading
  heading = atan2(Zm, Xm);// arc tangent of z/x

  // Correcting the heading with the declination angle depending on your location
  declination = 0.03717551307 ;
  heading += declination;

  // Correcting when signs are reveresed
  if(heading <0) heading += 2*PI;
  // Correcting due to the addition of the declination angle
  if(heading > 2*PI)heading -= 2*PI;
  headingDegrees = heading * 180/PI; // The heading in Degrees unit
  // Smoothing the output angle / Low pass filter
  headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;
  //Sending the heading value through the Serial Port to Processing IDE

  //this was done to fix an error.which was when the compass was made to turn by 180° the reading obtained did not change by 180°.
  if(headingFiltered >= 0 && headingFiltered <= 89){
    c_head=map(headingFiltered,0,90,270,359);
  }
  if(headingFiltered > 89 && headingFiltered <= 204){
    c_head=map(headingFiltered,90,204,0,90);
  }
  if(headingFiltered > 204 && headingFiltered <= 290){
    c_head=map(headingFiltered,205,290,91,180);
  }
  if(headingFiltered > 290){
    c_head=map(headingFiltered,291,359,181,269);
  }

  //Further calibration
  if(c_head>=0 && c_head<8){
    c_head=352+c_head;
  }
  if(c_head>=8){
    c_head=c_head-8;
  }

  // Serial.print("Degrees - ");
  // Serial.println(c_head);

  float teta1 = radians(clatval);
  float teta2 = radians(dlatval);
  float delta1 = radians(dlatval-clatval);
  float delta2 = radians(dlongval-clongval); //==================Heading Formula Calculation================//

  float y = sin(delta2) * cos(teta2);
  float x = cos(teta1)*sin(teta2) - sin(teta1)*cos(teta2)*cos(delta2);
  float brng = atan2(y,x);
  degris = degrees(brng);// radians to degrees
  degris = ( ((int)degris + 360) % 360 );

  dif_h=c_head - degris;
  abs_dif_h=abs(dif_h);
}

```

# Answer
> 2 votes
The problem comes from the low-pass filter you are using:

```
// Smoothing the output angle / Low pass filter
headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;

```

This filter is designed to smooth out rapid variations of the measured heading. If the heading suddenly jumps from 359° to 0°, the filter will replace that jump by a continuous change that goes through the intermediate values.

I can think of three different options for solving this problem.

## Option 1: filter the Cartesian coordinates

Unlike the heading, the in-plane components of the magnetic field vary smoothly as the vehicle rotates. You can filter these components before computing the heading as follows:

```
const float filter_constant = 0.15;

float filtered_angle(float y, float x)
{
    static float x_f, y_f;  // filtered components
    x_f += filter_constant * (x - x_f);
    y_f += filter_constant * (y - y_f);
    return atan2(y, x);
}

```

Then you would replace

```
heading = atan2(Zm, Xm);

```

by

```
heading = filtered_angle(Zm, Xm);

```

## Option 2: filter the unwrapped heading

Another possible approach is to *unwrap* the heading before filtering it. This is similar to phase unwrapping: instead of requiring the heading to be limited to the interval \[−π, π\] (or \[0, 360°) if you work with degrees), you let it take arbitrary values. Each time your vehicle does a full turn, the unwrapped heading varies by ±360°. Here is a simple unwrapping filter:

```
// Unwrap an angle in radians.
float unwrap(float angle)
{
    static int revolutions;
    static float previous_angle;
    float delta = angle - previous_angle;
    previous_angle = angle;
    if (delta >= M_PI)
        revolutions--;
    else if (delta < -M_PI)
        revolutions++;
    return 2*M_PI*revolutions + angle;
}

```

The unwrapped heading is continuous, and can be safely low-pass filtered without creating the kind of issue you have now. After the low-pass filter, you can wrap it again with `fmod()` if you wish.

## Option 3: wrap the heading differences within the filter

The previous idea can be applied backwards: instead of unwrapping the heading, you can wrap the heading *differences* within the low-pass filter, in order to keep them within \[−π, +π) (i.e. \[−180°, +180°)). Then, if the filtered heading is 359° and you get a new raw heading of 0°, the difference is −359°, but you wrap it to +1°. This will cause the filtered output to just slightly increase to 359.15°, given your chosen filter constant of 0.15.

Here is a low-pass filter based on this idea, that is aware of how angles are supposed to wrap:

```
const float filter_constant = 0.15;

// Wrap an angle to [-pi, pi).
float wrap(float angle)
{
    while (angle < -M_PI) angle += 2*M_PI;
    while (angle >= M_PI) angle -= 2*M_PI;
    return angle;
}

// Low-pass filter an angle.
float filter_angle(float angle)
{
    static float filtered_angle;
    filtered_angle += filter_constant * wrap(angle - filtered_angle);
    filtered_angle = wrap(filtered_angle);
    return filtered_angle;
}

```

I think I like this option better that the other two because it does its arithmetics in a way that is consistent with how angles are supposed to wrap, and also because it keeps less state (only one `static` variable). Also, you have implemented something very similar to the `wrap()` function above, in order to wrap the heading to \[0, 2π). You could instead reuse `wrap()` as:

```
// Wrap to [0, 2 pi).
heading = wrap(heading - M_PI) + M_PI;

```

**Edit**: There is a recently published Arduino library that implements this third option. It “provides a class, `runningAngle`, that computes an exponentially weighted running average of a series of angles, such as compass readings. It is aware of how angles wrap modulo 360°.” The library is called runningAngle and is available through the library manager of the Arduino IDE.

---
Tags: i2c, code-optimization, wire-library, magnetometer
---


# Question
Title: How to add another time counter to my functioning sketch?
I have a functional sketch that I run on an Arduino Uno, the output controlling a fan module; I need another timer to run a 2nd fan and I would like to use another output on the Uno to do that rather than using another unit.

What my sketch does is as follows:

* counts 15 minutes (interval\_1)
* starts the fan for 1 minute (interval\_2)
* starts another cycle.

What I need to do is to add another function that will start fan#2 for 15 sec (interval\_3) when the cycle starts, using another output (relayPin\_1), then stop.

So the flow will be:

* counts 15 minutes (interval\_1)
* starts fan#1 for 60 sec (interval\_2)
* starts fan#2 for 15 sec (interval\_3)
* resets and starts another cycle.

Unfortunately, can't figure out how to insert the 2nd timer.

Sketch is below, if you have any ideas that would be much appreciated.

Thanks

```
const byte relayPin = 4;                           // fan#1 control on pin 4,
const byte relayPin_1 = 7;                         // humidifier fan#2 control on pin 7,
const unsigned long interval_1 = 1000UL * 60,      // RUN timer, msec
                    interval_2 = 1000UL * 60 * 15, // OFF timer, msec
                    interval_3 = 1000UL * 15;      // Humidifier timer
unsigned long currentMillis, previousMillis = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(relayPin, OUTPUT);   // Output#1
    pinMode(relayPin_1, OUTPUT); //Output#2
    // relayPin_1 controls the humidifier's fan#2
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
    // at startup, fan is ON for interval_1 duration
    currentMillis = millis() - previousMillis;
    if (currentMillis <= interval_1) {
        digitalWrite(relayPin, HIGH);    // fan ON
        digitalWrite(LED_BUILTIN, HIGH); // LED ON (blinking)
        delay(333 / 2);
        digitalWrite(LED_BUILTIN, LOW);   // LED Off
        delay(999);
    }

    // when interval_1 is reached, turn fan OFF for the duration of interval_2
    else if (currentMillis <= (interval_1 + interval_2)) {
        digitalWrite(relayPin, LOW);    // fan OFF
        digitalWrite(LED_BUILTIN, LOW); // led OFF
    }
    else {
        // reset the timer
        previousMillis = millis();
    }

}

```

---

Okay... I had time to play with it today; what it does: it starts both fan#1 and fan#2, then stops fan#2 at (interval\_1 + interval\_2), but fan#1 continues running until the cycle ends. Therefore: fan#1 runs for 35 sec, fan#2 runs for 15 sec, as it should; and the cycle is stopped for 30 sec as it should. However, I can't make fan#1 to run for only 20 sec. as it is defined.

```

const byte relayPin = 4;   // recyrculation fan#1 control on pin 4,
const byte relayPin_1 = 7; // humidifier fan#2 control on pin 7,
const unsigned long interval_1 = 1000UL * 20,    // RUN timer fan#1, msec
                    interval_2 = 1000UL * 15,    // RUN timer fan#2, msec
                    interval_3 = 1000UL * 30;    // OFF timer
unsigned long currentMillis, previousMillis = 0;

void setup() {
   // put your setup code here, to run once:
   pinMode(relayPin, OUTPUT); // Output#1
    pinMode(relayPin_1, OUTPUT); //Output#2
     pinMode(LED_BUILTIN, OUTPUT); }

void loop() {
// at startup, fan#1 & fan#2 are ON
 currentMillis = millis() - previousMillis;
  if (currentMillis < interval_1) {
    digitalWrite(relayPin, HIGH);   // fan#1 ON
    digitalWrite(relayPin_1, HIGH); // fan#2 ON
     digitalWrite(LED_BUILTIN, HIGH); // builtin LED ON

 } else if (currentMillis < (interval_1 + interval_2)) {
    digitalWrite(relayPin_1, LOW); // fan#2 OFF

   // when (interval_1 + interval_2) is reached, turn fans OFF for the duration of interval_3
 } else if (currentMillis < (interval_1 + interval_2 + interval_3)) {
   digitalWrite(relayPin, LOW);      // fan#1 OFF
    digitalWrite(LED_BUILTIN, LOW); // led OFF

 } else {
   // reset the timer
     previousMillis = millis(); }
 }

```

# Answer
> 1 votes
Assuming you get your logic straightened out, you should be able to add as many cases to your if statement as you want:

```
  if (currentMillis <= interval_1) {
      // Before end of interval 1, fan off.
  } else if (currentMillis <= (interval_1 + interval_2)) {
      // In interval 2, fan on
  } else if (currentMillis <= (interval_1 + interval_2 + interval_3 )) {
      // In interval 3, fan2 on
  } else {
      // Turn everything off
      // reset the timer
  }

```

---
Tags: timers
---


# Question
Title: How do I repeat else if (cmd == '3') until I press another cmd?
This code is for automatically opening and closing a window using a motor with senors such as dust, humidity, temperature, and rain sensor with bluetooth module through phone. With this code if I press 1,2 it would close or open the window and 3 would let the window open or close regarding the measures that the sensor reads. Right now pressing 3 would only simulate this once and then turn off untill I press it again So I would want this part else if (cmd == '3') to repeat itself until I press another cmd button so the window keeps opening and closing.

```
//////////////////////////////////////////////////////////////////////////
#include <SoftwareSerial.h>
#include <Stepper.h>
#include <DHT.h>
#define DHTPIN A1
#define DHTTYPE DHT11
#define D_IN 3
#define A_IN A0

int Txpin = 7;
int Rxpin = 8;
int stepsmotor = 1024;
const int stepsPerRevolution = 64;
SoftwareSerial BTSerial(Txpin, Rxpin);
DHT dht(DHTPIN, DHTTYPE);
int measurePin = 0;          // measurePin을 0으로 설정합니다.
int ledPower = 2; // ledPower를 2로 설정합니다.
int samplingTime = 280;    // samplingTime을 280으로 설정합니다.
int deltaTime = 40;           // deltaTime을 40으로 설정합니다.
int sleepTime = 9680;       // sleepTime을 9690으로 설정합니다.
float voMeasured = 0;      // voMeasured를 0으로 설정합니다.
float calcVoltage = 0;       // calcVoltage를 0으로 설정합니다.
float dustDensity = 0;       // dustDensity를 0으로 설정합니다.

Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
  myStepper.setSpeed(550);
  pinMode(ledPower,OUTPUT);
  pinMode(D_IN, INPUT);
}

void loop()
{
 if (BTSerial.available())
  {
    char cmd = (char)BTSerial.read();
    if(cmd == '1'){
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
      }}
    else if (cmd == '2')
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
   }
    else if (cmd == '3'){
     int dIn = digitalRead(D_IN);
  double aIn = analogRead(A_IN);
    int h = dht.readHumidity();
    int t = dht.readTemperature();
digitalWrite(ledPower,LOW);
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin);
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH);
  delayMicroseconds(sleepTime);

  calcVoltage = voMeasured * (5.0 / 1024.0);

  dustDensity = (0.17 * calcVoltage - 0.1) * 1000;

    Serial.print(dustDensity);
    Serial.println(" ug/m3");
  Serial.print("Digital Input = "); Serial.println(dIn);
  Serial.print("Analog Input  = "); Serial.println(aIn);
  Serial.println();
    Serial.print("humidity:");
    Serial.println(h);
    Serial.print("temperature:");
    Serial.println(t);
    delay(1000);

    if (t >= 25 or h >= 70 or dustDensity >= 100 or aIn <= 50)
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
    }
    else
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
    }

  delay(3000);
    }
    else if (cmd == '4'){

    }
      }
    }

```

# Answer
> 1 votes
I would suggest to rewrite your program as a Finite State Machine (FSM). It's a simple but powerful concept. You first model your program into multiple states, that are connected through state transitions. It is a good way to first draw this as a graph. You can see one example in my answer to this question.

For your case I would use your "modes" as states for the FSM plus an idle state, where simply nothing happens. You would start in the idle stat and then change to different states depending on the Serial input. In the states/modes 1 and 2, which are only one time actions, you would execute the action in the state and then directly change to the idle state again.

From the programming side a FSM can be implemented in multiple ways. I have seen FSMs using a variable and switch cases, but also FSMs, that use a function pointer. The last is elegant, but not as easy to understand for beginners. So I suggest you use the switch-case variant, as you can see in the answer linked above. Basically you use a variable (something like `int` or `char`) to represent the current state. In your `loop()` function you then build a switch-case statement for different values of your state variable. Often an enum is used as variable type to make the code more readable. In each case statement you write the code for the corresponding state. In your state/mode 3 you would check your sensors and close/open the window as needed, then leaving the case statement. When the next iteration of the `loop()` function happens, the FSM will still be in this state, checking again the sensors. In your states/modes 1 and 2 you would check, if the window already has the needed state and - if not - drive to motor to close/open the window. Then - still in the case statement - you would set the state variable to the idle state, then leave the case statement. So in the next interation of the `loop()` function the FSM will be in the idle state, doing nothing, making the states/modes 1 and 2 a one-shot everytime, that you activate them.

In contrast to the code in the linked answer, I would read the Serial data outside of the switch statement, since you will write directly to the state variable in there.

I strongly suggest, that you try to implement this. It is an important principle, that makes your more structural sound and easier to extent. A great learning experience.

---
Tags: arduino-uno
---


# Question
Title: Powering ESP8266 module from arduino nano
I'm just starting up with arduino and i have few simple questions.

* Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail? There are bunch of tutorials explicitly avoiding this or using resistors and i would like to know why?
* Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano and therefore have stable voltage by avoiding batteries and by doing so, connect ESP8266 directly to arduino without fear of breaking something?
* Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

# Answer
> 2 votes
> Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail?

The 3.3V rail of the Arduino is not meant to provide much current. The onboard regulator is a simple linear voltage regulator, which will dissipate the extra power as heat. As you draw more current through it, it will get hotter and finally get fried, as it cannot dissipate the created heat. The ESP chip needs multiple hundreds of mA, especially, when it is connecting to a wifi network. The onboard voltage regulator of the Arduino cannot handle this much. So you cannot power it over the Arduino.

I don't really know, what you mean with "using resistors".

> Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano \[...\] connect ESP8266 directly to arduino without fear of breaking something?

Yes, you can power the Arduino with this power supply, but you should power the ESP through the Arduino. Not through the 3.3V, nor through the 5V rail (which will fry the protection diode, I think). Instead you should power the ESP directly from the power supply, in parallel to the Arduino. Often ESP modules have their own voltage regulator, that regulates the voltage from 5V to 3.3V. If that is the case for you, you should use this input of the ESP module with the power supply. If you don't have a 5V capable regulated input on your ESP module, you will have to use a dedicated voltage regulator for that. In that case be sure, that the voltage regulator can provide enough power for the ESP (with some headroom on top).

> Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

Yes, the Arduino Nano can be powered over USB. But again you must be sure to not draw too much current from the Arduino. Between USB and the 5V rail is a diode, that will be destroyed, if you draw too much current through it. And the standard USB port can only provide up to 500mA. And regarding the 3.3V rail: All the explanations above about the 3.3V rail apply here again, since the USB voltage (5V) is regulated down to 3.3V by the linear voltage regulator. So: No, you still cannot power the ESP through the Arduino. It's not about the power supply here, but about the electronic parts inbetween.

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


# Question
Title: How to conect multiple output pin from sensors to a single digital pin on a arduino
Hello i have several power management IC that have an active low indicator for a fault, it would be a waste to dedicate a single digital pin for each of them. So i thought of to interface them to a single digital pin. I do not need to know which of them has a fault, i just need to know that there is a fault.

How do i safely do this? and as a follow up question if the fault voltage is 5v and the arduino pins only take 3.3v how do i shift it down with minimal components. can i just add a resistor in series?

# Answer
If the ICs output 5V and your Arduino is 3.3V, you can simply use one voltage divider at the Arduinos pin to divide the voltage down to 3.3V.

But there is still one important thing to connect them safely: You have to check, if the outputs of the ICs are driven actively high, when no fault occured, or if they simply use a pullup resistor internally.

A pin, that is actively driven high, does not have an overcurrent protection. So, if one IC would pull it's pin to low and the others are still high, a high current would flow between them, potentially destroying them. In that case you need current limiting resistors in series with the ICs (directly at the ICs, so that the resistors are between them).

On the other side, if the ICs output a high level through a pullup resistor, you are safe to connect them directly, as there can only flow a very little current through the pullup resistors. Often such a situation is called Open-Drain (passive high level through pullup resistors, active low level by driving the pin to low through a MOSFET, like used in a digital output pin). In that case you don't need the current limiting resistors.

---

EDIT: The datasheet of the ICs, that you linked to states that the fault output is an

> Active-low open-drain output

Also the example circuit shows an external pullup resistor. That means, that the fault pin is internally connected to a MOSFET, which will connect the pin to ground in case of a fault. Otherwise the pin is floating. The external pullup resistor will pull the pin state to a high level, when the MOSFET is not activated. This is good for you, since you can now simply use 1 resistor (one resistor is enough for all ICs), to pull the level up to 3.3V. Then you directly have the correct level for your Arduino and you don't need a voltage divider.
> 1 votes

---
Tags: arduino-zero
---


title: Arduino Nano IoT Power Consumption

text:
# Question
Title: Arduino Nano IoT Power Consumption
I am trying to reduce the power of my Arduino Nano IoT. I would like to run it using a battery over a longer time period. I thought this would be possible when putting it to sleep most of the time. However, at the moment I can only reduce the power consumption to 10mA by

Is there anything else I can do to further reduce power consumption? If not, is there another, more suitable device I can use instead for this project? It has to support wifi and use very low power during sleep.

# Answer
Two of those 10mA come from the ATECC608 crypto chip which idles at 2mA. That leaves 8mA for you to track down.

The WiFi-NINA module has multiple "sleep" modes that range from 30mA down to 4.5µA. Since you can't be in the 30mA "modem sleep" mode (it's too high for your measurements) I suspect it enables "light sleep" at 800µA.

The switching regulator uses 200µA. So those two together probably account for 1mA in total, leaving you 7mA more to find.

The accelerometer can be up to 1.25mA. I'll assume that since you don't mention it, you haven't set that to "power down" mode. 5.75mA left.

The main MCU is actually quite hungry for power, even when sleeping. Looking at the datasheet it can be between 1.3mA and 2.4mA for the different "idle" modes. Only "standby" mode (where clocks are switched off, etc) drops it below 1mA. With it running a simple program you are looking at 4-6mA.

So it could be that the MCU isn't actually sleeping properly, or that other modules that you think are in low power aren't.

I would suggest manually disabling chips completely (pull their respective RESET pins if available LOW if available) to see how that affects the current.
> 4 votes

---
Tags: arduino-nano, power, iot
---


title: Arduino transmitter and receiver

text:
# Question
Title: Arduino transmitter and receiver
hi I am using Arduino transmitter and receiver it works properly with sending and receiving username and password but I would include to check the username if its true open the led , I added this in the code but it seems that the code ignoring it ( the last part) as well as I want it to take the password and username at the same time

this is the recover code

```
#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray

 RH_ASK rf_driver; // create ASK object
int ledon = 13;
String userid;
String password;
 //RH_ASK ID1; // create ASK object
//RH_ASK pass1; // create ASK object

void setup() {

  rf_driver.init(); //initialize ASK object

  Serial.begin(9600); //setup serial monitor to 9600

  //if(!rf_driver.init())
       //Serial.print("init failed");
}

void loop() {

  // set buffer to size of expected message
  uint8_t buf[9];
  uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  if (rf_driver.recv(buf,&buflen))
  {
    int i;
    // message received with valid checksum
    Serial.print("id: ");
    Serial.println((char*)buf);
      userid =(char*)buf;
        Serial.println(userid);

  }

delay(5000);

   uint8_t buf2[8];
  uint8_t buflen2 = sizeof(buf2);

   if (rf_driver.recv(buf,&buflen))

  {

    int i;
    // message received with valid checksum
    Serial.print("password: ");
    Serial.println((char*)buf);
      password = (char*)buf;
      Serial.println(password);

  }
  delay(5000);

while ( userid =="A00034732" && password == "123456789"){
digitalWrite(ledon, HIGH);
delay(2000);
digitalWrite(ledon, LOW);

}
}

```

transmitter code ----

```
//Include RadioHead Amplitidue shift keying library
#include <RH_ASK.h>
// Include dependatnt ISP library
#include <SPI.h>

//create Ampitude shift keying object
RH_ASK rf_driver;

void setup() {
 // intialize ASK objct
rf_driver.init();

Serial.begin(9600);

  //if(!rf_driver.init())
      //Serial.print("init failed");

}

void loop()
{

  const char *pass= "123456789";
rf_driver.send((uint8_t *)pass, strlen(pass));
rf_driver.waitPacketSent();
delay(5000);

const char *ID= "A00034732";

rf_driver.send((uint8_t *)ID, strlen(ID));
rf_driver.waitPacketSent();
delay(5000);

//const char *pass= "12345678";
//rf_driver.send((uint8_t *)pass, strlen(pass));
//rf_driver.waitPacketSent();
//delay(5000);

}

```

# Answer
> 1 votes
You're not comparing strings - you're comparing addresses of strings. Use `strcmp()`.

```
while (
    (strcmp(userid, "A00034732") == 0) &&
    (strcmp(password, "123456789") == 0)
) {

```

---
Tags: arduino-uno
---


# Question
Title: Protecting variables and functions within a library that has no class
If you want to have functions within a library that only the library itself should be able to use or variables that shouldn't be accessed from outside, you usually make them private by writing this in the header file:

```
class Lib{
  public:
    // All these can be accessed from outside
    void function1();
    void function2();
    int someNumber;
  private:
    // These two can't be accessed from outside
    void secretFunction();
    int secretNumber;
};

```

My question is this:

I want to write this library without using classes. How do I protect things from being accessed from anywhere in this case?

# Answer
> 1 votes
If your library is implemented in a single .cpp file, you can define these variables and functions within that file, and give them the `static` qualifier:

```
static int my_private_variable = 42;

static void my_private_function()
{
    ...
}

```

Obviously, there should be no mention of them in the .h file.

Note also that we are talking about global variables. Local variables are already hidden within the defining function.

---
Tags: library, variables, class, functions
---


title: 7 segment display with common anode

text:
# Question
Title: 7 segment display with common anode
I am brand new to electronics. I am trying to use a seven segment display breakout module with my arduino uno. My problem is that the display has a common positive instead of negative common. How do I make this work? As far as I am aware, all the arduino pins output positive with the exception of the ground, which is the negative common.

# Answer
> 2 votes
This answer assumes Arduino Uno. For other types, refer to the documentation.

Ardino pins are not positive per se: you can change the voltage with `digitalWrite()` to either 0V (`LOW`, equal to the GND pin) or 5V (`HIGH`, equal to VCC).

The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).

There is a description for the limits of sourcing and sinking:

> Pin SOURCE Current Limitations:
>
> 20 mA at VCC = 5 V
>
> Pin SINK Current Limitations:
>
> 20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.

You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.

For example, this one works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.

---
Tags: display
---


# Question
Title: Determine what size power supply I need to run stepper motors
I have recently purchased two 7.4V, 1A, Planetary Gear Unipolar Stepper Motors as well as two Cytron 3A 4-16V Dual Channel DC Motor Drivers. I was told that I would need these to run the motors off an Arduino board. The question I forgot to ask was: what size power supply I would need for something like this?

I am just looking to learn how to code these arduino boards. I was hoping to get something that I could plug into a wall to save me from buying multiple batteries.

# Answer
You can't run these off the Arduino board for several reasons:

1. the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
2. the Arduino board can provide about 20mA per pin, never 1A or higher
3. even if the board would only need to pass the voltage on, the total current were \>2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

1. one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
2. two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

1. one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

1. Arduino Uno board without any peripherals: ~45 mA
2. two Stepper motors: 1000 mA each
3. two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The datasheet is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.

A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.
> 0 votes

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


# Question
Title: automated parking system (sir sensor+ stepper motor)
my project about automated system I am using stepper motor to open and close the gate

I want my code be like when the gate opened it stays 5 seconds

then check the sensor, if there is a motion the gate should not close and stay open, when there is no motion the gate should close

if the gate is closing and there is a motion, motion should interrupt closing the gate and reopening the gate

I am using Arduino uno

the code is :

```
#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }

```

# Answer
> 0 votes
When you use `delay()`, your code stops and dont check anything at all until the delay is over, if you want to check for sensors during a timer, you have to use `millis()`

There is a lot of documentation and tutorials you can find to replace delay with millis when you know what you are searching for

---
Tags: arduino-uno
---


# Question
Title: Arduino ds3231to TM1638 problems,alarm clock project
Good morning, I am coding an alarm clock on arduino by using a DS3231 and a TM1638. The code works and the time updates in the serial monitor,although the time doesn't update on the tm1638. I'll attach the code here:

```
#include <DS3231.h>
#include <TM1638.h>
#include <Streaming.h>
#include <SPI.h>
#include <Wire.h>
#include <InvertedTM1638.h>
#include <TM1638.h>
#include <TM1638QYF.h>
#include <TM1640.h>
#include <TM16XX.h>
#include <TM16XXFonts.h>
byte buttons;
#define TM1638_STB D5
#define TM1638_CLK D6
#define TM1638_DIO D7

TM1638 module(TM1638_DIO, TM1638_CLK, TM1638_STB);
// DS3231 uses I2C - device ID 0x68
// on Wemos mini pins SDA -> D1 and SCL -> D2
DS3231 rtc;
int hours;
int minutes;
int seconds;
bool h12;
bool PM;
int data;
RifTime t;
char buffer[24];

void setup()
{
  // set up the 7-segment display
  module.clearDisplay();
  module.setupDisplay(true, 2);
  Wire.begin();
  Serial.begin(115200);

  Serial.println(F("\nDS3231 Hi Precision Real Time Clock"));

  // Fill these variables with the date and time.
  int seconds, minutes, hours, dayofweek, dayofmonth, month, year;

  // Example for april 15, 2013, 10:08, monday is 2nd day of Week.
  // Set your own time and date in these variables.
  // dayofweek = 4; // Day of week, any day can be first, counts 1...7
  hours = 14;
  minutes = 30;
  seconds = 0;
  year = 2019;
  month = 8; // month 1...12
  dayofmonth = 28; // Day of month, 1...31

  data=( hours * 10000 + minutes * 100 + seconds * 1 );

  rtc.setClock(year,month,dayofmonth,hours,minutes,seconds);
}

void loop()
{
  rtc.getTime(t);
  Serial << rtc.toString(buffer) << endl;

  delay(1000); // do nothing

  module.setDisplayToDecNumber(data,4,false);

  if(seconds==60)
  {
    seconds=00;
    minutes++;
  }
  if(minutes==60)
  {
    minutes=0;
    hours++;
  }

  if(hours==24)
  {
    data=00000000;
  }

  if((data)==143000)
  {
    module.setLEDs(0x0001);
  }
  else
  {
    module.setLEDs(0x0000);
  }

}

```

# Answer
> 2 votes
You set the variable `data` only in the setup function.

You also do not print out `data` to `Serial` but the output of `rtc.toString(buffer)`.

If data is not updated in the `loop` method, the display constantly shows the time you initially set in the setup method.

---
Tags: power, led
---


# Question
Title: Can I read from a memory card with three pins?
I have a project where I have three pins to use and I just realized it would be better to use a memory card than replacing the code each time.

I'm building a Arduino with a push button. Press the button and it sends keystrokes to the connected computer with login details.
The login details need to change every three months so having that on a memory card will be easier.

So since I use a digispark Attiny 85 with a total of 6 pins (where two is used to send the keystrokes).
I have one to the push button, and three pins left.

Is there any card reader that can work with three pins? I only need to read if that makes a difference.
The ones I find use four pins (+ vcc and gnd).

Pretty much any memory card type is ok.

# Answer
> 2 votes
Not with an ATTiny85, and not with so few pins, no.

However, all is not lost.

The ATTint85 has 512 bytes of EEPROM inside it where you can store your login details. All you need is some way of telling setting that data in your sketch from the PC - and the simplest way is probably through a USB serial connection.

If you don't have a serial connection available (I think Digispark has a custom interface they use) then you can use whatever interface you have available to do the job.

# Answer
> 1 votes
SD cards work with SPI. This needs only one pin per device (SlaveSelect) but 3 pins for the other common signals ( MISO / MOSI / SCK )

Card reader modules simply do some voltage level shifting (if at all).

But, you need a lot of RAM to work with SD cards, as data transfer always happens in 512 byte "sectors". With a file system, you need at least two such blocks in parallel. An attiny85 is simply too small.

---
Tags: sd
---


# Question
Title: Using Arduino Wifi Shield to Receive Signal
I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)

# Answer
> 1 votes
Look for the Web Server example in the arduino IDE. That will give you a starting point to allow you to control the arduino via a web page. This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/

---
Tags: arduino-uno
---


title: New OLED seems dead, how can I be sure?

text:
# Question
Title: New OLED seems dead, how can I be sure?
I bought this 2.8" OLED from Aliexpress a few weeks ago: https://www.aliexpress.com/item/32988174566.html?spm=a2g0s.9042311.0.0.72304c4dAWcHG8

And after a ridiculous amount of searching for a datasheet, I came across this one that seems to match the board I bought: https://www.buydisplay.com/download/manual/ER-OLEDM028-1\_Series\_Datasheet.pdf

Wiring up pins 1 and 2 to ground and 3.3V on a breadboard, I'd expect something to happen with the display, but I get nothing. The display is in 8080 mode, so I wire everything up to a standard UNO board and power everything on. Still nothing. Try changing the power to 5V, no joy.

During my testing, I noticed the back of the display is getting hot. Not sure if that's a good thing or not yet.

So what's the best way to 1) determine if the datasheet I found is correct? 2) check if the OLED is just broken? I don't have a ton of experience with these displays yet, so I'm not sure if just powering the thing on should net some visual response.

# Answer
The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.

The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.

To find if an OLED is working you have to actively wire it up. With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that. An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.

To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen. My usual test program when working with a new screen is to simply print `millis()` in the top left corner.
> 0 votes

---
Tags: display, wires
---


# Question
Title: Will an Arduino Uno be able to read 3x incremental encoders?
Encoders are quadrature 600ppr encoders with X2 counting. Therefore 1200 counts per revolution for each encoder. Is there an edge rate limit? I currently have one encoder hooked up using code with interrupts.

# Answer
> 1 votes
Here is an example of some code I used to read two encoders using pin change interrupts. This is possible to do with one ISR since they all share a common port. The key is it has to be short. As long as you can keep all 6 pins from your encoder on the same port, this should be easy to extend to 3 encoders. It might even work for four on one port. Or you can make a use a second port and get 3 or 4 more depending on which chip you have.

```
volatile uint8_t lastPortRead = 0;

volatile int32_t leftCounter = 0;
volatile int32_t rightCounter = 0;

ISR(PCINT2_vect){

    uint8_t portRead = PINC;

    uint8_t whoFired = portRead ^ lastPortRead;
    uint8_t pinsDiff = portRead ^ (portRead << 1); // Will have bits 5 or 7 set if pins on right motor or left motor are diff.  Cleared if same.

    if (whoFired & LEFT_INT_MASK) {
        if (pinsDiff & LEFT_INT_MASK) {
            leftCounter++;
        } else {
            leftCounter--;
        }
    }
    if (whoFired & RIGHT_INT_MASK) {
        if (pinsDiff & RIGHT_INT_MASK) {
            rightCounter++;
        } else {
            rightCounter--;
        }
    }

    lastPortRead = portRead;
}

```

# Answer
> 0 votes
The answer to the title's question is likely yes. But it would appear the real question is how fast can a given Arduino read a GPIO pin.

Consider there are multiple Arduino platforms. Each possibly using a different type of processors. Likely those processors are running at different speeds. To give a specific answer we need to assume a specific platform, processor and speed. The current (3rd generation) Arduino Uno runs at 16MHz. And the Arduino Due runs at 84Mhz. Since most people use an Arduino Uno let us use it for an example.

In this arduino.cc forum thread it is commented that an Arduino Uno running at 16MHz can execute the "Digital Pin Read" function call in about 4.78us. Rounding that up to 5us that would be 1/5E-6 or 200000 samples per second. Likely this can be improved upon if code were written to directly control the processors register for the desired outcome. This is usually considered a moderately difficult embedded programming task. And well outside normal Arduino knowledge. In addition, such code would likely no longer be portable between different Arduino platforms.

---
Tags: arduino-uno, programming, sensors, arduino-due, rotary-encoder
---


# Question
Title: How to connect MPU6050 to arduino using only digital pins
I am relatively new to Arduino and microchips, but I am good at electronics. I want to connect MPU6050 accelerometer+gyroscope module to Arduino. I searched on the internet and everywhere it is said to connect the SCL and SDA pins to two analog pins of the Arduino. As far as I know, the MPU6050 is a digital sensor, so why 2 analog pins are required for the sensor?

Also, is there any way to connect the sensor with only digital pins? because I need the analog pins for some other purpose.

# Answer
> 2 votes
The MPU6050 communicates over I2C. I2C uses clock line SCL and data line SDA. I2C pins on Uno are pins A4 and A5. This is because the ATmega328p MCU used on Uno has the I2C peripheral on the same pins. It has nothing to do with the DAC function of the pins.

~~Alternatively MPU6050 can communicate over SPI. This are pins 11, 12, 13 on Uno and one more pin for CS. Pin 10 must be output while ATmega328p is SPI master so it is recommended to use it as CS for the SPI slave device.~~  EDIT Sorry, only MPU6000 has SPI.

---
Tags: arduino-uno, mpu6050
---


# Question
Title: Reset Arduino by connecting vcc and gnd?
A follow up question on my previous question, if a memory card reader can be used with three pins (digispark Attiny 85):

Can I read from a memory card with three pins?

Now I came up with another idea.
Since the USB connector or the VCC pin can power an Arduino my guess is that they are in parallel and the actual Arduino is connected to both.
Kind of like this very bad schematic made on my phone: (sorry for that)  Where the blue stuff is the Arduino chip.

If that is true then adding the push button between VCC and GND with a resistor between should remove the power of the Arduino?
In that case I can have my code in setup() and use the pus button to reset the Arduino, and still have four pins to the memory card reader.

Or is this wrong? What kind of resistor value do I need to make sure I don't short the USB connector but still have less resistance than the Arduino chip?

# Answer
That is wrong. That is very, very wrong. That is one of the worst things you can do to a USB connection short of plugging it into the mains.

Do not even consider doing this. Short circuits are never a good idea.
> 1 votes

---
Tags: digispark
---


title: Arduino uno toggle switch help

text:
# Question
Title: Arduino uno toggle switch help
I am building a box that will start a genset. It has two buttons, run and stop. I would like button run to be able to start (and remain constant) until pressed a second time, I have sussed this bit so far, but this is where I get stuck. I would like the stop button to only stop the the engine (as a single function) So my question is how do I integrate the second button (stop) to carry out this one task?

```
int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDRedPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode (LEDYelPin,OUTPUT);
pinMode (LEDGrnPin, OUTPUT);
pinMode (RELAYRedPin, OUTPUT);
pinMode (RELAYYelPin, OUTPUT);
pinMode (RELAYGrnPin, OUTPUT);
pinMode (buttonPinOff, INPUT);
}
void loop() {
buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);
if(buttonOld==0 && buttonNew==1){
  if (LEDRedState==0){
    digitalWrite(LEDRedPin,HIGH);
    LEDRedState=1;
    digitalWrite(RELAYRedPin,LOW);
    RELAYRedState=1;

    digitalWrite(LEDYelPin, HIGH);
    LEDYelState=1;
    digitalWrite(RELAYYelPin, LOW);
    RELAYYelState=1;
    delay (8000);
    digitalWrite(LEDYelPin,LOW);
    digitalWrite(RELAYYelPin,HIGH);

    digitalWrite (LEDGrnPin,HIGH);
    LEDGrnState=1;
    digitalWrite (RELAYGrnPin, LOW);
    RELAYGrnState=1;
    delay(2000);
    digitalWrite  (LEDGrnPin,LOW);
    digitalWrite (RELAYGrnPin,HIGH);
    RELAYGrnState=1;
  }
  else{
    digitalWrite(LEDRedPin, LOW);
    LEDRedState=0;
    digitalWrite(RELAYRedPin, HIGH);
    RELAYRedState=0;
    digitalWrite(LEDYelPin,LOW);
    LEDYelState=0;

  }
}
buttonOld=buttonNew;
delay(dt);

}

```

# Answer
A general hint first: indent your code correctly. It makes it much easier to read and easier to spot logical errors.

Another improvement would be to name the pins with the same names as you name them when explaining the problem to us. I expected to find a `int buttonRunPin` and `int buttonStopPin`.

The first issue I see is:

```
buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);

```

This reads the same button twice. You probably wanted to read two different buttons: the "run" button and the "stop" button.

The next issue I see is:

```
delay(8000);
delay(2000);

```

During these 10 seconds, you can press and let go the button many times. But since there is no `digitalRead()` during that time, the button press will not be recognized.

The same applies to

```
int dt=100;
delay(dt);

```

If you press the button within these 100 ms, it will not be noticed.

Unfortunately, to fix that, you need to learn a completely new concept: interrupts. And even worse, not all pins support interrupts. On the Arduino Uno, it's only pin 2 and pin 3, which means you would need to change your hardware setup (because you use pin 12 and 13). Put both buttons from the pin to ground, so that it closes when pushed.

You would then prepare the interrupt in the `setup()` routine:

```
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
pinMode(buttonPinOff, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);

```

You also define global variables for the state of the buttons:

```
volatile bool running = false;
volatile bool stopped = false;

```

`volatile` is needed here to prevent the compiler from optimizing too much. The compiler does not know about the interrupts and thus can't know when the variable changes.

Next, you need two methods that are being executed whenever an interrupt occurs, i.e. you press a button:

```
void toggleRun() {
    running = !running;
}
void toggleStopped() {
    stopped = !stopped;
}

```

Note: the above `x = !x;` pattern is a short and efficient form of

```
if (x == false) {
    x = true;
}
else if (x == true) {
   x = false;
}

```

Once you have all that, you don't need the two `digitalRead()`s any more.

I'm afraid I haven't understood what your code's supposed to do. You have a lot of state variables that seem to have no use and especially they don't correspond to the motors. E.g. once `RELAYGrnState` is set to 1, it never changes back to 0.

This is what I have in the end:

```
int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;

volatile bool running = false;
void toggleRun() {
    running = !running;
}

volatile bool stopped = false;
void toggleStopped() {
    stopped = !stopped;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LEDRedPin, OUTPUT);
  pinMode (LEDYelPin,OUTPUT);
  pinMode (LEDGrnPin, OUTPUT);
  pinMode (RELAYRedPin, OUTPUT);
  pinMode (RELAYYelPin, OUTPUT);
  pinMode (RELAYGrnPin, OUTPUT);

  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
  pinMode(buttonPinOff, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);
}

void doSomething() {
  digitalWrite(LEDRedPin,HIGH);   // red LED is on
  LEDRedState=1;
  digitalWrite(RELAYRedPin,LOW);  // red motor off? others unclear
  RELAYRedState=1;

  digitalWrite(LEDYelPin, HIGH);  // yellow LED and red LED are on
  LEDYelState=1;
  digitalWrite(RELAYYelPin, LOW);  // yellow motor off?
  RELAYYelState=1;
  delay (8000);
  digitalWrite(LEDYelPin,LOW);     // red LED on
  digitalWrite(RELAYYelPin,HIGH);  // yellow motor on

  digitalWrite (LEDGrnPin,HIGH);  // red and green LED are on
  LEDGrnState=1;
  digitalWrite (RELAYGrnPin, LOW);  // green motor off
  RELAYGrnState=1;
  delay(2000);
  digitalWrite  (LEDGrnPin,LOW);    // red LED on
  digitalWrite (RELAYGrnPin,HIGH);  // green motor on
  RELAYGrnState=1;
}

void doLess() {
  digitalWrite(LEDRedPin, LOW);     // red LED off
  LEDRedState=0;
  digitalWrite(RELAYRedPin, HIGH);  // red motor on
  RELAYRedState=0;
  digitalWrite(LEDYelPin,LOW);      // yellow LED off
  LEDYelState=0;
}

void loop() {
  if(running){
    if (!stopped){
      doSomething();
    }
    else{
      doLess();
    }
  }
  delay(dt);
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Compass heading not varying linearly

text:
# Question
Title: Compass heading not varying linearly
I am using an HMC-5983 magnetometer compass on my arduino uno to find the heading of a car I'm building.But my compass readings aren't varying linearly.For example when I physically turn my compass by 90 degrees the change in the reading doesn't correspond to 90 degrees.I tried mapping the raw output of the compass to the actual heading but when I do this , the headings in between the points I mapped aren't accurate enough thereby causing my car to behave abnormally.I also looked up on google but couldn't find anything helpful though there was some mention about using an algorithm to sort this issue.Please help me fix this problem.

```
    #include <Wire.h> //I2C Arduino Library
#define Magnetometer_mX0 0x03
#define Magnetometer_mX1 0x04
#define Magnetometer_mZ0 0x05
#define Magnetometer_mZ1 0x06
#define Magnetometer_mY0 0x07
#define Magnetometer_mY1 0x08
int mX0, mX1, mX_out;
int mY0, mY1, mY_out;
int mZ0, mZ1, mZ_out;
float heading, headingDegrees, headingFiltered, declination;
float Xm,Ym,Zm;
#define Magnetometer 0x1E //I2C 7bit address of HMC5883
void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();
  delay(100);

  Wire.beginTransmission(Magnetometer);
  Wire.write(0x02); // Select mode register
  Wire.write(0x00); // Continuous measurement mode
  Wire.endTransmission();
}
void loop(){

//---- X-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
    if(Wire.available()<=1)
  {
    mX0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX1 = Wire.read();
  }
  //---- Y-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY1 = Wire.read();
  }

  //---- Z-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ1 = Wire.read();
  }

  //---- X-Axis
  mX1=mX1<<8;
  mX_out =mX0+mX1; // Raw data
  // From the datasheet: 0.92 mG/digit
  Xm = mX_out*0.00092; // Gauss unit
  //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.
  //---- Y-Axis
  mY1=mY1<<8;
  mY_out =mY0+mY1;
  Ym = mY_out*0.00092;
  //---- Z-Axis
  mZ1=mZ1<<8;
  mZ_out =mZ0+mZ1;
  Zm = mZ_out*0.00092;
  // ==============================
  //Calculating Heading
  heading = filtered_angle(Zm, Xm);// arc tangent of z/x

  // Correcting the heading with the declination angle depending on your location
  // You can find your declination angle at: http://www.ngdc.noaa.gov/geomag-web/
  // At my location it's 4.2 degrees => 0.073 rad
  declination = 0.03717551307 ;
  heading += declination;

  // Correcting when signs are reveresed
  if(heading <0) heading += 2*PI;
  // Correcting due to the addition of the declination angle
  if(heading > 2*PI)heading -= 2*PI;
  headingDegrees = heading * 180/PI; // The heading in Degrees unit
  // Smoothing the output angle / Low pass filter
  headingFiltered = headingDegrees;
  //Sending the heading value through the Serial Port to Processing IDE

  if(headingFiltered >= 0 && headingFiltered <= 89){
                c_head=map(headingFiltered,0,90,270,359);
        }
    if(headingFiltered > 89 && headingFiltered <= 204){
                c_head=map(headingFiltered,90,204,0,90);
        }
    if(headingFiltered > 204 && headingFiltered <= 290){
                c_head=map(headingFiltered,205,290,91,180);
        }
      if(headingFiltered > 290){
               c_head=map(headingFiltered,291,359,181,269);
        }

// Serial.print("Degrees - ");
 Serial.println(headingDegrees);
delay(500);
}

float filtered_angle(float p, float q) {
         const float filter_constant = 0.15;
         static float q_f, p_f; // filtered components
         q_f += filter_constant * (q - q_f);
         p_f += filter_constant * (p - p_f);
         return atan2(p, q);
        }

```

# Answer
> 0 votes
If you can't find and eliminate a systemic error, such as nearby ferrous, magnetic, or electromagnetic sources, causing the errors you see, you'll need to do what navigators have done for ages: swing the compass.

Swinging a compass involves taking the vehicle - your robo-car - somewhere away from external error sources (building wiring, iron/steel masses, f/ex) and taking a set of measurements by heading the vehicle in a number of directions known by a means independent of its own compass. Eg., with a boat, you'd choose a known place in the middle of a harbor and plot a line from that known position to each landmark (for a car, you could use a large playing field). That gives you the True bearing (bearing relative to the north pole) from the chosen position to the landmark. Make a list of those landmarks and their true bearings in columns 1 & 2 of sheet of paper, in clockwise order starting a true north.

Convert the True bearings to Magnetic bearings (relative to the direction from where you are now to the earth's magnetic north pole): Navigation charts will show the difference (in degrees) between True bearings and magnetic bearings for the location(s) covered by that chart; the difference is called "variation" (sometimes called declination). If the magnetic variation at your location is westerly (compasses point 15 degrees W of True North, f/ex), add that value to those bearings you just listed. This third column of numbers is the magnetic bearing to each of those landmarks, and the value an error-free compass should read.

Now take your vehicle to that known point (playing field, middle of the harbor, etc.) and point its center line at each of those landmarks and read its compass for each one. Write these numbers in the fourth column - the compass headings to the landmarks, for *this compass* in *this vehicle*.

Columns 3 & 4 are now a compass correction table. When the compass reads a number that is in column 4 (compass bearing), the actual (corrected) magnetic heading is the corresponding number in column 3 (the magnetic headings).

But of course you don't have every possible heading in your compass correction table. So when you need to know your car's direction, you have to interpolate between a pair of bearings you do have:

1. Find a pair of bearings in column 4, the compass headings, that bracket the reading you just took.
2. Find the percentage that reading is of the difference between the bracketing compass bearings.
3. Apply that same percentage to the difference between the adjacent magnetic bearings in column 3 to find the actual magnetic bearing.

I glossed over the process of interpolation pretty quickly as the question was about correcting the compass. Interpolation, or other ways of applying a correction, is a whole 'nuther topic but the Arduino `map()` function will be great help here. Also, the more correction values (landmarks) you use to make your table, and the more evenly they are spread around the compass, the more accurate your corrections will be.

---
Tags: arduino-uno, sensors, i2c, wire-library, magnetometer
---


# Question
Title: I want to send the last 10 minute data via bluetooth
This was for photocell data logging for 30 sec intervals, now I want to write a code which commands from the cellphone and sends back the last 10 minute data.

At first I thought if I make an array of 20 buckets and put it in a loop, then send the loop function to android would make it right. But it just sends me continues data. I only want the last 10 minute data of the program.

```
float sensorvalue[20];

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);

    for (int i = 0; i < 20; i++) {
        pinMode(sensorvalue, OUTPUT);
    }
}

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

    if(Serial.available()) {
        c=Serial.read();
        if (c=='t')
            sendvalues();
    }
}

void sendvalues()
{
    for (int i=0 ; i<20 ; i++) {

        Serial.println(sensorvalue);
        sensorvalue   = analogRead(A0);
        delay(30000); //every 30 seconds read data

        if (i>=20) {
            i=0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
        }
    }
    Serial.println("***********************************");
}

```

# Answer
> 1 votes
What you want for this project is called a ring buffer. Before reading the rest of this answer, I suggest you stop and take the time to carefully read the Wikipedia page I am linking to.

Did you read it? Good! Now, yours is a somewhat special case in that you don't need to continuously keep track of both a read pointer and a write pointer: you only need the write pointer, as the read happens all in one big batch.

Once your ring buffer is full, you will start overwriting the oldest readings, those that are more than 10 minutes old. When the program is instructed to dump the data, it will send out the whole buffer, starting with the cell pointed to by the write pointer (the cell that holds the oldest data point and was about to be overwritten).

There is one special case to take care of. What if the program gets the command to dump the data while it has less than 20 readings stored? You could decide that this is a user error, and it's OK for the program to give garbage. I suggest, however, that the program should be able to detect this situation, and then only send the valid data. For this, it needs to store a boolean variable in order to remember whether the buffer has been filled or not.

Here is an implementation I propose for such a ring buffer, together with the functions for adding an item and for dumping all the data through the serial port:

```
const uint32_t READING_PERIOD = 30000;  // one reading every 30 s
const int MAX_READINGS = 20;           // 20 readings = 10 min

int readings[MAX_READINGS];  // ring buffer
uint8_t reding_index = 0;    // next available slot
bool readings_full = false;  // did we fill the ring buffer?

static void register_reading(int value) {
    readings[reding_index] = value;
    if (++reding_index >= MAX_READINGS) {
        readings_full = true;
        reding_index = 0;
    }
}

static void dump_readings() {
    // If the buffer is full, then the next avaiable slot is the oldest
    // reading in the buffer.
    if (readings_full) {
        for (int i = reding_index; i < MAX_READINGS; i++)
            Serial.println(readings[i]);
    }
    for (int i = 0; i < reding_index; i++)
        Serial.println(readings[i]);
}

```

Now the main program is quite simple. You time the data taken using the technique shown in the Blink without delay tutorial. You don't want to use `delay()` because, when the program is delaying, it cannot respond to your commands. There is one last question remaining: when it dumps the data, should it forget it? In other words, if you ask it twice to dump the data, with less that 10 minutes in between, should it give repeated data the second time, or should it only provide the fresh data? In the code below I assume the later option, and thus reset the buffer, but in the end it is your choice:

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

void loop() {
    // Periodically take a reading.
    static uint32_t last_reading_time;
    if (millis() - last_reading_time >= READING_PERIOD) {
        last_reading_time += READING_PERIOD;
        register_reading(analogRead(A0));
    }

    // Dump the data on command.
    if (Serial.read() == 't') {
        dump_readings();
        reding_index = 0;       // reset the buffer
        readings_full = false;  // ditto
    }
}

```

# Answer
> 0 votes
Your code doesn't make much sense as written.

You need to:

Collect a new value every 30 seconds and save it into an array of values, incrementing a "current value index" variable with each read.

Do you want to trigger the sending of a buffer-full of data when the array is full, or using a command from the remote phone? If you want to trigger the sending from a phone, what would you do if there wasn't a full buffer of data? What would you do if the buffer gets full and there's no command sent from the phone?

Assuming you send a buffer-full of data every time it's available, just wait until the array index reaches the end. When that happens, transmit the entire buffer of data to your phone and reset the array index to start collecting new data.

If you want to trigger sending from your phone you have to handle edge cases like buffer overflow, or trying to send before you have a full buffer of data. I would suggest creating an array larger than you need (say 100 values), making it a ring buffer (google it) and saving new values continuously until the ring buffer is full. If the sketch receives a send command, it could check to see if it has at least 20 values in the buffer, and send those/remove them from the buffer if it does, or send back a "not enough data collected" message if not.

---
Tags: arduino-uno, c++, bluetooth
---


# Question
Title: Some Blocks of Code gets stuck in a loop, I do not know why
The code below Gets stuck at function "Led Off?" & "Check button". I'm using Blockyduino editor. The check button code was intended as a toggle switch for the lights. When I deleted "Led Off?" and "Turn off All LED", the code did not get stuck.

```
int Button_Status;

// Toggle Code for the button.
void Check_Button() {
  Serial.println("Check button Activated");
  if (Button_Status == 1) {
    if (digitalRead(13)) {
      Button_Status = 0;
    }
  }
  if (Button_Status == 0) {
    if (digitalRead(13)) {
      Button_Status = 1;
    }
  }
  LED_OFF_();
}

void Left_Animation() {
  Check_Button();
  digitalWrite(2, HIGH);
  digitalWrite(3, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  Check_Button();
  delay(300);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  Serial.println("Finshed Left cycle");
}

void Right_Animation() {
  Check_Button();
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  Check_Button();
  delay(300);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Serial.println("Finished Right cycle");
}

// Main Loop Core
void Main_Loop() {
  while (Button_Status == 1) {
    Left_Animation();
    Right_Animation();
    Serial.println("Finshed Main Loop 1111");
  }
  while (Button_Status == 0) {
    Check_Button();
    Serial.println("Finished Main Loop 2222");
  }
}

// Checks if button toggle variable is off.
void LED_OFF_() {
  Serial.println("LED off? Activated");
  if (Button_Status == 0) {
    Turn_Off_All_LED();
  }
  Main_Loop();
}

// Turns off all LED
void Turn_Off_All_LED() {
  Serial.println("LED Turn off Activated");
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Main_Loop();
}

void setup()
{
  Serial.begin(9600);
  pinMode(13, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop()
{
  // Start
  Button_Status = 1;
  Main_Loop();
}

```

# Answer
> 1 votes
You have a problem with infinite recursion in this program: `loop()` calls `Main_Loop()`, which calls `Left_Animation()`, which calls `Check_Button()`, which calls `LED_OFF_()`, which calls `Main_Loop()`, which calls `Left_Animation()`, which calls `Check_Button()`, which calls `LED_OFF_()`, which calls `Main_Loop()`, which calls... This will pretty quickly exhaust the memory of your Arduino.

If you only know about graphical programming, this may not make too much sense to you. So I ask you to imagine that, in your definition of `Main_Loop()` (the big structure titled “to Main Loop”) you replace the smallish box labeled “Left Animation” by its own definition (the big structure labeled “to Left Animation”). Within this definition, you replace “Check Button” by its own definition and so on. You will soon reach a point where you need to embed the definition of `Main_Loop()` within itself. It should then look more or less like this:

```
Main Loop
│ repeat while Button Status = 1
│ do Left animation
│ │  │ Check Button
│ │  │ │ Serial Print “Check button Activated”
│ │  │ │ ...
│ │  │ │ LED OFF?
│ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ if Button Status = 0
│ │  │ │ │ do Turn Off All LED
│ │  │ │ │ Main Loop
│ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ Main Loop
│ │  │ │ │ │ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Main Loop
...etc ad infinitum...

```

Note that it is possible to write programs using recursion, but:

1. This is kind of an “advanced topic”, not suitable for someone still programming at a graphic level.
2. You have to take precautions in order to avoid the program to infinitely recurse.
3. On a microcontroller with little memory, you have to make sure the recursion is always very shallow. Which is hard, so people writing embedded code tend to avoid recursion altogether.

---
Tags: arduino-uno, loop
---