title: GPS module Ublox Neo 6M issue

text:
# Question
Title: GPS module Ublox Neo 6M issue
I using the above mentioned GPS module with Arduino UNO. I find that I cannot receive the Latitude and Longitude values in the `$GPRMC` string in the NMEA data, as I used the module inside a concrete building. I got the values when I placed the module just outside the window. But I have noticed that the phones we use can get the location data just fine through their in-built GPS after waiting for just some time. How is this possible? Any way I can achieve this using the Ublox Neo 6M module?

# Answer
> 0 votes
Mobile phones use the mechanism of assisted GPS.

In contrast to your Arduino U-Blox module it uses the cell tower data your phone can provide to determine your location. This is especially helpful to get a quicker first fix and to get a fix even when you have poor satellite signal conditions.

That said, this will not be possible using only your GPS module connected to your Arduino.

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


# Question
Title: Coin recognition using Coin Accepter in Arduino Uno
I'm working on a vending machine project and I'm using CH-926 and an Arduino Uno for that. I've already set the coin accepter for different number of coins and respective output pulses. I'm unable to get the desired output for this. With every coin I insert the output varies even when I put the same coin.

```
int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
}

void loop() {
  if (digitalRead(2) == HIGH) {
    attachInterrupt(0, coin_value, FALLING);

    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
  }

  pulse = 0;
}

```

For each coin there are different specific pulses which helps to recognize the coin.`int pulse=0;`.

So when I insert coin 1 then the output should be 10, for coin 2 the output should be 20 and for coin 3 the output should be 50.

# Answer
> 1 votes
Your code is faulty in a number of respects.

---

1. `pulse` should be declared volatile, i.e.

```
volatile int pulse = 0;

```

That is because it can change in an interrupt service routine.

---

2. You should only do `attachInterrupt` once, in `setup`.

---

3. Your code to display the count will be timing dependent. What if you happen to display the count after one pulse has arrived, but before they all have? Then you set the count back to zero.

---

Better would be something like this, untested however:

```
volatile int pulse = 0;

void coin_value() {
  pulse = pulse + 1;
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.println("Ready to be collected");
  attachInterrupt(0, coin_value, FALLING);
}

void loop() {

  if (pulse > 0)
    {
    delay (1000);   // let the other pulses arrive
    if (pulse == 3) {
      Serial.println("50");
    }
    if (pulse == 2) {
      Serial.println("20");
    }
    if (pulse == 1) {
      Serial.println("10");
    }
    pulse = 0;  // clear for next time
  }

}

```

---

(Edited to add)

Even then your test for 1/2/3 might fail if the coin acceptor sends the pulses twice. Then you might get 2/4/6 pulses. You probably need to display something if there is another count, eg.

```
  if (pulse == 3) {
    Serial.println("50");
  }
  else if (pulse == 2) {
    Serial.println("20");
  }
  else if (pulse == 1) {
    Serial.println("10");
  }
  else {
     Serial.print ("Unexpected number of pulses: ");
     Serial.println (pulse);
  }

```

# Answer
> 1 votes
First of all you said

> So when I insert coin 1 then the output should be 10, for coin 2 the output should be 20 and for coin 3 the output should be 50.

Yes coin 3 would be 50 but it does not means that coin 3 has 3 impulses(he will have 5 impulse), I recommend to you always use this formula:

> Coin\_Value = Pulse\_Count * Denomination.

I don't recommend to you use 3 Impulses from coin acceptor Because you don't have 15 cent and 30 cent coins. In most cases Coin acceptors have:

> 1/4 1/2 1 2 4 5 8 10 impulses

Generally I prefer to save all data in variables

So lets get to variables for code

```
const int coinIntPin = 2;          //interruptPin 0 is digital pin 2
volatile boolean newCoin = false;
volatile int pulseCount;          //counts pulse for
volatile int timeOut = 0;         //counts timeout after last coin inserted
float coinType;
float denomination = 0.50;         // in my case 1 Pulse = 0.50 $
int max_impulse = 4;              // this is the maximum impulses I use
volatile long timeFPulse = 0;     // to determine when First impulse was interrupted
volatile long interval;           // to determine interval from first and last impulse

```

And always use attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); It is recommended by Arduino as below:

```
void setup(){
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(coinIntPin), coinInserted, FALLING);

}

```

And I will give you rest of code:

```
void coinInserted(){
    newCoin = true;
    timeFPulse = millis();
    pulseCount++;
}

void loop()
{

     while (newCoin == true)
    {
            interval = millis() - timeFPulse;  //interval from first and last impulse
            if(pulseCount == max_impulse || (interval > 500 && pulseCount > 0)) //Max_impulse will avoid any extra impulses for any reason.
            {
// This is the reason why I recommended to you use 1 2 4 5 10 20 Impulses instead of 3 7 9 etc...
              coinType = pulseCount * denomination;
              newCoin = false;
              sendData();
              delay(5);

             }

    }
}

void sendData(){
  Serial.print("Do what ever you want. Inserted Money = ");
  Serial.println(coinType);
  coinType = 0;  // remove if you want to save Coins and print sum of inserted coins
  pulseCount = 0;  // remove if you want to save impulses determined by coin acceptor
}

```

And Finally look at ( interval \> 500 ) If you have different max impulses you must change 500 to (impulse length * Max impulses + 100); so if you have max 10 impulses you must enter 1100 and not 500 (in my case);

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


# Question
Title: Where can I find the source codes for the various classes and methods used in Arduino Primo?
I am new to Arduino development. I am trying to connect a BLE device (Arduino Primo) with my iOS app. From the Arduino BLE examples, I understand how to initialize the BLEperipheral class and then call the setValue method to pass value to be transmitted. However I do not want to be dependent on example codes, rather I want read the source code and definitions to know about the available classes and their methods, what argument types passed etc.(not precompiled libraries with .o extension).

For my current issue, I want to know what type of arguments does the `setValue` take in the BLEperipheral class. Can I pass an int value(4 bytes) or it has to be a char only? These questions can be answered by reading the source code of these inbuilt libraries.

Any direction would not only help me with the current project, it would also help to tackle and understand any projects in the future, where I might use inbuilt library calls.

I have searched the internet, however not much information is available for newcomers like me. Below is a similar question link but outdated and does not solve what I am looking for.

How can I get the source files for Arduino libraries?

Thank you for any suggestions.

# Answer
The Arduino Primo is supported by Arduino nRF52 boards package. The boards packages can contain libraries special for boards handled by the package. The BLE library for Arduino Primo is included in the board package.

The location of boards packages on Windows is in hidden folder AppData in user's home directory. On my Windows computer it is

```
C:\Users\andrassy\AppData\Local\Arduino15\packages\arduino\hardware\nrf52\1.0.2\libraries\BLE

```

On Linux the 'Arduino 1.5' folder is `.arduino15` in users home folder.
> 1 votes

---
Tags: arduino-ide, bluetooth
---


# Question
Title: Create a device to detect object and voice alert what kind of object it is
Here is what I want to do (since I'm not a embedded guy)

* create a prototype with an Arduino to detect objects using camera(object classification?)
* that prototype will detect objects and alert that object's name

My questions are....

* Is it possible? :)
* What things should I use to create a prototype?
* What camera should I use?
* Is it related to image processing?
* Connection between object detection and voice alert?

# Answer
The Arduino is not the ideal platform for you since it is more "lightweight" and can't really meet the demand that your application is expecting.

A platform like for example Raspberry Pi that has a full-blown operating system and a lot of tools that fulfils your application needs.
> 1 votes

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


title: Can't flash ESP 32 Wroom

text:
# Question
Title: Can't flash ESP 32 Wroom
I have a new ESP32 Wroom attached to my USB and it shows up in the settings on my mac:

I do have another ESP thing from sparkfun which I can access via `/dev/cu.usbserial-DN02N1D8`. This device I can flash without problems or read its mac address using `esptool.py`.

```
Connecting........_____....._____....._____....._____....._____....._____....._____

```

So I wonder how I can flash the ESP32.

**Update**: Added a picture of my board.

# Answer
I did fix the problem now.

My mac has USB-C and I was using a single USB-C to USB Dongle. And the serial port never showed up on my mac:

```
crw-rw-rw-  1 root  wheel   18,   5 Mar  8 10:53 /dev/cu.Bluetooth-Incoming-Port
crw-rw-rw-  1 root  wheel   18,   7 Mar  8 10:53 /dev/cu.Heinz-WirelessiAP
crw-rw-rw-  1 root  wheel   18,   3 Mar  8 10:53 /dev/cu.MALS
crw-rw-rw-  1 root  wheel   18,   1 Mar  8 11:02 /dev/cu.SOC

```

As soon as I used the Satechi USB Dock the Silicon Labs USB to UART port showed up in the list:

```
[...]
crw-rw-rw-  1 root  wheel   18,  13 Mar  8 11:04 /dev/cu.SLAB_USBtoUART

```

I can now communicate with the ESP32:

```
esptool.py --port /dev/cu.SLAB_USBtoUART read_mac

esptool.py v2.6
Serial port /dev/cu.SLAB_USBtoUART
Connecting........___
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: XXXXXXXXX
Uploading stub...
Running stub...
Stub running...
MAC: XXXXXXX
Hard resetting via RTS pin...

```

Please note that if you'll need the Drivers for the USB to Serial Chip from Silabs.

If you do not see the device showing up you'll need to load the kernel extension:

```
sudo kextload /Library/Extensions/SiLabsUSBDriver.kext/

```

After this you might to confirm the extension in the Privacy section of the mac settings. See this forum post for reference.
> 0 votes

# Answer
**Flash ESP WROOM 32**

kindly refer the link : https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html#
> 0 votes

---
Tags: esp32, flash
---


title: L1 is not declared in this scope error

text:
# Question
Title: L1 is not declared in this scope error
I have a project where I have to control a DC motor. In this code the purpose is that every time you press a button the direction of the motor changes.

I only get the error that L1 (and L2,R1 and R2) are not declared in this scope. the place in the loop. How do I define the variables so that the code works?

```
int Motorforward = 10;   // MotorDirectionPin set to pin10
int Motorbackward = 11;   // MotorDirectionPin set to pin11
const int button1Pin = 2; //button control set to pin 2

int state = L1;
int state = L2;
int state = R1;
int state = R2;

int button1State;  // current reading from the input pin
int previous = LOW; //the previous reading from the input pin

char input;

void setup(){
pinMode(button1Pin, INPUT); //set pin as input
Serial.begin(9600);

pinMode(Motorforward, OUTPUT); // sets the pin as output
pinMode(Motorbackward, OUTPUT);
 }

  void loop(){
button1State = digitalRead(button1Pin);
input = button1State;

switch(state){
  case L1:
    if (state == L1){
    if (button1State == HIGH){
        state == L2;
    }
  }
  break;

case L2:
  if (state == L2){
    if (button1State == LOW){
      state == R1;
    }
  }
  break;

case R1:
  if (state == R1){
    if (button1State == HIGH){
      state == R2;
    }
   }
  break;

case R2:
  if (state == R2){
    if (button1State == LOW){
      state == L1;
    }
  }
  break;
}

```

# Answer
> 0 votes
I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.

For this, use an enum:

```
enum EState { L1, L2, R1, R2 };

```

Now create one state variable of that type and give it an initial value.

```
EState state = L1;

```

Some other problems I see at first sight:

```
case L1:
  if (state == L1){
  if (button1State == HIGH){
      state == L2;
  }
}
break;

```

In this statement, when there is `case L1`, it means the code following ( until the break) is only handled when the state (because of `switch(state)` is L1, so you can remove the check `if (state == L1)`. What is left is:

```
case L1:
  if (button1State == HIGH)
  {
    state == L2;
  }
  break;

```

Than you use `state == L2` to set a new state. However, the `==` only compares two values, if you want to assign it, you have to use a single `=`, thus the code should be:

```
case L1:
  if (button1State == HIGH)
  {
    state = L2;
  }
  break;

```

Of course you have to do this also for the other case statements.

Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.

# Answer
> 0 votes
You have not defined L1, L2, R1, or R2. You're also redefining the int variable 'state' four times.

Try replacing:

```
int state = L1;
int state = L2;
int state = R1;
int state = R2;

```

With something like:

```
#define L1  1
#define L2  2
#define R1  3
#define R2  4
int state = R2;

```

---
Tags: arduino-uno
---


title: NeoICSerial and SPI on the Uno - pin 10

text:
# Question
Title: NeoICSerial and SPI on the Uno - pin 10
The NeoICSerial documentation contains a table that states for the Uno:

* Transmit: 9
* Receive: 8
* PWM Unusable: 10

Pin 8 and 9 are used for the serial connection. Pin 10 is part of the pins for the SPI on the Uno. Does this mean SPI connections can't be used together with NeoICSerial or is this specific for using pin 10 for PWM?

# Answer
The "Unusable 10" is explained in AltSoftSerial library

> The "Unusable PWM" pins can be used normally, with digitalRead() or digitalWrite(), but their PWM function controlled by analogWrite() will not work properly, because AltSoftSerial uses the timer which controls that pin's PWM feature.

---

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).

If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.
> 1 votes

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


title: please explain the sketch attached

text:
# Question
Title: please explain the sketch attached
Sorry about a newbie. 1. what mening of:

```
    if(Xstr[XstrLength-1] != '|'){
      Xstr[XstrLength] = '|';
      Xstr[XstrLength+1] = '\0';

```
2. the setup: `char Xstr[60];` what means? and then: `itoa(Yint,Ystr,10);`

Code:

```
#include <VirtualWire.h>

//gamepad setup
int up_button = 2;
int down_button = 4;
int left_button = 5;
int right_button = 3;
int start_button = 6;
int select_button = 7;
int joystick_button = 8;
int joystick_axis_x = A0;
int joystick_axis_y = A1;
int buttons[] = {up_button, down_button, left_button, right_button, start_button, select_button, joystick_button};

void setup()
{

    //gamepad setup
    for (int i; i < 7; i++)
    {
        pinMode(buttons[i], INPUT);
        digitalWrite(buttons[i], HIGH);
    }

    Serial.begin( 9600 );

    //transmitter setup
    vw_set_tx_pin(12);          // Sets pin D12 as the TX pin
    vw_set_ptt_inverted(true);  // Required for DR3100
    vw_setup(2000);             // Bits per sec
}

int counter = 0;

int Xint;
int Yint;

char Xstr[60];
char Ystr[60];

void loop()
{
    // Read and store Sensor  data
    Xint = analogRead(joystick_axis_x);
    Yint = analogRead(joystick_axis_y);

    // Convert integer data to Char array directly
    itoa(Yint,Ystr,10);
    itoa(Xint,Xstr,10);

    int XstrLength = String(Xstr).length();

    if(Xstr[XstrLength-1] != '|'){
        Xstr[XstrLength] = '|';
        Xstr[XstrLength+1] = '\0';
    }

    char combinedArray[String(Xstr).length() + String(Ystr).length() + 1];
    sprintf(combinedArray, "%s%s", Xstr, Ystr);

    vw_send((uint8_t *)combinedArray, strlen(combinedArray));
    vw_wait_tx(); // Wait until the whole message is gone

    Serial.println(combinedArray);

}

```

# Answer
1. This adds some end of string characters.

if(Xstr\[XstrLength-1\] != '|'){ Xstr\[XstrLength\] = '|'; Xstr\[XstrLength+1\] = '\0'

First it checks if Xstr last character is a '|', if not: Place a | directly after the last character And append a '\0', which is a symbol to 'end' a string

A string in C/C++ is normally build up like this, e.g. "Hello" contains of the bytes:

```
'H', 'e', 'l', 'l', 'o', \0

```

Where each of the above are ASCII characters/values and the last \0 a 0 byte.

2. `char Xstr[60];` defines a character array (string) that can contain 60 characters. Note however, that the ending \0 also needs to be in this string, so you can actually only put 59 characters inside.
3. `itoa(Yint,Ystr,10);` converts Yint which is an integer value to a string (where each digit has each own byte), and 10 is the length.
> 2 votes

---
Tags: sketch
---


# Question
Title: Arduino software won't open in Mac OSX 10.10.1
I am having trouble opening the Arduino software on my mac, since I have updated Java to version 8 the Arduino software won't open. It does not give an error just closes instantly.

I have tried getting the newest version of the Arduino.cc site but no change.

Can anyone tell me how to open Arduino using an older version of Java?

# Answer
> 2 votes
Download and install the Apple version of Java (6): http://support.apple.com/kb/DL1572

If you need Java 8 SDK for some reason, the two can coexist because the Arduino IDE will explicitly ask for the (Apple Version) of Java 1.6 using 'JavaApplicationStub':

```
$ ./JavaApplicationStub
[JavaAppLauncher] Requested [1.5*], launching in [1.6] instead.
Experimental:  JNI_OnLoad called.
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7

```

Note however that if you have both Apple Java and Oracle installed, running 'java' or 'javac' form the command line will run the Oracle version.

```
$ java -version
java version "1.8.0_25"

```

If you need to switch the 'command line' version, change the symlinks in:

```
/System/Library/Frameworks/JavaVM.framework/Versions/

```

'JavaApplicationStub' will use the Apple version located in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

As such, 'normal' java programs will generally use the Oracle version, while applications running in your browser or using JavaApplicationStub explicitly (like Arduino) will use the 'Apple' version.

# Answer
> 0 votes
I just clicked on the apple icon =\> about this Mac =\> software update =\> Mac Sierra update.

now to get the USB port to work

numbatmark

---
Tags: arduino-ide, mac-os
---


title: Servo won't stop rotating

text:
# Question
Title: Servo won't stop rotating
I have an Arduino Uno R3 board and after some time not in use it seems to have corrupted. My code is below, basically I want to rotate a servo 90 degrees every 12 hours but as soon as I plug it in the servo starts rotating non-stop. Have tried multiple delay steps and shortening and lengthening the write but the same effect happens.

```
#include <Servo.h>

Servo myservo;

void setup {
  myservo.attach(10);
}

void loop() {
  myservo.write(90);
  delay(3600000);
}

```

# Answer
I suppose you are using a continuous servo otherwise you wouldn't be able to make it turn 90° more than twice (a normal servo has a varying angle of only 180°).

Now if you are using a continuous servo, you have to be aware that the value you pass to `myservo.write()` does not represent an angle anymore!

With a continuous servo, the value passed to `myservo.write()` now means a speed of rotation where, but the range of acceptable values is the same as for a normal servo, i.e. `[0; 180]`:

* `0` means max speed clockwise
* `90` means no motion
* `180` means max speed counter-clockwise

Now if you want to turn the servo exactly 90°, then you must know the max speed of the servo, and from that, compute the time during which you must let it turn:

```
// Start turning clockwise
myservo.write(0);
// Go on turning for the right duration
delay(TURN_TIME);
// Stop turning
myservo.write(90);

```

The problem here is to compute `TURN_TIME`. For this, you must check the datasheet of your servo.

On my own servo, a Feetech Micro 1.3kg Continuous Rotation Servo FS90R, the max speed is:

* 0.12s/60° when powered with 4.8V
* 0.10s/60° when powered with 6V

However, with the Arduino UNO, the supplied voltage should be **exactly 5V, neither 4.8V, nor 6V**.

If we take a linear approximation, then we can apply the following formula to find out the speed `T` (in **s/60°**):

```
T = (0.12 - 0.10) * (V - 4.8) / (4.8 - 6.0) + 0.12

```

Hence, for 5V, we can take it for granted that the max speed should be:

```
T = (0.12 - 0.10) * (5.0 - 4.8) / (4.8 - 6.0) + 0.12 = 0.116667

```

Since we need 90°, this means we must run the servo at its max speed during:

```
T' = T * 1.5 = 0.175s

```

Hence we now have the following program:

```
#include <Servo.h>

#define TURN_TIME 175

Servo myservo;

void setup {
    myservo.attach(10);
    // Initially the servo must be stopped
    myservo.write(90);
}

void loop() {
    // Start turning clockwise
    myservo.write(0);
    // Go on turning for the right duration
    delay(TURN_TIME);
    // Stop turning
    myservo.write(90);

    // Wait for 12h
    delay(12 * 3600 * 1000);
}

```

Of course, you will need some experiments to find the **exact** right values; you may also find out that the servo may be sensitive to noise and even when it should not move (value = `90`), it does move (not fast, but still it moves).
> 8 votes

# Answer
That was useful. I was getting the same rotation thing when I had servos at 90. What I did to stop that was use the detach command. Using the Particle Photon with a continuous servo attached.

```
bool state = LOW;

Servo servo1;
Servo servo2;// create servo object to control a servo
                // a maximum of eight servo objects can be created

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

void setup()
{
  servo1.attach(D0);
  servo2.attach(D1);
  Spark.function("test", testFunction);
  servo1.attach(10);
  servo1.write(90);
  servo2.attach(10);
  servo2.write(90);
}

void loop()
{
    servo2.detach(), servo1.detach();
    delay (25);
    servo2.attach(D0), servo1.attach(D1);
    delay (25);
    servo1.write(0), servo2.write(180);
    delay (1000);
    servo2.write(180), servo1.write(0);
    delay (1000);
    //I did this to make the servo not move when it is at 90.
    servo2.detach(), servo1.detach();
    delay (25);
    servo1.write(90), servo2.write(90);
    delay (1000);
    //end
    //You must attach the servos again to make them move again.
    servo2.attach(D0), servo1.attach(D1);
    delay (25);
    //end
    servo1.write(180), servo2.write(0);
    delay (1000);
    servo2.write(180), servo1.write(100);
    delay (1000);

}

int testFunction(String args) {

    return 200; // This is checked in the web app controller for validation
}

```
> 2 votes

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


# Question
Title: Blinking 2 LED having input from serial monitor
Sir while entering the values on the serial monitor, I ask the user to enter the value for red led voltage(0-255) then again ask for yellow at the red voltage asking it produces the user to put the value, after that it asks for yellow led input but the time to enter the value for yellow led input is very less and so it does not get entered and the futher program starts. So only red led works where as Yellow does not.

```
int REDledpin=9;        //RED led on pin 9 of the uno board.
int YELledpin=7;        //YELLOW led on pin 8 of the uno board.
int REDonleddelay=500;  //The red led will be on for 500 ms.
int REDoffleddelay=500; //The red led will be off for 500 ms.
int YELonleddelay=600;  //The YELLOW led will be on for 600 ms.
int YELoffleddelay=600; //The YELLOW led will be off for 600 ms.
int countredled=5;        //The RED LED count variable
int countyellowled=5;     //The YELLOW LED count variable
String red="Red led is blinking";
String Yellow="Yellow led is blinking";
int redintensity;
int yellowintensity;

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

void loop() {
Serial.println(red);
for(int j=1;j<=countredled;j=j+1)
  {
    Serial.print("The red LED blink star: ");
    Serial.println(j);
    analogWrite(REDledpin,redintensity);
    delay(REDonleddelay);
    analogWrite(REDledpin,0);
    delay(REDonleddelay);
  }

Serial.println(" ");
Serial.println(Yellow);
  for(int j=1;j<=countyellowled;j=j+1)
  {
   Serial.print("The yellow LED blink stars");
   Serial.println(j);
   digitalWrite(YELledpin,yellowintensity);
   delay(YELonleddelay);
   digitalWrite(YELledpin,0);
   delay(YELoffleddelay);
  }
 Serial.println(" ");
}

```

# Answer
@Juraj was on the right track however the end-of-line characters for example may not be buffered and the problem could continue.

The correct approach is the wait for the end-of-line character specifically. Let's take the easy way out and use Serial.readStringUntil

```
#define EOL_CHAR '\n'

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.readStringUntil(EOL_CHAR); // clear serial buffer to end of line character

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

```

This all depends on what you're Serial Monitor is sending as a new line; it could be CR (\r), LF (\n) or CRLF (\r\n), so change the EOL\_CHAR value accordingly depending on your serial monitor setup.
> 1 votes

---
Tags: serial
---


# Question
Title: What data type are the analog pin labels (A0, A1, etc)?
Arduino Mega

I would like to have an array containing analog pin labels something like...

```
int analog_pins[] = {A0, A1, A2, A3};
int num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

```

Is this possible? It has compiled without any warnings or errors but I'm dont have my board with me (yes beginners mistake) so cant really check if it works.

# Answer
As you can see in Arduino.h, the analogRead() has `uint8_t` as parameter. You can define them as `byte` or `uint8_t` and you don't have to use the sizeof().

The type of A0 is defined in the file pins\_arduino.h:

```
#define PIN_A0 (14)
static const uint8_t A0 = PIN_A0;

```

Nevertheless, what you have with integers is 100% okay as well.

When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at Tinkercad.

---

As @DataFiddler writes below this answer, using a 'const' keyword is preferred:

```
const uint8_t analog_pins[] = {A0, A1, A2, A3};

```
> 2 votes

# Answer
Your calculation will be correct for num\_analog\_pins, however it's convention to use the *type* of the array like so

```
int num_analog_pins = sizeof(analog_pins) / sizeof(int);

```

As @Jot noted, you'd save much space by declaring your array using uint8\_t like so

```
uint8_t analog_pins[] = {A0, A1, A2, A3};
uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(uint8_t);

```
> 2 votes

---
Tags: pins, analogread, data-type
---


title: Data type problem

text:
# Question
Title: Data type problem
I have a program I would like to ask: I use the Bluetooth control LED to light up. In the picture, the serial port window shows r, but the LED does not light up. What went wrong? Ask everyone, thank you very much.

# Answer
it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。
> -1 votes

---
Tags: led
---


title: Attach() resets servo's angle

text:
# Question
Title: Attach() resets servo's angle
I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32. Controlling servo Works as expected. But I don't want next behavior - `attach()` function sets servo to 180°(maybe 0°, not sure). In my project I want next:

* Servo stays at angle before going off/reboot
* Servo goes to 90° after turning on/reboot

I googled about this problem and tried with `write(90);` before `attach()` in `setup()` function. Servo goes to 90° but after like 50ms `attach()` stops `write(90)` function and it goes back to 180°. So this didn't solve my problem. Next I've open `Servo.cpp` and found that `attach()` function contains next code:

```
    bool Servo::attach(uint8 pin,
                   uint16 minPW,
                   uint16 maxPW,
                   int16 minAngle,
                   int16 maxAngle) {
    timer_dev *tdev = PIN_MAP[pin].timer_device;

    if (tdev == NULL) {
        // don't reset any fields or ASSERT(0), to keep driving any
        // previously attach()ed servo.
        return false;
    }

    if (this->attached()) {
        this->detach();
    }

    this->pin = pin;
    this->minPW = minPW;
    this->maxPW = maxPW;
    this->minAngle = minAngle;
    this->maxAngle = maxAngle;

    pinMode(pin, PWM);

    timer_pause(tdev);
    timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
    timer_set_reload(tdev, SERVO_OVERFLOW);
    timer_generate_update(tdev);
    timer_resume(tdev);

    return true;
}

```

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.

# Answer
> 1 votes
You can avoid using the `attach();` method by programming without the servo library.

```
  for(x=0; x<150; x=x+1)
  {
    digitalWrite(Servomotor, HIGH);
    delayMicroseconds(2350); //Change the delay here to change the angle it goes to
    digitalWrite(Servomotor, LOW);
    delayMicroseconds(18550);
  }

```

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".

---
Tags: servo, pwm
---


# Question
Title: Mapping segments and memory allocation on a segment LCD driver
I've just configured a segment LCD and driver, everything works fine, but because I decided to not use vias on the PCB, the connections between the two are mixed.

To be more precise, in order to display the number 12, both memory addresses should be accessed.

So right now it's impossible to display a single digit without mapping all the segments.

In static mode, this is how RAM memory is allocated to SEG0-SEG7 and SEG8-SEG15 respectively:

What I've tried was to create two multidimensional arrays and map possible combinations of the two digits, like this:

```
// 01 to 09
const byte map1[10][2] = {
  {B01110111, B111111 },
  {B01110001, B100111},
  {B01111011, B011111},
  {B01111011, B110111},
  {B01111101, B100111},
  {B01111110, B110111},
  {B01111110, B111111},
  {B01110011, B100111},
  {B01111111, B111111},
  {B01111111, B110111}
};

// 10 to 19
const byte map2[10][2] {
  {B00010111, B111100},
  {B00010001, B100100},
  {B00011011, B011100},
  {B00011011, B110100},
  {B00011101, B100100},
  {B00011110, B110100},
  {B00011110, B111100},
  {B00010011, B100100},
  {B00011111, B111100},
  {B00011111, B110100}
};

```

If there is no way to mix or map them in a dynamic way so any possible combination between 00 and 99 can be achieved, the only solution is to add vias on the PCB and rewire everything as explained in the datasheet.

Any ideas?

Thanks

# Answer
> 0 votes
The trick here is to employ both a local memory buffer, and digit masking.

Step one: create a pair of *masks* that define which bits of the memory are associated with which digit.

Imagine you have your digits wired in this order in memory. For simplicity I am working with 16-bit values, but there is no reason why you can't split them into two 8 bit values each if you find that easier (P is the decimal point. Lower case is the left digit, upper case the right digit):

```
      MSB                         LSB
      a C d g E B p A c D f b e G F P

```

You would then create a pair of corresponding 16-bit values that represent which bits are associated with each digit.

```
      MSB                         LSB
      a C d g E B p A c D f b e G F P
Left  1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
Right 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1

```

The right is just the inverse of the left, so for `right` you can actually use `~left` and save yourself 2 bytes.

So that would end up as:

```
uint16_t leftDigit = 0xB2B8;
uint16_t rightDigit = 0x4D47;

```

Now you create yourself a table of which segments create which numbers. Now the magic here is that you don't want individual digits. Not yet. What you want is a table of 16-bit values that represent the numbers 00, 11, 22, 33, 44, 55, 66, 77, 88, 99 (and optionally two spaces, but that's just 0x0000, so you may not need to store that explicitly).

You may end up with something like:

```
uint16_t digits[] = {
    0b1110110111111010, // 00
    0b0100010010010000, // 11
    0b1011110101011100, // 22
    // ... etc ...
};

```

Now the real magic happens.

You need a memory buffer that mirrors the contents of your driver memory. You don't directly modify the driver memory - you modify your memory buffer, and then send both bytes of it to the display driver at once, updating all the segments together.

```
uint16_t buffer = 0;

```

Now to set a digit you first need to erase whatever is in the bits that correspond to the digit you want. Let's say we want to display the number 12. We'll start with the left digit.

```
// Step one, erase the left digit
buffer &= ~leftDigit;
// Step two, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[1] & leftDigit);

// Step three, erase the right digit
buffer &= ~rightDigit;
// Step four, place into it the bits for 1 with the left digit mask imposed:
buffer |= (digits[2] & leftDigit);

```

That is actually quite a long winded way. But it does allow you to just change one digit without affecting the other. If you want to just replace the entire content of the display (both digits at once) then you don't need as much work:

```
buffer = (digits[1] & leftDigit) | (digits[2] & rightDigit);

```

I'll just dismantle that for you so you can see what it does.

```
            MSB                         LSB
            a C d g E B p A c D f b e G F P
 digits[1]: 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0
 leftDigit: 1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
       AND: 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 // b and c enabled

 digits[2]: 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 0
rightDigit: 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1
       AND: 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 // A B D E and G enabled

OR of ANDS: 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 // b c A B D E G enabled

```

And map those segments on to the standard layout of a 7 segment display:

And you form the number 12.

Then you take the buffer value and write it out to your display memory. You can split the 16 bit value into 8 bit values with bit masking (`& 0xFF`) and bit shifting (`>> 8`).

```
uint8_t b1 = buffer & 0xFF; // Lower byte of memory
uint8_t b2 = (buffer >> 8) & 0xFF; // Upper byte of memory

```

---
Tags: lcd, 7-segment
---


# Question
Title: making power harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are)
i have been intendng to make a power frequency harmonics analyser which will measure the amplitudes of the fundamental and its multiples (like 50hz, 100hz, 150hz,200 hz,...) there are examples for making spectrum analyser with fft library's here is the example for the kosome made fft library

```
   #include <arduinoFFT.h>

   #define SAMPLES 128             //Must be a power of 2
   #define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

   arduinoFFT FFT = arduinoFFT();

   unsigned int sampling_period_us;
   unsigned long microseconds;

   double vReal[SAMPLES];
   double vImag[SAMPLES];

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

        sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
   }

   void loop() {

        /*SAMPLING*/
        for(int i=0; i<SAMPLES; i++)
        {
            microseconds = micros();    //Overflows after around 70 minutes!

            vReal[i] = analogRead(0);
            vImag[i] = 0;

            while(micros() < (microseconds + sampling_period_us)){
            }
        }

        /*FFT*/
        FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
        FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
        FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
        double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

        /*PRINT RESULTS*/
        //Serial.println(peak);     //Print out what frequency is the most dominant.

        for(int i=0; i<(SAMPLES/2); i++)
        {
            /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

            //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
            //Serial.print(" ");
            Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
        }

        //delay(1000);  //Repeat the process every second OR:
        while(1);       //Run code once
   }

```

how can i seperate the amplitudes for particular frequencies like amplitude of 50hz = ?, 150hz = ? and store them in other variables

# Answer
> 1 votes
The general idea of your code looks OK, but consider using a hardware timer rather than the `for` loop for data acquisition. The sampling rate will be much more accurate and uniform because you eliminate (possibly cumulative) errors in timing. See this post for an example.

Do you know how the `FFT.MajorPeak` function works? If it simply finds the frequency of the largest point in the magnitude spectrum, this may not be a good measure of the 50 Hz peak etc. Instead, consider taking the area under the curve around the frequency of interest `f_0`, say `f_0 - 2 Hz` to `f_0 + 2 Hz`. The same code should be usable to measure the spectral power around any of the harmonics.

Also note that the mains electricity frequency is not exactly 50 Hz / 60 Hz. The short-term variation is around plus/minus 1 Hz. The above approach will also help make reliable readings.

---
Tags: arduino-uno, analogread, frequency, signal-processing, mathematics
---


# Question
Title: Can a Lithium Polymer battery charging circuit on Arduino boards also charge Lithium Lion batteries?
I have a project that the form factor of 18650 batteries works well for. The board I'm using is a esp32 based board with built in battery charging: https://www.amazon.com/gp/product/B072HBW53G/ref=ppx\_yo\_dt\_b\_asin\_title\_o00\_s02?ie=UTF8&psc=1

1. I've heard that the flatpack type Lithium Polymer batteries have built in over charge circuitry. Is this generally true?
2. Can I directly charge a 18650 battery from Arduino type boards that have built in battery charging functionality?

EDIT: So from looking at the battery circuit schematic from the Wemos link and the board itself it uses a TP4054 "Standalone Linear **Li-lon** Battery Charger with Thermal Regulation in SOT". And since I can confirm the board works with 3.7V batteries and my 18650 is a 3.7V type I think I'm good.

EDIT: Found info on this board: http://www.raspberrypiwiki.com/index.php/WEMOS\_ESP32\_Board\_with\_OLED

Also by "Arduino type" boards I mean any popular micro controller board that has a battery charging function such as the Adafruit feather boards.

EDIT: To clarify: Reading here Li Poly and Li Ion batteries are essentially the same https://scottiestech.info/2015/06/21/lithium-polymer-vs-lithium-ion-batteries-whats-the-deal/

I believe the board is a Wemos D32 with an attached display though I can't find any specific info on this exact board. https://wiki.wemos.cc/products:d32:d32#technical\_specs

I basically want to know if I can charge a Lithium Ion battery with this type of board. As this is potentially a safety concern I wanted to ask some experts.

# Answer
> 2 votes
There are Lead based, Nickel-based and Lithium-based batteries (there are actually more, but these ones are the most popular). Each need a different charger, but since lithium polymer and lithium ion are in the same group, it **should** work but I don't have the option to test it out for you.

Q1: Not every battery has a built in over- and undercharge function. Some do, some don't. To find out if yours does, if the internet can't help, tear it apart (be extremely careful about it).

Q2: Depends what you mean by " built in battery charging functionality". If that includes the over- and undercharge functionality, then it will work (tested).

Looking at the board (https://wiki.wemos.cc/products:d32:d32#technical\_specs) it seems doable.

The most important thing is to check, if the supported voltage of the li ion battery equals the supported voltage of the li polymer battery that can be charged with the li polymer charger. Since it says 3.7V on the data sheet, don't get a li ion battery with 3.7V+

---
Tags: battery, esp32, charging
---


title: delay() not working inside loop() block

text:
# Question
Title: delay() not working inside loop() block
Edited and attached code here.
This section didn't execute. The `delay(15000);` doesn't execute, I mean the sketch didn't execute this line no matter where to put it.

```
    // include the SPI library:
    #include <SPI.h>

    // set pin 53 as the slave select for the digital pot:
    const int slaveSelectPin = 53; //WAS 10 on Arduino uno.
    const int shutdownPin = 7; // was 7 on uno.
    const int wiper0writeAddr = B00000000;
    const int wiper1writeAddr = B00010000;
    const int tconwriteAddr = B01000000;

    const int tcon_0off_1on = B11110000;
    const int tcon_0on_1off = B00001111;
    const int tcon_0off_1off = B00000000;
    const int tcon_0on_1on = B11111111;

    const int analogInPin_c = A5;  // center Vc=Vss/2 from the PAD, use for set ini V. here no use, Vc directly goes to pad.

    const int analogInPin_x = A1;  // Analog input pin that the potentiometer is attached to
    const int analogInPin_y = A2;  // Analog input pin that the potentiometer is attached to

    const int analogOutPin_x = wiper0writeAddr; // write MCP POT
    const int analogOutPin_y = wiper1writeAddr; // write MCP POT

    int sensorValue_c = 0;        // value read from the PAD, Vc=Vss/2
    int sensorValue_x = 0;        // value read from the PAD, Vc=Vss/2
    int sensorValue_y = 0;        // value read from the PAD, Vc=Vss/2

    //?int outputValue_c = 0;        // value output to the PWM (analog out)
    int outputValue_x = 0;        // mid variable stored the value from 'sensorValue_c' and MAP that for use
    int outputValue_y = 0;        // mid variable stored the value from 'sensorValue_c' and MAP that for use

    int Vcr = 0;        // value read from the PAD, Vc=Vss/2
    int Vc = 0;        // value read from the PAD, Vc=Vss/2
    const int LEDpin1 = 47;
    const int LEDpin2 = 46;
    int count = 0;

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

      // set the slaveSelectPin as an output:
      pinMode (slaveSelectPin, OUTPUT);
      // set the shutdownPin as an output:
      pinMode (shutdownPin, OUTPUT);
      // start with all the pots shutdown
      digitalWrite(shutdownPin, LOW);
      // initialize SPI:
      SPI.begin();
      Serial.println("Setup complete");
      //??
      Serial.println("Starting loop");
      digitalWrite(shutdownPin, HIGH); //Turn off shutdown
    }

    void loop() {
      AnalogInOut(); //
      ArduinoDAC(); //
    }
    void AnalogInOut() {
      // take from some where used for testing joystick control LED,
      //need change to get date fron RC and write to MCP pots
      // read the analog in value:

      Vcr = analogRead(analogInPin_c);
      delay(1000);
      Serial.print("Vcr= ");
      Serial.println(Vcr);
      Vc = map(Vcr, 0, 1023, 165, 225);
      Serial.print("Vc = ");
      Serial.println(Vc);
      delay(10);
      Serial.print("count_ini= ");
      Serial.println(count);

      if (count = 0)  {

        if (Vc > 188)   {

          digitalWrite(LEDpin1, HIGH);
          Serial.print("Vc TOO HIGH: ");
          Serial.println(Vc);
          exit(0);
          delay(100);
        }

       if (Vc < 165) {

          digitalWrite(LEDpin2, HIGH);
          Serial.print("Vc TOO LOW = : ");
          Serial.println(Vc);
          exit(0);
          delay(10);
        }
        else {

          Serial.print("analogInPin_c_T00: ");
          Serial.println(analogInPin_c);

          /// digitalPotWrite(wiper0writeAddr, Vc);
          ///digitalPotWrite(wiper1writeAddr, Vc);

          digitalPotWrite(wiper0writeAddr, 100);
          digitalPotWrite(wiper1writeAddr, 220);

          count = 1;
          Serial.print("count_new= ");
          Serial.println(count);
        }
        delay(15000);
      }

      ////////////////////////////////////////////////////////////////////////////////////////////////////////////

      sensorValue_x = analogRead(analogInPin_x);
      sensorValue_y = analogRead(analogInPin_y);
      // map it to the range of the analog out:
      outputValue_x = map(sensorValue_x, 0, 1023, 70, 248);
      outputValue_y = map(sensorValue_y, 0, 1023, 70, 248);  // change the analog received to the value suite for PAD joystick

      //   print the results to the Serial Monitor:
      Serial.println("sensor_x =_T10 ");
      Serial.println(sensorValue_x);
      Serial.println("sensor_y = ");
      Serial.println(sensorValue_y);
      Serial.println("\t output = ");
      Serial.println(outputValue_x);
      Serial.println(outputValue_y);

      // wait 2 milliseconds before the next loop for the analog-to-digital
      // converter to settle after the last reading:
      delay(2);
    }

    void ArduinoDAC() {
      Serial.println("Starting loop");
      digitalWrite(shutdownPin, HIGH); //Turn off shutdown

      digitalPotWrite(wiper0writeAddr, outputValue_x); // Set wiper 0 to 200

      delay(5);

      digitalPotWrite(wiper1writeAddr, outputValue_y); // Set wiper 1 to 200

      delay(5);
    }

    // This function takes care of sending SPI data to the pot.
    void digitalPotWrite(int address, int value) {
      /// Serial.print("wiper0 position_t30: ");////
      /// Serial.println();////
      // take the SS pin low to select the chip:
      digitalWrite(slaveSelectPin, LOW);
      //  send in the address and value via SPI:
      SPI.transfer(address);
      SPI.transfer(value);
      delay(30);
      // take the SS pin high to de-select the chip:
    }

    int digitalPotRead(int address) {
      // take the SS pin low to select the chip:
      digitalWrite(slaveSelectPin, LOW);
      //  send in the address via SPI:
      SPI.transfer(address);
      // send zero to read data from the address
      delay(30);
    }

```

# Answer
> 1 votes
Basically it works.

Here you find a little sketch to see how it works. Try to transfere it to your solution.

```
#include <M5Stack.h>  // only necessary for my board (M5Stack)

bool condition_while = true;
bool condition_loop = true;
int condition_if = 0;

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

void loop() {
   while (condition_while) {
       if (condition_if == 0) {
           Serial.println("testcase #1: if path reached");
           condition_if = 1;
       }
       else if (condition_if == 1 ) {
           Serial.println("testcase #2: if else path reached");
           condition_if = 2;
       }
       else {
           Serial.println("testcase #3: else path reached");
           condition_while = false;
       }
       Serial.println("testcase #4: path reached inside while");
   }
   if (condition_loop) {
       Serial.println("testcase #5: path reached outside while");
       condition_loop = false;
   }
}

```

This is the output on COM3

# Answer
> 0 votes
I would suggest you go through the coding tutorials on arduino website. It would be absolutely possible to have the above `structure` in an arduino code.

This link has a working and validated example showing `while` loop calling other function using `if-else-if` structure.

https://www.arduino.cc/en/Tutorial/WhileStatementConditional?from=Tutorial.WhileLoop

Please go through the tutorials and post specific problem if and when you encounter them.

# Answer
> 0 votes
If the code (not shown) within the if/else if/else structure doesn't affect the flow of control, then either delay() placement will work. But the placement within the loop will delay at every cycle of the loop. The placement below the loop will only delay after the loop finishes executing.

---
Tags: code-review
---


title: Arduino and Solenoid Water Valve

text:
# Question
Title: Arduino and Solenoid Water Valve
I use Arduino UNO and two SPST Relay (Wemos Mini D1 Relay) to make the reverse polarity circuit. I use this circuit to open and close the Solenoid Water Valve (SWV), which work with 9 to 12 volt. The connections are as follows:

```
NO (Relay1) --> NC (Relay2) --> +12 Volt
NC (Relay1) --> NO (Relay2) --> 0
D1 (Relay1) --> D1 (Relay2) --> Digital pin 3 of Arduino
COM (Relay1) --> SWV1
COM (Relay2) --> SWV2
GND Relay1) --> GND (Relay2) --> GND of Arduino
5V (Relay1) --> 5V (Relay2) --> 5 Volt of Arduino

```

the circuit work perfectly with Arduino boar. But the problem is that when I use ATMEGA328p-PU on breadboard as explained in LINK, Relays are not working properly. Actually, relays connecting and disconnecting continuously when ATMEGA328p sends 1 to D1 pins of Relays.

The point is when I de-attach the SWV, relays work properly. but if the SWV is connected it still is not working.

I've checked the connection many times and they are correct.

I used the following code in arduino:

```
int Relay = 3;
void setup() {
  // put your setup code here, to run once:
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  digitalWrite(Relay, HIGH);
  delay(2000);
  digitalWrite(Relay, LOW);

}

```

Any help is highly appreciated.

Thanks in advance.

# Answer
> 1 votes
The problem is most likely EMI (electromagnetic interference) from the switching of the inductive load by the relays.

The fact that you have your setup on a breadboard means that each and every pin of the ATMega328 is connected to a little antenna. That massively increases its susceptibility to falling prey to EMI. Add to that the fact that there is absolutely no decoupling of the power supply (thanks to Arduino producing shoddy worthless tutorials) makes the whole chip very fragile.

When running with a real Arduino board you have decoupling on the power which helps to reduce induced power rail bounce which can cause the chip to fail.

There are two things that can help mitigate this:

* Add decent decoupling to the ATMega328

This means adding capacitors between each VCC pin and ground. At the bare minimum a 100nF capacitor on each VCC pin is needed. Additionally a 1nF capacitor can be beneficial. A 10µF capacitor should also be added on the breadboard's power rails to act as a board-level reservoir.

* Snubber networks on the switching

A snubber network, in its most simple form, is a resistor and capacitor in series. It is placed across the switching terminals of a device that is switching an inductive load to absorb the sudden spike of back-EMF from the collapsing magnetic field whenever the load is switched off.

simulate this circuit – Schematic created using CircuitLab

Note that the capacitors here should be rated for at least 400V since the voltages involved are quite high.

# Answer
> 0 votes
An inductor can create large pulses of power when turned off and on such as in a relay or a solenoid. A flyback diode is usually added across inductors to suppress these pulses. Indeed if you look at the schematic of the Wemos Relay Board used in this project you see where D1 is used in just such a way. Unfortunately the voltage is being applied in both directions across the solenoid so a flyback diode can not be used directly across the solenoid. However, it may be possible to add a flyback diode before the relays where the voltage is not reversing.

It is almost always better to mitigate electrical noise such as Electromagnetic Field (EMF) interference at its source. Hence the flyback diode. However, many combination logic and processor designers add decoupling capacitors as close as possible to the power terminal of each logic chip. This may be the reason a real Arduino board works while the bread board does not.

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


# Question
Title: Sending command through SPI on Arduino UNO
I am assuming the default pin configuration is pin 10(SS), 11(MOSI), 12(MISO), 13(CLK) from a default setup, SPI.begin(). The code compiles OK. Not sure about the int valuex and using the SPI.transfer() function.

```
#include <SPI.h>

int value1 = 0x8026;
int value2 = 0x0801;
int value3 = 0x8027;
int value4 = 0x0000;

void setup (void)
{
  Serial.begin (9600);
  Serial.println ("Starting");
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV4);

}  // end of setup

void loop (void)
{
  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer (1);   // initiate transmission
  SPI.transfer (value1);
  SPI.transfer (value2);
  SPI.transfer (value3);
  SPI.transfer (value4);

  // disable Slave Select
  digitalWrite(SS, HIGH);

delay (1000);
}

```

# Answer
> Not sure about the int valuex and using the SPI.transfer() function.

A couple of things to know:

1. You are storing an unsigned 16-bit literal into a signed 16-bit variable. You should be using `uint16_t value1 = 0x8026;` etc. Also, unless you are planning to change the values, they should be `const`.
2. `SPI.transfer()` transfers only 8 bits of data. You are only sending the lowest byte of your `valuex` variables. `SPI.transfer16()` sends an unsigned 16-bit value.

To illustrate, this is how your program should look:

```
#include <SPI.h>

const uint16_t value1 = 0x8026;
const uint16_t value2 = 0x0801;
const uint16_t value3 = 0x8027;
const uint16_t value4 = 0x0000;

void setup(void) {
    Serial.begin(9600);
    Serial.println("Starting");
    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    // Put SCK, MOSI, SS pins into output mode
    // also put SCK, MOSI into LOW state, and SS into HIGH state.
    // Then put SPI hardware into Master mode and turn SPI on
    SPI.begin();
    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV4);
}  // end of setup

void loop(void) {
    // enable Slave Select
    digitalWrite(SS, LOW);
    SPI.transfer(1);    // initiate transmission
    SPI.transfer16(value1);
    SPI.transfer16(value2);
    SPI.transfer16(value3);
    SPI.transfer16(value4);
    // disable Slave Select
    digitalWrite(SS, HIGH);
    Delay(1000);
}

```

That will transfer the stream of 8-bit values:

```
0x01 0x80 0x26 0x08 0x01 0x80 0x27 0x00 0x00

```
> 1 votes

---
Tags: arduino-uno, spi
---


title: MIDI keyboard controlled LED strip

text:
# Question
Title: MIDI keyboard controlled LED strip
My objective is to light a led on a strip corresponding to a keyboard note. I have Arduino Uno with MIDI in module hooked up to a serial port. Piano is hooked with a standart midi cable, Led Strip is powered using Arduino's 5v (Figured i don't need more because Max 10 leds will be active at a time).

My setup works but not accurately. All is fine when only 1 note at a time is played, but the denser the music becomes (faster or more notes are played simultaniously) more inaccuracies show - more leds don't turn off or on, or the notes I didn't play light up.

At first i used software serial and there were even more mistakes, when i switched to hardware it became better. Could it be that Arduino UNO is just not powerfull enough and cannot keep up with incoming midi input or is there another problem?

Here is the code:

```
#include <MIDI.h>
#include <Adafruit_NeoPixel.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define STRIP_PIN 11
#define STRIP_NUM_PIXELS 88

Adafruit_NeoPixel strip = Adafruit_NeoPixel(STRIP_NUM_PIXELS, STRIP_PIN, NEO_GRB + NEO_KHZ800);

void handleNoteOn(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(50, 50, 50));
  strip.show();
}

void handleNoteOff(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(0, 0, 0));
  strip.show();
}

// -----------------------------------------------------------------------------

void setup()
{
    MIDI.setHandleNoteOn(handleNoteOn);
    MIDI.setHandleNoteOff(handleNoteOff);
    MIDI.begin(MIDI_CHANNEL_OMNI);
    strip.begin();
}

void loop()
{
    MIDI.read();
}

```

# Answer
> 0 votes
The biggest problem is that updating the LEDs is an intensive task.

* Hand-crafted assembly is written to get the timing right
* Interrupts are disabled while the update is running
* 88 LEDs take a (relatively) long time to update.

At about 1.2µS per LED plus 50µS for the reset pulse, you're looking at about 155µS that the Arduino can't be doing anything else at all. That includes receiving anything through serial. And since you update for every note you receive, if there is a second note coming in with 155µS of that one, it will be missed.

You may get better results with the FastLED library instead of the Adafruit Neopixel library, but ideally you want to work with a board that is fast enough to not need to do such tight bit-banging for the protocol, so that interrupts can still be enabled for receiving data.

---
Tags: arduino-uno, midi, led-strip
---


# Question
Title: REST API on Industrial 101 (Yún family) lags, then crashes
I have tried to set up a very simple REST API on an Arduino Industrial 101 (which is, as far as I understand, equivalent to a Yún). The Arduino is hooked up to a temperature sensor, which value is returned over the REST interface. Everything works fine at first, but over the course of a day it starts taking longer and longer for the device to respond until it completely crashes and becomes unresponsive. (At that point it also doesn't respond to `ping` and `ssh` anymore.)

On the Arduino forum there are several threads reporting similar problems (e.g. this one) but they all seem to be at least a few years old and have been solved in the mean time. (The solution reported here, for instance, has already been incorporated in my Linino version.)

If I reset the ATMega the problem persists, but if I reboot the OS it is solved for a day, so I have reason to suspect something on the Linino side is not working properly. Any help would be much appreciated, although I realize this is quite an old board.

My sketch is basically a dumbed-down version of the Bridge example:

```
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  BridgeClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

void process(BridgeClient client) {
  // no matter what the command is, return value on A1 sampled 4096 times

  int pin = 1;
  float val = 0;
  for (int i = 0; i < 4096; i++){
    val += float(analogRead(pin))/4096.0;
  }
  client.println(val*5.0/1024.0, 5); //multiply by 5/1024 to get volts

}

```

# Answer
> 0 votes
I inspected the source code of the Bridge library. It is very simple.

There are no dynamic memory allocations. It uses String in client.connect(), but your sketch doesn't use it. You could print free memory in ATmega with MemoryFree library. But I am 99% percent sure it will show no memory leak.

There is no 'background' processing in the Bridge library as suggested by other answers. All commands and data are sent to the WRT on Atheros and wait for result or acknowledge. The WRT side of the Bridge library is coded in python.

The fact that the restart of the WRT is what helps to continue, confirms that the problem is on the python side of the Bridge.

Python on WRT is very far from Arduino knowledge base, so I doubt you will get a solution here.

# Answer
> 0 votes
First of all you should try changing the `delay(50);`. Try using `millis();` instead and see if the problem still persists.

```
int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

```

If that doesn't help, try adding the `yield();` method after the `delay(50);` / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.

My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.

---
Tags: wifi, arduino-yun
---


# Question
Title: Measure small capacitances with ATtiny85 (Digispark board)
I have successfully run the code provided here on an Arduino Nano. If nothing is connected, it will output a very small capacitance (~ 1 pF).

Then I tried to migrate the code to the ATtiny85 (using a Digispark USB Development Board), but I fail to get anything reasonable out of the code. The first `analogRead` will always give 1023, whereas on the Nano it gives a very small value (again for nothing connected to the input pins).

It's a bit trickier on the ATtiny85 because the pin numbers are different for digital and analog, but I thought I got that right, so what went wrong in the migration?

```
const int OUT_PIN = 2; // digital pin PB2 is 2, positive pin of C
const int IN_PIN  = 5; // digital pin PB5 is 5, negative pin of C
const int OUT_ANA = 1; // analog read PB2 is 1
const int IN_ANA  = 0; // analog read PB5 is 0

const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

#include "DigiKeyboard.h"

void setup() {
  pinMode(1, OUTPUT);
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(IN_PIN, LOW);
  DigiKeyboard.update();
}

void loop() {

    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_ANA); // IN_PIN in Nano version
    digitalWrite(OUT_PIN, LOW);

    DigiKeyboard.println(val);
    if (val < 1000) {
      pinMode(IN_PIN, OUTPUT);
      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);
      DigiKeyboard.print(capacitance);
      DigiKeyboard.println(" pF");
    } else {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_ANA); // OUT_PIN in Nano version
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      if (capacitance > 1000.0) {
        DigiKeyboard.print(capacitance / 1000.0);
        DigiKeyboard.println(" uF");
      } else {
        DigiKeyboard.print(capacitance);
        DigiKeyboard.println(" nF");
      }
      DigiKeyboard.println(val); // usually ~ 520 (because we wait until digVal == 1?)
      DigiKeyboard.println(t); // depends on C: ~ 26000 for 1 µF, ~ 2600 for 100 nF, ~ 250000 for 10 µF
  }

  digitalWrite(1, 1);
  delay(10);
  while (micros() % 1000 != 0);
  digitalWrite(1, 0);

}

```

# Answer
> 1 votes
The reason this doesn't work is that PB5 is pulled high (as it's used as -RESET pin on the board). The code can be rewritten to use only one ADC pin though.

---
Tags: analogread, attiny85, digispark
---


# Question
Title: How to use power led from arduino-pro-micro?
In my project I need 3 leds. I would like to use on-board leds if possible.

I know how to use `PB0` and `PD5` red on-board leds, and I would like to hack the board somehow to use the green power led.

If I do not find a way to use the power led from MCU, I'm planning to destroy it anyway, because it is constantly on, which is harmful in my project.

# Answer
> 0 votes
There are 34-pin atmega32u4-based boards. They have 3 leds. So use them instead of pro-micro board.

---
Tags: arduino-pro-micro
---


# Question
Title: KY-022 IR receiver, LED always on, no output
I've been trying to use a KY-022 to read IR signals. However no output is being produced and the LED on the board is constantly on.

Board: Arduino Uno R3

I followed the procedure found here.

The code:

```
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  // In case the interrupt driver crashes on setup, give a clue
  // to the user what's going on.
  Serial.println("Enabling IRin");
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("Enabled IRin");
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

```

The output:

```
Enabling IRin
Enabled IRin

```

The LED is constantly on, it should come on when there's a signal received. However this is not shown in the output. :/ I don't know what to do.

Pictures:

# Answer
The first thing to look at is the circuit board. Are they using the resistor and LED to indicate the board is receiving power? The data sheet has a schematic showing several passive components in the "3. ApplicationCircuit" section. Here is a copy of the schematic I have used that worked with the IRremote library (Version 0.1 July, 2009 - Copyright 2009 Ken Shirriff).
> 1 votes

# Answer
This happened to me when I "fried" my IR receiver.

Everything was fine and working until I accidentally reversed ground and +5v when putting my project back together after a tear down. After correcting the wiring, the LED stayed on, and no reading was coming out.

Did you ever get any pins wrong?

This video show the correct wiring. https://www.youtube.com/watch?v=iFpAqG90zY0
> 0 votes

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


title: Finding ESP8266 in a network

text:
# Question
Title: Finding ESP8266 in a network
I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.

What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.

I just need to find the ESP8266 on the network, get its IP address and send commands to it.

Thanks in advance.

# Answer
The best way to do this if you are doing it for product is using SSDP protocol. It's Simple service discovery protocol which allows you to search for device in a network. It's implemented in many smart devices now a days with dlna or upnp.

Implement a SSDP server on esp8266 and Implement a SSDP client on Android device.

You can find many devices with this approach, using simple filter to result with your specific information you want from SSDP packet can allow you to only get desired devices from network.

All the documentation about SSDP is given on Arduino esp8266 GitHub page.

You can broadcast your IP in your SSDP packet and then use it in your app, But still your most imp problem of dynamic IP remains unsolved as your IP will always be changing and using IP for accessing a hardware like home automation is not proper way.

You can either use. 1) Static IP for this if you want offline access or 2) Use cloud based solutions, such as mqtt to access device anywhere without the worries of NAT, IP or anything.

But second option is more of commercial kind, you need multiple resources to implement it.
> 2 votes

# Answer
Some solutions that have worked for me:

1. **Reserved IP** \- use the router's DHCP reservation to give the same ESP the same IP each time.
2. **Static IP** \- Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. `WiFi.config(ip, gateway, subnet);`
3. **Dump the IP** address to Serial on boot, so that you can at least see what's assigned: `Serial.println(WiFi.localIP());`
4. Give the **STA a unique name** that you can find in the router's DCHP clients page: `WiFi.hostname("look_here");`
5. use **mDNS** to assign a domain-like local URL to the device: `MDNS.begin("esp8266");// default to "http://esp8266.local/"`
> 3 votes

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


title: What should the cut-off frequency be?

text:
# Question
Title: What should the cut-off frequency be?
To convert a PWM signal to a DC voltage it must be filtered with a low pass filter. How can you know which cut-off frequency should be used and how do you calculate the values for the resistor and capacitor belonging to that cut-off frequency. I do know that the cut-off frequency needs to be much higher/lower in comparison to the PWM signal, for example a factor 100 lower/higher.

# Answer
> 2 votes
The PWM frequency on the Arduino is about 500Hz by default, so you want your -3dB frequency to be below that. How far below? That's subjective. Lower gives a smoother output but a lower response speed. Since you want DC out then you can afford to go very low, unless you need it to respond to changes in the set point quickly.

---
Tags: pwm, resistor, capacitors, calculation
---


# Question
Title: Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding
Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.

My Setup:

1. Win7 64bit
2. Arduino 1.6.9 IDE freshly reinstalled
3. COM14 port in Arduino IDE checked
4. Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
5. I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
6. I have bought 2 Arduino Nanos and both show same error
7. Both Nanos came pre-soldered, (no noob soldering by me)
8. I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.

The problem:

1. When I try upload I get the same message every time: **avrdude: stk500\_recv(): programmer is not responding**

a. it does this 10 times and then fails

b. Rx and Tx LED's are ON and do NOT blink at all at any point in time

c. Green power LED is always ON, no blinking

d. Pin13 LED blinks consistently

e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.

Any help would be greatly appreciated please.

# Answer
The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)
> 2 votes

# Answer
Sorry for posting this as an answer, I don't have enough rep to write comments yet.

1) Have you tried different USB cables? A dodgy USB cable could power the Nano just fine, giving the impression that it's properly connected, without not actually supporting the data rate required for programming. The fact that something shows up on a USB port on your computer makes this explanation less plausible, though.

2) I notice that there are different versions of the Nano, some with ATmega168 and some with ATmega328. If you have the ATmega328, maybe try selecting "Arduino Uno" in the IDE? If you have the ATmega168, maybe try "Arduino Mini"?
> 1 votes

# Answer
The baudrate for those is 57600. Try checking for an error in your boards.txt .
> 0 votes

# Answer
try a different COM port. I had a corrupted COM3 and it gave the exact same error message that you got
> 0 votes

---
Tags: arduino-nano, uploading, programmer, windows
---


title: Can ESP8266 send AT commands to self?

text:
# Question
Title: Can ESP8266 send AT commands to self?
I'm having some problems with my ESP8266 stopping transmission of MQTT messages after a while. Therefore I'm writing some error handling messages, and I want to publish some AT data to MQTT.

It's probably a simple solution, but how can I, though the code, send AT messages from my 'own' device? Also, does AT messages get parsed at a higher level than any other user input, so it can't get stuck in any user made input loop?

Many thanks!

# Answer
The AT command set for the ESP8266 is implemented through custom firmware which has to be flashed to the chip to use.

If you've written your own software which is running on the ESP8266 then that's what's flashed to it - the AT command set will not be available because you've overwritten it with your own software. So there's no way to send AT commands to yourself because if you've written software that could do that, then it's present and the AT command-interpreting software is not.

In that case you should look deeper into the Arduino core for the ESP8266 to find the equivalents to the AT commands you wanted to use. This is the code that calls `setup()` and `loop()` and implements Arduino-compatible functions like `pinMode()`. It also provides libraries like `ESP8266WiFi`. There are many un- and under-documented functions in the code. You can almost certainly find the equivalents to anything that you can do with an AT command in here.
> 1 votes

---
Tags: esp8266
---


title: Replace Arduino bootloader

text:
# Question
Title: Replace Arduino bootloader
My Arduino board is malfunctioning in its bootloading and I thought weather I can overwrite the previous bootloader on the atmega. I mean to ask than can I simply reinstall bootloader on a chip that already has a bootloader installed.

# Answer
Yes you can. A Programmer that is driven from a PC and connects to SCK/MOSI/MISO/Reset/Power/Gnd (the ICSP header on an Uno/Mega), or a Standalone Programmer that can program a bootload program stored on an SD card and connects to the same ICSP pins, is needed to access the bootload memory to load/reload the bootloader.
> 1 votes

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


# Question
Title: invalid conversion from 'uint16_t* error when creating an array of uint16_t items
I'd like to create an array of remote control codes provided by the raw read feature of the irlib2 library.

irlib2 provides the following uint16t arrays using the following format:

```
#define RAW_DATA_LEN 68

const uint16_t powerOff[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000};

```

I'd like create an array of these arrays using the code below, but get the following errors.

**CODE**

```
#define RAW_DATA_LEN 68

const uint16_t powerOff[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000};

uint16_t sourceCD[RAW_DATA_LEN]={
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000};

uint16_t sourceAUX[RAW_DATA_LEN]={
  8550, 4310, 526, 1634, 506, 566, 502, 1634,
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000};

uint16_t sourceCDR[RAW_DATA_LEN]={
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000};

//This is the problem code:
uint16_t sources[3] = {sourceCD, sourceAUX,  sourceCDR};

```

**ERRORS**

```
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]
 uint16_t sources[3] = {sourceCD, sourceAUX,  sourceCDR};
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]
warning: invalid conversion from 'uint16_t* {aka unsigned int*}' to 'uint16_t {aka unsigned int}' [-fpermissive]

```

I gather this has something to do with mixing and converting invalid types, but I'm not quite sure where to go from here

# Answer
You have two options.

1. You can make an array of arrays like this:

```
const uint16_t sources[3][RAW_DATA_LEN] = {
    { 8546, 4310, 558, ... }, // CD
    { 8550, 4310, 526, ... }, // AUX
    { 8550, 4306, 530, ... }  // CDR
};

```

But then you don't have the `sourceCD`, etc. variables any more. If you want, you could `#define` aliases for them like this:

```
#define sourceCD  (sources[0])
#define sourceAUX (sources[1])
#define sourceCDR (sources[2])

```
2. You can make an array of pointers, as suggested in the comments:

```
const uint16_t sourceCD[RAW_DATA_LEN]  = { 8546, 4310, 558, ... };
const uint16_t sourceAUX[RAW_DATA_LEN] = { 8550, 4310, 526, ... };
const uint16_t sourceCDR[RAW_DATA_LEN] = { 8550, 4306, 530, ... };
const uint16_t *sources[3] = { sourceCD, sourceAUX,  sourceCDR };

```

This works because, in the last line, the array identifiers such as `sourceCD` implicitly “decay” to pointers to their first elements. Note the `const` keyword in the last line, needed for consistency with the types of the arrays declared above.
> 2 votes

---
Tags: ir, data-type
---


# Question
Title: Please explain the void loop() section of the sketch
```
#include <VirtualWire.h>

int PWMB = 5; //Speed control

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

  //receiver setup
  vw_set_rx_pin(2);
  vw_set_ptt_inverted(true);
  vw_setup(2000);
  vw_rx_start();
}

void loop(){
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int i;
    int column = 0;
    String message;
    int commands[30];

    for (i = 0; i < buflen; i++)
    {
      //DEBUG:
      Serial.print(char(buf[i]));

      if(char(buf[i]) == '|'){
        commands[column] = message.toInt();
        message = "";
        column++;
      } else {
        message += char(buf[i]);
      }
    }

  commands[column] = message.toInt();
  }
}

```

This topic is the receiver side of my last topic: please explain the sketch attached that one sending date and this is a receiver.

questions:

1. The transmitter transfer date array of \[60\] like: 523 | 487, here `int commands[30];` just 30, is it OK?
2. `if(char(buf[i]) == '|') / commands[column] = message.toInt();`, seems just convert the date before '|'?
3. What is the result of `message += char(buf[i]);`?

Thanks

# Answer
> 1 votes
> The transmitter transfer date array of \[60\] like: 523 | 487, here " int commands\[30\];" just 30, is it OK?

If you have a maximum of 59 characters (59 printable characters plus the NULL at the end equals 60), and each number is separated by a `|` character, then the maximum possible numbers you can have, if they are all single digit, is 30. So yes, an array of 30 integers is fine.

> " if(char(buf\[i\]) == '|') / commands\[column\] = message.toInt();", seems just convert the date before '|'?

Yes. It takes whatever has been placed in `message` and converts it to an integer, then empties `message` ready for the next number.

> what is the result of " message += char(buf\[i\]);"? Thanks

It adds the current character from the buffer (pointed to by `i`) to the end of the `message` string.

It's not the best way of doing it, and it can make a mess of your heap causing your Arduino to crash after a while.

Personally I would use `strtok()` directly on the buffer:

```
int i = 0;
char *part = strtok(buffer, "|");
while (part) {
    command[i] = atoi(part);
    i++;
    part = strtok(NULL, "|");
}

```

This of course assumes that `buffer` is properly NULL terminated.

---
Tags: sketch
---


# Question
Title: Run website / Javascript game from a Arduino UNO device?
I apologise if this is a dumb question, but I'm trying to find information on whether or not this is possible. I'd like to build a arcade machine to play my custom Javascript 2D game. The game currently runs in the browser (of course), but is it possible to execute the code in the Arduino. I'd like to make an arcade machine that runs from the Arduino and connect the game controls to a joystick. Can anyone tell me is this is possible, or any suggestions about how I can achieve this without rewriting the application.

I found the below link that has some information but this is for a PI https://www.raspberrypi.org/forums/viewtopic.php?t=194808

# Answer
> 1 votes
The Arduino cannot run Javascript, no.

It could *serve* Javascript from an SD card to a web browser running on a PC / Pi / Phone, etc, but there is no way it can run it itself.

---
Tags: arduino-uno, raspberrypi, web, joystick
---


title: Switch Statement stuck in loop

text:
# Question
Title: Switch Statement stuck in loop
I am writing a code for a user to enter a 4 digit pin, then use this pin later to unlock a box. The loop is stuck between the "ready to unlock box" and "enter pin" it just keeps flipping between values but i want both to be displayed, just at different times.

```
#include <Keypad.h> //install keypad library
#include <LiquidCrystal.h> //install LCD screen library

const byte ROWS = 4; //include four rows of keypad
const byte COLS = 4; //indclude four cols of keypad

char keys[ROWS][COLS] = { //set keypad array equal to numbers on keypad
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

int pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8;
int code[] = {pin1, pin2, pin3, pin4};

byte rowPins[ROWS] = {45,43,41,39}; //connect to the row pins of keypad
byte colPins[COLS] = {37,35,33,31}; //connent to the column pins of keypad

LiquidCrystal lcd(7, 8, 9, 10, 11, 12); //set up pins lcd will be connected to
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); //set keypad up to use as variable

int solenoidPin = 1; //connect motor pin to code

bool in_press = false;
void setup() {
   Serial.begin(9600); //start code
   lcd.begin(16,2); //start screen with dimensions
}

void loop() //loop of functions to run through
{
  int key; //initialize key as integer

  lcd.setCursor(0,0);
  lcd.print("Press # to lock,");//welcome screen
  lcd.setCursor(0,1);
  lcd.print("or * to unlock.");

  key = keypad.getKey(); //let arduino know it is waiting for a value

    while (in_press && key == NO_KEY) //check if they want to begin
    {
      in_press = false; //if no key was clicked
      return; //exit the loop and restart
    }

    while (key != NO_KEY){ //if a key was clicked
      switch(key){
      case '#':
        lcd.clear();
        lcd.setCursor(0,0);
        *lcd.print("Ready to lock"); //let user know ready for next step of process
        lcd.setCursor(0,1);
        lcd.print("keys!");
        delay(1000);
        EnterPin1();
        break;*

      case '*':
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Ready to unlock"); //let user know ready for next step of process
        lcd.setCursor(0,1);
        lcd.print("keys!");
        delay(1000);
        EnterPin5();
        break;

       default:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("No input");
       lcd.setCursor(0,1);
       lcd.print("detected.");
       break;
  }
 }
}

void EnterPin1()
{
  Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
  bool in_press = false;
  int pin1;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Enter your pin.");//let user know you are waiting for input
  delay(1000);

  pin1 = keypad.getKey(); //let arduino know it is waiting for a value

    while (in_press && pin1 == NO_KEY) //check if they want to begin
    {
      in_press = false; //if no key was clicked
      return; //exit the loop and restart
    }

    while (pin1 != NO_KEY) //if a key was clicked
    {
      switch(pin1){
      case '1':
        pin1 = 1;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*"); //let user know ready for next step of process
        EnterPin2(); //go to enter pin function
        break;

      case'2':
        pin1 = 2;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*"); //let user know ready for next step of process
        delay(1000);
        EnterPin2();
        break;

      case '3':
        pin1 = 3;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '4':
        pin1 = 4;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '5':
        pin1 = 5;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '6':
        pin1 = 6;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '7':
        pin1 = 7;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '8':
        pin1 = 8;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '9':
        pin1 = 9;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;
   }
  }
 }

```

# Answer
Your primary loop code sets `key`, and then has a `while (key != nokey) {}` loop after, but the value of key never changes inside the while loop. Thus, if key is not equal to noKey, the while loop will never exit.

```
key = keypad.getKey();

while (key != noKey) {
  //code that does not change key
}

```

That is an endless loop. The fact that there’s a switch statement inside the while loop is immaterial. None of that code changes the value of `key`, so the loop will never exit.

Write it like this instead:

**EDIT**

```
key = keypad.getKey();
while (key != noKey) {
  //Your current code
  key = keypad.getKey();
}

```

You have the same logic problem in your `enterPin1` function. You don’t provide the code for your `enterPin2` function, but I would guess it **also** has the same logic problem.
> 1 votes

---
Tags: lcd, switch, keypad
---


# Question
Title: 16 X 2 LCD display blank with Arduino Uno
So I am following this tutorial to make my arduino display hello world and `millis()`, I got it to work for a minute, but then it stopped updating the milliseconds, and when I pushed the reset button it went blank. since then, It has been blank but I have double, triple, and qaudruple checked checked my wiring, and it is flawless. I tried it with both of my 16 segment displays, but to no avail. I have redone the wiring, but it is still blank. Does anybody know what I could be doing wrong?

I followed this diagram  this is my code:

```
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

This is the result (the screen is lit up, but there is no text even when turning the potentiometer)

# Answer
It is most likely that I wasn't providing enough power to the arduino, and or had the potentiometer set to the wrong point. according to this post, you shouldn't run the arduino and display off of USB, because it may not actually be providing 5 volts. So I plugged it into the wall using a DC adapter. It now works.
> 2 votes

---
Tags: arduino-uno, lcd, display, wires
---


# Question
Title: Why is AREF connected to a capacitor in the Arduino Pro Mini Schematic?
I'm currently looking at the Arduino Pro Mini schematic and have noticed that the pin AREF (analogue reference) is connected to a 0.1uF capacitor as shown below:

I have done some research and read this great explanation into AREF and now understand its purpose as a voltage reference. What I do not understand however is the purpose of the capacitor. Is it as a means of stabilising the pin when an external voltage is applied, or something else?

A full schematic of the Arduino Pro Mini can be sourced from here.

# Answer
> 4 votes
On the datasheet for the Atmega328P, in the Analog-to-Digital Converter section, is the sentence:

> The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

Also:

> The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.

Thus the capacitor is there to reduce noise on the AREF pin.

# Answer
> 0 votes
An ideal capacitor presents an impedance of wC (radian frequency * capacitance -- ohms). Of course ideal capacitors do not exist in real component selections or circuits and all include parasitic losses and inductance. The parasitic components depend on the type of the capacitor, lead length, connecting circuits, etc. Oscilloscopes, network analyzers and spectrum analyzers serve to identify fundamental performance of voltage reference points.

The decoupling capacitor should be connected using short leads to a ground plane layer and the Aref pin.

---
Tags: arduino-pro-mini, capacitors
---


# Question
Title: Reading NFC card (PN532) with Arduino Uno
I am trying to detect a RFID card using the NFC-PN532 module and Adafruit\_PN532 library.

Initialization code:-

```
#include <Adafruit_PN532.h>
#include <Wire.h>

#define SCK  (13)
#define MISO (12)
#define MOSI (11)
#define SS   (10)
Adafruit_PN532 nfc(SCK, MISO, MOSI, SS);

void setup()
{
  Serial.begin(9600);
  Serial.println("Initializing please wait.......");
  delay(3000);
  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata)
  {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }

  Serial.print("Device Found PN5 Chip");
  Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware version > ");
  Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.println((versiondata>>8) & 0xFF, DEC);
  nfc.SAMConfig(); //Set to read RFID tags
  Serial.println("Waiting for RFID Card ...");
}

```

Main loop:-

```
void loop()
{
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      Serial.println("Card Detected!");
  }
  else
  {
      Serial.println("Card Not Detected or Removed!");
  }
}

```

Whenever i place a valid card on the PN532, *Card Detected!* is printed on the serial monitor.

However, when i remove the card, *Card Not Detected or Removed!* does not get printed.

How can i make the program to loop in such a way that it can detect when the card is present/removed?

# Answer
The default behaviour of `readPassiveTargetID` is to wait "forever" for a card - which is why your code only sees when there is a card present

So, in setup() add `nfc.setPassiveActivationRetries(0x10);` as follows - comments came from my own code, but I'm sure they were originally in some example or other :p

```
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0x10);

// configure board to read RFID tags
nfc.SAMConfig();

```

As for "detecting" removal

```
void loop()
{
  static bool wasSuccess = false;
  uint8_t success = 0;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
  uint8_t uidLength;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
  if (success)
  {
      wasSuccess = true;
      Serial.println("Card Detected!");
  }
  else if (wasSuccess)
  {
      wasSuccess = false;
      Serial.println("Card Removed!");
  }
  else
  {
      // you may want to remove this, it will flood the output :p
      Serial.println("Card Not Detected!");
  }
}

```
> 3 votes

---
Tags: arduino-uno, rfid
---


# Question
Title: Force TCNT to stay below OCRxA on ATmega328P
I'm using a timer and the `TIMERx_COMPA` ISR to generate a signal in "the background".

This ISR is triggered when the timer reaches a certain value (`OCRxA`), which in turn can be changed by the user. Once the ISR triggers, the timer is reset and the next waiting period occurs.

If the compare value (`OCRxA`) is changed to a value below the current timer value before having hit the old compare value, the timer keeps running until it overflows back to 0 and hits the new `OCRxA` value. This results in no signal being generated until the timer has looped around, which can be quite long for the 16-bit `TIMER1` timer.

There are multiple way to get around this:

1. Reset `TCNTx` to zero whenever `OCRxA`. Easy, but one signal will always be off-clock
2. If `TCNTx` is greater than `OCRxA` (after changing `OCRxA`), reset it to just below `OCRxA`
3. If `TCNTx` is greater than `OCRxA`, trigger the interrupt manually, where the signal is generated and `TCNTx` is reset

I belive the third option would be the cleanest, both in checking whether the issue has occured as well as for the signal quality.

This is certainly an `X -> Y` problem, so I'm open for other approaches.

My question, for now, would be: **Can I manually jump to an ISR regardless of its "normal" trigger?**

# Answer
> 2 votes
> Can I manually jump to an ISR regardless of its "normal" trigger?

This should be possible, but is probably not the best solution.

> This is certainly an `X -> Y` problem, so I'm open for other approaches.

It would seem you are using the timer in CTC mode. In this mode, when you write to `OCRxA`, the register is updated immediately, which leads to the problem you are experiencing. The solution is to instead set the timer to “fast PWM” mode. In fast PWM mode, the `OCRxA` register is double buffered: you will be actually writing to a buffer register, and `OCRxA` is automatically updated from that buffer on the same timer clock cycle that clears the counter.

It may sound counter-intuitive to use a PWM mode when you do not need the PWM feature. However, as long as the “compare output mode” is set to “normal port operation” for both channels, the timer will not generate any PWM output, and you can legitimately use the fast PWM mode only for its double buffer feature.

---
Tags: arduino-uno, interrupt, atmega328, timers, avr
---