# Question
Title: Out of two logically similar sketches, one works while the other does not
I am currently making a project involving a self balancing bot & found this code online:

```
#include "PID_v1.h"
#include "LMotorController.h"
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

#define MIN_ABS_SPEED 20

MPU6050 mpu;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorFloat gravity;    // [x, y, z]            gravity vector
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

//PID
double originalSetpoint = 178.57;
double setpoint = 178.57;
double movingAngleOffset = 0.1;
double input, output;
double Kp = 50;
double Kd = 1.4;
double Ki = 60;
PID pid(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);

double motorSpeedFactorLeft = 0.6;
double motorSpeedFactorRight = 0.5;
//MOTOR CONTROLLER
int ENA = 5;
int IN1 = 6;
int IN2 = 7;
int IN3 = 8;
int IN4 = 9;
int ENB = 10;
LMotorController motorController(ENA, IN1, IN2, ENB, IN3, IN4, motorSpeedFactorLeft, motorSpeedFactorRight);

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady()
{
    mpuInterrupt = true;
}

void setup()
{
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(262);
    mpu.setYGyroOffset(-29);
    mpu.setZGyroOffset(-10);
    mpu.setXAccelOffset(-2109);
    mpu.setYAccelOffset(394);
    mpu.setZAccelOffset(1341); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0)
    {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();

        //setup PID

        pid.SetMode(AUTOMATIC);
        pid.SetSampleTime(10);
        pid.SetOutputLimits(-255, 255);
    }
    else
    {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }
}

void loop()
{
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize)
    {
        //no mpu data - performing PID calculations and output to motors

        pid.Compute();
        motorController.move(output, MIN_ABS_SPEED);

    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024)
    {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    }
    else if (mpuIntStatus & 0x02)
    {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        #ifdef LOG_INPUT
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif
        input = ypr[1] * 180/M_PI + 180;
        Serial.println(input);
   }
}

```

The repo is linked to https://github.com/kurimawxx00/arduino-self-balancing-robot

My code is as below:

```
    /* For documentation purposes
 *
 * #define MPU6050_INTERRUPT_FF_BIT            7
 * #define MPU6050_INTERRUPT_MOT_BIT           6
 * #define MPU6050_INTERRUPT_ZMOT_BIT          5
 * #define MPU6050_INTERRUPT_FIFO_OFLOW_BIT    4
 * #define MPU6050_INTERRUPT_I2C_MST_INT_BIT   3
 * #define MPU6050_INTERRUPT_PLL_RDY_INT_BIT   2
 * #define MPU6050_INTERRUPT_DMP_INT_BIT       1
 * #define MPU6050_INTERRUPT_DATA_RDY_BIT      0
 *
  */

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "PID_v1.h"
#include "LMotorController.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include <Wire.h>
#endif

#define MIN_SPEED 20

#define DEBUG_BUILD

MPU6050 mpu;

// Variables for MPU status and control
bool isDMPReady = false;
uint8_t dmpStatus; // 0 if initialization succeeds
uint16_t dmpPacketSize; // default = 42
uint16_t fifoCount;
uint8_t fifoBuffer[64];
uint8_t mpuIntStatus;

// Variables for calculated data from DMP
Quaternion q; // // holds QUAT_W, QUAT_X, QUAT_Y, QUAT_Z from FIFO
int16_t gyro[3]; // Holds rotation
VectorFloat gravity; // holds gravity vector calculated from DMP
float ypr[3]; // 0 = yaw, 1 = pitch, 2 = roll

// PID data
double setPoint = 178.57;
double input = setPoint, output;
double Kp = 50;
double Kd = 1.4;
double Ki = 60;
PID pid(&input, &output, &setPoint, Kp, Ki, Kd, DIRECT);

// Motor config
const int inA = 6;
const int inB = 7;
const int inC = 8;
const int inD = 9;
const int enA = 5;
const int enB = 10;
const double motorCorrectionA = 0.6;
const double motorCorrectionB = 0.5;
LMotorController motorController(inA, inB, inC, inD, enA, enB, motorCorrectionA, motorCorrectionB);

// =================================================
// ===         Interrupt Service Routine         ===
// =================================================
volatile bool mpuInterrupt = false;
void dmpDataReady() {
    mpuInterrupt = true;
}

// =================================================
// ===              Program Setup                ===
// =================================================
void setup() {
    // join the I2C bus
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(115200);
    while(!Serial);

    // Initialize mpu
    Serial.println(F("Initializing I2C Devices: "));
    mpu.initialize();
    dmpStatus = mpu.dmpInitialize();

    // Gyro and accel offsets
    mpu.setXGyroOffset(262);
    mpu.setYGyroOffset(-29);
    mpu.setZGyroOffset(-10);
    mpu.setXAccelOffset(-2109);
    mpu.setYAccelOffset(394);
    mpu.setZAccelOffset(1341);

    // Verify initialization
    #ifdef DEBUG_BUILD
        Serial.println(F("Testing MPU Status: "));
        Serial.println(mpu.testConnection() ? F("MPU6050 initialization success!") : F("MPU6050 initialization failed!"));
        Serial.println(dmpStatus == 0 ? F("DMP initialization successful!") : F("DMP initialization failed!"));
    #endif

    if(dmpStatus == 0){
        // Enable DMP
        mpu.setDMPEnabled(true);

        attachInterrupt(0, dmpDataReady, RISING);

        // Get interrupt byte
        mpuIntStatus = mpu.getIntStatus();

        // Get DMP packet size ; default = 42B
        dmpPacketSize = mpu.dmpGetFIFOPacketSize();

        // Verify DMP initialization
        #ifdef DEBUG_BUILD
            Serial.println(mpu.getFIFOEnabled() ? F("FIFO Enabled!") : F("FIFO Not Enabled!"));
            Serial.println(mpu.getXGyroFIFOEnabled() ? F("FIFO X Gyro Enabled!") : F("FIFO X Gyro Not Enabled!"));
            Serial.println(mpu.getYGyroFIFOEnabled() ? F("FIFO Y Gyro Enabled!") : F("FIFO Y Gyro Not Enabled!"));
            Serial.println(mpu.getZGyroFIFOEnabled() ? F("FIFO Z Gyro Enabled!") : F("FIFO Z Gyro Not Enabled!"));
            Serial.println(mpu.getAccelFIFOEnabled() ? F("FIFO Accel Enabled!") : F("FIFO Accel Not Enabled!"));
            Serial.print(F("DMP Packet Size: "));
            Serial.println(dmpPacketSize);
        #endif

        isDMPReady = true;

        // Setup PID
        pid.SetMode(AUTOMATIC);
        pid.SetSampleTime(10);
        pid.SetOutputLimits(-160, 160);
    }
    else{
        Serial.println(F("DMP Error!!!"));
    }
}

// =================================================
// ===            Main Program Loop              ===
// =================================================
void loop() {
    // Do nothing if DMP initialization failed
    if(!isDMPReady) return;

    while(!mpuInterrupt && fifoCount < dmpPacketSize){
        pid.Compute();
        motorController.move(output, MIN_SPEED);
    }

    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    fifoCount = mpu.getFIFOCount();

    if(mpuIntStatus & 0x10 || fifoCount == 1024){
        mpu.resetFIFO();
        Serial.println("FIFO Overflow");
    }
    else if(mpuIntStatus & 0x02){
        while(fifoCount < dmpPacketSize) fifoCount = mpu.getFIFOCount();

        mpu.getFIFOBytes(fifoBuffer, dmpPacketSize);
        fifoCount -= dmpPacketSize;

        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        // TODO: implement complementary filter
        input = ypr[1] * 180 / M_PI + 180; // Supposing at upright position, pitch is 180 degrees

        #ifdef DEBUG_BUILD
            Serial.print("Yaw/Pitch/Roll: ");
            Serial.print(ypr[0] * RAD_TO_DEG);
            Serial.print("\t");
            Serial.print(ypr[1] * RAD_TO_DEG);
            Serial.print("\t");
            Serial.println(ypr[2] * RAD_TO_DEG);
        #endif
    }
}

```

I am using the exact same libraries and classes as in the repo. Yet my code does not work at all, the motors move erratically. All the physical connections are ok since the code from the repo works flawlessly. I've no idea why this is happening. Help is very much appreciated.

# Answer
Given that both libraries are the same.

The two sketches seem to set up the motorcontroller quite differently. Changing an "input pin" and "enable pin" around, would lead to errratic motor behaviour.

\`\`\` LMotorController motorController(ENA, IN1

LMotorController motorController(inA, inB \`\`\`

To me, an input pin would be an PWM signal to drive the speed of the motor. An enable pin, would enable/disable the whole driver (both left/right).

But it's hard to tell, also, if the above sketch is working, why not use the above sketch and adjust that?
> 2 votes

# Answer
Another thing I noticed while tinkering, interrupts from the MPU6050 can only be caught by the Uno when serial comm is set to 115200 baud rate or higher. Anything lower causes the MPU interrupts to be never caught. Maybe this is a particular problem of my board (it's a cheap chinese one), but maybe this will help someone out somehow. :)
> 0 votes

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


title: client.connect() problem

text:
# Question
Title: client.connect() problem
I'm using XAMPP(version-7.2.1) server in my PC to publish my arduino sensor data in a webpage. I have tried the code above and it shows an error like:

> Ethernet configured via DHCP
>
> Connecting...
>
> --\>connection failed

I have also followed the steps given in this https://forum.arduino.cc/index.php?topic=40448.0 but it doesn't work. The code runs till client.connect() after that it doesn't get inside the if(client.connect(server,80)) loop.

The arduino's ethernet shield is assigned an IP by the PC via ICS. I believe that the problem is in connecting the arduino to the localhost but I don't know how to resolve it. The XAMPP server seems to run properly. I have checked it logs.

I have also posted at https://forum.arduino.cc/index.php?topic=525947.0.

Hope someone can help me

Thanks in advance

```
#include <SPI.h>
#include <Ethernet.h>
#include "DHT.h"
DHT dht;
const int sensor_pin = A1;
unsigned int ldr;
byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 33);
char server[] = "192.168.1.7"; // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie. "www.yourwebpage.com")
EthernetClient client;

void setup() {
  Serial.begin(9600); // Serial.begin starts the serial connection between
  computer and Arduino
  Ethernet.begin(mac, ip);
  Serial.println("Ethernet configured via DHCP");
  delay(1000);
  dht.setup(2);
}

void loop() {
  delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */
  float soilmoisture;
  int sensor_analog;
  sensor_analog = analogRead(sensor_pin);
  soilmoisture = ( 100 - ( (sensor_analog / 1023.00) * 100 ) );
  float temperature = dht.getTemperature();
  float humidity = dht.getHumidity();
  ldr = analogRead(A0);

  Serial.println("Connecting...");
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("--> Connected");
    client.print("GET /write_data.php?"); // This
    client.print("temperature="); // This
    client.print(temperature); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&humidity="); // This
    client.print(humidity); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.print("&soilmoisture="); // This
    client.print(soilmoisture); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.1.7"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println( "Content-Type: application/x-www-form-urlencoded" );
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
  }
  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  client.flush();
  client.stop();
  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

```

My PHP code is as follows:

```
<?php
// Prepare variables for database connection
$dbusername = "x";  // enter database username, I used "arduino" in step 2.2
$dbpassword = "y";  // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
$dbname = "arduinotest1";
// Connect to your database
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword,$dbname);
if (!$dbconnect) {
    die("Database connection failed: " . mysqli_connect_error());
}
$dbselect = mysqli_select_db($dbconnect, "arduinotest1");
if (!$dbselect) {
    die("Database selection failed: " . mysqli_connect_error());
}
// Prepare the SQL statement
$sql = "INSERT INTO arduinotest1.tabletest2 (temperature,humidity,soilmoisture) VALUES ('".$_GET["temperature"]."','".$_GET["humidity"]."','".$_GET["soilmoisture"]."')";
// Execute SQL statement
mysqli_query($dbconnect,$sql);
?>

```

# Answer
As far as I can see, when you call `client.connect(server, 80)`, you call it with char\[\] variable that holds `char server[] = "192.168.1.7"`. And from library code it seems that it will call function with those parameters which will try to resolve dns but can't do it and returns `0`.

It calls: `int EthernetClient::connect(const char * host, uint16_t port)` ,
when it should call: `int EthernetClient::connect(IPAddress ip, uint16_t port)`
Source code: https://github.com/arduino-libraries/Ethernet/blob/master/src/EthernetClient.cpp

So you need to change `char server[] = "192.168.1.7";` to `IPAddress server(192,168,1,7);` That way it will call the right connection -function and wont get stuck with dns.

*Edit: added details*
> 2 votes

# Answer
Check the server ip is correct and server is running. Then check the return value of client.connect() function. If it's a 0 then most likely your server is behind a firewall. If so, unblock the apache server to pass through it. I had this similar issue with wamp.

Although 0 is not a valid return code for client.connect() according to http://www.arduino.cc/en/Reference/ClientConnect , it weirdly returns a 0. Oherwise it will give you a clue.

Also use IPAddress class for assigning the server address instead of using char \[\].
> 0 votes

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


title: Deploying an Arduino Uno R3 standalone

text:
# Question
Title: Deploying an Arduino Uno R3 standalone
I have an Uno R3 with a sensor board and a temperature sensor. I'm running a simple temperature check and would like to store that data outside the Ardunio for keeping records, graphs, etc.

I powered it from my PC during development, but obviously I want something more compact when deployed. It's still inside the house, but I want the PC shut down, not running 24/7.

I do have wireless access, and a Raspbery Pi 3 model B. Can any of those help? Or should I buy an ethernet/WiFi shield and try to get acces with those?

# Answer
The simplest is to use an SD card shield and write your data to the card, occasionally exchanging cards. This can be very infrequent if you like; SD cards are pretty dense. Advantage: Simple and direct. Data remains under your direct control. Disadvantage: Finite (but potentially large) capacity; Data remains on your Arduino -- sort-of. Not sure how "outside the Arduino" you need it to be).

Another option, though a little more complex, is to use a networking device to log your data to an online service such as Thingspeak. I personally favor ESP8266 radios, as they're very cheap and easy to work with, but the choice of an Ethernet shield, WiFi shield, or whatever else, is up to you, and the techniques (from the Arduino's point of view) are similar. Advantage: Your data is saved off your Arduino immediately, somewhere with an "approximately infinite" capacity; provider may (Thingspeak does) offer plotting and analysis tools. Disadvantage: Your data does not remain under your direct control (though you can presumably collect it if you need/want to).
> 1 votes

# Answer
My first reaction is similar to Juraj's - go straight to the PI with the sensor; this is the most straightforward and maybe the simplest answre. There are caveats - your sensor may not have a straight-forward hookup and, more importantly, the Raspberry PI uses 3.3V inputs - the Arduino can take up to 5V. Don't fry your PI.
**Next**, you'll have to program your PI to read the sensor.
Another option is to use your Arduino to send the data serially to the PI. Again, verify your voltages.
**Third**, you can, mentioned, use an Ethernet shield, or some wireless daughter-board to talk to another computer like the PI or a server somewhere that stores/analyzes the data. It tends to get more open-ended and can be as complicated as you like at this point. Good luck!
> 1 votes

# Answer
So you would rather use your Raspberry Pi than your PC? Easy, as it turns out that a Raspberry Pi is not that different from a PC running Debian or a Debian-like OS (e.g. Ubuntu).

Just connect the Uno to the Raspberry Pi through the USB link. Log the data on your Raspberry exactly like you would do on the PC. You don't need any Ethernet or WiFi shield. You just need to make sure that whatever logging program you use on the PC can run on the Raspberry Pi. This is most often trivial if the PC is itself running a Linux distro.
> 1 votes

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


# Question
Title: ESP8266 - Sending a software Reset Command
I have an ESP8266 running an Arduino code to control a dual relay device ( Up, Down, Off ), both from a physical switch and MQTT commands. After mounting the device in place I have no access in case of a need to reset ( just as a precaution ).

My workaround:

1) condition: function that on 4 detection of 4 repeated UP button presses - it should send a reboot signal.

2) the reboot signal is :

```
void sendReset() {
  Serial.println("Sending Reset command");
  Serial.println(1/0);
}

```

`sendReset` function actually reboots the device and boot occurs as needed, BUT - is doing it this way is a valid solution ? does boot process actually boots all services and freeing/ memory or any other.... AS NEEDED ?

Guy

# Answer
> 5 votes
1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: `ESP.reset()`. Calling this function you get a valid reset.

Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.

---
Tags: esp8266, reset
---


# Question
Title: Help with simple gradually brighter flickering led
im a newcomer for arduino and sorry for any grammar error. So what im trying to do is replicating a flickering effect found on spacecraft thruster when they about to take off where the fire bursting from dim to bright with flickering,similiar to afterburner on aircraft model which use neopixel led but this time only using common led. I could mimic the flickering on the led with various brightness level using the simple analogWrite,the problem is i cant really merge them since i use delay which is affecting how fast the flickering effect is and i need 1 sequence of flickering to stay a while before going next to brighter flickering and so on. My code is quite too simple

```
    Int led = 9;
    void setup () {
    pinMode (led, OUTPUT);
    }

    void loop() {
    {analogWrite (led, random (10,15));
    delay (30);}

    }

```

Im thinking adding a new line with higher random led states (ex. 50,100) should be okay,but then the delay which affect the flickering speed are too short and making both line merging useless since its will go to the brightest in no time. Is there's any way to hold the first dim line for an amount of time then continue to the next brighter line and so on without affecting the filckering delay? Any help will be appreciated

Thank you!

# Answer
Before using millis() you can try to create the thruster effect with delay().

I think 40Hz update rate for the led should be enough. The sketch starts with a random value between 5 and 15 and ends with a random value between 80 and 256. The part in the middle that gradually increases between those values is a mathematical problem.

```
// Led mimic spacecraft thruster.
//
// Update rate 40Hz for the led.
// That is a delay of 25ms.

#define RATE 40  // update rate of led in Hz
const int ledPin = 9;   // it must be a PWM pin !

void setup () {
  pinMode(ledPin, OUTPUT);

  Serial.begin(9600);

  randomSeed(analogRead(A0));
}

void loop() {
  int n;

  Serial.println("10 seconds low brightness");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(5,15));
    delay(1000/RATE);
  }

  Serial.println("5 seconds gradually brighter");
  n = 5*RATE;
  for(int i=0; i<n; i++) {
    //   random start: from 5 to 80     (75 increase)
    //   random end  : from 15 to 256   (241 increase)
    //   The calculation is with long, it might not fit in a 16 bit integer

    int random_start = 5 + int((long(i) * 75) / long(n));
    int random_end   = 15 + int((long(i) * 241) / long(n));
    analogWrite(ledPin, random(random_start,random_end));
    delay(1000/RATE);
  }

  Serial.println("10 second full thrust");
  n = 10*RATE;
  for(int i=0; i<n; i++) {
    analogWrite(ledPin, random(80,256));
    delay(1000/RATE);
  }

  analogWrite(ledPin,0);
  delay(2000);
}

```
> 1 votes

---
Tags: arduino-nano, led, pwm, analogwrite
---


title: Can batteries be damaged?

text:
# Question
Title: Can batteries be damaged?
I have some questions when it comes to draining batteries with low power projects.

I have been making a few low power projects with Arduino Pro Minis running on batteries. Some run on single non-recharchable CR123As while others run on two or three recharchable AAAs. I have removed the regulator and the power led on the Pro Minis, and I have changed the fuses making them run as low as 1.8v (or according to my measurements 1.7v). This way they consume a few µA and should be able to run for years on those batteries.

Now, what started to concern me is that this setup will be able to run the batteries very low. According to the voltage curve of a CR123A, it will be practically drained when reaching 1.7v. The same goes for two or three recharchable NiMH AAAs, that will have an individual voltage of 0.85v or 0.55v. Unless the batteries themselves have a discharge protection built in. In that case there might be no problem at all; I just don't know if batteries such as Eneloops have that.

So my questions are:

1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

# Answer
> 1 votes
> 1) Do batteries such as CR123As and Eneloops have built in discharge protection so that they stop supplying power when the voltage is too low?

No, they don't. They just run till there is nothing left.

> 2) If no, will draining a non-rechargable CR123A be dangerous or problematic in any way? And will draining MiMHs down to 0.85v/0.55v hurt the batteries?

A single cell can be run completely flat without problems. NiMH may need some "recovery" to wake them back up again, but shouldn't suffer serious problems (and no safety issues). However, *batteries* are a different matter: see below.

> 3) And, a question that I suppose applies to any battery powered Arduino project: When the supplied voltage drops below the Pro Minis BOD limit, will the Arduino stop using any power, or will it continue draining the batteries until they are completely empty? (In the first case I guess I could stick with the factory set BOD at 2.7v to protect the batteries.)

It will continue draining power. The BOD is a *reset* circuit - designed to recover the system into a known good state after a dip in the power. A permanent decrease in the input power is beyond the scope of the BOD system. It will just get stuck in a BOD reset loop and consume all your remaining power.

> 4) Finally, relating to the first question: Should I try to construct some kind of battery protection in the circuit, or is unnecessary when using CR123A and NiMH batteries?

For a single non-rechargeable cell you can just let it run flat. For NiMH you need to protect them. Here's why (and what I was alluding to above):

---

When you have two or more cells in series (a *battery*) the current flows through all the cells of the battery equally. That is all fine when the cells are all fully charged - however no two cells are precisely the same.

As the battery runs down each cell will approach "empty" at a different time. With a single cell that's not really a problem, since it will just stop providing enough current to run. However, with multiple cells one cell will run flat before the others. At that point the current provided by the other cells which still have some charge in them will be pushed through the flat cell *backwards*. It is at that point that the flat cell becomes irrevocably damaged. Current flowing backwards through the cell will try to *reverse charge* the battery and mess up the internal chemistry beyond recovery.

In the best case scenario, your battery will now have a much lower capacity and need recharging far more often. Worst case scenario: that damaged cell overheats and explodes.

The most prevalent problem that is caused by reverse charging is the depositing of metal crystals on the dielectric (the separator between the two electrodes) in the cell which grow and pierce the dielectric causing short circuits within the cell. There is no way back from that happening.

So you should protect your NiMH batteries from over-discharge by cutting the power to your circuit when the voltage drops below a specific threshold. You should also recharge all the cells individually, not together in series, or they will end up unbalanced and the same problems of over-discharge can occur.

---

As a side note: I use the terms "cell" and "battery" with their "proper" usage: A *cell* is a single power-producing unit, such as an AA "battery". A *battery* is a collection of cells. This is the *proper* usage of the words, not the common usage where *battery* can also be taken to mean *cell*. I use these terms specifically to differentiate between a single unit and a collection of units because of the major differences in how you need to handle them. It helps prevent confusion if you know that I am talking about just one AA (a cell) or a collection of three AA in series (a battery), for example.

---
Tags: arduino-pro-mini, battery
---


title: 4052 interfacaing with arduino uno

text:
# Question
Title: 4052 interfacaing with arduino uno
I am trying to interface 4052 demux with arduino, but my program is not working as high is not displayed on serial monitor corresponding to select lines.

```
//output coming from demux pins
int sensorValue0=A0;
int sensorValue1=A1;
int sensorValue2=A2;
int sensorValue3=A3;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
  //select pins connected A,B connected to 2 and 3
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  analogRead(sensorValue0);
  //Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  int voltage0= sensorValue0 * (5.0 / 1023.0);
  Serial.println("volatge0");
  Serial.println(voltage0);
}

```

# Answer
> 1 votes
You are ignoring the value read by `analogRead()`. You are then using the value `A0` (14) in your sum to calculate the voltage.

Instead:

```
int adcReading = analogRead(sensorValue0);
int voltage0 = adcReading * (5.0 / 1023.0);

```

Although I *think* what you really meant to write was, in total:

```
int sensorPin = A0;
int sensorValue0;//output coming from demux pins
int sensorValue1;
int sensorValue2;
int sensorValue3;

void setup() {
Serial.begin(9600);
  Serial.println("start");
  pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  sensorValue0 = analogRead(sensorPin);
  float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  Serial.print("voltage0 = ");
  Serial.println(voltage0);
}

```

Note that the value `sensorPin` is where you read the voltage from, and `sensorValue0` is where you store that reading. Also note the use of a `float` type to store the calculated voltage, since an `int` will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).

---
Tags: arduino-uno
---


# Question
Title: Using an Arduino for learning embedded C programming
I'm a computer systems engineering student and was planning to buy an Arduino to learn embedded C programming. After researching I found mention that an Arduino may not be a good choice for a beginner that wants to learn about programming embedded systems using C.

I'm not sure if that is true, can an Arduino be programmed in C without using C++ and the other included class libraries? I'd prefer to learn how to program things at a fairly low level and not rely on libraries that hide details of the underlying hardware. Can the Arduino be used as a general AVR / microcontroller development platform to learn embedded C programming?

# Answer
> 3 votes
The Arduino is a great place to start embedded C programming. You can use both C and CPP. There are tons of tutorials online and there are a bunch of books available. In addition there are lots of libraries available on GIT HUB for interfacing with all types of hardware like RF24 Wireless Transceivers.

If you want to go into more low level programming, you can. For example, you can set all Port B pins to Output:

```
// the setup routine runs once when you press reset:
void setup() {

  // initialize the digital pins as an output.
  DDRB = 0xff;
}

```

# Answer
> 2 votes
\[Not sure who's listening, as this is a 4 year old question posted by someone who no longer seems to have an account here, but... \]

> ... can an Arduino be programmed in C without using C++ and the other included class libraries?

You absolutely can use either C or C++, and make use of class libraries or write your own functions for either or both of computing tasks and managing your external hardware.

> Can the Arduino be used as a general AVR / microcontroller development platform to learn embedded C programming?

Yes, for the reasons above, and more. Embedded systems differ from other computing systems by having deadlines the must meet. These can be soft deadlines (try to keep visible delays to a minimum so you don't annoy the user/operator) or hard deadlines (if you miss one, something could fail or someone might die). They come in different scales: my home thermostat could be capably run by an Attiny "with one pin tied behind its back". :) Other systems might contain many large-scale chips or a mix of both, networked internally to one another. A mid-scale example of this is an automobile engine controller. It runs your signals, entertainment system, ABS brakes and traction control, and more, all while opening and closing injector valves and firing spark plugs with precise timings, at up to 125 times per second. And that is for a pretty normal, family-car, "street" engine.

The Atmega328p (Uno's MCU) is sufficiently over-engineered to tolerate occasional misuse, being over-clocked or supplied a lower than spec'd voltage, has several ways to update/replace its program, is easy to hand-build into a custom micro-controller board, and after all that abuse, is cheap enough to replace if you do manage to damage one.

Documentation is readily available as are online communities like this one, to help with beginners questions, unusual questions, esoteric uses that maybe only a handful of people have tried or know about.

So, tl;dr: yes, I'd call it an ideal platform for everything you asked about.

---
Tags: c
---


title: Using Sprintf() to left pad a string?

text:
# Question
Title: Using Sprintf() to left pad a string?
I've been at this all day, and I just can't seem to wrap my mind around how to use sprintf() to set a width for my string so that my characters are right justified.

What I'm trying to do is scooch my output over to the right on my touchscreen when the value is positive.
My output string is always a predictable length, so it seems like it should be easy.
I tried concatenating a string with just a space in it, and every other way I could think of to add a space to the beginning of my string. No luck.

```
char stringval[8] = 1.08;
char juststringval[8];
            if (hashpos > 0 && hashpos < 10) {

                sprintf(juststringval,  " %5s" , stringval);
                Serial.println(juststringval);
            }

```

output:

```
1.08 (no spaces in front)

```

In case you're curious why I need to use a string, my touchscreen will print floats, but my library won't rotate them properly.
Only strings can be rotated the way I need them.

Isn't there some simple way of doing this?

**EDIT:**

It seems I can use the width trick as long as I include some character besides an empty space.
For example:

```
void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = "rr";         ////THIS WORKS: OUTPUT IS  rr      1.08
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

void setup()
{
char stringval[33] = "1.08";
char juststringval[33];
char space[] = " ";     ////THIS DOESNT WORK. OUTPUT IS 1.08 LEFT JUSTIFIED
float hashpos = 1.08;
if (hashpos > 0 && hashpos < 10) {

    sprintf(juststringval, "%s  %7s", space, stringval);
    Serial.println(juststringval);
}
}

```

But I can't live with other characters in my string.
Isn't there something I can do?

# Answer
> 2 votes
The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. `"% 5s"` not `"%5s"`

---
Tags: string
---


# Question
Title: Can Arduino accept HDMI input video stream, and output it without any modification to the video?
I'd like to know please whether an Arduino can accept an HDMI signal from a satellite receiver, let it flow without any modification to the stream, and output it to TV?

# Answer
> 3 votes
No.

HDMI uses multiple serial data streams at gigabit rates. No Arduino is ever going to do that sort of thing. If you want something programmable to do that kind of thing you need an FPGA.

---
Tags: input, stream
---


title: Problems on convert byte[] to String

text:
# Question
Title: Problems on convert byte[] to String
I'm reading a RFID Card from RC522 and send the data to my computer. My problem is the conversion of `byte[]` to `String` or `std::string`.

```
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {0};
byte tam = SIZE_BUFFER;

// get data
status = mfrc522.MIFARE_Read(bloco, buffer, &tam);

  Serial.print(F("\nDados bloco ["));
  Serial.print(F("]: "));

// printing...
 for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      Serial.write(buffer[i]);
      str += String(buffer[i]);
  }

```

OUTPUT:

```
Dados bloco []: asdas

```

So, it's ok! But if I try make a string:

```
  String str = "";

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      str += String(buffer[i]);
  }
  Serial.println(" ");
  Serial.println(str);

```

The output is:

```
97115100971153232323232323232323232

```

What is the correct way to create a `String` from `byte[]`?

# Answer
byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.

```
buffer[tam] = 0;
String str((char*) buffer);

```

Let in the buffer a place for the zero. `(char*)` is cast that says that the byte array is a char array.

Note: Don't use String class in a MCU, use zero terminated character arrays.
> 3 votes

# Answer
If you change `str += String(buffer[i]);` to `str += (char)buffer[i];`, it will print the ascii characters to the serial monitor.

The following sketch can be used to see the difference in binary compiled size using these two methods of "adding to the string".

```
// 4026 to 3758 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

String str = "";

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 4026 bytes. Prints: "97115100971153232323232323232323232"
      //str += String(buffer[i]);

      // 3758 bytes. Prints: "asdas           "
      str += (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(str);
}

void loop(){}

```

Casting each element in the byte buffer to Char, then adding it to the string drops the binary compiled size from 4026 to 3758 bytes. This is good, but we can really improve the sketch by **not** using the `String` object at all.

This sketch is the same as the first one, except it uses a `Character Array` instead of a `String`.

```
// 2074 bytes.
#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {
  0x61, 0x73, 0x64, 0x61,
  0x73, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20,
  0x20, 0x20, 0x20, 0x20
};

// Use a char array instead of the String object.
char outputBuffer[SIZE_BUFFER];

void setup(){

  Serial.begin(9600);

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      // 2074 bytes. Prints: "asdas           "
      outputBuffer[i] = (char)buffer[i];
  }
  Serial.println(" ");
  Serial.println(outputBuffer);
}

void loop(){}

```

The binary compiled size is 2074 bytes. That's 1684 bytes **less** than using the `String` object.

There are many functions available to work with `Character Arrays` on an Arduino, such as http://www.cplusplus.com/reference/cstring/ and http://www.cplusplus.com/reference/cstdlib/.
> 3 votes

---
Tags: arduino-ide, string, convert, byte-order, c-string
---


# Question
Title: Nano & Ethernet will not write to PushingBox on a workplace network (but will at home)
I have a Nano+ENC28J60 and I'm using Pushingbox which I have setup to write data to a GoogleDrive spreadsheet which works *perfectly* at home. However when I take it to my workplace it no longer works.

At work, serial tells me that the

* Ethernet connection is good;
* I get a client connection OK too.

*However*, \[edit\] even with 5 attempts at a response client.read(); it reports nothing at all. Serial shows

```
OK connected! Written. Checking response: + + + + +

```

I assume it is to do with some firewall or other restriction, but if I can get a connection that should be enough, no?

\[edit\] note: i have also tried connecting to port 443 instead of port 80 in case it was an HTTPS issue - same results, though\]

**How I can write to GDrive on my work network?**

The code \[edit#2 modified client.connect() to try 5 times and a response check via client.read() to try 5 times and Serial.print("+ "); each time\] :

```
#include "DHTesp.h"
#include <SPI.h>
#include <UIPEthernet.h>

DHTesp dhtA; DHTesp dhtB;

const int ledPin =  LED_BUILTIN;
int ledState = LOW;
int interval = 20; // this is the num seconds between reads (120=2mins) ***************************
int numReads = 2;   // Amount of reads between posting to Gdocs.  ***************************

byte mac[] = {0xAA, 0xF0, 0xDE, 0xDE, 0x06, 0xAF };  // Ethernet shield MAC addy
byte ip[] = { 10, 10, xx, yy };
char devid [] = "vXXXXXXXXXXXXXXXX";  //  device ID from Pushingbox

char server[] = "http://api.pushingbox.com";
EthernetClient client;

int c = '\0';

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

  Serial.print(F("dB_CoSdataV3.  Establishing..."));
  if (Ethernet.begin(mac) == 0) {
    Serial.println(F("Failed to configure ethernet"));

    //while (true); // no point in carrying on, so do nothing forevermore
  }
  else {
    Serial.println(F("Ethernet OK."));
    // print the Ethernet board/shield's IP address:
    Serial.print(F("local IP addy: "));
    Serial.println(Ethernet.localIP());
  }

  // give the Ethernet shield a second to initialize:
  delay(3000);

  Serial.println("____________________________________________");  Serial.println();

  dhtA.setup(3); //  sensor A
  dhtB.setup(4); //  sensor B
  //dhtC.setup(7); dhtD.setup(7);

  pinMode(ledPin, OUTPUT);

}

void loop(){

  int Ahumidity = 0;   int Atemperature = 0 ;
  int Bhumidity = 0;   int Btemperature = 0;

  int j = 0;
  for (j = 1; j <= numReads ; j++ ) {
    int p = 0;
    for (p = 1; p <= interval ; p++) {
      delay (1000);
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW) {        ledState = HIGH;       }
      else {        ledState = LOW;      }
      Serial.print (F("."));
      digitalWrite(ledPin, ledState);
    }

    Serial.print (" reading: ");
    Ahumidity += 10 * dhtA.getHumidity();  Atemperature += 10 * dhtA.getTemperature();
    Bhumidity += 10 * dhtB.getHumidity();  Btemperature += 10 * dhtB.getTemperature();

    Serial.print (j);     Serial.print (F("/"));     Serial.print (numReads);
    Serial.println();
  }

  Serial.print (F("Show the averaged val.s : "));
  Serial.print(F("\t\tA:")); Serial.print(Atemperature/(numReads)); Serial.print(F("\t")); Serial.print(Ahumidity/(numReads));
  Serial.print  (F("\tB:")); Serial.print(Btemperature/(numReads)); Serial.print(F("\t")); Serial.print(Bhumidity/(numReads));

  // now connect + write to Gdrive....................
  boolean connected;
  int counter1 = 0;
  do {
      connected = client.connect(server, 80);
      if (connected) { break; }
      client.stop();
      delay(1000);
      Serial.println("retry");
      counter1++;
  } while (!connected && counter1 <5);

//------------------
//if (client.connect(server, 80)) {

if (connected){
    Serial.println();
    Serial.print(F("OK connected! "));

      String buf;

      buf += F("GET /pushingbox?devid=");
      buf += String(devid);

      buf += F("&tempA=");  buf += String(Atemperature/numReads);
      buf += F("&tempB=");  buf += String(Btemperature/numReads);
      buf += F("&tempC=0&tempD=0&tempE=0&tempF=0&tempG=0&tempH=0"); // null data needed

      buf += F("&humidA=");  buf += String (Ahumidity/numReads);
      buf += F("&humidB=");  buf += String (Bhumidity/numReads);
      buf += F("&humidC=0&humidD=0&humidE=0&humidF=0&humidG=0&humidH=0"); //null data needed

      buf += F("&submit=Submit");
      buf += F(" HTTP/1.1");
      //client.println(F("Host: api.pushingbox.com"));
      buf += F("Host: http://api.pushingbox.com"); // trying the addition of http://...
      buf += F("Connection: close\r\n");
      //client.println();

      client.print(buf);
      Serial.print(F(" Written. "));
      delay(1000);
      int counter2 = 0;
      Serial.print ("Checking response: ");

      do {
          if (client.available()) {
              Serial.print("Y ");
              c = client.read();
              Serial.print((char)c);
          }
          delay(2000);
          Serial.print("+ ");
          counter2++;
      } while (counter2 < 5);

      Serial.println ();       Serial.println ();
      //client.stop();
  }

}

```

# Answer
> 1 votes
Your code for HTTP request has multiple issues.

After you connect to an HTTP server, it doesn't send anything until it receives your request. Your check for available bytes should always fail. Remove the `if (client.available())` part, including the `else` part.

You make a POST request, but you put all parameters to URL and the request has no body. Change it to GET or put the parameters into request body and use "Content-type: application/x-www-form-urlencoded". Don't forget the Content-length parameter.

You send the request in very small parts. Every single print is send right away over network. Concatenate strings and print one or use buffered print.

And you should read the HTTP response and check the status.

---
Tags: arduino-nano, ethernet, ethernet-shield
---


# Question
Title: What is a cheap way to measure co2 or o2 level in air?
I am making an air purifier which also increases o2 level as a school project but facing some difficulties. I plan to run the purifier whenever the co2 level is higher than usual or o2 level is lesser than usual but the sensor available in the market are quite expensive. So is there any cheaper alternative or any other method to detect a change in concentration?

# Answer
Well, MQ 135 sensor is very cheap general air quality measurement device. It costs around 3$. There is another similar on AliExpress, not even worth mentioning. What is your budget? Gravity from Adafruit seems proper, yet it is at 56$. One that seems actually serious is K30 sensor, but that is around 100$. That 3$ stuff is general, and will work when temperature is constant, humidity is constant and Mars is aligned with Venus.

I think 56$ is ok if they want to have something proper. Remember that you get what you pay for.
> 5 votes

---
Tags: arduino-uno
---


title: SD card failed to initialize

text:
# Question
Title: SD card failed to initialize
I have a Pro Micro board and I try to make it list my files as in the example of the Arduino IDE. The pins I use are the following:

```
board    micro sd module
   D4  ---> CS
   D15 ---> SCK
   D14 ---> MISO
   D16 ---> MOSI
   GND ---> GND
   VCC ---> VCC

```

On the serial monitor I get "initiallization failed".

What is wrong with my setup?

This is the code running:

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

File root;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  root = SD.open("/");

  printDirectory(root, 0);

  Serial.println("done!");
}

void loop() {
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

```

And this is my wiring:

# Answer
> 1 votes
The SD library works only with FAT and FAT32 format. SD.begin() reads the 'disc volumes' and opens the root folder. If the card is not formatted or formatted with other file system standard, begin() fails.

EDIT: and the pin headers must be soldered

# Answer
> 0 votes
Here's my setup code for my SD card for a little circuit where I was writing temperature data to the card.

```
const int SD_CS = 10;
   const long SLEEP_TIME = 60000;  // write to card every minute
   long multiplier = 0;

   LiquidCrystal_I2C lcd(0x3F, 20, 4);

   void setup() {

     lcd.begin();
     lcd.setCursor(2,0);
     lcd.print("Hello, LCD!");

     if (SD.begin(SD_CS)) { // init SD
       lcd.setCursor(2,2);
       lcd.print("SD card init");
     }

 }

```

I set the CS pin to D10.
Try switching it to another pin like this and see if you get a different result. I believe I had a challenge when I used pin 4 but can't quite remember.

**Note**: And of course remember to move your CS wire to pin D10 or whichever one you use.

---
Tags: sd-card, arduino-pro-micro
---


# Question
Title: Print out times tables from 1 to 10 with array
I would like to `Serial.print();` the multiplication tables, 1 - 10. This is my work so far. Is there an easier way to do this with array? Thanks

```
// "MultiTable"

//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//Define variable
int prod;

void setup() {
  // Open serial connection at 9600Bd
  Serial.begin(9600);
}

void loop() {
  //Print the times table for 1

  for(int i = 0; i <=9; i=i+1) {
   prod = i*1+1;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 2

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*2+2;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();

//Print the times table for 3

  for(int i = 0; i <= 9; i=i+1) {
  prod = i*3+3;
   Serial.print(prod);
   Serial.print(",  ");
  }

  Serial.println();
  delay(3000);
  Serial.println();
}

```

# Answer
> 0 votes
```
//Define global array, is this needed? Makes no difference for my output in serial monitor.
//int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

```

This is not needed, you can use a for lop from 1 to 10.

The void loop will look like this (not checked, no IDE nearby):

```
void loop()
{
  for (int multiplier = 1; multiplier <= 3; multiplier++)
  {
      for(int i = 0; i <= 9; i++)
      {
         prod = i * multiplier + multiplier;
         // or: prod = (i + 1) * multiplier;
         Serial.print(prod);
         Serial.print(",  ");
      }

      Serial.println();
      Serial.println();
      delay(3000);
  }
}

```

Some remarks:

* To go to the main for loop (with multiplier):
    + Identify the similar parts
    + Check the differences within each similar part (only the multiplier value, 1, 2 or 3)
    + Make this a for loop and instead of 1, 2, 3 use the multiplier variable
    + Instead if i = i + 1 you can use i++. It means exactly the same.
    + For clearity I put the Serial.println() together. You also can use Serial.print('\r\n\r\n') or Serial.println('\r\n') to achieve the same

---
Tags: arduino-uno
---


# Question
Title: NODEMCU 1.0 HX711 Load cell reading weird text
Hi Guys! i have a problem with the reading with my NODEMCU where i tried this code on an arduino UNO it is working perfectly fine but until i tried to switch it to NODEMCU 1.0 which have a wifi function that i need, the reading turn out to have this type of error, i've tried looking for solution online and tried every single of them but apparently none of it help. The image is the error i have faced and the connection i have made from the nodemcu to hx711 is VCC --\> Vin or 3.3v, GND --\> GND, DT --\> D2, SCK --\> D3. Here's the code that i found online to use:

```
#include <HX711.h>

// Scale Settings
const int SCALE_DOUT_PIN = D2;
const int SCALE_SCK_PIN = D3;

HX711 scale(SCALE_DOUT_PIN, SCALE_SCK_PIN);

void setup() {
  Serial.begin(115200);
  scale.set_scale(-47740);// <- set here calibration factor!!!
  scale.tare();
}

void loop() {
  float weight = scale.get_units(1);
  Serial.println(String(weight, 3));
}

```

Thanks in advance!!

# Answer
Try D1 instead of D3. D3 is io 0, a boot configuration pin with pull-up on board.
> 1 votes

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


# Question
Title: How can I calculate approximate cycles per second from pulsed pin on Arduino MKR Zero?
The relevant tech specs for a MKR Zero are: 32.768 kHz (RTC\*), 48 MHz

\*Real-Time Clock

What I'm curious about is how I might do an approximate calculation of cycles per second from operations.

I'm running the following (extremely simplified) code :

```
int pin3 = 3;
void setup() {
  //set digital pin pin3 as output

  pinMode(pin3,OUTPUT);
}

void loop(){
  digitalWrite(pin3,HIGH);//set pin pin3 to +5V
  delay(100);//wait 100ms
  digitalWrite(pin3,LOW);//set pin pin3 to 0V
  delay(100);//wait 100ms
}

```

Now I'm curious how many cycles per second (approximately) that might account for.

**The Equation?**

What would the equation be to calculate that?

**Not Processor Op Codes**

Is this even possible to approximate? I understand it will be difficult because those lines of code do not equal the actual op codes and don't exactly break down to specific cpu cycles or whatever.

Would it be something like:

```
48,000,000 (48MHz) / 200 (millisecond pause) = 240KHz?

```

Or would I use the real-time clock speed?

```
32768 / 200 = @163Hz

```

Or something completely different? I'm trying to better understand how I might create a very simple frequency generator and I know that depending upon the chip speed the code will vary.

# Answer
It is unclear exactly what you are trying to do, however the frequency generated by the code would be ~5Hz - corresponding to a period of 200mS
> 1 votes

# Answer
The dependency on the clock speed is hidden in the implementation of the delay() function. It works with 'human readable' milliseconds.

Hertz is count of repeating in one second. One second has 1000 ms. So with 200 ms delay, 5 repeating happen in a second. Then the frequency is 5 Hz.
> 1 votes

---
Tags: frequency, mkr1000
---


# Question
Title: ESP8266-12E as WiFi interface for Arduino Mega
I have an Arduino Mega 2560 that I would like to connect to the internet using an ESP8266-12E.

Searching the internet for relevant keyphrases only yielded one type of result: The articles all explain how to **program** the ESP using the Arduino. Been there, done that.

Does anybody know of a way to use the ESP as a "wifi interface" for an Arduino, e.g. using a Serial interface from the Arduino?

Basically, I'd want to use the library ESP8266Wifi transparently on my Mega 2560, and maybe in conjunction with something like WifiManager \- all of that running on the Mega.

The only thing I found was this: https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e. But this uses AT commands only.

Any hint is appreciated.

# Answer
> 1 votes
If you know how to write code for the esp8266, then write the networking part in the esp8266 and exchange data and commands with the sketch in Mega over Serial.

Other option is to use AT firmware with the WiFiEsp library or WiFiLink firmware with WiFiLink library.

Or you can connect the ESP-12 to Mega over SPI and use the WiFiSpiESP firmware with WiFiEsp library.

All mentioned libraries are 'clones' of the WiFi library.

# Answer
> 0 votes
ESP8266-01 usually come pre-programmed with the "AT" instructions interpreter for WiFi communication. If your -12 didn't, or if you've reprogrammed it, you'll need to find and download a copy of the AT interpreter to re-load.

Then you'll cross-connect one of the Mega's UARTs to the ESP (Tx \> Rx and Rx \> Tx), respecting the voltage level differences between the Mega and the ESP (5v vs. 3.3v). You'll need use a level-shifter or make a voltage divider for at least the Mega Tx \> ESP Rx connection.

Then it's just a matter of using an existing Arduino ESP-WiFi library, or writing your own serial communications using the ESP's AT commands if you want the challenge.

I generally use the Blynk Internet of Things service and libraries as the quickest and a full-featured way to put a device online with access to/by your cellphone. It's not the only way but it's a good start.

---
Tags: esp8266
---


title: Arduino Uno - Building a Controller

text:
# Question
Title: Arduino Uno - Building a Controller
I have the Arduino Uno and I'm working on a project to build a controller with different inputs and some outputs for readouts. In classic style, I got the Arduino Uno before realising that I might not have enough I/O points to connect everything I want.

I believe there is a way to expand my Uno by using an I/O Expander? Has anyone done something similar? The controller will be for a specific game called Kerbal Space Station. There are quite a few articles helping with the build but not specific to what I am looking at.

Components I'll be using:

INPUTS:

* 2x 3 Axis Joysticks
* 11x Microswitches
* 6x Toggle switches
* 1x Analogue slider
* 1x 10 point rotary switch

OUTPUTS:

* 4x 12 pin LED Bargraphs
* 1x Serial LCD module display

# Answer
Yes, all those things have been done before. Here's some suggestions for components:

* MCP23S17 / MCP23017 - SPI / I2C IO expander (16 IO pins, many can be connected together) (MCP23S17 library)
* MCP3208 - 8 channel 12-bit SPI ADC (MCP3208 library)
* TLC59116 - I2C Constant Current LED PWM driver (16 channel) (TLC59116 library)

Some other useful tutorials that may help:

* Keypad \- read lots of buttons / switches with not many pins
* Multiplex \- Control many LEDs with not many IO pins
> 1 votes

# Answer
Sparkfun also sells a SX1509 module for a very good price. It can do a matrix keyboard all on its own (hardware support) with similar (independent hardware-driven) LED heartbeat control. Aside from that, you can use any remaining pins as normal I/O (read/write/pwm). There are 16 pins total, and it's controlled over I2C.

Adafruit also has a board called the Seesaw, which is a small Atmel SAMD09 with I2C slave firmware. It works similarly, but the pins are much more limited.

Either way, you simply include a library to your code, and use the object to interface with the pins rather than the usual functions on your Arduino. Most seem to use identical syntax (someclass.digitalWrite()...) to the normal Arduin functions.
> 0 votes

---
Tags: arduino-uno, io-expander
---


title: Detecting pulsed LED

text:
# Question
Title: Detecting pulsed LED
I am trying to use an Uno to detect if an LED is on or not. Sounds simple, but I am tearing my hair out on this one, here is why.... This is a model railway application and I want to detect an LED being lit on the control panel showing how a route (points/turnouts) is set. The LED is lit by a point position indicator (www.blocksignalling.co.uk/index.php/points-position-indicator-ppi4-dc) which works perfectly but the LEDs are not permanently on when lit, even though they appear so, they are pulsed at around 8khz. I tried using opto isolators triggering an digital input on the Uno. They all happily detect 'no light' and the pin goes HIGH, but when the led is lit, the pin flucuates between 0 and 1 so not a true or stable LOW. I also made my own opto using a TCRT5000 with the leds pointing at eachother encased in shrinkwrap, using standard breadboard set-up which worked perfectly when powering the transmitter from the Uno, but same result when powered from the LED. Anyone out there got any ideas please?

# Answer
Count HIGH values read for example in 2 ms. It should be zero if the LED is not lit and more then zero if it is lit.
> 3 votes

# Answer
Why not connect a low pass filter to the LED, and measure the DC level coming out? Will certainly be higher when on than when off. Resistor from anode to analog input pin, and capacitor to Gnd.
> 2 votes

# Answer
Use a photoresistor (also called LDR).

Connect the photoresistor between Vcc and an analog input and place it physically next to the LED you want to monitor.

In your arduino code simply monitox the analog input value. When the LED will be on the photoresistor will have a lower resistance andyou will read a higher analog voltage.
> 1 votes

---
Tags: led
---


# Question
Title: Using mills() in place of delay() on relays not getting solid switch over
I know I should post some code that maybe cleaner but really I am just in need of a answer to a problem I seem to run into a lot when using `mills()` in place of `delay()`, whilst making a Christmas light display.

Maybe it's me but I do not get contestant switching over of mechanical relays when I try to use `mills()` timing to switch relays . I seems like the code trips the relay then untrips the relay in milliseconds and not really latching the relay like I get with `delay()`. Is this the nature of the `mills()` choice where the output is triggered every cycle but is not truly an output during the whole process cycle? Now if this is true, then is there a good way to latch a relay with out using a `delay()`?

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
//

  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
  int interval_on = 2000; //  Length of time On

  unsigned long currentMillis_off = millis();
  unsigned long previousMillis_off ;
  int interval_off = 2000; // length of time off

//
#define button 4
int Lite_1=0;

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";
boolean buttonState = 0;

unsigned long time;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();        // must be in loop
   unsigned long currentMillis_off = millis();  // Must be in loop
  //                             const char text[] = "Hello World";
 //                       radio.write(&text, sizeof(text));
  //delay(1000);

   //                       delay(5); Removed to help in timing
   //                       radio.stopListening(); removeded to help in timing
   // Lite_1 = 1;
    radio.write(&Lite_1, sizeof(Lite_1));
  //    delay(1000);
 //   Lite_1 = 0 ;
 // radio.write(&Lite_1, sizeof(Lite_1));
  // delay(250);

  if (Lite_1 == 0 && currentMillis - previousMillis > interval_off)
    {
    previousMillis = currentMillis;
    previousMillis + 10;
    previousMillis_off = currentMillis_off  ;
    Lite_1 = 1;
    Serial.println(currentMillis);    //prints time since program started
      }
    //Debug
  // Serial.print("Time: ");
 // time = millis();

 // Serial.println(time);    //prints time since program started
//  Serial.println(currentMillis);    //prints time since program started
//  Serial.println(previousMillis);    //prints time since program started
//  Serial.println(previousMillis_off);    //prints time since program started
 // Serial.println(currentMillis_off);    //prints time since program started
  //delay(250);

    if (Lite_1==1 && currentMillis_off - previousMillis_off > interval_on)
       {
    previousMillis_off = currentMillis_off;
    previousMillis = currentMillis;
    previousMillis + 10;
    Lite_1 = 0;
    Serial.print("OFF: ");
    Serial.println(previousMillis_off);    //prints time since program started
    }

  }

```

# Answer
Something like this works.

```
  unsigned long currentMillis;
  unsigned long previousMillis;
  unsigned long nextEventTime;

  unsigned long interval_on  = 2000;        // length of time On
  unsigned long interval_off = 2000;        // length of time off

  bool Lite_1;

  void setup() {

    previousMillis = millis();

    Lite_1 = false;                                     // start at the begining of the off cycle
    nextEventTime = previousMillis + interval_off;      // start at the begining of the off cycle

    Serial.begin(9600);
    Serial.print("starting in OFF cycle\t");
    Serial.println(previousMillis);
  }

  void loop() {

    if (millis() > nextEventTime) {                     // check the interval before doing any other checks

    currentMillis = millis();

    if (Lite_1) {

      nextEventTime = currentMillis + interval_off;     // do the calculation only once
      Serial.print("OFF:\t");

    } else {

      nextEventTime = currentMillis + interval_on;
      Serial.print("ON:\t");
    }

    Lite_1 = !Lite_1;                           // invert value
    Serial.println(currentMillis);              // prints time since program started
    }
  }

```
> -1 votes

---
Tags: relay, nrf24l01+, millis, timing
---


# Question
Title: How to integrate nRF24L01 to esp8266 nodeMCU?
I can't seem to integrate an nRF module to my nodeMCU. I just want to verify my code but an error message keeps popping up

Below is the sketch:

```
#include <SPI_Class.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <ESP8266WiFi.h>
#define PIN_CE D4
#define PIN_CSN D3
RF24 radio(PIN_CE, PIN_CSN);

struct package{
  int id = 1;
  int location = 1;
  char timeStamp = "date/time"
};

typedef struct package Package;
Package data;

public int data1=data.id;
public int data2=data.location;
public char data3=data.timeStamp;

byte  address[][6] = "00001"

const char* ssid = "Jino";
const char* pass = "myinternet";

char server[] = "cdgresearch.000webhostapp.com";

WiFiClient client;

int led = 2;

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid,pass);
  pinMode(led,OUTPUT);
  digitalWrite(led, HIGH);
  delay(500);
  Serial.println("Connecting to: ");
  Serial.println(ssid);
  Serial.print("Connecting");
  while(WiFi.status() != WL_CONNECTED)
  {

    delay(1000);
    Serial.print(".");
  }

  delay(300);
  digitalWrite(led, LOW);
  Serial.println();
  Serial.println("Successfully connected to the network");
  Serial.print("NodeMCU IP Address: ");
  Serial.println(WiFi.localIP());

  delay(1000);

  radio.begin();
  radio.setChannel(115);
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(address[0]);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(9000);
  sendData();
}

void sendData(){
  Serial.println("Sending Data...");
  delay(1000);
  if (client.connect(server, 80)){
    WiFi.printDiag(Serial);
    Serial.println("Connected to server");
    client.print("GET /tag2.php?");
    client.print("incoming=Id ");
    client.print(data1);
    client.print("&incoming2=Loc");
    client.print(data2);
    client.println(" HTTP/1.1");
    client.println("Host: cdgresearch.000webhostapp.com");
    client.println("Connection: close");
    client.println();
    Serial.println();

    while(client.connected()){
      while(client.available()){
        Serial.write(client.read());
       }
      }
    radio.write(&data,sizeof(data));

    Serial.print("\nPackage: ");
    Serial.println(data1);
    Serial.print("Location: ")
    Serial.println(data2)
    Serial.println(data3)
    data1+=1;
    data2+=1;
    delay(1000);

  }

  else{
    Serial.println("Failed to Connect to server...");
    }

  client.stop();
  Serial.println("Disconnected from Server");
  while(client.status()!=0){
    delay (10);
   }
  }

```

and this error comes up in the console:

even if I use the #include, still this pops out

# Answer
Your error is: .../packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI/**src/SPI.h**:1:23: fatal error: SPI\_Class.h: No such file or directory...

You have some wrong SPI library there. The original folder `packages/esp8266/hardware/esp8266/2.4.2/libraries/SPI` doesn't contain `src` subfolder.
> 2 votes

# Answer
I can confirm that it's possible to connect the two with TMRH20's RF24 library, which seems to be what you are using (judging by the name of the library). I'm currently building something with those very two components.

*Instead, the error is that **SPI\_Class.h** can't be found by the IDE*. I can't recognize the name either, but if that is from attempting to include SPI to interface with the NRF24L01, you'd want **SPI.h** instead.
> 1 votes

# Answer
I reinstalled Arduino IDE and the libraries that I need, it works fine now. It must be because someone used my laptop and installed some rfid libraries which caused some problems in the libraries folders.
> 1 votes

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


title: How to know which event fired first?

text:
# Question
Title: How to know which event fired first?
I want to automate the chicken coop of my grandmother. To do so, I want to use Arduinos and NodeMCUs, respectively. I want to check if all chickens are in the coop at night and then close a little door. I was trying to use RFID technology and tag the chickens with a little RFID tag but the read range I got was too short to get it working properly. Now, I am trying to implement a light gate with two small lasers and two receivers. I want to detect the direction (in or out) of the chickens. I got the lasers working and I get a signal (1 and 0 = light gate interrupted). I have to know which of the two laser detectors first detected a 0 (zero). I have no idea how to implement this in code. I was trying to use timers to no avail. I also was trying to use interrupts (see small code fragment).

I hope I made clear what I am trying to achieve. Please tell me if and how I can improve this question. Any google fu was to no avail. Every hint/help is greatly appreciated.

```
#include <Arduino.h>

// Functions
void pin_ISR();

const int detectorPin = 3;     // the number of the detector pin
const int ledPin =  13;      // the number of the LED pin
const int Laser = 6;
// variables will change:
volatile int buttonState = 1;         // variable for reading the status

void setup() {
Serial.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(detectorPin, INPUT);
pinMode(Laser, OUTPUT);
digitalWrite(Laser, HIGH);
// Attach an interrupt to the ISR vector
attachInterrupt(digitalPinToInterrupt(3), pin_ISR, CHANGE);
}

void loop() {
Serial.print(buttonState);
delay(100);
}

void pin_ISR() {
Serial.println("There was an interrupt!");
buttonState = digitalRead(detectorPin);
digitalWrite(ledPin, buttonState);
}

```

# Answer
Consider using quadrature encoding to detect travel direction using two light beams. A method used in older mechanical mouse pointer devices and track balls. Using an Arduino to decode quadrature encoding is talked about in many places on the web.

Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

Because the activation of beam B occurs first we know the chicken is walking out of the coop. If beam A occurred first we know the chicken is walking into the coop.

The shape of a chicken is irregular and a chicken may change its mind half way out of the coop. These and other unexpected anomalies may lead to unexpected results. Consider supplementing the beams with a PIR sensor outside the coop to confirm there are no chickens left outside.
> 0 votes

---
Tags: arduino-uno, nodemcu, time, events
---


title: Time between two IR beam sensors

text:
# Question
Title: Time between two IR beam sensors
I am working with two sets of IR beam, they are to be placed in X distance. My goal is to measure speed. I would like to measure time between the first IR beam to the second beam when the beam breaks.

I am not sure what's going on, I am not getting any time of the serial port but the LEDs are turning on and off the way I wanted.

Please help me with getting the time between two IR beam sensors.

This the sensor that I am using - Adafruit IR breakbeam sensors and I am working with a Mega2560.

```
#define LEDPIN 13
int startPin = 8, finishPin = 5;
unsigned long starttime = 0, finishtime, time_interval;
float distance = 1, Speed; // Speed calculated
int trigger1 = 0; // Sensor 1
int trigger2 = 0; // Sensor 2
int sensor1State; // Sensor 1 status
int sensor2State; // Sensor 2 status

void setup() {
  pinMode(startPin, INPUT_PULLUP); // Sensor 1 as input
  digitalWrite(startPin, HIGH); // Turn on the pullup
  pinMode(finishPin, INPUT_PULLUP); // Sensor 2s input
  //digitalWrite(finishPin, HIGH); // Turn on the pullup

  pinMode(LEDPIN, OUTPUT);
  time_interval = ((finishtime - starttime) / 1000000);
  Serial.println(time_interval);
}

void loop() {
  sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
  if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
  {
    if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
    {
      starttime = micros(); // Save time when sensor 1 was triggered
      digitalWrite(LEDPIN, HIGH);
      trigger1 = 1; // Prevent sensor 1 from triggering again
    }
  }
  if (trigger1 == 1) {
    sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has been broken
    if (sensor2State == LOW) {
      // Check to make sure sensor 1 has triggered but not sensor2
      if (trigger2 == 0) {
        // Run speed function
        trigger2 = 1;
        finishtime = micros(); // Save time when sensor 2 was triggered
        digitalWrite(LEDPIN, LOW);
        // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
        Serial.println(time_interval);
      }
      // Reset both sensors
      trigger1 = 0;
      trigger2 = 0;
    }
  }
}

```

# Answer
You've tried to print an interval at the bottom of the setup() function, using finishtime before you have ever used it. Fortunately, finishtime will have been initialized to zero before the program runs so the the arithmetic result will be zero, though meaningless.

In loop(), you've never completed the interval calculation before you try to print it.

If nothing at all is being printed, check your wiring and be sure your code is getting the triggers. You haven't showed your wiring, so we can't help you debug that, in case there is a problem with that also.
> 1 votes

# Answer
You never calculate the time\_interval that you print. Add that after the finishtime line

```
  if (trigger2 == 0) {
    // Run speed function
    trigger2 = 1;
    finishtime = micros(); // Save time when sensor 2 was triggered
    digitalWrite(LEDPIN, LOW);
    // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
    Serial.println(time_interval);
  }

```
> 0 votes

---
Tags: arduino-mega, ir
---


title: Problem with interrupts

text:
# Question
Title: Problem with interrupts
Alright. This is what I wanted to do:

Make a circuit and code the arduino such that there are 2 tactile switches, each with a predefined pwm value. Whenever any one button is pressed the led should run at that pwm value, until the button is released. There is also an ultrasonic sensor on the same arduino that triggers an interrupt at a threshold distance that stops the led. When no button is pressed or the ultrasonic isnt active, the led should run at another pwm value.

Here is the code:(updated)

```
const int trig = 9;
const int echo = 10;
const int redswitch = 2;
const int yellowswitch = 3;
int redled = 6;
int greenled = 5;
volatile int pwm = 50;

volatile bool rs = LOW;      //RS - RED SWITCH
volatile bool ys = LOW;      //YS - YELLOWSWITCH
bool last_rs = LOW;
bool last_ys =  LOW;
volatile long distance=0;
long duration=0;
long temp=0;

void setup(){
  pinMode(trig,OUTPUT);
  pinMode(echo,INPUT);
  pinMode(redled,OUTPUT);
  pinMode(greenled,OUTPUT);
  pinMode(redswitch,INPUT);
  pinMode(yellowswitch,INPUT);
  Serial.begin(9600);

  attachInterrupt(digitalPinToInterrupt(redswitch), red,CHANGE);
  attachInterrupt(digitalPinToInterrupt(yellowswitch), green,CHANGE);

  digitalWrite(greenled,LOW);
  digitalWrite(redled,LOW);
}

boolean debounce(boolean temp,int switchPin)
{
  boolean current = digitalRead(switchPin);
  if (temp != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void loop(){

  //Ultrasonic sensor's distance calculation
  digitalWrite(trig,LOW);
  delayMicroseconds(5);

  digitalWrite(trig,HIGH);
  delayMicroseconds(10);
  digitalWrite(trig,LOW);

  duration = pulseIn(echo, HIGH);
  temp = duration * 0.0343 / 2;
  noInterrupts();
  distance = temp;
  rs = debounce(last_rs,redswitch);
  ys = debounce(last_ys,yellowswitch);
  last_rs = rs;
  last_ys = ys;
  if(distance>8)interrupts();

  Serial.println(distance);
  analogWrite(redled,pwm);
  analogWrite(greenled,pwm);
}

void red(){

  if(rs == HIGH) pwm = 150;
  else pwm = 0;

}

void green(){

  if(ys == HIGH) pwm = 250;
  else pwm = 0;

}

```

Now, when the arduino is connected to my laptop, led runs at the a particular value. But whenever I press a button they go off. Can you help me find out what's wrong here?

# Answer
> 1 votes
Look at these lines:

```
distance = temp;
duration = pulseIn(echo,HIGH);
distance = duration * 0.0343 /2;

```

Here is what they do:

* The first line sets the variable `distance` to zero (that's the value of `temp`).
* The second line waits for the ultrasonic pulse to reach the target, bounce against it and come back, while at the same time timing the whole trip. This can take a long time (several milliseconds). Chances are your program spends *most* of its time executing this line.
* The third line sets the variable `distance` to something sensible.

This means `distance` is zero most of the time (while the second line executes). When the interrupt fires, there is a very high probability for the interrupt handler to find a zero distance, and thus to set `pwm` to zero.

Simple fix: never set `distance` to an unreasonable value. Leave it's value alone until you have a new distance measurement ready, and only then update that variable. In other words, just remove the first of those three lines.

But there is a catch now. The variable is four bytes long, and updating it takes four instructions. There is a small probability that the interrupt fire *in between* these instructions. When that happens, the interrupt handler finds the `distance` variable half-updated, with a mix of bytes from the previous and the current distance measurements. This is called a “race condition”, and is one of the worst kind of bugs you can meet, because it is very hard to systematically reproduce.

The fix to the race condition is to update the variable with interrupts disabled. The wrong way to do it is:

```
duration = pulseIn(echo, HIGH);
noInterrupts();
distance = duration * 0.0343 / 2;
interrupts();

```

This is bad because interrupts are blocked during the distance calculation, which is too much. The right way is this:

```
duration = pulseIn(echo, HIGH);
temp = duration * 0.0343 / 2;
noInterrupts();
distance = temp;
interrupts();

```

Now interrupts are blocked only while writing the `distance` variable.

Personally I don't think it is such a great idea to read the buttons with interrupts. Buttons are extremely slow peripherals. If you make your code non-blocking, your `loop()` will always be fast enough to deal with them. Handling the buttons in `loop()` means you don't have to worry about all the bugs that can easily sneak into interrupt-driven code, like the above mentioned race condition.

---

**Edit**: In the original version of your code, interrupts were used to read the switches. In the edited version, you added a debouncer, and you don't need interrupts anymore. In fact, the way this version uses interrupts makes no sense at all. The most problematic bit is the fact that this code can disable interrupts for arbitrarily long times. This is not good, and you should be aware that the Arduino's timekeeping functions rely on interrupts to perform their job.

I suggest you just remove from this code every single line where you see the word “interrupt” (singular or plural), and you replace

```
if(distance>8)interrupts();

```

by

```
if (distance > 8) {
    red();
    green();
}

```

or, to streamline things a little bit, by

```
if (distance > 8) {
    if (ys == HIGH) pwm = 250;
    else if (rs == HIGH) pwm = 150;
    else pwm = 0;
}

```

---
Tags: arduino-uno, led, interrupt, pwm, hc-sr04
---


title: Two ports on Uno with ethernet shield

text:
# Question
Title: Two ports on Uno with ethernet shield
I am making an Arduino mod-bus device and I want to make a webpage as well that will allow me to reset the unit if there is any issues remotely. To do this I would need the mod-bus to operate on port 502 and the webpage to operate on port 80. is it possible for the Arduino to support two ports? I am using an Uno with a Ethernet shield and the standard ehternet.h file with a Modbus library. Any suggestions or ideas?

```
 #include SPI.h
 #include VL53L0X.h
 #include Ethernet.h
 #include Modbus.h
 #include ModbusIP.h
 #include VL53L0X.h
 #include Wire.h

VL53L0X sensor;
EthernetServer server(80);

//Modbus Registers Offsets (0-9999)
const int SENSOR_Hreg0 = 100;

//ModbusIP object
ModbusIP mb;

short ts;

void setup() {
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  byte ip[] = { 192, 168, 1, 177 };

  Wire.begin();
  mb.config(mac, ip);

  // Add SENSOR_Ireg register - Use addIreg() for analog Inputs
  mb.addHreg(SENSOR_Hreg0);

  ts = millis();

  //Sensor setup
  sensor.init();
  sensor.setTimeout(500);
  sensor.startContinuous();

  //remote reset
    pinMode(13, INPUT);
    digitalWrite(13, LOW);

   // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Ethernet WebServer Example");

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);

  // Check for Ethernet hardware present
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) {
      delay(1); // do nothing, no point running without Ethernet hardware
    }
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }

  // start the server
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

}

void loop() {

  mb.task();

    //Webpage
    // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin

            client.print("Distance Measures ");
            client.print(sensor.readRangeContinuousMillimeters());
            client.print("mm");
            client.println("<br />");
            client.print("Filter Count:");
            client.print(-2.2*sensor.readRangeContinuousMillimeters()+404);
            client.println("<br />");
          }
          client.println("</html>");
          break;
        }

      }

  //Modbus
  if (millis() > ts + 100) {
    ts = millis();

     mb.Hreg(SENSOR_Hreg0, sensor.readRangeContinuousMillimeters() );

     }
}}

```

Edit: Note: The issue seems to lie somewhere in with the sensor, because when I run it with out have the sensor code in there is no problem but when I add it the issue starts again.

# Answer
* **move the modbus refresh out of the `if (client)` condition**
* `mb.begin()` calls `Ethernet.begin()`. Do not repeat it in setup()
* move `client.println("</html>"); break;` inside the `if` block before it
* copy the rest of the detection of empty line from the WebServer example
* `stop()` the client after response
* change type of `ts` to `unsigned long`
> 0 votes

---
Tags: arduino-uno, port-mapping, ethernet-shield
---


title: Dimmer.h issues with ATmega 128

text:
# Question
Title: Dimmer.h issues with ATmega 128
I am using a ZCD circuit controlling a TRIAC. Now I am using Dimmer library for this purpose. It works fine with ATMega 328 but whenever I try to upload the code in ATMega 128 using Arduino IDE this error pops up:

```
Arduino: 1.8.4 (Windows 10), Board: "ATmega128, 2.7v, Disabled (default), 16 MHz external"

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp: In member function 'void Dimmer::begin(uint8_t, bool)':

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:15:20: error: 'TCCR2A' was not declared in this scope

 #define _TCCRxA(X) TCCR ## X ## A

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:16:19: note: in expansion of macro '_TCCRxA'

 #define TCCRxA(X) _TCCRxA(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:157:5: note: in expansion of macro 'TCCRxA'

     TCCRxA(DIMMER_TIMER) = TCCRxA_VALUE;         // Timer config byte A

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:17:20: error: 'TCCR2B' was not declared in this scope

 #define _TCCRxB(X) TCCR ## X ## B

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:18:19: note: in expansion of macro '_TCCRxB'

 #define TCCRxB(X) _TCCRxB(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:158:5: note: in expansion of macro 'TCCRxB'

     TCCRxB(DIMMER_TIMER) = TCCRxB_VALUE;         // Timer config byte B

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:19:20: error: 'TIMSK2' was not declared in this scope

 #define _TIMSKx(X) TIMSK ## X

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:20:19: note: in expansion of macro '_TIMSKx'

 #define TIMSKx(X) _TIMSKx(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:159:5: note: in expansion of macro 'TIMSKx'

     TIMSKx(DIMMER_TIMER) = 0x02;                 // Timer Compare Match Interrupt Enable

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:21:19: error: 'OCR2A' was not declared in this scope

 #define _OCRxA(X) OCR ## X ## A

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:22:18: note: in expansion of macro '_OCRxA'

 #define OCRxA(X) _OCRxA(X)

                  ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:160:5: note: in expansion of macro 'OCRxA'

     OCRxA(DIMMER_TIMER) = 100 * 60 / acFreq - 1; // Compare value (frequency adjusted)

     ^

exit status 1
Error compiling for board ATmega128.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Any idea what is the issue ?

# Answer
The Dimmer library doesn't support Atmega128/164/16/32. It has

```
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define DIMMER_TIMER 4
#elif defined(__AVR_ATmega32U4__)
#define DIMMER_TIMER 3
#else
#define DIMMER_TIMER 2
#endif

```

For the Atmega128/164/16/32 it will use timer 2. The main errors are:

```
'OCR2A' was not declared in this scope
'TCCR2A' was not declared in this scope
'TCCR2B' was not declared in this scope
'TIMSK2' was not declared in this scope

```

**Possible solution**:

You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change `TIMSKx(DIMMER_TIMER) = 0x02` perhaps to `bitSet(ETIMSK, 3);`. Check the datasheet. I can't test it, I don't have the chip.
> 1 votes

---
Tags: arduino-mega, atmega328
---


# Question
Title: Websockets with the ESP8266 using arduino uno board
I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.

I've got an ardunio uno board and this ESP8266:

I found this websockets library but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE

**My question:** Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.

# Answer
The library you linked is not for Uno with esp8266 module.

It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.

Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.
> 0 votes

---
Tags: arduino-uno, esp8266, wifi, iot
---