title: Unstable analog sensor readout

text:
# Question
Title: Unstable analog sensor readout
I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module. The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.

Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?

Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.

Thanks!

(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )

The code of the sketch is:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
int sensorValue;
float sensorVoltage;
LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
void setup() {
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("");
}

void loop() {
  sensorValue = analogRead(A0);
  sensorVoltage = sensorValue * (5.0 / 1023.0);
  lcd.setCursor(0, 0);
  lcd.print(sensorVoltage/0.1); // rather low voltage is expected
  delay(1000);
}

```

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.

With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.

# Answer
> the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle

If your sensor outputs 0 to 5V and you're only getting 0.03 to 0.04 variance then I would say that it's working pretty well. You can get a more stable output by averaging several readings before printing them.

Additionally, for even more stable readings consider powering your Audrino from a battery. USB power can induce a considerable amount of noise if it's coming from a PC or Laptop USB port. Also, there is a low noise mode where you can put the Arduino to sleep during your ADC reading (and it wakes up afterwards) which helps a lot with ADC noise reduction.
> 2 votes

---
Tags: arduino-uno, sensors, analogread
---


# Question
Title: How to burn bootloader into arduino uno without using another arduino
I need to bootload my Uno board but I do not have another Arduino at my disposal so how do I bootload without another Arduino board

# Answer
There are 3 main options how to write bootloader or program to AVR over ISP.

1. dedicated AVR programmer or Arduino ISP programmer
2. other Arduino with Arduino as ISP sketch or similar
3. parallel port of a computer
> 2 votes

# Answer
The USBTinyISP programmer attaches to your computer's USB port and uses the 6-pin ICSP port on your Arduino to program it. It can program both bootloaders and sketches. It can be purchased for less than $10 from Amazon or Ebay.

USBTinyISP programmer
> 2 votes

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


# Question
Title: Arduino write to memory and self shut down (over MOSFET) - An idea help
i would like to ask you for help with design of an circuit.

I have and atmega328p, with detection for voltage on its Vin (Vcc). I have made and voltage divider and its output i connected to Analog Pin. And i would like to, if an voltage decrease under an certain level (4.5V), to shutdown itself (atmega328p).

As i said the voltage detection is no problem (there is an voltage divider), programing it is as well no problem, but i though that i program it like this:

> Detect voltage on analog pin A0, if the voltage is less than certain level (4.5V), write to memory and send to digital pin 3 an "LOW" (0) logical state.

This will turn the mosfet off and the atmega will loose its ground (GND) and its shuts down, but i have there an pull-up resistor which when the atmega shutsdown takes its lead an set Gate at MOSFET to high (transistor will turn on) and atmega turns on, then it shuts down and this will do the infinite cycling until there's no power to turn on atmega.

I want to use an Supercapacitor (2.2F 5.5V) to power it when the main input is lost and to give an atmega a time to write to memory and steadily turns off.

I am adding an schematics to better look at the problem.

*I know that there is no crystal and capacitors and the other things to make it reliable and fully functional, but this is not a subject of this question.Its an first sketch, which is not completed.*

I know some ICs that can detect Voltage and turn its output to some logical state (1 or 0), like an MAX809 (803 or 810) and so on and of course this is my backup plan, but i want to ask you, if you have any great idea to make this without any special ICs and more easily? I also thought about some OPamp or thyristor maybe, i don't know......

Can you help me with an idea or better with an schematics how to do it ? Thanks.

# Answer
> 3 votes
You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

simulate this circuit – Schematic created using CircuitLab

In this schematic M1 is normally off. You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on. When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.

This arrangement means:

* You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
* You get a soft-power switch to turn the power on
* Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
* You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
* You are switching VCC, not GND (switching GND can cause all sorts of problems).

# Answer
> 0 votes
It would be easier to simply to power down the CPU using software once you're ready to shut down:

```
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();

```

---
Tags: arduino-ide, atmega328, memory, mosfet
---


# Question
Title: Is Arduino Keyboard in Single User Mode Possible?
Has anyone had success using the keyboard functionality of any arduino in single user mode of mac computers? I would like to inject keystrokes in single user mode, and have been unsuccessful with the atmega32u4.

# Answer
> 0 votes
I have found the solution to my problem. The issue is that the presence of both the usb device and serial port causes issue in single user mode. For the keyboard to work properly, the serial port must be disabled. This means that reflashing the micro requires pulling the reset pin low twice quickly for the port to show up again. Here is an example of how to remove the serial port: https://github.com/gdsports/usb-metamorph/tree/master/USBSerPassThruLine

# Answer
> 2 votes
OS X requires a "Boot Interface" compatible HID profile for a keyboard to work in single user mode (it has only loaded very rudimentary drivers by that point). The Arduino doesn't provide that interface, so can only work with the more advanced drivers the OS provides once booted.

You can *try* setting the "boot interface" flag to 1 in the interface subclass (here, I think, changing `HID_SUBCLASS_NONE` to `HID_SUBCLASS_BOOT_INTERFACE`) though I have no clue what the actual effect of that will be given that it's a composite device that may or may not conform to the boot interface standard.

---
Tags: arduino-micro, keyboard, atmega32u4
---


# Question
Title: ESP8266 WebServer not responding (connection time out)
My web server running on ESP8266, stop working after while. I cannot connect to it - browser shows `connection time out` error. No error, no crash... nothing.

Have you any idea how to fix it?

My code:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <FS.h>

#include "console.h"
#include "tictactoe.h"
#include "main.h"

#define L_GREEN 2
#define L_YELLOW 0
#define L_ORANGE 4
#define L_RED 5

const char* ssid = "***";
const char* password = "***";

int requests = 0;
String IPs = "[";

IPAddress staticIP86_10(192,168,0,115);
IPAddress gateway86_10(192,168,0,1);
IPAddress subnet86_10(255,255,255,0);

ESP8266WebServer server(80); //Server on port 80

String getContentType(String filename);
bool handleFileRead(String path);

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "1.sk.pool.ntp.org", 60*60, 60*1000);

//===============================================================
// Game Data
//===============================================================

/*String ticPlayer1 = "";
String ticPlayer2 = "";
String ticClick = "-1";
int ticReset = 0;*/

//===============================================================
// LEDs
//===============================================================
void LEDblink(int pin) {
  requests++;
  digitalWrite(pin, HIGH);
  delay(10);
  digitalWrite(pin, LOW);
}
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleNotFound(){
  if(server.uri().indexOf(".php")>-1) {
    Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+" (Blocked)\n");
    return;
  }
  Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+"\n");
  String s = HTML_Pro_notFound;
  server.send(404, "text/html", s);

  LEDblink(L_YELLOW);
}
void sendFile(String path, String type) {
  Serial.print(server.client().remoteIP().toString()+": "+server.uri()+"\n");
  if (SPIFFS.exists(path)) {                            // If the file exists
    File file = SPIFFS.open(path, "r");                 // Open it
    size_t sent = server.streamFile(file, type);        // And send it to the client
    file.close();                                       // Then close the file again
  }
}
//===============================================================
void reboot() {
 server.send(200, "text/plain", "true");
 LEDblink(L_RED);
 digitalWrite(15, LOW);
 digitalWrite(0, HIGH);
 digitalWrite(2, HIGH);
 ESP.restart();
}
void admin() {
 if(!server.hasArg("user") || !server.hasArg("pass") || server.arg("user") == NULL || server.arg("pass") == NULL || server.arg("request")=="login") {
    String expire = "";
    if(server.arg("remember")=="on"){expire="30";}else{expire="0";}
    server.send(200, "text/html", "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><title>ProTools.tk | Please Wait</title><link rel='stylesheet' type='text/css' href='/main.css'><script src='/cookies.js'></script></head><body style='background:#2d2d2d'><form class='center' action='/admin' method='post' style='display:none;'><input class='a' type='text' name='user'><input class='a' type='password' name='pass'><input class='a' type='text' name='request' value='panel'><button class='a' type='submit'></button></form><div class='loading center' style='margin-top:150px'></div><script type='text/javascript'>var u = '"+server.arg("user")+"';var p = '"+server.arg("pass")+"';if(u.length > 7 && p.length > 7) {delCookie('user');delCookie('pass');setCookie('user', u, "+expire+");setCookie('pass', p, "+expire+");}if(getCookie('user') && getCookie('user')) {var a=document.getElementsByClassName('a');a[0].value=getCookie('user');a[1].value=getCookie('pass');a[3].click();}else{location.replace('/login');}</script></body></html>");
    //server.sendHeader("Location","/login");
    //server.send(303);
 }
 if((server.arg("user")=="***")&&(server.arg("pass")=="***")) {
   if(server.arg("request")=="data") {
     String c = "{\"uptime\":"+String(millis(),DEC)+",\"req\":"+String(requests)+",\"ips\":"+IPs+"]}";
     server.send(200, "text/json", c);
   }
   else if(server.arg("request")=="panel") {
     server.send(200, "text/plain", "Admin panel here");
   }
   else {
    server.send(400, "text/plain", "400 Bad Request");
   }
 }
 else{
   server.sendHeader("Location","/login");
   server.send(303);
 }
 LEDblink(L_RED);
}
void console() {
 Serial.print("Console :"+server.client().remoteIP().toString()+"\n");
 String s = HTML_console;
 server.send(200, "text/html", s);
 LEDblink(L_ORANGE);
}

//===============================================================
/*void minesPage() {
 String s = HTML_mines;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void minesScript() {
 String s = JS_mines;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void minesStyle() {
 String s = CSS_mines;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}*/

//===============================================================

/*void ticPage() {
 String s = HTML_tictactoe;
 server.send(200, "text/html", s);
 LEDblink(L_YELLOW);
}
void ticScript() {
 String s = JS_tictactoe;
 server.send(200, "text/javascript", s);
 LEDblink(L_YELLOW);
}
void ticStyle() {
 String s = CSS_tictactoe;
 server.send(200, "text/css", s);
 LEDblink(L_YELLOW);
}

void ticData() {
 Serial.print("TicTacToe: "+server.client().remoteIP().toString()+"\n");
 String user = server.arg("user");
 String clicked = server.arg("click");
 String request = server.arg("request");
 String leave = server.arg("leave");
 if(user != "") {
  if(user == "get") {
   server.send(200, "text/plain", "{\"Player1\":\""+ticPlayer1+"\", \"Player2\":\""+ticPlayer2+"\"}");
  }
  else if(ticPlayer1 == "") {
   ticPlayer1 = user;
   server.send(200, "text/plain", "player1");
  }
  else if(ticPlayer2 == "") {
   ticPlayer2 = user;
   server.send(200, "text/plain", "player2");
  }
  else {
   server.send(200, "text/plain", "Full");
  }
  if(ticPlayer1 != "" && ticPlayer2 != "") {
   ticClick = "0";
  }
  digitalWrite(L_ORANGE,HIGH);
  delay(500);
  digitalWrite(L_ORANGE,LOW);
 }
 else if(leave != "") {
  if(leave == ticPlayer1) {
   ticPlayer1 = "";
  }
  else if(leave == ticPlayer2) {
   ticPlayer2 = "";
  }
  ticClick = "-1";
  server.send(200, "text/plain", leave+" left");
 }
 else if(clicked != "") {
  ticClick = clicked;
  server.send(200, "text/plain", "OK: "+ticClick);
 }
 else if(request != "") {
  if(request == "checkClicked") {
   server.send(200, "text/plain", ticClick);
  }
  if(request == "reset") {
   ticReset++;
   if(ticReset == 2) {
    ticPlayer1 = "";
    ticPlayer2 = "";
    ticClick = "-1";
    ticReset = 0;
    server.send(200, "text/plain", "Reseted");
   }
   else {
    server.send(200, "text/plain", "Verification required");
   }
  }
 }
 LEDblink(L_YELLOW);
}*/
//==============================================================
//                  SETUP
//==============================================================
void setup(void){
  Serial.begin(9600);

  //Onboard LED port Direction output
  pinMode(L_GREEN,OUTPUT);
  pinMode(L_YELLOW,OUTPUT);
  pinMode(L_ORANGE,OUTPUT);
  pinMode(L_RED,OUTPUT);

  digitalWrite(L_RED, HIGH);

  WiFi.hostname("ESP8266");

  WiFi.begin(ssid, password);     //Connect to your WiFi router

  MDNS.begin("ESP8266");
  MDNS.addService("http", "tcp", 80);

  digitalWrite(L_RED, LOW);
  // Wait for connection
  digitalWrite(L_ORANGE, HIGH);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  digitalWrite(L_ORANGE, LOW);
  digitalWrite(L_YELLOW, HIGH);

  WiFi.config(staticIP86_10, gateway86_10, subnet86_10);

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  SPIFFS.begin();

  server.on("/", []() {                                          // root
    sendFile("/page.html", "text/html");
    LEDblink(L_YELLOW);
  });
  server.on("/main.css", []() {                                  // main.css
    sendFile("/main.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.css", []() {                                  // page.css
    sendFile("/page.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/page.js", []() {                                   // page.js
    sendFile("/page.js", "text/javascript");
    String ip = server.client().remoteIP().toString();
    if(IPs=="["){
      IPs+="{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }else{
      IPs+=",{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
    }
    LEDblink(L_YELLOW);
  });
  server.on("/login/style.css", []() {                           // login/style.css
    sendFile("/login/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/cookies.js", []() {                                // cookies.js
    sendFile("/cookies.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/translator", []() {                                // translator
    sendFile("/translator/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/style.css", []() {                      // translator/style.css
    sendFile("/translator/style.css", "text/css");
    LEDblink(L_ORANGE);
  });
  server.on("/translator/script.js", []() {                      // translator/script.js
    sendFile("/translator/script.js", "text/javascript");
    LEDblink(L_ORANGE);
  });

  server.on("/login", []() {                                     // login
    sendFile("/login/page.html", "text/html");
    LEDblink(L_ORANGE);
  });
  server.on("/admin", admin);
  server.on("/reboot", reboot);
  server.on("/console", console);

  /*server.on("/minesweeper", minesPage);
  server.on("/minesweeper/script.js", minesScript);
  server.on("/minesweeper/style.css", minesStyle);

  server.on("/tictactoe", ticPage);
  server.on("/tictactoe/script.js", ticScript);
  server.on("/tictactoe/style.css", ticStyle);
  server.on("/tictactoe/data", ticData);*/

  server.onNotFound(handleNotFound);

  server.begin();                  //Start server
  timeClient.begin();
  Serial.println("HTTP server started");
  digitalWrite(L_YELLOW, LOW);
  digitalWrite(L_GREEN, HIGH);
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void){
  timeClient.update();
  server.handleClient();          //Handle client requests
}

```

# Answer
> 1 votes
Use the latest version of Arduino esp8266 core package (2.4.2 or higher).

---
Tags: esp8266, arduino-ide, c++
---


title: How to connect NodeMCU to NRF24L01

text:
# Question
Title: How to connect NodeMCU to NRF24L01
I need to connect NodeMCU and NRF24L01. where I'm receiving data from another NRF24L01 Transmission. I managed to connect to a WiFi network but the data receiving is not taking place as expected. Here is my code

```
#include <SPI.h>
#include "RF24.h"
#include <ESP8266WiFi.h>

RF24 myRadio(7, 8);
const char* ssid = "******";
const char* password = "********";
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    WiFi.begin(ssid, password);

    Serial.println();
    Serial.print("Connecting");
    while (WiFi.status() != WL_CONNECTED)
    {
     delay(500);
     Serial.print(".");
    }
    Serial.println("success!");
    Serial.print("IP Address is: ");
    Serial.println(WiFi.localIP());
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
}

void loop()
{

    if (myRadio.available())
    {
        while (myRadio.available())
        {
            myRadio.read(&data, sizeof(data));
        }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }
}

```

Any idea on why this is not receiving data as expected?. This somehow managed to connect to my WIFI successfully. Here are my pin connection

# Answer
> 1 votes
The Dx pin labels on NodeMcu and Wemos/Lolin boards do not correspond to esp8266 internal io pin numbers. The pins\_arduino.h file in core defines Dx constants which map internal io numbers to Dx labels.

Use `RF24 myRadio(D7, D8);`

---
Tags: esp8266, nodemcu, nrf24l01+
---


# Question
Title: How long does it takes for arduino to reach main()?
I am trying to emulate the behavior of a circuit using an Attiny85

This is the result I got so far:

In the picture above, D2 is VCC, D4, D5 and D6 are outputs of the circuit I am trying to emulate. D7 is the output of Attiny85

The code I am using is:

```
#define F_CPU 8000000L
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

int main() {

  DDRB = 0b00001000;

  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);
  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);

  _delay_ms(5);

  while(1)
  {
     PORTB = 0b00001000;
    _delay_ms(1);
     PORTB = 0b00000000;
    _delay_ms(1);
  }
    return 0;
}

```

According to this, it takes roughly 64ms from powerup until it actually run the main program.

Is there any reason for such a delay? How can I reduce it somehow (ideally to 20ms or less)?

# Answer
> 5 votes
The ATtiny85 has a built-in delay counter that keeps the MCU in reset mode for some time after the power is applied. This seems to be intended as a wait for the clock and power to be stabilized. The length of this delay depends on your selected clock source, and is somewhat configurable with the fuses.

According to your code, your MCU is clocked at 8 MHz. I assume you are then using the internal RC oscillator as a clock source. If this is the case, you have three choices for the startup delay:

* 20 CPU cycles
* 20 CPU cycles + 4 ms
* 20 CPU cycles + 64 ms

The latter is recommended if your power rises slowly, and is the default configuration in which these MCUs are shipped. If you power level rises fast, you may want to select a shorter delay by programming the SUT fuses. See the datasheet for details (section System Clock and Clock Options → Clock Sources → Calibrated Internal Oscillator).

---
Tags: attiny85
---


title: Communicating with a 12V device?

text:
# Question
Title: Communicating with a 12V device?
I'd like to connect a 12V access control device to the Arduino, but I lack the understanding.

How can the signals from and to the device be done when they have different voltages?

I am afraid that the 12V would brick the Arduino.

# Answer
> 1 votes
You could use an opto-coupler:

> An opto-isolator (also called an optocoupler, photocoupler, or optical isolator) is an electronic component that transfers electrical signals between two isolated circuits by using light. Opto-isolators prevent high voltages from affecting the system receiving the signal. Commercially available opto-isolators withstand input-to-output voltages up to 10 kV and voltage transients with speeds up to 25 kV/μs.
>
> A common type of opto-isolator consists of an LED and a phototransistor in the same opaque package. Other types of source-sensor combinations include LED-photodiode, LED-LASCR, and lamp-photoresistor pairs. Usually opto-isolators transfer digital (on-off) signals, but some techniques allow them to be used with analog signals.

Here is an example schematic and packaging:

If you have a heavy load (although this does not seem to be your case) then they can also be used in conjunction with relays - here is an eight channel opto-coupler relay module board:

>

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


title: Arduino Object Array initialization

text:
# Question
Title: Arduino Object Array initialization
I just got an Idea of trying to code rain simulation with arduino and Adafruit OLED display. When I finished it was quite messy code so I thought That maybe doing it Object Oriented would help. This code is just a sketch that MAYBE works. The thing is that I need to create an array of objects(drops) and then display them. I have tried to display just one drop and it does not seem to do anything, even Serial wont print the **pos\_y**. I have never wrote an Arduino code with objects so I just made a quick research and tried. here is the code:

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

class Drop{
  private:
  int pos_x = random(0, 128);
  int pos_y = random(-5, -20);
  int len = random(3, 7);
  int speed = random(6, 13);
public:
 void fall()
{
 display.drawFastVLine(pos_x, pos_y, len, 1);
 pos_y = pos_y + speed;
 delay(5);
 Serial.println(pos_y);
 display.display();
 display.clearDisplay();
}

};

Drop* drop = new Drop[50];

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

void loop() {
  drop[1].fall();
}

```

I will appreciate any suggestion or solution, spent almost entire day doing this "simple thing"..

# Answer
The code works without the display commands. A problem could be that you start with negative `pos_y` and use it as parameter for `drawFastVLine`.

Function random returns first parameter if it is a larger value then the second parameter. `random(-5, -20)` always returns -5.

To have more random random values, you should call randomSeed in setup().

And you can use global array `Drop drop[50];`.
> 0 votes

---
Tags: arduino-uno, array
---


title: Serial data not parsed correctly

text:
# Question
Title: Serial data not parsed correctly
The code I have works for the most part but when I send data via bluetooth received over software serial, too quickly, it is not parsed correctly.

I'm a bit stuck with what can be done to a void the incorrect formatting, since it works correctly if I send data slowly.

I could have a buffer to not send data more than once every set amount of time, but more responsiveness is preferred.

I am sending a string "center:255,0,255;" it saves the command in a char array untill it sees the ":", then it saves the red in a char array breaking on "," then same for the blue and green. when it reaches the ";" it send the four arrays to print to a console. Later it the data will be used to light specific leds based on the command, but when I send data too quickly it gets parsed incorrectly, for example:

```
command: center
red:195
green:0
blue:255
command: center
red:208
green:0center:221
blue:0,255
command: center
red:246
green:0
blue:255

```

the 'green:0center:221' isnt correct, its either not seeing the "," or seeing the ";" too soon. Not sure how to avoid it.

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  mySerial.begin(57600); //required when using the hm-10 with an arduino nano
  mySerial.listen();
}

void loop() {
  while (mySerial.available () > 0) {
    processIncomingByte (mySerial.read ());
  }
}

const unsigned int MAX_INPUT = 50;

void processIncomingByte (const byte inByte) {
  static int parse_the_string = 0;
  static char command [MAX_INPUT];
  static char red [MAX_INPUT];
  static char green [MAX_INPUT];
  static char blue [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (parse_the_string) {
    case 0:
      switch (inByte) {
        case ':':
          command [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            command [input_pos++] = inByte;
          break;
      }
      break;
    case 1:
      switch (inByte) {
        case ',':   // end of text
          red [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
       default:
          if (input_pos < (MAX_INPUT - 1))
            red [input_pos++] = inByte;
          break;
      }
      break;
    case 2:
      switch (inByte) {
        case ',':   // end of text
          green [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            green [input_pos++] = inByte;
          break;
      }
      break;
    case 3:
      switch (inByte) {
        case ';':   // end of text
          blue [input_pos] = 0;  // terminating null byte
          // terminator reached! process input_line here ...
          process_data (command, red, green, blue);
          input_pos = 0;
          parse_the_string = 0;
          break;
        case '\r':   // discard carriage return
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            blue [input_pos++] = inByte;
          break;
      }  // end of switch
      break;
    default:
      break;
  }
}

void process_data (const char * command, const char * red, const char * green, const char * blue)
  {
  // for now just display it
  Serial.print ("command: ");
  Serial.println (command);
  Serial.print ("red:");
  Serial.println (red);
  Serial.print ("green:");
  Serial.println (green);
  Serial.print ("blue:");
  Serial.println (blue);
  }

```

# Answer
Set higher baud rate for Serial and in Serial Monitor. It slows down the processing and the mySerial buffer overflows.
> 0 votes

---
Tags: softwareserial, serial-data
---


# Question
Title: How to concatenate a part of a string and convert then to a int?
Lets say I have

```
String myString="AR0236";

```

I wish to extract the number 236 and assign it to an `int`. How can this be done?

P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!

# Answer
> 1 votes
There's multiple ways.

The String class (which TBH you should avoid) has some useful methods:

* substring \- extract part of a string as a new string
* toInt \- convert a string to an integer

So you can join them together:

```
int val = myString.substring(3).toInt();

```

That's the *easy* way. Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.

If you are avoiding String, as you should, then you are working with pointers. For instance:

```
char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data

int val = atoi(myString + 3);

```

`myString + 3` gives you a new string pointer to a location that is 3 bytes further up in memory from `myString` \- which equates to where the start of your number is. Then convert that portion of the string to an integer.

The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.

---
Tags: arduino-uno
---


title: How to convert hex to ASCII

text:
# Question
Title: How to convert hex to ASCII
I am receiving bytes, converting them into hex and now I need to convert the hex to ASCII. Can it be done on an Arduino? Or do I need something else? I am new to programming with Arduino.

# Answer
> 2 votes
If you have a byte variable `b`, you can

* `write(b)` it as it is. if it is ASCII code of a readable character, the Serial Monitor will display it as that character, for example for 65 it will printt 'A'
* print it as decimal number with `print(b)`. for 65 it will print "65"
* print it as hexadecimal number with `print(b, HEX)`. for 65 it will print "41"
* print it as a number in other base with `print(b, base)`, for example `print(b, 2)` will print 1000001 if b is 65 in decimal

---
Tags: arduino-uno
---


# Question
Title: Arduino Due randomly slows down, serial communications stops
I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.

I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.

I'm using Arduino-MemoryFree to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the ArduinoJson library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).

Could someone please advise me on what could be causing this slow down?

# Answer
> 1 votes
> The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.

Here is the typical manifestation of heap fragmentation in an Arduino sketch.

Solution:

1. Remove as many `String`s as possible and replace them with `char[]`
2. Use a `StaticJsonBuffer` instead of a `DynamicJsonBuffer`

If you remove all the `String`s and use a `StaticJsonBuffer`, your program will run without any heap. No heap, no fragmentation! Not only it will be **more reliable**, it will also be **smaller** and **faster**.

**If you must** use `String`, then call `String::reserve()` to make sure the size is the same at each iteration. Indeed, repeated allocation of the same size doesn't increase fragmentation.

---
Tags: arduino-due
---


# Question
Title: Assigning array variables to int variables
I need to control thousands of rgb leds.To make animations I want to assign led numbers(addressable led strip) to arrays.For example `floor[2]room[14]=106` 106 is the number of led,there are many floors and rooms.I want to change floor or room numbers with that way I will make animations. We can say its 92x30 pixel monitor.I tried to create list of floor and rooms but I couldnt make it. I'm new to programming,help please!

**Solved with this way `#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))`**

# Answer
> 4 votes
You really don't need to maintain a list.

Just calculate the LED index from the location:

```
int room = 14;
int floor = 2;

const int rooms = 92;

int led = room + (floor * rooms);

```

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.

You could make a macro:

```
#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

```

Then your LED number is just:

```
int led = LEDNO(2, 14);

```

Here's an example taken from your code:

```
void floorsup(){

  FastLED.setBrightness(brightness);

  for(int a=1;a<255;a+=40){
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
  }
}

```

# Answer
> 1 votes
Something like this would work:

```
#define MAX_FLOORS  92
#define MAX_ROOMS   30

struct floor_str {
  int Room[MAX_ROOMS];
} Floor[MAX_FLOORS];

```

You would then access an individual LED address like:

Floor\[2\].Room\[14\] = 106;

---
Tags: array, variables
---


# Question
Title: Passive buzzer works with analogWrite(), but not with digitalWrite(). It also has constant static noise
I have a YL-44/MH-FMD passive piezo buzzer hooked up to an ESP8266/NodeMCU.

It's connected like this: Buzzer ---\> NodeMCU
\- GND ---\> G
\- VCC ---\> 3V
\- I/O ---\> D2

This code makes a clear beep.

```
void loop() {
  analogWrite(BUZZER, 255);
  delay(100);
  analogWrite(BUZZER, 0);
}

```

This code makes a weird low clicking sound, no beep.

```
void loop() {
  digitalWrite(BUZZER, HIGH);
  delay(100);
  digitalWrite(BUZZER, LOW);
}

```

I have no idea why the second one doesn't work, as all the tutorials reference that one.

**Also, why does the buzzer have a weird constant static noise and gets hot?**

Am I doing something wrong in the wiring? I use no resistors, as the tutorials don't show that.

# Answer
To sound a passive buzzer, use Arduino tone() function. If you set the pin HIGH the piezo surfaces are pulled together (or pulled away). It is what makes one click but nothing more. To make a tone the input must oscillate at right frequency. PWM is one way how to do a beep. Use tone() function to generate tones of desired frequency.

Your analogWrite(255) is PWM at 1/4 of full on, because max analogWrite value on esp8266 is at default 1023. So it makes a nice beep with 255.

If you use a speaker or passive piezo with esp8266 you can expect noise generated by WiFi operations. I set the pin as INPUT after tone() to eliminate the noise.
> 3 votes

# Answer
One thing to note about the digital write part. While you have a delay between the `HIGH` to `LOW`, there is no delay to go back to `HIGH` (other than the time to leave loop and re-enter; which can be very small amount of time).

While on a slower processor (like AVR) this time maybe enough to cause some buzz (and consistent buzz), on the esp8266 its going to be fast enough that IO pin may not change state at all from `LOW` to `HIGH`. On Esp8266, IO physical pin state is at a different frequency than instruction counts. I believe its only 8 MHz. Due to the time before a pin state change to take effect, changing back before it got around to changing the physical state may ignore that state change. In the specific example, the `LOW` may get ignored often and you will have more random effects from that sketch.

Try adding another delay of 100 ms after setting the pin `LOW`. this will simulate a PWM of 1000 ms on width of a 1100 ms duty cycle. And even better, lower the delays by a factor of 100 (first being delay 10 ms, the new one a delay of 1 ms), you get a 10 (or so) Hz buzz.
> 1 votes

# Answer
Your code example does not work because you have a PASSIVE buzzer. Your example would work okay with an ACTIVE buzzer.

With a passive buzzer you must turn on/off the digital I/O pin at the desired audio frequency. Using the tone() API is an easy way to do this.

tone(BUZZER\_PIN, 432, 250); // Play the buzzer at 432Hz for 250ms

Your buzzer is getting hot because it likely uses a PNP transistor to switch the coil on your buzzer module. This type of transistor conducts when the input is LOW. Some buzzer modules use NPN transistors and conduct when the input is HIGH.

To keep your buzzer from getting hot (and wasting current) set its input HIGH to turn it off (assuming it's using a PNP transistor which it sounds like it is based on your description)

digitalWrite(BUZZER\_PIN, HIGH);

You'll need to do this after using tone() each time as it leaves the output pin LOW.

I recently created a discussion on this topic on AVRFreaks forum: Buzzer Module gets Warm and Wastes Power
> 1 votes

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


# Question
Title: Do serial ports on Arduino UNO / Leonardo initialize differently?
What are the differences in serial communication between PC \<---\> Arduino UNO (ATMEGA328p) and PC \<---\> Arduino Leonardo (ATMEGA32u4)?

I am asking because of a problem related to using these two Arduino boards for data logging in the following way:

1. PC sends a specific char string to Arduino, via serial port, to initialize datalogging
2. Arduino measures data, let's say a fixed number of ADC readings
3. Arduino stops measuring, sends data back to the PC over serial port
4. Arduino waits until new serial data are received before logging new data

If I send/receive data via the Arduino IDE serial monitor, this procedure works on both boards. However, I want a separate GUI program (Qt) to handle the serial communication, where one clicks a button to send the data in step 1, and plot the data from step 3 on a graph.

I wrote a simple Qt GUI where a button is clicked, and the measured data are printed to the GUI screen. Observations while testing it:

* **Arduino UNO as datalogger**: Arduino is plugged into USB socket of PC, then I launch the GUI, then click button to start data acquisition. The data are shown. Program appears to work fine.
* **Arduino Leonardo as datalogger**: Arduino is plugged into USB socket of PC, then I launch the GUI, then click button to start data acquisition. The data are not received, program hangs.

Then

* **Arduino Leonardo as datalogger**: Arduino is plugged into USB socket of PC, **Open Arduino IDE serial monitor, send command to acquire data**. Then close Arduino IDE serial monitor, launch the GUI, click button to start data acquisition. The GUI program now works.

Long story, but basically there appears to be a difference when using the two Arduino boards with external programs to do serial communication. Can someone outline the differences and why Leonardo needs the "jump start" I described above using Arduino serial monitor? Ultimately I want to fix the problem and avoid that hack.

Reluctant to post Qt code on Arduino stack exchange, but here is how I start the serial port:

```
ui->setupUi(this);
microcontroller_is_available = false;
microcontroller_port_name = "false";
microcontroller = new QSerialPort(this);
qDebug() << "Number of available ports: " << QSerialPortInfo::availablePorts().length();
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
    qDebug() << "Has product ID " << serialPortInfo.hasProductIdentifier();
    if(serialPortInfo.hasProductIdentifier()){qDebug() << "Product ID: " << serialPortInfo.productIdentifier();}
    qDebug() << "Has vendor ID " << serialPortInfo.hasVendorIdentifier();
    if(serialPortInfo.hasVendorIdentifier()){qDebug() << "Vendor ID: " << serialPortInfo.vendorIdentifier();}
}

foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
   if(serialPortInfo.hasVendorIdentifier() && serialPortInfo.hasProductIdentifier()){
       if(serialPortInfo.vendorIdentifier() == micro_vendor_id){
           if(serialPortInfo.productIdentifier() == micro_product_id){
              microcontroller_port_name = serialPortInfo.portName();
              microcontroller_is_available = true;
           }
       }
   }
}

if(microcontroller_is_available){  // open and configure serialport
    microcontroller->setPortName(microcontroller_port_name);
    microcontroller->open(QSerialPort::ReadWrite);
    microcontroller->setBaudRate(QSerialPort::Baud115200);
    microcontroller->setDataBits(QSerialPort::Data8);
    microcontroller->setParity(QSerialPort::NoParity);
    microcontroller->setStopBits(QSerialPort::OneStop);
    microcontroller->setFlowControl(QSerialPort::NoFlowControl);
}
else{QMessageBox::warning(this, "Port error", "Cannot connect DAQ.");}

```

Setup part of my Arduino code:

```
void setup(){
  DDRB  |= B11111111;  // (654210 outputs, miso input)
  PORTB &= ~_BV(RF_AMPL);
  DDRD  |= B1100010;
  PORTD |= (_BV(SRAM_HOLD) | _BV(SRAM_SS1));
  ADCSRA=0;
  SPCR = B01010000;           // SPI init (could get away with 11010000 on 328p but not 32u4)
  SPSR = B00000001;
  PORTD &= ~_BV(SRAM_SS1);     // Slave init
  SPDR=WRMR;  while(!(SPSR & (1<<SPIF)));
  SPDR=SEQUENTIAL_MODE; while(!(SPSR & (1<<SPIF)));
  PORTD |= _BV(SRAM_SS1);
  __builtin_avr_delay_cycles(160);
  PORTD &= ~_BV(SRAM_SS1);
  SPDR=RDMR; while(!(SPSR & (1<<SPIF)));
  SPDR=0x00; while(!(SPSR & (1<<SPIF)));
  PORTD |= (_BV(SRAM_HOLD) | _BV(SRAM_SS1));
  state1=0;
  count=0;
  pulse_count=0;
  serial_counter=0;
  Serial.begin(115200);  while(!Serial){}
}

```

# Answer
> 1 votes
I solved this by resetting the Arduino (open serial port at 1200 baud, then close serial port) when launching the Qt program.

Here is the relevant part of the Qt program:

```
        microcontroller->setPortName(microcontroller_port_name);
        microcontroller->open(QSerialPort::ReadWrite);
        microcontroller->setBaudRate(QSerialPort::Baud1200);
        microcontroller->setDataBits(QSerialPort::Data8);
        microcontroller->setParity(QSerialPort::NoParity);
        microcontroller->setStopBits(QSerialPort::OneStop);
        microcontroller->setFlowControl(QSerialPort::HardwareControl);

        qDebug() << "open 1200 baud";
        Sleep(10);
        microcontroller->close();
        Sleep(10);

        microcontroller->open(QSerialPort::ReadWrite);
        microcontroller->setBaudRate(QSerialPort::Baud115200);
        microcontroller->setDataBits(QSerialPort::Data8);
        microcontroller->setParity(QSerialPort::NoParity);
        microcontroller->setStopBits(QSerialPort::OneStop);
        microcontroller->setFlowControl(QSerialPort::HardwareControl);

```

Now whenever I launch the Qt program, the Arduino is ready to accept serial data.

# Answer
> 1 votes
Yes, there are differences.

* The Uno has an ATMega16U2 as a USB to UART bridge. When you open the serial port the ATMega16U2 signals to the ATMega328p to reset and start your sketch from the beginning.
* The Leonardo has an ATMega32U4 as the main MCU which is directly connected to the USB port. When you open the serial port you connect to your program wherever it happens to be at the time.

The key thing there is that when you open the Uno's port the board reboots and your sketch restarts. When you open the Leonardo's port the board *doesn't* reset and your sketch is wherever your sketch happens to be.

So: you have to ensure that your sketch doesn't rely on things in setup() or early on in its execution for making the serial connection work.

---
Tags: serial, arduino-ide, arduino-leonardo
---


# Question
Title: Smaller and cheaper alternative to Arduino Uno for permanent projects
I have played a bit around with a Arduino Uno that came in a kit with a breadboard and components. Soon I would like to make some more permanent things.

I would prefer a smaller and cheaper unit than the Arduino Uno but that is almost as easy to use as the Arduino Uno, and very similar to use.

Is the Arduino Pro Mini 328 - 5V/16MHz a logical next step? At 1/6 of the size of the Arduino Uno it is plenty small. At 10 $ a piece the price is also good.

I understand that I must solder to get it to work. That should not be a problem.

Will I also need a USB serial board to program the unit?

# Answer
> 12 votes
I think the first best choice is to remove the ATMega328p-pu chip from your Arduino UNO and incorporate it into your final circuit. The chips are only about $1.50.

That way, you can just use your UNO as a programmer instead of the final device that you deploy.

I'm not sure why there isn't more documentation about the proper way to remove the ATMega328p-pu chip and using it on your breadboard, after completing your programming.

I explain exactly how to do this on my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone

But, here are the basics. First you remove the chip. It will look like the following after you do so. (Note: I'm using the Elegoo clone of an UNO).

Next, you apply power to pin 7 and connect pin 8 to GND.

**Need A 16MHz Crystal**

But, the chip won't seem to run your sketch at this point. That's because you actually need a crystal to run at 16MHz.

The UNO board has that chip installed and that is why it works. You can see it here:

Finally you add the 16MHz crystal and a couple of 22pF caps and your chip will run standalone (no UNO).

You add the crystal to pins 9 & 10. You can see all the details by reading my blog entry or reading the atmega328 datasheet.

**Finally, Just Wire Everything Else Up**

After that, just wire the rest of your circuit up to the proper pins and you can run your ATMega328p-pu standalone.

It's actually a nice learning experience too.
Just buy replacement atmega328p-pu chips for your UNO and you can create all the projects you want to for very cheap.

# Answer
> 7 votes
Check the STM32F103C8T6 development board, cost about $ 1.5, and is faster/has more memory than the Arduino Uno, and is much smaller.

It can work with the Arduino IDE, but not all libraries are supported, so check before you want to use it if your used libraries are supported, or if there are different libraries you can use instead.

**Update**

Differences:

```
                       Arduino Uno       STM32F103C8T6 Mini Dev Board

MicroController            Atmega328P           Cortex M3
MIPS/MHz                        1                   1.25
Operating Voltage [V]           5                   3.3, most pins 5V tolerant
Input Voltage   [V]            7-12               USB only
Input Voltage (limit) [V]      6-20                (USB)
Digital I/O Pins               16                   37
From them:PWM Digital I/O Pins  6                   12
Analog Input Pins               6                   10
DC Current per I/O Pin [mA]    20                    ?
DC Current for 3.3V Pin [mA]   50                    ?
Flash [KB}                     32                   64
SRAM [KB]                       2                   20
EEPROM [KB]                     1                    -
Clock Speed [MHz]              16                   72

I2C                             1                    2
SPI                             1                    2 (18 MBit/s)
UART                            1                    3
CAN                             0                    1
USB                             0          USB 2.0 FS 12 MBit
DMA                             0          7 channels (ATsP, SPI, I2C, USART)
RTC                             0                    1
CRC                             0                    1
Unique ID                       0                    1

Programmed by                  USB                 SWD Debug (around $5)

IDE                         Arduino IDE         Arduino IDE, CubeMX, ...
Libraries                      Many               Limited

Dimensions  [mm]            68.6 x 53.4           53 x 22
Weight       [g]               25                    ?
Price (cheapest)  [$]         2.50                 1.50

```

Note: as written earlier, despite the mostly better specs, not all libraries are supported. Also a programmer need to be bought (only once, cost about $5).

# Answer
> 7 votes
For my product, I went from an Arduino Uno:

to the Arduino Pro Mini:

Yes you will need a FTDI cable for programming and serial coms to the PC, but providing you don't need coms all the time, you will only need the one cable to upload the program to each device. They can be found pretty cheap too.

However I notice that the Arduino Pro Mini is retired now, so it may be a bit harder to source (it is still available on AliExpress). So for this reason, I suggest that you instead try the Arduino Nano:

which has the added advantage of onboard USB, meaning you no longer need the FTDI cable for programming or coms.

The ATMega328P that is the processor of these 3 boards does not have native USB, which means that the board also needs to include the FTDI FT232RL IC that is used in the FTDI cable. Having this IC can add additional costs to your bottom line.

For a few dollars cheaper per device, you can use a microcontroller (such as the ATMega32U4) that has native USB coms (and hence you save on the FTDI IC). One such product is the Arduino Micro:

All of these boards mentioned are native within the Arduino Ecosystem and (apart from the retired Pro Mini) should be easy to source online or at your local electronics shop. Your Arduino Uno program will work for all of these alternatives - you just have to change the board in the Arduino IDE:

There is one more board that I would like to mention - the DigiSpark:

It is only suitable for smaller programs, is limited in some of its features and is not an oficial Arduino board. Having said that, there is plenty of Arduino support \- and its cheap!

# Answer
> 4 votes
I like the Nano and the Pro Mini. I like to work with it on a breadboard with other modules. If there is more circuitry involved I found it much more convenient than using an Uno. There are faster processors but for a lot of projects the 16Mhz 328 is more than sufficient. And like the Uno, these two are 5 volt powered parts. Sometimes what you need to connect to doesn't work well with 3.3 volt processors.

The Pro Mini and the Nano with easily be soldered into 0.1" spaced "Veroboard" (or equivalent) If you don't mind buying cloned parts, the cost of a Nano and Pro Mini is only a couple of dollars. Buying parts off Aliexpress, or even Ebay, can save you a lot, as long as you are patient when it comes to delivery.

The module that I am now use most often is the ESP8266. It is a powerful WiFi platform that only costs a few dollars and has quite a mature Arduino framework. Often I use this as the only processor in the design. I have even used it as the basis for a data logger and completely ignored the WiFi capability. 20x4 character LCD, current/voltage measurement chip (INA219), and a SD memory card, powered by a 18650 lithium battery.

There are lots of good inexpensive options.

# Answer
> 4 votes
If you want to stick with using Arduino and it's toolchain, you can order just a bare ATmega 328p (the microcontroller at the heart of the Arduino Uno) and use it by itself!

They're fairly low cost ($1.50-$3.00 range) and are breadboard friendly. For a more permanent solution, you can solder them into a proto-board (perfboard), or even a custom designed circuit board once your design gets to that level.

Here's an excellent guide from the Arduino folks about setting up an Arduino on a breadboard, using only raw components such as the ATmega 328p. This design uses an external 16MHz clock crystal, just like an Arduino Uno.

If you're OK with using the internal 8MHz clock onboard the 328p, you can do away with most of the extra components and just run the raw chip like in this guide (using the Arduino Lilypad Bootloader instead of the default Arduino bootloader). This will save even more money!

Either way, you'll need an AVR Programmer unit, since there is no USB port built into the 328p. This will be the most expensive part of this setup, but good news is you only need one, and it can program any 328p's you need. They can also be used to program non-standard chips that are capable of being programmed over Serial Tx/Rx pins, such as the ESP chips (you just hand-wire them). Very useful to have one of these if you're serious about these types of microcontrollers.

ATmega 328p Microcontroller Chip

ATMega Pin Stickers

Perfboard

AVR Programmer

# Answer
> 2 votes
Arduino Pro Micro clones are super cheap and all you need to program them is a normal micro USB cable. You will probably have to solder the headers to do anything useful. They are available in a 3.3V/8MHz and a 5V/16Mhz version.

---
Tags: arduino-uno
---


# Question
Title: Cannot compile code from Arduino WIFI shield example
I'm trying to launch the piece of code in this Wifi example: https://www.arduino.cc/en/Reference/WiFiConfig via Arduino.cc online editor, but I'm getting those errors:

```
/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:87:24: error: 'PINS_COUNT' was not declared in this scope

```

and

```
/home/ubuntu/opt/libraries/latest/wifinina_1_2_0/src/utility/spi_drv.cpp:97:15: error: 'NINA_GPIO0' was not declared in this scope

```

Do someone has an idea of how to solve this?

# Answer
> 3 votes
Those kinds of errors are usually caused by the selection of an incorrect hardware in the IDE.

Choosing a correct board in the IDE will solve the compilation issue.

Since you said that you used the Arduino.cc online editor, I pasted your code into the editor.

You did not say which Arduino board or which WiFi module you are using, so I chose `Arduino Uno WiFi` board as a starting point.

Compiling the code produced the same errors as in the post.

Next I chose `Arduino Uno WiFi Rev2` board, and compiled without errors.

---
Tags: arduino-uno-wifi
---


# Question
Title: how to use arduino to detect an 8Mhz ultrasonic pulse using piezo disc as receiver?
i need a code to detect an 8MHz ultrasonic pulse and show its properties eg wave pattern and amplitude on serial plotter( like an oscilloscope)

# Answer
> 0 votes
In a word: no.

Let's crunch some numbers... You want detail like an oscilloscope. Okay...

My scope is 50MHz bandwidth and runs at 1 giga samples per second.

Drop that down to 8MHz with the same kind of resolution, and you get (1,000,000,000 * (8/50)) = 160,000,000 samples per second.

That's 10 times more samples per second that the clock speed of the Arduino, and it takes at least 1664 clock cycles to take one sample.

So, no. You need a board with an ADC which can run in the hundreds of millions of samples per second. The Arduino can only run at just under 10 thousand samples per second.

A slight discrepancy.

Even the Arduino Due can only get as good as 1Msps. I have seen MCUs with 15Msps theoretical maximum, but for the kind of output you want you would need considerably more.

So no, there won't be a cheap development "Arduino-like" board around that will do what you want. There may be an expensive one with a very fast CPU, DSP, ultra-high-speed ADC, etc, but you won't be programming it with Arduino, and you most likely won't be able to afford it to just play with.

---
Tags: programming
---


# Question
Title: If a condition is ever met I want to run a loop permanently
I am trying to run an LED to do SOS in morse code if a temperature is over 20 C and motion is detected, but I want it to continue doing SOS even after the motion goes away or the temperature comes down.

Right now it simply does SOS 1 time and stops.

(sorry if coding is messy)

```
   int counter;
   int motion = 0;

   void setup()
  {

    {Serial.begin(9600);
     pinMode(4, INPUT);
     pinMode(0, OUTPUT);
     pinMode(2, OUTPUT);
     pinMode(1, INPUT);
     digitalWrite(0, HIGH);

     }
  }

    void loop()
   {

   int sensorA0Value = analogRead(A0);
   float voltage = sensorA0Value * (5.00 / 1023.00);
   Serial.print("Voltage: ");
   Serial.print(voltage);

   float temp = (voltage -.5)*100;
   Serial.print("| Temp: ");
   Serial.print(temp);
   Serial.println(" Celcius|");

   motion = digitalRead(4);

   if(motion == HIGH)
    {Serial.println("Motion Detected");}
   if(motion == LOW)
     {Serial.println("No Motion");}

   if(motion == HIGH && temp > 30)
     {
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);

     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);
     delay(600);
     digitalWrite(2, HIGH);
     delay(600);
     digitalWrite(2, LOW);

     delay(600);
     digitalWrite(2, HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(300);
     digitalWrite(2,HIGH);
     delay(300);
     digitalWrite(2, LOW);
     delay(1000);

   }
     else {
     digitalWrite(2, LOW);

     }
   delay(1000);
    }

```

# Answer
You could use a `while`-loop like this:

```
if(motion == HIGH && temp > 20) {
  while(true){
   SosMethod();
   }
}

```

to clean everything up, then outside your `void loop()` you declare your `SOSMethod()`

```
void loop() {
 ... .
 }

 void SosMethod(){
 your-led-code-with-delays
 }

```
> 0 votes

# Answer
It seems this is your SOS code:

```
if(motion == HIGH && temp > 30)
{
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);

 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);

 delay(600);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(1000);
}

```

Step 1: I think you want to send the first S (.-.-.-.-) as 3 sequences instead of 2 sequence, so the code is:

```
if(motion == HIGH && temp > 30)
{
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);

 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);
 delay(600);
 digitalWrite(2, HIGH);
 delay(600);
 digitalWrite(2, LOW);

 delay(600);
 digitalWrite(2, HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(300);
 digitalWrite(2,HIGH);
 delay(300);
 digitalWrite(2, LOW);
 delay(1000);
}

```

Step 2: Reduce the duplicate code (each 6 sequences of digitalWrite and delay), you will get:

```
if(motion == HIGH && temp > 30)
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

void send(int delayTime)
{
   for (length = 0; length < 3; length++)
   {
      digitalWrite(2, HIGH);
      delay(delayTime);
      digitalWrite(2, LOW);
      delay(600);
   }
}

```

Than you want to fix your problem to keep it sending Instead of

```
if(motion == HIGH && temp > 30)
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

```

Use

```
while ((motion == HIGH) && (temp > 30))
{
  send(300);
  send(600);
  send(300);
  delay(1000);
}

```

For easy reading, I always use parenthesis around equal conditional operator (like ==, \>). The variables motion and temp will not be changed in the while loop, so you can use a while here. It is assumed that the variables are not changed in an interrupt.
> 0 votes

# Answer
This may be unrelated to the actual question but... your Morse timings are completely messed up. The standard timings are:

```
element         duration
------------------------
dot                 1
dash                3
interelement gap    1
intercharacter gap  3
interword gap       7

```

where the time unit is the duration of a dot. A correctly timed SOS can be implemented as follows:

```
const uint32_t DOT_TIME = 150;  // 8 words per minute

void dot() {
    digitalWrite(2, HIGH);
    delay(1 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void dash() {
    digitalWrite(2, HIGH);
    delay(3 * DOT_TIME);
    digitalWrite(2, LOW);
    delay(1 * DOT_TIME);
}

void send_sos() {
    dot(); dot(); dot();
    dash(); dash(); dash();
    dot(); dot(); dot();
    delay(6 * DOT_TIME);  // interword gap
}

```

Notice that there are no intercharacter gaps within SOS, as this is a procedural signal, transmitted with no letter boundaries. It is *not* a three-letter word. The last delay is written as `6 * DOT_TIME` as there is already a one `DOT_TIME` delay at the end of the function `dot()`.
> 0 votes

---
Tags: programming, loop
---


# Question
Title: How to solve this "xpected primary-expression before ',' token"
I'm new in this arduino world, and I'm having some trouble. I am programming something for a school assignment. The program gives an error, and my teacher also doesn't know how to solve it. Maybe someone can help me?

```
#include <CapacitiveSensor.h>
#define speaker

CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);

int s1;
int s2;
int s3;
int s4;
int s5;
int s6;
int s7;
int s8;

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

void loop()
{

  s1 =  cs_2_3.capacitiveSensor(3000);
  s2 =  cs_2_4.capacitiveSensor(3000);
  s3 =  cs_2_5.capacitiveSensor(3000);
  s4 =  cs_2_6.capacitiveSensor(3000);
  s5 =  cs_2_7.capacitiveSensor(3000);
  s6 =  cs_2_8.capacitiveSensor(3000);
  s7 =  cs_2_9.capacitiveSensor(3000);
  s8 =  cs_2_10.capacitiveSensor(3000);

  Serial.print("s1: ");
  Serial.println(s1);
  Serial.print("s2: ");
  Serial.println(s2);
  Serial.print("s3: ");
  Serial.println(s3);
  Serial.print("s4: ");
  Serial.println(s4);
  Serial.print("s5: ");
  Serial.println(s5);
  Serial.print("s6: ");
  Serial.println(s6);
  Serial.print("s7: ");
  Serial.println(s7);
  Serial.print("s8: ");
  Serial.println(s8);

  if (s1 > 500){
    tone(speaker,131);
   }
  else if (s2 > 500){
    tone(speaker,147);
   }
  else if (s3 > 500){
    tone(speaker,165);
   }
  else if (s4 > 500){
    tone(speaker,175);
   }
  else if (s5 > 500){
    tone(speaker,196);
   }
  else if (s6 > 500){
    tone(speaker,220);
   }
  else if (s7 > 500){
    tone(speaker,247);
   }
  else if (s8 > 500){
    tone(speaker,262);
   }

  if (s1<=500  &&  s2<=500  &&  s3<=500 && s4<=500  &&  s5<=500  &&  s6<=500 &&  s7<=500 &&  s8<=500){
    noTone(speaker);
  }
}

```

# Answer
> 4 votes
This:

```
#define speaker

```

defines "speaker" as nothing, an empty string. Then:

```
tone(speaker,131);

```

is translated into

```
tone(,131);

```

which makes no sense. The compiler expected to find an expression before the comma.

---
Tags: programming
---


# Question
Title: Need some help in coding a "timer" in an if else statement
I want to code something like a "timer" (don't know what to call it) in an if else statement in my arduino uno.

Basically I have 2 buttons. If the button1 is pressed and button2 is also pressed in a certain amount of time (let's say 3 seconds), the code will execute. If button1 is pressed but button2 is not pressed within 3 seconds then it will loop back up. How do I go about writing this code?

I've included a flowchart to make my question clearer.

Thanks all :)

```
if(digitalRead(button1) == LOW)       // this is where I need help
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=30; x++)
    {
      digitalWrite(dir, HIGH);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 50)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 50)
      {
      }
    }
    x=0;
  }
}

else if(digitalRead(button2) == LOW)    //same here >_<
{
  if(digitalRead(selectbutton) == LOW)
  {
    for(x=1; x<=10; x++)
    {
      digitalWrite(dir, LOW);
      delayMicroseconds(10);
      time_now = millis();
      digitalWrite(led, HIGH);
      while(millis() < time_now + 150)
      {
      }

      time_now = millis();
      digitalWrite(led, LOW);
      while(millis() < time_now + 150)
      {
      }
    }
    x=0;
  }
}

```

}

# Answer
Your flowchart seems to be in conflict with the code. `button1` and `button2` are self-explainatory, but what is the `selectButton`?

Here's some code which may accomplish what you're trying to do:

```
uint8_t bool_waitforbutton2 = 0;
uint32_t num_timeatbutton1 = 0;
void loop() {
  //your other looping code here
  if(digitalRead(button1) == LOW) {
    num_timeatbutton1 = millis();
    bool_waitforbutton2 = 1;
  }
  if(bool_waitforbutton2 == 1 && digitalRead(button2) == LOW){
    bool_waitforbutton2 = 0;
    //Your code here
  }
  if (millis() > (num_timeatbutton1 + 3000)) {
    bool_waitforbutton2 = 0;
  }
}

```

This would give you 3000 ms to press `button2` after you've let go of `button1` to execute your code, otherwise the "readyness-flag" `bool_waitforbutton2` is reset.
> 2 votes

# Answer
A flowchart is not bad, but it's not really the most appropriate kind of diagram for this sort of problems. You should try to think in terms of finite state machines instead, which is a very useful concept whenever you try to implement “reactive” systems, i.e. systems that have to react to some kind of input.

Here is your problem, as I understand it, translated into a state diagram:

This system has two states:

* “waiting”, when it waits for the first button to be pressed
* “stand by” when the first button has been pressed and it waits for the second.

Pressing button 1 makes a transition from “waiting” to “stand by”. The transition back to the initial “waiting” state can be triggered by two distinct events:

* 3 seconds spent in the “stand by” state
* the user pressing button 2.

Note that in the second case, the system runs your code while making the transition.

Once you have the state diagram, and assuming you have read (and understood) the finite state machine tutorial I linked to, translating the diagram into code is almost trivial.
> 3 votes

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


# Question
Title: Can I use arduino to generate 8mhz frequency ultrasonic pulses in piezo discs?
```
void setup()
{
    pinMode(freqOutputPin, OUTPUT);
    Serial.begin(9600);

    // Set Timer 2 CTC mode with no prescaling.  OC2A toggles on compare match
    //
    // WGM22:0 = 010: CTC Mode, toggle OC
    // WGM2 bits 1 and 0 are in TCCR2A,
    // WGM2 bit 2 is in TCCR2B
    // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
    //
    TCCR2A = ((1 << WGM21) | (1 << COM2A0));

    // Set Timer 2  No prescaling  (i.e. prescale division = 1)
    //
    // CS22:0 = 001: Use CPU clock with no prescaling
    // CS2 bits 2:0 are all in TCCR2B
    TCCR2B = (1 << CS20);

    // Make sure Compare-match register A interrupt for timer2 is disabled
    TIMSK2 = 0;
    // This value determines the output frequency
    OCR2A = ocr2aval;

    Serial.print("Period    = ");
    Serial.print(period);
    Serial.println(" microseconds");
    Serial.print("Frequency = ");
    Serial.print(freq);
    Serial.println(" Hz");
}

void loop(){}

```

I am working on a project where i need an ultrasonic pulse of 8Mhz every one second and emitter is piezo disc. Please help me with the code.

# Answer
With 8 Mhz pulse, I assume you mean a pulse of 0.125 µs duration every second. "Frequency" may be misleading here.

Since the ATmega328 in the Arduino Uno is only clocked at 16 Mhz, you only have one extra cycle before having to turn it back off. Debugging and developing at this sort of speed absolutely requires a good oscilloscope.

I would attempt setting your output pin via register, and then turning it off again right after. Use `cli()` to prevent interrupts during your desired pulse.

```
void setup() {
  DDRC |= (1 << DDRC0);   //Set PC0 as output (Analog Pin 0)
}
void loop() {
  cli();                  //Disable interrupts
  PORTC = 0b00000001;     //Set Analog Pin 0 HIGH
  PORTC = 0b00000000;     //Set Analog Pin 0 LOW
  sei();                  //Enable interrupts again
  delay(1000);            //Delay for 1000ms until next pulse
}

```

Beware that this would also set all other pins on Port C (Analog Pins 1 through 5) LOW.

This

```
  PORTC |= (1 << PORTC0);     //Set Analog Pin 0 HIGH
  PORTC &= ~(1 << PORTC0);     //Set Analog Pin 0 LOW

```

would be cleaner and only affect Analog Pin 0, but it may take more than one clock cycle to execute. Unfortunately, I don't have a quick enough oscilloscope to try this out. If it is too fast (e.g., you get a pulse of duration 0.06125 µs, you may want to insert another `PORTC = 0b00000001;` before turning it off again. It is not unlikely that compiler optimization might just remove this when compiling, so you may have to set some other register to waste that one clock cycle.
> 1 votes

---
Tags: programming, timers, frequency
---


# Question
Title: Controlling stepper motor direction with push buttons
I'm trying to control the direction of three 28byj-48 stepper motors using the ULN2003 drivers. I am using 6 push buttons, 2 for each motor. what I want is for each motor to be stationary by default and rotate forward when I press on one button and reverse when I press the other.

You can find my code below. When I use the same approach for coding for one motor, it works fine with a suitable speed. But once I add all 3 motors, motor A and C perform fine but with low speed, motor B keeps rotating forward from the start, stops while I'm pushing its forward button and nothing happens when I push its reverse button. I have checked my circuit several times and there's nothing wrong with it.

```
#include <Stepper.h> //including stepper motor library

//defining pins section

// pins for motor A:
int stepAIN1Pin = 5;
int stepAIN2Pin = 4;
int stepAIN3Pin = 3;
int stepAIN4Pin = 2;

// pins for motor B:
int stepBIN1Pin = 9;
int stepBIN2Pin = 8;
int stepBIN3Pin = 7;
int stepBIN4Pin = 6;

// pins for motor C:
int stepCIN1Pin = 13;
int stepCIN2Pin = 12;
int stepCIN3Pin = 11;
int stepCIN4Pin = 10;

int stepsPerRevolution = 2048; // amount of steps per revolution for the 28BYJ48 motor

int buttonA1Pin = A5;  // pushbutton 1 pin for clockwise rotation of motor A
int buttonA2Pin = A4;  // pushbutton 2 pin for counter clockwise rotation of motor A

int buttonB1Pin = A3;  // pushbutton 1 pin for clockwise rotation of motor B
int buttonB2Pin = A2;  // pushbutton 2 pin for counter clockwise rotation of motor B

int buttonC1Pin = A1;  // pushbutton 1 pin for clockwise rotation of motor C
int buttonC2Pin = A0;  // pushbutton 2 pin for counter clockwise rotation of motor C

Stepper myStepperA(stepsPerRevolution, stepAIN1Pin, stepAIN3Pin, stepAIN2Pin, stepAIN4Pin); // stepping sequence for motor A

Stepper myStepperB(stepsPerRevolution, stepBIN1Pin, stepBIN3Pin, stepBIN2Pin, stepBIN4Pin); // stepping sequence for motor B

Stepper myStepperC(stepsPerRevolution, stepCIN1Pin, stepCIN3Pin, stepCIN2Pin, stepCIN4Pin); // stepping sequence for motor C

void setup()
{
  // Setting up the pushbutton pins to be an input:
  pinMode(buttonA1Pin, INPUT);
  pinMode(buttonA2Pin, INPUT);

  pinMode(buttonB1Pin, INPUT);
  pinMode(buttonB2Pin, INPUT);

  pinMode(buttonC1Pin, INPUT);
  pinMode(buttonC2Pin, INPUT);

myStepperA.setSpeed(15); // Setting the speed for motor A

myStepperB.setSpeed(15); // Setting the speed for motor B

myStepperC.setSpeed(15); // Setting the speed for motor C
}

void loop()
{

int buttonA1State, buttonA2State, buttonB1State, buttonB2State, buttonC1State, buttonC2State;

  buttonA1State = analogRead(buttonA1Pin);
  buttonA2State = analogRead(buttonA2Pin);

 if ((buttonA1State != 0) && !(buttonA2State != 0))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(stepsPerRevolution/8);

 if (((buttonA2State != 0) && !(buttonA1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperA.step(-stepsPerRevolution/8);

  buttonB1State = analogRead(buttonB1Pin);
  buttonB2State = analogRead(buttonB2Pin);

 if (((buttonB1State != 0) && !(buttonB2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(stepsPerRevolution/8);

 if (((buttonB2State != 0) && !(buttonB1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperB.step(-stepsPerRevolution/8);

  buttonC1State = analogRead(buttonC1Pin);
  buttonC2State = analogRead(buttonC2Pin);

 if (((buttonC1State != 0) && !(buttonC2State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(stepsPerRevolution/8);

 if (((buttonC2State != 0) && !(buttonC1State != 0)))  // if we're pushing button 1 and NOT button 2
  myStepperC.step(-stepsPerRevolution/8);

  }

```

# Answer
> 3 votes
Try using `digitalRead()` for button presses. Chances are your buttons, especially when on a breadboard, don't return exactly 0 for `analogRead()`.

IMHO, simple On-Off switches should always connect your pin to either Vcc or GND, with either the internal pullup turned on (if connected to GND), or an external pulldown resistor in place.

To debug this, you might want to `Serial.println()` the values of your button states to your Arduino IDE and observe if their values are like you'd expect.

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


# Question
Title: Trying to use a 7 segment display to count 0/9 with a potentiometer
im trying to switch number on the display using a potentiometer, it is just counting from 0/9. All help is much appreciated!

```
int SegmentA = 6;
int SegmentB = 7;
int SegmentC = 8;
int SegmentD = 9;
int SegmentE = 10;
int SegmentF = 11;
int SegmentG = 12;

const int PP = A0;

void setup()
{
  pinMode (SegmentA, OUTPUT);
  pinMode (SegmentB, OUTPUT);
  pinMode (SegmentC, OUTPUT);
  pinMode (SegmentD, OUTPUT);
  pinMode (SegmentE, OUTPUT);
  pinMode (SegmentF, OUTPUT);
  pinMode (SegmentG, OUTPUT);

}

void loop() {

  int POD = analogRead(PP);
  int SM = map(POD, 0, 1023, 0 , 8);
  switch (SM) {

    case 0:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //0
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 1:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //1
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 2:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, LOW);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //2
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 3:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //3
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 4:
      digitalWrite (SegmentA, LOW);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //4
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 5:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, LOW);   //5
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 6:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, LOW);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //6
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

      delay(1000);

    case 7:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, LOW);
      digitalWrite (SegmentE, LOW);   //7
      digitalWrite (SegmentF, LOW);
      digitalWrite (SegmentG, LOW);

      delay(1000);

    case 8:
      digitalWrite (SegmentA, HIGH);
      digitalWrite (SegmentB, HIGH);
      digitalWrite (SegmentC, HIGH);
      digitalWrite (SegmentD, HIGH);
      digitalWrite (SegmentE, HIGH);   //8
      digitalWrite (SegmentF, HIGH);
      digitalWrite (SegmentG, HIGH);

  }

}

```

# Answer
You miss the break statement at the end of each case. e.g.:

```
  digitalWrite (SegmentF, LOW);
  digitalWrite (SegmentG, HIGH);

  delay(1000);

  break;

case 4:

```

This causes each case to perform, and continue with the next case. However, since there is a delay of 1 second, it looks like it is counting.

Actually, I would expect it counts from a certain value depending on the pot meter to 7, since there is no digit 9 implemented, and the delay for the 8 digit is missing too.

To further improve your code, you can add the delay not in every case but at the end, since I assume there always will be one digit selected.

Also you can make a function void showDigit with a parameter for each of the possible segment states and replace all (almost) duplicated code by that function call, or send the digit and use showDigit to set internally the states of each segment (by using a boolean array\[nr\_of\_digits\]\[nr\_of\_segments\], somewhat like Nic Hartley proposes below.
> 9 votes

# Answer
You'll want a single delay (if any) at the bottom of the loop() function. You may not need it since it will keep displaying the current digit until you move the potentiometer. Exception: if the pot is near the edge between 2 digits, you could see some dithering.

Replace the delay-calls in the `case`s with `break;` statements. Otherwise whichever case you call will fall through into the case below it, and so on, displaying subsequent each digit in turn, which isn't what you wanted (and is what you are already seeing).

Change the map() call to `map(POD, 0, 1024, 0 , 10)`. Otherwise there will be no '9' band on potentiometer and the '8' band will be only 1 value wide (out of 1023): exactly the value "1023". You'd like the '9' band to be about as wide as all of the others. It's even possible that a given potentiometer won't get close enough to zero resistance for you to get a 1023 reading.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)?
All of the wiring diagrams I've found for wiring up a GY-521 accelerometer to an Arduino have looked something like this:

I've read in several places that it needs to be connected to `A4` and `A5`. I want to connect one to a SparkFun ThingDev, which unfortunately only has a single analog input:

Is this possible?

I only need it for a very simple application (finding out if a machine is vibrating or not).

# Answer
A4 and A5 on the Arduino double as the I2C pins SDA and SCL. You are communicating with I2C, not analog.

The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins. The pinout you show has I2C labeled on pins 2 and 14. While you *can* use those you could use any two pins of your choosing.

Note that I2C on the ESP8266 has a slightly different begin function:

```
Wire.begin(2, 14);

```

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.
> 1 votes

---
Tags: esp8266, accelerometer
---


# Question
Title: Trouble configuring Arduino Due SPI to ADC
I am having trouble configuring Arduino Due SPI to an AD7490 ADC.

Here is how I have the pins connected:

* +3.3V \> 7490 pin 22 Vin
* +3.3V \> 7490 Vref
* DUE CS (8) \> 7490 pin 20 SS - slave select)
* DUE SCK \> 7490 pin 16 (SCK - clock)
* DUE MOSI \> 7490 pin 19 (MOSI - data out)
* Ground \> 7490 pin 24 (all ground lines are tied together)
* DUE MISO \> 7490 pin 15

Below is my code, I feel like I am writing the correct bits into the register. The problem I think I'm having is getting the timing write. The code is a simple attempt to read a single channel.

```
#include <SPI.h>

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the
ADC:

// Start setup function:
void setup() {

pinMode (adcChipSelectPin, OUTPUT);
// set the ChipSelectPins high initially:
digitalWrite(adcChipSelectPin, HIGH);
// initialise SPI:
SPI.begin();
SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be
sure.
SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be
sure.
Serial.begin(9600);
//Clock Speed: Master clock/divider
//84Mhz/64 =  1.3 MHz
SPI.setClockDivider(SPI_CLOCK_DIV64);

} // End setup function.

// Start loop function:
void loop() {
float voltage[2];
for (int i = 0; i < 3; i++) {
voltage[i] = readAdc(0, 0);
}

}// End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {

float value;
if (slave == 0) {
noInterrupts(); // disable interupts to prepare to send address data to the
ADC.
digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to
select the ADC.

byte FirstByte = 0b10000011;
byte SecondByte = 0b00110000;

SPI.transfer(FirstByte);

byte response1 = SPI.transfer(SecondByte);
byte response2 = SPI.transfer(0x00);

digitalWrite(adcChipSelectPin, HIGH); // take the Chip Select pin high to
de-select the ADC.
interrupts(); // Enable interupts.
Serial.println(response1);
Serial.println(response2);

}

```

The serial.prints output 255 consistently. In my experience this means the SPI is configured incorrectly.

Any pointers are appreciated.

# Answer
> 1 votes
For anyone else who comes across the same problem, this worked for me:

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

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the ADC:

// Start setup function:
void setup() {
    pinMode (adcChipSelectPin, OUTPUT);

    // set the ChipSelectPins high initially:
    digitalWrite(adcChipSelectPin, HIGH);

    // initialise SPI:
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be sure.
    SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be sure.
    Serial.begin(9600);

    //Clock Speed: Master clock/divider
    //84Mhz/64 =  1.3 MHz
    SPI.setClockDivider(SPI_CLOCK_DIV64);

    //Send dummy values over when ADC is turned on
    //Hold Din High for 16 clock cycles twice
    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);

    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    //Send dummy values, next read should have correct values

    digitalWrite(adcChipSelectPin, LOW);
    byte FirstByte = 0x83;
    byte SecondByte = 0x50;
    byte response1 = SPI.transfer(FirstByte);
    byte response2 = SPI.transfer(SecondByte);

    digitalWrite(adcChipSelectPin, HIGH);

    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    ///////////////////////////////////////////////////////////////////////////////////

    //50ns quiet time?
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
} // End setup function.

// Start loop function:
void loop() {
    float voltage[2];
    for (int i = 1; i < 17; i++) {
        voltage[i] = readAdc(0, 1);
        //50ns quiet time?
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
    }
} // End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {
    float value;
    if (slave == 0) {
        byte FirstByte = 0x83;
        byte SecondByte = 0x50;
        FirstByte |= channel << 2;

        noInterrupts(); // disable interupts to prepare to send address data to the ADC.

        digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to select the ADC.
        //Write = 1
        //SEQ = 0
        // ADD3-ADD0 = 0000
        //PM1 = PM0 = 1
        //Shadow = 0
        //WEAK/Tri = 1
        //Range = 0
        //Coding = 1
        //0b10000010 1010 0000
        //extra 4 zeros to fill

        //May need to wait 16 * (1/freq)
        //16 * (1/1.3MHz)
        byte response1 = SPI.transfer(FirstByte);
        byte response2 = SPI.transfer(SecondByte);
        digitalWrite(adcChipSelectPin, HIGH);

        interrupts(); // Enable interupts.

        //Serial.println(response1);
        Serial.println(response2);
        byte channel = (response1 >> 4);
        //byte value = (response1 << 4);
        //byte digitalValue = (response1 << 4) | response2;
        //Serial.println(digitalValue);
        //Serial.println(channel);

        byte digitalValue = 0x00;
        float value = (float(digitalValue) * 3.3) / 4096.000; // The digital value is
        converted to an analogue voltage using a VREF of 2.048V.
        //Serial.print(channel);
        //Serial.print("\t");
        //Serial.println(value);
    }
}

```

---
Tags: arduino-due, spi, adc
---


title: How can I simulate an accelerometer?

text:
# Question
Title: How can I simulate an accelerometer?
I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

# Answer
Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g. This means you have a signal averaging at "338" when read using Arduino's `analogRead()` function, with spikes in either direction when acceleration changes.

You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:

```
int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  }
  else if (num_random == 0) {
    num_xaxis -= 200;
  }
  else if (num_random < 100) {
    num_xaxis += 1;
  }
  else if (num_random > 155) {
    num_xaxis += 1;
  }
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  }
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;
  }
  Serial.println(num_xaxis);
  delay(10);
}

```

Explanation: First, the value for 0g is determined from the voltage difference. A random value is generated, ranging from 0 to 255. If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added. If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.

The serial commands only serve to let you watch the result in Arduino IDE's serial plotter. If you need the spike to occur less frequently, adjust the `delay()`, or let the counter run to higher numbers. If the CPU-blocking `delay()` command is an issue in your project, you could run the randomization code using a timer and an interrupt.

Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num\_random is below 100 and +1 if it is above 155).
> 5 votes

---
Tags: accelerometer
---


# Question
Title: can homemade arduino be powered up with battery?
I am new to arduino. It is costly for me to buy an arduino uno board. Therefore I am going to make a Arduino with breadboard at my home. I also want to make my Arduino portable. Arduino Uno boards can be powered up with battery. But can I do so with my homemade Arduino? If it is possible, what things need to be included in my homemade Arduino?

# Answer
First, of course, you'll need a battery with enough capacity, and voltage enough greater than 5v (assuming you want to run your home-built at 5v - typical, but you could run it lower, say 3.3v) to give enough run-time before the battery discharges to where it can no longer supply the system. Note that the 9v, so-called "Transistor battery" is not capable of supplying much current. A battery pack of off-the-shelf alkaline batteries or rechargables, or a Lithium Polymer rechargable battery will do much better.

You'll need a low dropout voltage regulator to reduce the battery voltage to your chosen Arduino supply voltage. National Semiconductor's LM1117 would be a good choice. The diagram below from NS's datasheet shows a simple-to-make voltage regulator. Its input is your battery; its output will be the supply voltage to the chip and any accessory circuitry.
> 3 votes

# Answer
Yes you can power it from a battery, as long as you add a 5V regulator to your board. You might get strange behaviour when the battery is running low.

These links all tell you what you need to build the board, good luck.

https://www.arduino.cc/en/Main/Standalone

http://www.instructables.com/id/How-to-make-your-own-Arduino-board/

http://www.instructables.com/id/DIY-Arduino-or-The-DIY-Duino/
> 2 votes

# Answer
I mostly use two AA batteries to power my 'standalone' ATMega328s. One of the downsides of this, is that you can't run the ATMega at 16Mhz, but only at 8Mhz. I don't mind that, as running at a slower speed reduces the current usage.

You could use 3 AA batteries, or 4 rechargeable AA batteries, instead to get a voltage that is closer to 5V

To get your circuit to run for more than a couple of days, you have to implement ways of reducing the current consumption. One of the first things would be to put the processor into sleep mode.
> 1 votes

# Answer
You can use 9 Volt batteries to power most Arduino Boards. For instance the Mega 2560 has a rated Vin range of 7 to 12 Volts. A car battery can be used for longer life, although not nearly as portable as a 9 Volt one with a clip. I'd recommend a common 7809 Positive Voltage Regulator TO-220 between a car battery charged using a car alternator and an Arduino board though, because the Voltage may vary quite a bit above the 12 V maximum.

I've used batteries with microprocessors for years for various embedded applications where access to AC is inconvenient, impractical, or nearly impossible.

The Mega page on the Arduino site explicitly permits battery power 1.

**Helpful Guidelines**

Here are some important criteria to meet.

* The Voltage is within the published range for the Arduino model you are using
* The positive of the battery supply connected to Vin (NOT any of the other power pins)
* The negative of the battery supply is connected to Gnd
* Critical applications don't run under the assumption that the battery will never drop below the minimum of the published supply range
* The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

**Connection Safety Using Plug and Jack**

If you are connecting and disconnecting the Arduino from your battery frequently or you just want .

See the Power section of the pageto make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack 2. When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.

**Battery Use in Robotics and Flight Control**

A 9V battery will eventually drop in Voltage below the rated minimum, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 3.

Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU. The Atmel CPU used by the Arduino Mega 2560 4 has a Brown-Out Detection feature 5.

A simpler approach for critical applications is a resistor divider on an analog input is another related approach.

.....

*\[1\] See the Power section of this page https://www.arduino.cc/en/Main/ArduinoBoardMega*

*\[2\] Information about compatible plugs is at http://forum.arduino.cc/index.php?topic=4892.0.*

*\[3\] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino. They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel (See https://electronics.stackexchange.com/questions/177204/will-connecting-two-batteries-in-parallel-increase-current-drawn-in-simple-led-c and http://www.zbattery.com/Connecting-Batteries-in-Series-or-Parallel).*

*\[4\] http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561\_datasheet.pdf*

*\[5\] The Atmel CPU for the Due and other boards have under-voltage detection too.*
> 1 votes

# Answer
You can also use two 18650 batteries as they have a higher charge capacity

Each battery is about 3.7-4.2 V

That would be perfect for arduino....
> 0 votes

---
Tags: power, avr, battery
---