# Question
Title: How to start particular event for particular time using millis()?
In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.

The code is below:

```
const int ledPin =  LED_BUILTIN;

int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 5000;

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

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;

    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    digitalWrite(ledPin, ledState);
  }
}

```

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.

# Answer
Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.

To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.

To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.

```
const int ledPin =  LED_BUILTIN;

unsigned long previousMillis;
const unsigned long interval = 5000UL;
boolean enableDelay = false;

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

void loop()
{
  unsigned long currentMillis = millis();

  // Trigger the delay, I use analogRead.
  if (analogRead(A0) > 500)
  {
    enableDelay = true;
    previousMillis = currentMillis;
    digitalWrite(ledpin, HIGH);
  }

  // Checking the millis delay should be done in the loop.
  // This code is not inside the code to start the delay, but
  // at the same level as other code in the loop.
  if (enableDelay)
  {
    if (currentMillis - previousMillis >= interval)
    {
      enableDelay = false;
      digitalWrite(ledPin, LOW);
    }
  }
}

```

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis **must** be unsigned long, but it is okay if "interval" is a long.

This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.
> 2 votes

---
Tags: arduino-uno, millis
---


# Question
Title: How to connect an Arduino via an ethernet cable to a laptop directly?
Maybe a silly question, because it is a usual topic, but I have a problem with my Arduino Leonardo ETH.

I want to create a web server on the Arduino with the example sketch `File > Examples > Ethernet > WebServer`. I plugged in the ethernet cable directly to my laptop. So there is no router or switch between them.

I also set the configuration to my ethernet port to the following IPv4 properties:

Then in the example sketch, I changed the MAC address according to the bottom sticker of my Arduino.

```
byte mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x33, 0xD6};
IPAddress ip(192, 168, 1, 177);

```

Now when I compile and upload the sketch to the Arduino, everything is working fine until it prints the IP address. According to the IP address which I have set in the code (`192.186.1.177`), it shows me `0.46.46.46` as you can see in the picture:

This happens when I print that:

```
Serial.println("server is at ");
Serial.println(Ethernet.localIP());

```

Do you have any ideas how I could fix this? And why does it show me that invalid IP address?

Thank you in advance.

# Answer
> 1 votes
use the Ethernet2 library for W5500

---
Tags: ethernet, arduino-leonardo, web-server
---


# Question
Title: LSM9DS1: Inconsistent data from an accelerometer
I'm currently getting inconsistent data from the accelerometer of my Adafruit LSM9DS1. To be more precise I either get a value close to the correct gravity (eg. 9.496515) or some reading like it was in space/free fall (eg. -0.023928225).

This seems to happen on all three the axes (I tried rotating the LSM9DS1).

I get the same behavior with FIFO enabled or not and with the Gyro enabled or not.

This is a set of 32 consecutive samples that I read from the FIFO memory:

```
result = {float[32][]@5092}
 0 = {float[3]@5100}
  0 = -0.41754755
  1 = 0.19501504
  2 = 9.519247
 1 = {float[3]@5112}
  0 = -0.421735
  1 = 0.19980069
  2 = 9.51805
 2 = {float[3]@5120}
  0 = -0.4229314
  1 = 0.20757735
  2 = 9.510274
 3 = {float[3]@5128}
  0 = -0.4127619
  1 = 0.2207379
  2 = 9.502497
 4 = {float[3]@5139}
  0 = -0.39302114
  1 = -0.06580262
  2 = -0.0017946169
 5 = {float[3]@5140}
  0 = -0.06939186
  1 = -0.045463633
  2 = -0.020937197
 6 = {float[3]@5141}
  0 = -0.05742774
  1 = -0.03469593
  2 = -0.0317049
 7 = {float[3]@5142}
  0 = -0.053838514
  1 = -0.039481573
  2 = -0.041874394
 8 = {float[3]@5143}
  0 = -0.054436717
  1 = -0.052642096
  2 = -0.043669015
 9 = {float[3]@5144}
  0 = -0.059820566
  1 = -0.068793654
  2 = -0.03469593
 10 = {float[3]@5145}
  0 = -0.06819545
  1 = 0.22731815
  2 = -0.019142581
 11 = {float[3]@5146}
  0 = -0.38644087
  1 = 0.2225325
  2 = -0.00418744
 12 = {float[3]@5147}
  0 = -0.40079778
  1 = 0.21535406
  2 = 9.505488
 13 = {float[3]@5148}
  0 = -0.40977085
  1 = 0.21355942
  2 = 9.525827
 14 = {float[3]@5149}
  0 = -0.40917268
  1 = 0.21296123
  2 = 9.540783
 15 = {float[3]@5150}
  0 = -0.40558344
  1 = 0.2207379
  2 = 9.5455675
 16 = {float[3]@5151}
  0 = -0.39960137
  1 = 0.22671993
  2 = 9.544371
 17 = {float[3]@5152}
  0 = -0.39302114
  1 = 0.22791636
  2 = 9.534203
 18 = {float[3]@5153}
  0 = -0.3906283
  1 = 0.21535406
  2 = 9.517452
 19 = {float[3]@5154}
  0 = -0.38584265
  1 = 0.19441684
  2 = 9.496515
 20 = {float[3]@5155}
  0 = -0.384048
  1 = 0.17347965
  2 = -0.023928225
 21 = {float[3]@5156}
  0 = -0.38883367
  1 = 0.15553348
  2 = -0.042472597
 22 = {float[3]@5157}
  0 = -0.39541394
  1 = -0.014356935
  2 = -0.05802595
 23 = {float[3]@5158}
  0 = -0.40259242
  1 = -0.026919257
  2 = -0.06580262
 24 = {float[3]@5159}
  0 = -0.40977085
  1 = -0.03589234
  2 = -0.071186475
 25 = {float[3]@5160}
  0 = -0.4151547
  1 = -0.040677987
  2 = -0.062213387
 26 = {float[3]@5161}
  0 = -0.421735
  1 = -0.03888337
  2 = -0.04965107
 27 = {float[3]@5162}
  0 = -0.42831525
  1 = -0.040677987
  2 = -0.032303106
 28 = {float[3]@5163}
  0 = -0.4372883
  1 = -0.04426722
  2 = -0.014356935
 29 = {float[3]@5164}
  0 = -0.445065
  1 = -0.04785645
  2 = 9.496515
 30 = {float[3]@5165}
  0 = -0.44865423
  1 = -0.04666004
  2 = 9.503693
 31 = {float[3]@5166}
  0 = -0.44865423
  1 = -0.04426722
  2 = 9.506086

```

As you can see 15 times the Z axis shows the correct value and 17 shows -0.

This is how I'm initializing the sensors:

```
        // soft reset & reboot accel/gyro
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG8, (byte) 0b00000101);
        // soft reset & reboot magnetometer
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG2_M, (byte) 0b00001100);

        SystemClock.sleep(10);

        byte idXg = readRegByte(SensorType.XG, REGISTER_WHO_AM_I_XG);
        byte idMag = readRegByte(SensorType.MAG, REGISTER_WHO_AM_I_M);
        if (idXg != XG_ID || idMag != MAG_ID) {
            throw new IllegalStateException("Could not find LSM9DS1, check wiring!");
        }

        setFifoMemoryEnabled(false);

        // enable gyro continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG1_G, (byte) 0b11000000); // on XYZ

        // Enable the accelerometer continuous
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG5_XL,
                (byte) (CTRL_REG5_XL_ZEN_XL | CTRL_REG5_XL_YEN_XL | CTRL_REG5_XL_XEN_XL)); // enable X Y and Z axis
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG6_XL, (byte) 0b11000000); // 1 KHz out data rate, BW set by ODR, 408Hz anti-aliasing
        writeRegByte(SensorType.XG, REGISTER_CTRL_REG7_XL, (byte) 0b10000000); // HR - High resolution mode

        // enable mag continuous
        writeRegByte(SensorType.MAG, REGISTER_CTRL_REG3_M, (byte) 0x00); // continuous mode

```

And this is how I'm reading the accelerometer data:

```
        byte[] buffer = new byte[6];
        int[] result = new int[3];
        readRegBuffer(SensorType.XG, REGISTER_OUT_X_L_XL, buffer, buffer.length);
        result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
        result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
        result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values
        return result;

```

I'm then converting the raw values with this formula (but this is a constant change so it should not matter):

```
rawAccelerometerData[i] * mAccelMgLsb / 1000f * mGravity;

```

I've also tried to disable the gyro and the magnetometer and left only the Z axis enabled and than tried to fetch the data using different output data rate but the result is the same.

The full code of my driver is available here.

I currently have only one LSM9DS1 so I have no clue if this is a defective product or an expected behavior and if this can be fixed with a different configuration.

PS

> ! as you might have guessed looking at the code I'm not really using an Arduino to access the LSM9DS1 but I still believe that this is still a good place to ask for help since I don't think my issue is platform related but is either some error in my code or a faulty sensor. And my code is just a port of this Arduino driver: https://github.com/adafruit/Adafruit\_LSM9DS1.

# Answer
> 0 votes
The problem is how the accelerometer data is read, to be precise is in these lines:

```
result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values

```

What I'm getting from the sensor is a 16bit in two’s complement spitted in 2 bytes, for example `buffer[4]` and `buffer[5]` where 4 is the low byte and 5 is the high.

In Java the `&` and `|` are defined to operate only on `int` and `long` values, so what happens is that the `byte` is always promoted to signed `int`:

```
buffer[5] = 00111100
buffer[4] = 11110110
(int)buffer[4] = 11111111111111111111111111110110 = FF FF FF F6
(buffer[5] << 8) | buffer[4] = FF FF FF F6

```

With the original code both bytes are handled has two’s complement when actually **only the high byte is holding the sign**.

Long story short, you have to keep the sign for the high byte (cast to `int`) and threat the low as unsigned (autocast to `int` using the `&` and keeping only the original byte with `0xFF`):

```
result[0] = (((int) buffer[1]) << 8) | (buffer[0] & 0xFF); // Store x-axis values
result[1] = (((int) buffer[3]) << 8) | (buffer[2] & 0xFF); // Store y-axis values
result[2] = (((int) buffer[5]) << 8) | (buffer[4] & 0xFF); // Store z-axis values

```

---
Tags: sensors, i2c, adafruit, accelerometer, android
---


# Question
Title: How to switch a low-voltage (1.5V) toy motor with an arduino?
I would like to add an Arduino to control a toy with a 1.5V battery and motor in it. The toy is currently controlled by a SPST switch in series with a single 1.5V AA battery and a cheap motor.

I could put in a transistor like How to switch an external circuit with Arduino? or To connect a simple toy circuit and trigger with an arduino? but I would think the voltage drop of the transistor would be significant in the 1.5V circuit.

What would you recommend for switching a 1.5V circuit?

# Answer
> 4 votes
You would be better off using a MOSFET which, when on, has quite a low resistance. For example the RFP30N06LE datasheet shows a RDS(on) of 0.047 Ω at 30A and 5V.

Using Ohm's Law we therefore expect a voltage drop of:

```
V = IR
V = 0.5 x 0.047
V = 0.0235

```

Thus, only 23 mV drop if you are drawing half an amp. I measured using a toy that drew 200 mA and found a 5 mV drop at 1.5V (compared to the theoretical 9 mV).

I have a page about driving motors that illustrates how you might wire up such a device.

The 12V on that schematic could just as easily be 1.5V.

The diode on the schematic is a snubber diode which protects the transistor from flyback voltages from the motor.

---

## Comparison to transistor

BJT transistors will have a higher voltage drop between collector and emitter. For example the 2N3904 has a 200 mV drop (0.2V) (called VCE(sat)) when conducting 50 mA. This is a somewhat larger drop than the 5 mV drop that I got with the MOSFET, and a somewhat larger percentage of the 1.5V that you are starting with.

---
Tags: voltage-level
---


# Question
Title: Error while uploading code with Arduino on breadboard using FTDI 232
My circuit is as seen and I hope there is no error with the wiring. I'm using an ATmega328P. The error suggests that the programmer is not responding and ten attempts issuing not in sync code. There isn't any bootloader issue as pin 13 LED flickers as soon as I plug in USB cable. I have selected the following board specification in the Arduino IDE:

* Board: Arduino Uno
* Programmer: Arduino as ISP

Schematics I followed:

ATmega pinout reference:

Connections:

* Pin 1: 10k resistor to 5V, 0.1uF capacitor pin series with DTR of FTDI
* Pin 2: Tx of FTDI
* Pin 3: Rx of FTDI
* Pins 9 & 10: 16 MHz oscillator and 22pf capacitor in series
* Pins 7, 20, 21: 5v
* Pins 8, 22: ground
* Pin 19: status LED (similar to pin 13 LED on standard Arduino Uno)

I used both ways of uploading (directly and upload using programmer) and nothing worked. The bootloader in the chip is that of the Arduino Uno and it was burned using another Uno board. SPI programming using another Uno board works fine. I tried different combination of programmer in IDE but futile. The capacitor for reset is 0.1 µf and it seems that connections are fine as there was no issue with uploading using another Uno board as ISP.I would love if anyone can help me out with this.

Related images are:

PS: \[Post comment changes\]

-I added a 47uF and 0.1uF caps for cleaner supply to the chip based on suggestions in comment section.

* board with changes\[by pass capacitors ,resistor visible on pin 19\] \[\]
* IDE specifics

**Solution-**

* credits- @Nickgammon
* had problem with bootloader which was initially uploaded . later solved it by following instructions from NickGammon Forum - http://www.gammon.com.au/breadboard

related images-

* snap shot from bootloading window in arduino IDE

# Answer
> 0 votes
Here is a photo of the setup I used on this page about a breadboard Arduino. I can't see any material differences between yours and mine, except that I wouldn't connect Aref (pin 21) to anything.

Close-up of the FTDI connection:

I have 0.1 µF capacitors as decoupling capacitors on both sides of the breadboard.

> I used both ways of uploading (directly and upload using programmer) and nothing worked.

Assuming you have the Uno bootloader installed (and that the fuses are still set to what they should be for a Uno) then you want direct uploading (with board type set to Uno), not uploading via a programmer.

---
Tags: arduino-uno, serial, ftdi
---


title: How to make a smooth serial print?

text:
# Question
Title: How to make a smooth serial print?
I have a code which make some calculations using sensor values and provide two comma separated values.

```
float x;// initialization
float y;// initialization
//some calculations here using sensor values
Serial.print(x);Serial.print(",");Serial.print(y);

```

but the issue is due to some unstable situations of the sensor readings, I don't receive sensor data in same time intervals (overall delay is 1 second). I send these values to my Android device through a Bluetooth connection. At that stage, android device cannot separate two values due to lack of smoothness of the Serial.print(). Is there any way to make it smooth (like saving to a buffer before serial print or something) ?

# Answer
I bet your problem has nothing to do with “smoothness” (whatever that means), but is entirely due to lack of *message framing*. The serial and bluetooth links do not transmit messages: they transmit only a stream of bytes, with no built-in notion of where a message ends and the next one starts. Relying on the timing of the received bytes to tell the messages apart is very unwise. You should instead use some kind of delimiter for your messages.

For text-based transmissions like yours, the most natural choice is to send a line terminator at the end of each message. Typically a CR+LF pair. The `Serial` object has the `println()` methods designed precisely for this purpose: they send their arguments immediately followed by CRLF:

```
Serial.print(x); Serial.print(","); Serial.println(y);

```

At the receiving end, you have to buffer all the incoming characters until you see the line termination. Then you know the message is complete and you can process it.
> 2 votes

# Answer
> Are there any way to make it smooth. (like saving to a buffer before serial print or something) ?

you can use sprintf function

```
char buff[50];
sprintf(buff, "{i:%i,t:%lu,v1:%d,v2:%d,c:%u}", ix, events[ix].timestamp, events[ix].value1, events[ix].value2, events[ix].count);
s.print(buff);

```

but this will not help you, I think. if you do not print nothing else only those 3 prints, then your next loop will print the first number 'glued' to the last number from the previous loop. use for example prinln to separate them with a newline.

if you have an interrupt in work which can interrupt the execution of the loop and make the prints 'not smooth', it too will be not repaired by printing a buffer. because the interrupt disrupts the Serial too
> 0 votes

---
Tags: serial, arduino-ide, bluetooth, android
---


# Question
Title: Need help on the "expected primary expression before "}" token"
```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

#define M11  2
#define M12  3
#define M13  4
#define M14  5

#define M21  6
#define M22  7
#define M23  8
#define M24  9

uint32_t commands[32];
int confirmationBuzzer = 17;
int i = 0;
boolean DirectionR = true;
boolean DirectionL = true;
int StepsR;
int StepsL;
int steps_left = 4095;
int caseLeft;

RF24 radio(10, 14); // CE, CSN
SoftwareSerial mySoftwareSerial(15, 16); // RX, TX

DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

const byte address[6] = "00001";

void stepperR(int xw) {
    for (int x = 0;x < xw;x++) {
        switch (StepsR) {
        case 0:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, HIGH);
            break;
        case 1:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, HIGH);
            break;
        case 2:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, LOW);
            break;
        case 3:
            digitalWrite(M11, LOW);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, LOW);
            break;
        case 4:
            digitalWrite(M11, LOW);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 5:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 6:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 7:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, HIGH);
            break;
        default:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        }
        SetDirectionR();
    }
}

void SetDirectionR() {
    if (DirectionR == 1) { StepsR++; }
    if (DirectionR == 0) { StepsR--; }
    if (StepsR>7) { StepsR = 0; }
    if (StepsR<0) { StepsR = 7; }
}

void stepperL(int xw) {
    for (int x = 0;x<xw;x++) {
        switch (StepsL) {
        case 0:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, HIGH);
            break;
        case 1:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, HIGH);
            break;
        case 2:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, LOW);
            break;
        case 3:
            digitalWrite(M11, LOW);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, HIGH);
            digitalWrite(M14, LOW);
            break;
        case 4:
            digitalWrite(M11, LOW);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 5:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, HIGH);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 6:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        case 7:
            digitalWrite(M11, HIGH);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, HIGH);
            break;
        default:
            digitalWrite(M11, LOW);
            digitalWrite(M12, LOW);
            digitalWrite(M13, LOW);
            digitalWrite(M14, LOW);
            break;
        }
        SetDirectionL();
    }
}

void SetDirectionL() {
    if (DirectionL == 1) { StepsL++; }
    if (DirectionL == 0) { StepsL--; }
    if (StepsL>7) { StepsL = 0; }
    if (StepsL<0) { StepsL = 7; }
}

void setup() {

    myDFPlayer.volume(7);

    radio.begin();
    radio.openReadingPipe(0, address);
    radio.setPALevel(RF24_PA_MIN);
    radio.startListening();
}
void loop() {

    if (radio.available()) {
        radio.read(&commands, sizeof(commands));
    }
    for (i = 0; i<15; i++) {
        switch (i) {

        case(0):

            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }

            break;

        case(1): {
        case1:
            int caseLeft = 1;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }

            break;
        }
        case(2): {
        case2:
            int caseLeft = 2;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(3): {
        case3:
            int caseLeft = 3;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(4): {
        case4:
            int caseLeft = 4;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(5): {
        case5:
            int caseLeft = 5;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(6): {
        case6:
            int caseLeft = 6;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(7): {
        case7:
            int caseLeft = 7;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(8): {
        case8:
            int caseLeft = 8;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(9): {
        case9:
            int caseLeft = 9;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(10): {
        case10:
            int caseLeft = 10;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(11): {
        case11:
            int caseLeft = 11;
            switch (commands[i]) {
            case(0):
                goto outoftheloop;
                break;

            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):

                goto function1;

                break;
            }
            break;
        }
        case(12): {
        function1:
            switch (commands[i]) {
            case(0):
                switch (caseLeft) {

                case(0):
                    goto case1;
                    break;

                case(1):
                    goto case2;
                    break;

                case(2):
                    goto case3;
                    break;

                case(3):
                    goto case4;
                    break;
                case(4):
                    goto case5;
                    break;

                case(5):
                    goto case6;
                    break;

                case(6):
                    goto case1;
                    break;

                case(7):
                    goto case2;
                    break;

                case(8):
                    goto case1;
                    break;

                case(9):
                    goto case2;
                    break;
                case(10):
                    goto case1;
                    break;

                case(11):
                    goto case2;
                    break;
                }
                break;
            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                goto function2;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function2;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function2;
                break;

            case(4):
                goto function1;

                break;

            }
            break;
        }
        case(13): {
        function2:
            switch (commands[i]) {
            case(0):
                switch (caseLeft) {

                case(0):
                    goto case1;
                    break;

                case(1):
                    goto case2;
                    break;

                case(2):
                    goto case3;
                    break;

                case(3):
                    goto case4;
                    break;
                case(4):
                    goto case5;
                    break;

                case(5):
                    goto case6;
                    break;

                case(6):
                    goto case1;
                    break;

                case(7):
                    goto case2;
                    break;

                case(8):
                    goto case1;
                    break;

                case(9):
                    goto case2;
                    break;
                case(10):
                    goto case1;
                    break;

                case(11):
                    goto case2;
                    break;
                }
                break;
            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                goto function3;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function3;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function3;
                break;

            case(4):
                goto function1;

                break;

            }
            break;
        }
        case(14): {
        function3:
            switch (commands[i]) {
            case(0):
                switch (caseLeft) {

                case(0):
                    goto case1;
                    break;

                case(1):
                    goto case2;
                    break;

                case(2):
                    goto case3;
                    break;

                case(3):
                    goto case4;
                    break;
                case(4):
                    goto case5;
                    break;

                case(5):
                    goto case6;
                    break;

                case(6):
                    goto case1;
                    break;

                case(7):
                    goto case2;
                    break;

                case(8):
                    goto case1;
                    break;

                case(9):
                    goto case2;
                    break;
                case(10):
                    goto case1;
                    break;

                case(11):
                    goto case2;
                    break;
                }
                break;
            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                goto function4;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function4;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                goto function4;
                break;

            case(4):
                goto function1;

                break;

            }
            break;
        }
        case(15): {
        function4:
            switch (commands[i]) {
            case(0):
                switch (caseLeft) {

                case(0):
                    goto case1;
                    break;

                case(1):
                    goto case2;
                    break;

                case(2):
                    goto case3;
                    break;

                case(3):
                    goto case4;
                    break;
                case(4):
                    goto case5;
                    break;

                case(5):
                    goto case6;
                    break;

                case(6):
                    goto case1;
                    break;

                case(7):
                    goto case2;
                    break;

                case(8):
                    goto case1;
                    break;

                case(9):
                    goto case2;
                    break;
                case(10):
                    goto case1;
                    break;

                case(11):
                    goto case2;
                    break;
                }
                break;
            case(1):

                DirectionR = true;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(2);
                    stepperL(2);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(2):
                DirectionR = true;
                DirectionL = false;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(3):
                DirectionR = false;
                DirectionL = true;

                while (steps_left>0) {

                    stepperR(1);
                    stepperL(1);
                    steps_left--;
                }
                steps_left = 4095;
                break;

            case(4):
                goto function1;

                break;

            }
            break;
        }
        }
    }
outoftheloop:
}

```

Sorry for the long code,I would send only a part of the code that shows error however I am not sure if the other parts are related to the code. I get this error.

> Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"
>
> C:\Users\TEDNOKENT2\Desktop\sketch\_dec22a\sketch\_dec22a.ino: In function 'void setup()':
>
> C:\Users\TEDNOKENT2\Desktop\sketch\_dec22a\sketch\_dec22a.ino:183:35: warning: invalid conversion from 'const byte\* {aka const unsigned char\*}' to 'uint64\_t {aka long long unsigned int}' \[-fpermissive\]
>
> radio.openReadingPipe(0, address);
>
> In file included from \>C:\Users\TEDNOKENT2\Desktop\sketch\_dec22a\sketch\_dec22a.ino:3:0:
>
> C:\Users\TEDNOKENT2\Documents\Arduino\libraries\RF24-master/RF24.h:350:8: note: \>initializing argument 2 of 'void RF24::openReadingPipe(uint8\_t, uint64\_t)'
>
> void openReadingPipe(uint8\_t number, uint64\_t address);
>
> C:\Users\TEDNOKENT2\Desktop\sketch\_dec22a\sketch\_dec22a.ino: In function 'void loop()':
>
> sketch\_dec22a:1288: error: expected primary-expression before '}' token
>
> }
>
> exit status 1 expected primary-expression before '}' token
>
> This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences.

Normally, it should have been fixed adter I deleted some extra brackets but it just stayed there. I have no idea why. I know I shouldn't use gotos that often, however, I am kind of a novice programmer and goto s make it a lot easier to code. I would appreaciate any suggestions on the error. If anthing else that is not related to the error but you think is not necessary, you can mention them too.

Thanks in advance

# Answer
Actually, although I'm not going to check for every bracket, here are some tips to prevent the problem (and if you follow them you will find your missing/extra bracket):

* Align brackets, I know it saves one line if you put the { directly after statements, but much neater to put them separately on the next line.
* Make short functions. If you get a compiler error in a function, it's much easier to find the location. It also helps clearity, maintainability, testability etc. To do this:
* Do not use more than 2 or 3 compound statements (while, switch, if etc).
* Put (almost) duplicate code in separate functions and call them (either without parameters or with parameters if needed).
* Never use goto statements. You can always replace them by if, while, for or do statements.
> 1 votes

# Answer
My two cents here.

When you have lots of repetitive structures, like in function `stepperR`, is time to simplify, put some things as data and reduce the repetitiveness of your code.

Here is `stepperR` reimplemented

```
byte values[9] = {1, 3, 2, 6, 4, 12, 8, 9, 0};
void stepperR(int xw) {
    for (int x = 0;x < xw;x++) {
            digitalWrite(M11, values[StepsR] & 0x08);
            digitalWrite(M12, values[StepsR] & 0x04);
            digitalWrite(M13, values[StepsR] & 0x02);
            digitalWrite(M14, values[StepsR] & 0x01);
            SetDirectionR();
    }
}

```

I choose `StepsR == 8` as the *default* value (all zeros).
> 0 votes

---
Tags: code-review, compilation-errors
---


# Question
Title: how to check 24c32 eprom is connected or not to arduino runtime?
I want to check it on runtime if runitme i remove eprom then it shows "please insert dongle " also tried using while loop showing eroor.. How can i solve it?

```
Wire.beginTransmission(80);
      error = Wire.endTransmission();
    if (error == 0)
    {
    serial.print("connected");
    }
    else
    {
    serial.print("please insert dongle");
    }

```

also tried using while loop in loop()

```
void loop()
{
while (error == 0){
Serial.print("connected");
}

Serial.print("insert dongle");
}

```

# Answer
You should take parts of the I2C Scanner. You don't need to scan for all addresses - you can just scan for the one address you're interested in:

```
Wire.beginTransmission(80);
error = Wire.endTransmission();

if (error == 0)
{
  Serial.print("Connected");
} else {
  Serial.println("Insert dongle");
}

```
> 0 votes

---
Tags: arduino-uno, serial, programming, eeprom
---


# Question
Title: Problem uploading the code into an Arduino Uno
I was trying to upload code for a blinking LED. It is a new Arduino Uno board. Any further help will be appreciated.I got the following error:

> Info.: OS- Ubuntu 16.04
>
> Software: Arduino IDE 1.8.5

I could not see any port.

I have tried dialout. But still it is not working.

I also have a confusion, i.e. the `Programmer` menu shows AVRISP mkll.

If anyone wants any information, please do comment.

Error:

> An error occurred while uploading the sketch avrdude: ser\_open(): can't open device "COM1": No such file or directory\`

# Answer
> 1 votes
Ubuntu and other Linux operating systems don’t name the serial ports “COM1” or similar.

They use special files like

```
/dev/tty.[something]

```

The \[something\] depends on the USB device driver. The IDE should list available serial ports in the Port selection menu.

---
Tags: arduino-uno, compilation-errors
---


title: Receive data using ESP8266

text:
# Question
Title: Receive data using ESP8266
I have connected ESP8266 to my Raspberry Pi's WiFi network and assigned a static IP.

My Arduino code

```
#include "SoftwareSerial.h"

String ssid = "Rpi";
String password = "raspberry";

SoftwareSerial esp(3, 2);// RX, TX

String server = "192.168.50.1"; //my Host

void setup() {
  esp.begin(115200);
  Serial.begin(115200);
  connectWifi();
  httpget();
  delay(1000);
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);
  if (esp.find("OK")) {
    Serial.println("Connected!");
  }
  else {
    Serial.println("Cannot connect to wifi ! Connecting again...");
  }
  connectWifi();
}

/////////////////////////////GET METHOD///////////////////////////////
void httpget() {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",1234");//start a TCP connection.
  if ( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  /*
    String getRequest =
    "GET " + uri + " HTTP/1.0\r\n" +
    "Host: " + server + "\r\n" +
    "Accept: *" + "/" + "*\r\n" +
    "Content-Type: application/json\r\n" +
    "\r\n";
  */
  String sendCmd = "AT+CIPSEND=";
  esp.print(sendCmd);
  //esp.println(getRequest.length() );
  delay(500);
  if (esp.find(">")) {
    Serial.println("Sending..");
    //  esp.print(getRequest);
    if ( esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String response = esp.readString();
      }
      esp.println("AT+CIPCLOSE");
    }
  }
}

void loop() {
  httpget();
}

```

I get this message

> > Cannot connect to wifi ! Connecting again...

In my Raspberry Pi I am constantly sending a signal to this IP address.

```
import socket

TCP_IP = '192.168.50.1' #Local Host
TCP_PORT = 1234            #Listening Port
BUFFER_SIZE = 12

SERVER_IP = '192.168.50.18'  #Arduino IP
SERVER_PORT = 3007            #Server Port

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((TCP_IP,TCP_PORT))
#s.listen(1)

#(conn,addr) = s.accept()
#print 'Connection address: ',addr
while True:
    print 'Sending message'
    s.sendto('1',(SERVER_IP,SERVER_PORT))
    print 'Waiting for response'
    data,addr = s.recvfrom(BUFFER_SIZE)
    if not data: break
    print 'received data: ',data
    print 'data recieved from: ',addr
    conn.close()
s.close()

```

But I can not see it in my Serial Monitor. Do I need to create a separate program for getting from WiFi?

# Answer
> 1 votes
You are recursively calling `connectWifi()` and therefore your setup function results in an infinite loop. You must not implement loops and for processes, which take some time, you should set and ask a flag. Btw. why don't you use the official ESP WiFi library?

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


# Question
Title: Will Arduino Mega support stepper motor NEMA 24, NEMA 34
Will two stepper motor NEMA 24, 10 kg cm, 2. 8 amp, 24 vdc work at same time on Arduino Mega and when they stop stepper motor NEMA 34, 34 kg cm, 4amp, 24 VDC will work or not? This is my first project please help me to choose the controller.

# Answer
> 1 votes
I'm using 4x Nema 24s for a CNC project of mine. They only need a couple of signals/pins each from the Arduino to work, the rest is up to the stepper controller board.

For my steppers, I'm using TB6600s, since I need ~3.5 amps per motor/channel. There are others out there that'll work, but it's what I saw other people at my maker space using.

Nema34s would probably need higher rated amps, so that would determine what controller you need to use.

In fact, every motor is rated for different amps and voltages, so that will always determine what motor controller you use. Since you need a higher voltage to run the motor controllers than the Arduino, using a separate stepping power supply is a requirement.

The Arduino gets hooked to the step/pulse and direction pins of the motor controller and the other pins on the motor controller go elsewhere. The CNC motor controller shields you normally see are for lower amp controllers and do most of the pin connections for you. With the higher amperage motors, you'll have to do this yourself.

When you determine what motor controller you are going to use, find a wiring diagram for it (and maybe a friend) to figure out how it should be wired.

---
Tags: arduino-mega, stepper
---


# Question
Title: WiFi module ESP8266-01 for Arduino not working
I am new to using Arduino just bought my first one yesterday, and I also got an WiFi module. The Arduino I got is another brand but should be the same as the Arduino Uno rev 3 and I got the ESP8266-01 wifi module.

I've tried doing some simple examples projects following some YouYube videos, and all those have worked without problem.

What I am trying to create is a simple magnetic door switch. When it's opened I get a signal to my computer. Getting the magnetic door switch wired with the Arduino and getting an LED to light up when the magnetic switch opened worked without problem.

But to set up the wifi module, I can't get it to work.

I have spent hours and hours watching tutorials reading all I can find to trying everything to get this to work, but no luck.

I don't know If I am doing something wrong (probably) or if something is broken.

These are the instructions I am trying currently.

Video of my Arduino setup

For the Arduino board I use 12v DC in and USB from my PC.

Code:

```
#include "Arduino.h"
#include "ESP8266.h"

#include "SoftwareSerial.h"
SoftwareSerial  ConsoleOut(8, 9);

#define SSID  "ASUS"
#define PWD   "tmpPassword"

void setup() {
  char  *ipAddress, ap[31];

  WiFi.reset(WIFI_RESET_HARD);
  WiFi.begin(9600);
  ConsoleOut.print("flag2");
  if (WiFi.join(SSID, PWD) == WIFI_ERR_OK) {
    ipAddress = WiFi.ip(WIFI_MODE_STA);
    ConsoleOut.print(F("\n\rIP address:"));
    ConsoleOut.print(ipAddress);
    ConsoleOut.print(':');
    ConsoleOut.print("flag1");
    if (WiFi.isConnect(ap))
      ConsoleOut.println(ap);
    else
      ConsoleOut.println(F("not found"));
  } else
    while (1);
}

void loop() {
  if (WiFi.connect((char *)"www.google.co.jp", 80) == WIFI_ERR_CONNECT) {
    if (WiFi.send((const uint8_t *)"GET / HTTP/1.1\r\n\r\n") == WIFI_ERR_OK) {
      int16_t c;
      uint16_t len = WiFi.listen(10000UL);
      while (len)
        if ((c = WiFi.read()) > 0) {
          ConsoleOut.write((char)c);
          len--;
        }
    } else
      ConsoleOut.println(F("Send fail"));
    WiFi.close();
  } else
    ConsoleOut.println(F("TCP connect fail"));
  WiFi.disconnect();
  while (1);
}

```

Code:

Different from the example sketch is that I use 2K instead of 3K resistors for R2, R4 and 1K for R1, R3. (2K on left side in the video 1K on the right side)

The LED of the WiFi lights red constantly. I don't know what that means, and the blue LED on the wiFi module lights up whenever I upload a sketch to the Arduino.

Thanks in advance. Any help is really, really appreciated.

# Answer
> 1 votes
Use this code to send commands to the ESP:

```
#include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

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

      esp8266.begin(9600);
    }

    void loop() {
      while(esp8266.available()) {
         Serial.write(esp8266.read());
      }

      while(Serial.available()) {
        esp8266.write(Serial.read());
      }
    }

```

This simply reads everything from the ESP chip and sends it to the console and vica versa.

To modify the baud rate on the chip, send the following command in the serial monitor:

```
AT+UART_DEF=9600,8,1,0,0

```

This sets the baud rate to 9600 and remembers it for further use.

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


# Question
Title: How to fade an LED in response to a sensor?
As the sensor "sees" an object nearby, it makes the LED go to full brightness and it remains like that for as long as the sensor keeps on sensing the object. Then, as soon as the sensor stops sensing it, the LED goes OFF instantly... and so on, endlessly. This part of the code works perfectly as it is right now.

MY PROBLEM:

I need all of this ON and OFF switching to happen with smooth PWM fades instead of with abrupt "instant ON" and "instant OFF" changes. I need to have a 1.5 seconds PWM fade-in of the LED from 0% to 100% as soon as the sensor gets activated; and then a 3.5 seconds fade-out as soon as the sensor stops sensing something nearby. As long as the sensor is activated, the LED needs to remain at full brightness. So, simply put: I need the LED to dim smoothly between the sensor's state-changes, instead of changing instantly in an abrupt manner.

# Answer
> 1 votes
This is the typical problem which calls for a finite state machine. You create a “state” variable to keep track of the LED state, which can be `OFF`, `FADING_IN`, `ON` or `FADING_OUT`. You also need another variable to remember *when* you started the fade-in or the fade-out. I would start the program some declarations like the following:

```
const uint8_t  LED_PIN       = 3;
const uint32_t FADE_IN_TIME  = 1500;
const uint32_t FADE_OUT_TIME = 3500;

static enum { OFF, FADING_IN, ON, FADING_OUT } led_state;
static uint32_t fade_start;

```

Now that you know the LED state, you use it to condition the LED handling on the current state. For example, the brightness at any given time can be computed as:

```
/* Compute the LED brightness after the given fade time */
static uint8_t led_brightness(uint32_t fade_time)
{
    int mapped;
    switch (led_state) {
        case FADING_IN:
            mapped = map(fade_time, 0, FADE_IN_TIME, 0, 255);
            return constrain(mapped, 0, 255);
        case FADING_OUT:
            mapped = map(fade_time, 0, FADE_OUT_TIME, 255, 0);
            return constrain(mapped, 0, 255);
        case ON:
            return 255;
        default:
            return 0;
    }
}

```

where `fade_time` would be `millis() - fade_start`. Note the use of the standard `map()` function to generate a linear ramp, and `constrain()` to avoid overflowing the range 0 – 255.

Now, switching the LED on or off is just a matter of setting the correct state... *and* updating `fade_start` as necessary:

```
/* Set the LED pin to HIGH or LOW, through fading. */
void ledWrite(uint8_t value)
{
    uint32_t now = millis();
    if (value == HIGH) {
        if (led_state == OFF) {
            fade_start = now;
        }
        else if (led_state == FADING_OUT) {
            fade_start = now - map(now - fade_start,
                    0, FADE_OUT_TIME,
                    FADE_IN_TIME, 0);
        }
        if (led_state != ON)
            led_state = FADING_IN;
    }
    else {
        if (led_state == ON) {
            fade_start = now;
        }
        else if (led_state == FADING_IN) {
            fade_start = now - map(now - fade_start,
                    0, FADE_IN_TIME,
                    FADE_OUT_TIME, 0);
        }
        if (led_state != OFF)
            led_state = FADING_OUT;
    }
}

```

A few things worth noting:

* trying to switch the LED on has no effect if it's already on or fading in, and trying to switch it off has no effect if it's either off or fading out
* if you switch it on while it's fading out, it will move to the state `FADING_IN`, and the `fade_start` time will be set to a value that ensures continuity of the brightness; same thing when switching from `FADING_IN` to `FADING_OUT`.

There is one more thing to do. Your program should periodically update the LED state, not only to update its brightness, but also to enforce the transitions `FADING_IN``ON` and `FADING_OUT``OFF` when needed:

```
/* This should be called periodically to update the LED. */
void update_led()
{
    uint32_t fade_time = millis() - fade_start;
    if (led_state == FADING_IN && fade_time >= FADE_IN_TIME)
        led_state = ON;
    else if (led_state == FADING_OUT && fade_time >= FADE_OUT_TIME)
        led_state = OFF;
    analogWrite(LED_PIN, led_brightness(fade_time));
}

```

With all this in place, you can write the main program just as you did with no fading, only with the extra call to `update_led()` on every loop iteration:

```
void setup()
{
    // Initialize the sensor.
    sensor.begin();
}

void loop()
{
    // Set the LED as per the sensor reading.
    if (sensor.detects_object())
        ledWrite(HIGH);
    else
        ledWrite(LOW);

    // Update the LED brightness on every loop iteration.
    update_led();
}

```

Oh, and beware not to do anything blocking in `loop()` (e.g., no calls to `delay()`). Otherwise the LED brightness would be “jumpy”.

# Answer
> 2 votes
Do analogRead(sensor) and check what range of values you are getting. Arduino has 10 bit adc which means you can get 0-1023 in readings. However the sensor might not go complete LOW (0) or complete HIGH (1023). So just measure what's the range you are getting. Assume the range is 125 - 980.

PWM on arduino - This one is 8 bit, which means you can write 0-255. 0 means LED is OFF and 255 means LED is fully ON. Now you need to map 125-980 to 0-255 (as far as I can understand from your comments about synchronizing it with the sensor).

Here is what your code will look like:

```
/* Map an analog value (125-980) to 8 bits (0 to 255) */

    void loop()
    {
      int val = analogRead(0); //sensor attached to A0
      val = map(val, 125, 980, 0, 255);
      analogWrite(9, val); //LED attached to D9
    }

```

---
Tags: led, time
---


# Question
Title: Object Sensor on conveyor belt (want to record the data in EEPROM for testing)
```
void setup ()
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED_Blue_pin, OUTPUT);
pinMode(LED_White_pin, OUTPUT);

Serial.begin(9600);
digitalWrite(LED_Blue_pin, LOW);
digitalWrite(LED_White_pin, LOW);

void loop()
{
    long duration, cm;

    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);

    cm = microsecondsToCentimeters(duration);
    long distance = 70 - cm ;

    if (distance < 20) {
        Serial.println("NO ITEM");
        digitalWrite(LED_White_pin, HIGH);
    } else {
        digitalWrite(LED_White_pin, LOW);
    }

    if (distance > 20 && distance < 70) {
        digitalWrite(LED_Blue_pin, HIGH);
        Serial.print("Item : ");
        Serial.print(item++);
        Serial.println(" stk");
    } else {
        digitalWrite(LED_Blue_pin, LOW);
    }

    delay(1500);
}

long microsecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

```

The code above is for the Ultrasonic Sensor HC-SR04. The sensor detects items that passes through and counts them along the way. The Blue Led indicates that the sensor detected an item while the White Led detects none. How can I store the data from HC-SR04 to EEPROM? The reason is, I just want to test it out before I sent the data from EEPROM to a database server. I'm still a novice at this.

# Answer
You can use the EEPROM.write() function. There is a useful tutorial on the Arduino site.

The sample code from that tutorial is shown below:

```
/*
 * EEPROM Write
 *
 * Stores values read from analog input 0 into the EEPROM.
 * These values will stay in the EEPROM when the board is
 * turned off and may be retrieved later by another sketch.
 */

#include <EEPROM.h>

/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int addr = 0;

void setup() {
  /** Empty setup. **/
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/

  int val = analogRead(0) / 4;

  /***
    Write the value to the appropriate byte of the EEPROM.
    these values will remain there when the board is
    turned off.
  ***/

  EEPROM.write(addr, val);

  /***
    Advance to the next address, when at the end restart at the beginning.

    Larger AVR processors have larger EEPROM sizes, E.g:
    - Arduno Duemilanove: 512b EEPROM storage.
    - Arduino Uno:        1kb EEPROM storage.
    - Arduino Mega:       4kb EEPROM storage.

    Rather than hard-coding the length, you should use the pre-provided length function.
    This will make your code portable to all AVR processors.
  ***/
  addr = addr + 1;
  if (addr == EEPROM.length()) {
    addr = 0;
  }

  /***
    As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an
    EEPROM address is also doable by a bitwise and of the length - 1.

    ++addr &= EEPROM.length() - 1;
  ***/

  delay(100);
}

```
> 1 votes

---
Tags: arduino-uno, eeprom, hc-sr04
---


# Question
Title: I put some defines into a .h file, and get errors
I'll post the whole code if you really need to see it, but my question is pretty simple.

In my sketch I define some parameters:

```
#define SSID "Kaywinnet"
#define PASSWORD "806194edb8"
#define MQTT_SERVER { 192, 168, 1, 124 }

```

And, the sketch compiles just fine. But, rather than putting my net parameters into every sketch, I wanted to just use a .h file so that if something changes, I only have to change it once.

Here's the problem. When I put these three lines into a .h file, I get an error when the first parameter is used in the sketch:

```
expected primary-expression before '.' token

```

Here is the code where I use the value:

```
//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

```

The error is on the .ssid= line.

So, why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??

Here's the ino file:

```
    /*****

  Projects/esp8266/MQTT nodes/light2.ino
  10/3/2017- Clone of studio.ino

  IDE settings:
  Board: "Generic 8266 Module"
  Flash Mode: "DOUT"

*****/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESPHelper.h>

//#include <Kaywinnet.h>
#define SSID "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

//#define toggle    //Using toggle switch.
#define pushbutton    //Using pushbutton switch

#define NODENAME "light2"
const char *cmdTopic =  NODENAME "/light";
const char *statusTopic = NODENAME "/light/status";
const char *connectName =  NODENAME "lights";
#define OTAPASSWORD "xxxx"

//Defaults to DHCP, if you want a static IP, configure below
//#define STATIC_IP
#ifdef STATIC_IP
IPAddress ip(192, 168, 1, 50);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
#endif

//Initialize ESPHelper
netInfo homeNet = {
  .mqttHost = mqtt_server,
  .mqttUser = "",
  .mqttPass = "",
  .mqttPort = 1883,
  .ssid = SSID,
  .pass = password
};
ESPHelper myESP(&homeNet);

//Declare an object of class WiFiClient
WiFiClient esplight2;
PubSubClient client(esplight2);

#define esp8266-01    //Either sonoff or esp8266-01

//Define the GPIO pins on the 8266-01
#ifdef esp8266-01
const int buttonPin = 0;    //GPIO0
const int relayPin = 2;     //GPIO2
#endif

#ifdef Sonoff
const int buttonPin = 0;     //GPIO0
const int extraPin = 14;
const int ledPin = 13;
const int relayPin = 12;
const bool ledOFF = HIGH;
const bool ledON = LOW;
#endif

int switchVal = 0;
int currentVal = 0;
bool relayState;
String payLoad;

// * *************** RelayControl, remember the state ***************
//
void RelayControl(bool state) {
  //Serial.print("relayState: ");
  //Serial.println(relayState);

  digitalWrite(relayPin, state ? HIGH : LOW);
  relayState = state;

  //Feedback over MQTT
  if (relayState) {
    client.publish(statusTopic, "on");    //Tell Node Red about the current status
    Serial.println(String(statusTopic) + "= on.");
  } else {
    client.publish(statusTopic, "off");
    Serial.println(String(statusTopic) + "= off.");
  }
  Serial.println();
}

void timeLoop (long int startMillis, long int interval) { // the delay function
  while (millis() - startMillis < interval) {}
}

/*
 * ************** blink the LED ************************
   We assume the LED is on after connecting.
*/
void blinkLED() {
#ifdef esp8266-01
  return;   //No led on the esp to blink..
#endif
#ifdef Sonoff
  digitalWrite(ledPin, ledOFF);
  delay(500);
  digitalWrite(ledPin, ledON);
#endif
}

/*
 * ******************** set up WiFi ****************
*/
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(SSID);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}

/*
 * *************** MQTT callback ********************
*/
void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");

  String messageTemp;
  for (int i = 0; i < length; i++) {
    //Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  messageTemp.trim();            // trim the white space off the string

  Serial.println(messageTemp);

  // If a message is received with the topic 'cmdTopic', check if the message is either on or off.
  if (topic == cmdTopic) {
    if (messageTemp == "on") {
      Serial.println("Light2 is ON");
      RelayControl(HIGH);
      blinkLED();

    }
    else if (messageTemp == "off") {
      Serial.println("Light2 is OFF");
      RelayControl(LOW);
      blinkLED();

    }
  }
}

/*
 * **************** Connect to MQTT broker **************
   This functions reconnects your ESP8266 to the MQTT broker and subscribes to topics.
*/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(connectName)) {
      Serial.println("connected");
#ifdef Sonoff
      digitalWrite(ledPin, ledON);
#endif
      // Subscribe or resubscribe to a topic
      client.subscribe(cmdTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

/*
 * *************** SETUP ********************
*/
void setup() {

  //espHelper
  myESP.OTA_enable();
  myESP.OTA_setPassword(OTAPASSWORD);
  myESP.OTA_setHostname(NODENAME);
  myESP.begin();

#ifdef Sonoff
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledOFF);     //The Sonoff LED is low-true.  This starts with it off.
#endif

  pinMode(relayPin, OUTPUT);
  RelayControl(LOW);  //Start with the heat off

  pinMode(buttonPin, INPUT_PULLUP);

  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  //Save the initial switch position.
  currentVal = digitalRead(buttonPin);

  Serial.print("cmdTopic= ");
  Serial.println((String(cmdTopic)));
  Serial.print("statusTopic= ");
  Serial.println((String(statusTopic)));
  Serial.print("connectName= ");
  Serial.println((String(connectName)));
  Serial.println("...............");
}

/*
 * *************** LOOP ***********
   The loop function begins with making sure that your ESP is connected to the broker.
*/
void loop() {
  myESP.loop();  //run the loop() method - this keeps the network services running

  if (!client.connected()) {
    reconnect();
  }
  if (!client.loop())
    client.connect(connectName);

#ifdef toggle
  /*
   * ******** Toggle switch attached **********
  */
  //Has the switch position changed from the last loop?
  //If yes, the save the new setting and toggle the heat.
  switchVal = digitalRead(buttonPin);
  if (switchVal != currentVal) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal != currentVal) {   //debounce
      currentVal = switchVal;
      relayState = !relayState;
      RelayControl(relayState);

      /*    //For simultaneous control over MQTT
            if(relayState){
                client.publish("studio/heat","on");
              }else{
                client.publish("worksgop/light","off");
              }
      */

    }
  }
#endif

#ifdef pushbutton
  /*
   * ***** Momentary pushbuttom switch attached *******
  */
  //When the switch input goes low, toggle the light.
  switchVal = digitalRead(buttonPin);
  if (switchVal == LOW) {
    delay(500);
    switchVal = digitalRead(buttonPin);
    if (switchVal == LOW) {   //debounce
      relayState = !relayState;
      RelayControl(relayState);
      delay(1000);            //Delay if the button is held too long.
    }
  }
#endif

  yield();
}

```

And here is Kaywinnet.h

```
#define ssid "Kaywinnet"
#define password "806194edb8"
#define mqtt_server "192.168.1.124"

```

# Answer
> 1 votes
> Here's the ino file:
> ...
>
> ```
> #define SSID "Kaywinnet"
>
> ```
>
> ...
>
> ```
>   .ssid = SSID,
>
> ```
>
> ...
> And here is Kaywinnet.h
>
> ```
> #define ssid "Kaywinnet"
>
> ```
>
> ...
> The error is on the .ssid= line.

C++ is case sensitive. You changed the macro name from `SSID` to `ssid` when you moved the defines to the .h file.

# Answer
> 0 votes
> why does it compile when I define the parameters in the sketch, and gives an error when I put them into a .h file??

easy:

1) go back to the non-fancy version where you put the strings back into the code.

2) get it to compile.

3) then extract the strings to macros.

by going through that, you will know precisely the mistakes you made.

---
Tags: esp8266
---


title: Can't stop my variable value at zero?

text:
# Question
Title: Can't stop my variable value at zero?
In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).

My code is below:

```
const int kPinSw1 = 2;
const int kPinSw2 = 3;

int plusBtnIncState = 0;
int lastPlusBtnIncState = 0;

int minusBtnDecState = 0;
int lastMinusBtnDecState = 0;

unsigned long currentMillis;
unsigned long previousMillis;
unsigned long interval = 0UL;

void setup() {
  Serial.begin(9600);
  pinMode(kPinSw1, INPUT_PULLUP);
  pinMode(kPinSw2, INPUT_PULLUP);
}

void loop() {
  //---------------INC_TIMER---------------//
  plusBtnIncState = digitalRead(kPinSw1);
  if(plusBtnIncState != lastPlusBtnIncState) {
    if(plusBtnIncState == HIGH) {
      interval = interval + 1000;
    }
    delay(50);
  }
  lastPlusBtnIncState = plusBtnIncState;

  //---------------DEC_TIMER---------------//
  minusBtnDecState = digitalRead(kPinSw2);
  if(minusBtnDecState != lastMinusBtnDecState) {
    if(minusBtnDecState == HIGH) {
      interval = interval - 1000;
      if(interval <= 0) {
        interval = 0;
      }
    }
    delay(50);
  }
  lastMinusBtnDecState = minusBtnDecState;

  //---------------------------------------//
  Serial.print("Int:");
  Serial.print(interval);
  Serial.print("\n");
}

```

And output:

```
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296

```

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

# Answer
> 5 votes
The `interval` variable is `unsigned long`.

In this example, we are using `int` that are 4 bits long (just to keep thing short) just to subtract 1 from 0:

```
    0b0000
   -0b0001
    ------
    0b1111

```

That is normal arithmetic, but in binary.

The result `0b1111` can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.

The same thing is working in your case, only that your `int` are 32 bits long.

The `unsigned` keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.

# Answer
> 2 votes
The variable "interval" is an unsigned long. This means it can not go negative. It also means that it is made up of a 32 bits.

Instead of going negative, an unsigned variable will cycle to its most maximum value by following a modulo 2 math behavior. So a 32 bit value will become 2^32 or 4294967296 if, for example, decremented 1 past 0.

In the above program the 32 bit value was decremented by 1000 past 0 resulting in 4294967296 - 1000 or 4294966296.

Testing if an unsigned number is negative is futile. So this code:

```
  if(interval <= 0)
  {
    interval = 0;
  }

```

...does nothing. Instead, test if "interval" is larger than 1000 before subtracting 1000.

# Answer
> 0 votes
As already mentioned in previous answers, the issue is that an unsigned number wraps modulo MAX+1. The obvious fix would be to make `interval` a signed number.

Another option would be to avoid subtracting from `interval` anything larger that `interval` itself. You could do this by replacing

```
interval = interval - 1000;
if(interval <= 0) {
  interval = 0;
}

```

by

```
if (interval >= 1000)
  interval -= 1000;
else
  interval = 0;

```

Note that the `else` clause could be dropped if you can guarantee that `interval` is always a multiple of 1000.

---
Tags: arduino-uno, time
---


# Question
Title: Is there a good Arduino enclosure for that works with the Olimex MIDI shield
I have a MIDI project I put together using an Arduino UNO R3 and the Olimex Shield-MIDI.

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.

Has anyone come up with a good solution for Arduino + MIDI projects? A metal enclosure would be a plus.

# Answer
> 1 votes
**Your best bet is to 3D print the enclosure.**

There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend Shapeways as they are fairly reasonable in price and ship worldwide.

If you are a handy DIY person you could use SketchUp or Tinkercad to design your enclosure. Also there are many Arduino enclosures on Thingiverse that you could use as a starting point.

Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.

---
Tags: arduino-uno, midi, enclosure
---


title: Why is my DS18B20-PAR not picked up?

text:
# Question
Title: Why is my DS18B20-PAR not picked up?
I have had a DS18B20-PAR for some time and have often used it without a problem until now. Yesterday it just suddenly stopped working. I was trying to use it along with two i2C sensors at the time. I don't really know of anything which could have fried it, though.

**Edit**: It is turning out much more complicated than I thought. I can't ever get it to work on pin 10. The sensor sometimes works on other pins (3, 9 and 11), but it often does not. I can still use pin 10 to blink and fade an LED, and receive input from a button, but it never picks up my DS18B20-PAR. What is happening here?

# My setup:

I have just one DS18B20-PAR connected to my Arduino Uno look-alike as shown in the following image:

Please note that on the DS18B20-PAR the third pin is internally not connected.

# The code:

My Arduino is running this code (a OneWire example sketch which has always worked before):

```
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

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

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

```

On the serial monitor is just prints "No more addresses." every 250 milliseconds.

# Answer
If the setup worked fine and then stopped, you must examine what changed. If your code is unchanged then it could be your sensor or your Arduino.

You can try putting the sensor on a different input pin and update the code accordingly.

You can try the sensor on a different Arduino or a new sensor if the same type on your Arduino.

These are the first steps to troubleshooting.
> 1 votes

---
Tags: arduino-uno, temperature-sensor
---


title: Uploading code to Mega 2560 is stuck

text:
# Question
Title: Uploading code to Mega 2560 is stuck
I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:

```
void setup() {
}

void loop() {
  digitalWrite(52,HIGH);
}

```

The Arduino application (with same code copied in) comes up with this error:

```
Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "COM1": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
ioctl("TIOCMGET"): Inappropriate ioctl for device
avrdude: ser_send(): write error: Bad file descriptor
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

```

I hope someone can work out why it doesn't upload!

# Answer
> 0 votes
I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).

Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.

---
Tags: uploading, atmega2560
---


# Question
Title: Arduino Leonardo as keyboard for an iPad
I'm trying to make a Arduino Leonardo as a Keyboard for an iPad. I was successful with an Arduino UNO. However I'm hoping to use an ATmega 32U4 because of the better HID functionalities and smaller boards like the Beetle.

The problem I'm having is that when I connect the Leonardo to my iPad, the iPad shows an alert saying that the Leonardo is using too much power.

Tried running the board with an external power source. Then I get a different alert: Device not Supported.

At this point I believe that the problem is not necessarily power, but the fact that the Leonardo is announcing itself to the iPad and the iPad does not like it. In the UNO project, through re-flashing, the board acts only as a HID.

Is there a way to make the Leonardo (or other ATmega 32U4 based board) to not advertise itself on the USB port while allowing the HID functionality to operate?

# Answer
> 6 votes
If indeed the descriptor is the problem then yes you can change it.

In the core file `USBCore.h` is the line:

```
#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

```

Just change the 500 to something smaller (it has to be an even number).

However it may be that the Leonardo isn't programmed to support the Boot Protocol for HID. In which case that would require bigger changes to the USB and HID stacks in the core.

# Answer
> 0 votes
i will stress now that i haven't tested this, and if it doesn't work you may have to reflash the bootloader in order to program the arduino again. in the arduino install directory we are looking for the following file:

```
Arduino\hardware\arduino\avr\cores\arduino\main.cpp

```

at line 40 (i'm using 1.6.9) we have:

```
#if defined(USBCON)
    USBDevice.attach();
#endif

```

in theory if you comment this out the serial port may not be ennumerated, however i don't know if the keyboard functions will still work.

if it does work you should wrap it in an if block so that the serial port shows if a certain pin is pulled high/low whatever your preference. this would enable you to program it as normal.

# Answer
> 0 votes
I have found the solution - your USB \> Lightning adapter must has the option for charging.

For example i use Arduino Leonardo connected to IPhone 6 by USB to adapter who has USB nest and charging nest. IPhone shows me info that "This device is not supported.", but all works fine and I can control IPhone by Arduino Leonardo.

---
Tags: usb, keyboard, atmega32u4
---


# Question
Title: HM-10 send and receive data and checking received value
I am wondering what is wrong with my code below. I have 2 issues.

The first issue, I am checking if **c** equals "hi" and if it does then display **said hi**. I currently see the output of **c** when it hits `Serial.println(c);` but never see the **said hi** even though `Serial.println(c);` does say "said hi".

The second issue is that when I start up the Arduino I am sending the `AT` command using `bluetooth.println("AT");`, but all it seems to do is display `AT` on the phone instead of `OK` as it should.

```
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(8,9); // RX, TX

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("PC Side Connected");
  bluetooth.begin(9600);
  while (!bluetooth) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop() { // run over and over
  String c;
  if (bluetooth.available()) {
    //What is sent back from the BT module
    c = bluetooth.readStringUntil('\n');
    delay(10);
    Serial.println(c);
    if (c.equals('hi')) {
      Serial.println("said hi");
    }
  }
  if (Serial.available()) {
    //Send back data to Bluetooth module
    bluetooth.write(Serial.read());
  }
}

```

# Answer
> The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is *not* how you compare:

```
  if (c.equals('hi')) {

```

Single quotes indicate a single (or multi-byte) character. A character string (lower-case) is enclosed by double quotes:

```
  if (c == "hi") {

```

But it's better to avoid the `String` class (more info here).

To eliminate the `String` class, use `char` arrays instead (aka "C strings") and accumulate characters until the newline is received. There are many, many C string functions for manipulating and searching. In this specific case, you would use strcmp or strstr for comparison:

```
#include <AltSoftSerial.h>

AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

char btResponse[ 20 ];
uint8_t count;
const uint8_t BT_MAX = sizeof(btResponse);

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

  Serial.println("PC Side Connected");
  bluetooth.begin(9600);

  bluetooth.println("Bluetooth Side Connected");
  bluetooth.println("AT"); // just a check
}

void loop()
{
  if (bluetooth.available()) {
    // Read what is sent back from the BT module
    char c = bluetooth.read();

    if (c == '\n') {
      btResponse[ count ] = '\0'; // NUL-terminate the character array

      // Use C string functions to parse the response

      if (strcmp( btResponse, "hi" ) == 0) {
        Serial.println("only said hi");

      } else if (strstr( btResponse, "hi" ) != nullptr) {
        Serial.println("said hi, among other things...");

      }

      // And if there is a comma in there somewhere, display all comma-separated fields
      if (strchr( btResponse, ',' ) != nullptr) {
        uint8_t fieldNumber = 0;

        char *field = strtok( btResponse, "," );
        while (field != nullptr) {

          Serial.print( "Field " );
          Serial.print( fieldNumber );
          Serial.print( " = " );
          Serial.println( field );

          // Some fields might be numbers.  Parse them into integers.
          if ( isdigit( field[0] ) ) {
            int value = atoi( field );
            Serial.print( "  value = " );
            Serial.println( value );
          }

          // get next field
          field = strtok( nullptr, "," );
          fieldNumber++;
        }
      }

      // Reset the counter to receive another response
      count = 0;

    } else if (c >= ' ') {
      // Accumulate another non-control char, if there's room
      if (count < BT_MAX-1) {
        btResponse[ count++ ] = c;
      }
    }
  }

  if (Serial.available()) {
    // Send data to Bluetooth module
    bluetooth.write( Serial.read() );
  }
}

```

Notice that it shows how to use strtok to break the response string into individual fields, if a comma character is somewhere in the line. For example, entering this:

```
hi,123,456

```

... produces this output:

```
said hi, among other things...
Field 0 = hi
Field 1 = 123
  value = 123
Field 2 = 456
  value = 456

```

It also uses `AltSoftSerial` for the BT connection. `SoftwareSerial` is very inefficient, and it cannot send and receive at the same time. It will lose received data while it is transmitting to the BT. This can also interfere with other parts of your sketch or other libraries.

This answer has a good summary of the alternatives and how to select one. Since you are already using pins 8 & 9, it would be easy to switch to the `AltSoftSerial` library. All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.
> 1 votes

---
Tags: arduino-ide, bluetooth, softwareserial, arduino-leonardo, atmega32u4
---


title: How to post JSON data from Arduino?

text:
# Question
Title: How to post JSON data from Arduino?
I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.

For example:

if data=15, it is converting into string.

```
String st=String(data);

```

Now I want to post `st` every 5 seconds.

```
    int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
    Serial.print("Sensor Status: ");
    Serial.println(S2);

```

st1 is the previous value, it is printing httpcode -2(invalid Syntax).

Can anyone help me with this issue?

Thanks in advance.

# Answer
> 2 votes
The string

```
"{\"AssetSensorDistance\":\"+st+\"}"

```

contains a literal "+st+". If you want to do string concatenation, you should terminate the string with a double quote character, then add st, then use another double quote to start the second part of the string:

```
"{\"AssetSensorDistance\":\""+st+"\"}"

```

---
Tags: esp8266, arduino-ide, nodemcu, http, json
---