title: NodeMCU - Vin pin as 5V output?

text:
# Question
Title: NodeMCU - Vin pin as 5V output?
I know that Vin can be used to power the board but have also been reading that it can be used as a 5V output. Is it possible to assign Vin as an output as I would any other GPIO?

If I want to power an LED from GPIO 12, I would assign GPIO:

```
const int LEDpin_0 = 12; // D6, LED power pin

```

...and in the setup:

```
pinMode(LEDpin_0, OUTPUT);

```

I can then turn on and off the LED based on whether or not GPIO 12 goes HIGH or LOW.

Can I do the same with Vin without resorting to relays or other hardware?

# Answer
> 28 votes
There is confusion about what is and what isn't possible with this board. This is because there are different versions with different power arrangements.

## NodeMCU 0.9

In this board the USB's 5V and the 5V pin are directly connected together. The combined result is then fed through a diode before entering the 3.3V voltage regulator.

With this arrangement the 5V pin will provide the exact same voltage that the USB port feeds the board. However it is dangerous to connect that pin to any power source - it may kill (or at the very least disable) the USB port in your computer - when the board is also connected to a computer through the USB port.

## NodeMCU 1.0 and 1.1

On this version the USB's power is first fed through the diode and then to the 5V pin and the 3.3V regulator together. This means that the 5V pin will show about 0.5V below whatever voltage is fed in through USB. This isolates the USB from the 5V pin so it becomes safe to provide power through the 5V pin whilst at the same time having the board plugged in to the computer - at the cost of having a slightly lower output from the 5V pin.

---

Original answer:

The VIN pin not directly connected to the USB's 5V supply (at least on the LoLin v3 board). this means the pin cannot be used as a 5V supply output.

* You cannot control that voltage. It is always on, and always 5V (or whatever your USB port happens to provide - 4.75v - 5.25v).
* You must never ever connect VIN to a power source *and* connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on that board.
* Drawing more than 500mA from the VIN pin could cause the USB port of your computer to be shut down.

# Answer
> 7 votes
my 2 cents:

A LoLin NodeMCU V3 when powered via USB in the Vin pin reads 2.2 V (don't know why) but... in the VV pin you can get the 5V coming from the USB; so if you need 5V use that pin.

The board if powered via Vin with 5V, the VV pin reads 2 V (don't know why either)

in any case you can always get 3V in the 3V pin.

Cheeers!

# Answer
> 4 votes
No you cannot use a Vin or VU pin as a GPIO pin which can be controlled by a program. Vin can be used as an input for 5V battery or as a 5V output when NodeMCU is powered by USB (except on NodeMCU v3 by LoLin).

On the V0.1 LoLin board, there are 2 diodes between the VIN and VU pins. So you cannot get power from one to the other. These diodes isolate the two possible sources of 5V power from each other while allowing the board to obtain the 5V needed by its its 3.3V power supply from either 5V source.

Other board versions might be different.

To control 5V sensor with help of GPIOs on NodeMCU you will need a logic shifter connected between your sensor and GPIO pin thats boost the 3v3 to 5V.

---
Tags: pins, nodemcu, voltage
---


# Question
Title: Why is the Arduino IDE ignoring my replacement start up code?
I am trying to replace the standard startup code to save flash space.

I've put the new `startup.s` in my `core` directory and added the `-nostartfiles` parameter to the linker reciepe in my `platform.txt`.

When I compile with the IDE, it does not include my start code at all.

When I use Atmel Studio or a makefile, the code assembles and is included just fine.

How can I get the Arduino IDE to use my new start up code?

# Answer
The Arduino builder is case sensitive and will only see files that end in `.S` and not files that end in `.s`.

Renaming the new start up file to `startup.S` and then deleting the precomplied core archive fixed the problem.

Note that committing this change to git slightly complicated!
> 1 votes

---
Tags: startup
---


# Question
Title: The Capacitive Sensor library on a D1 Mini
I want to set up a hand-made capacitive sensor on a D1 Mini, as in this tutorial, so that I can get specific capacitive readings. But I couldn't get the CapacitiveSensor library to work with the D1 Mini. Just to make sure I wasn't crazy, I fired up an Arduino Nano knockoff, and the library worked just fine.

I found a thread from early 2017 on this topic, which had various suggestions, none of which worked.

Does anyone know either how to make this library work with a D1 Mini, or another efficient way of getting capacitive readings on digital pins on a D1 Mini?

# Answer
Actually it looks like the answer was in the early 2017 thread all along. I switched to a 400k resistor and it works! (I've only verified this just for pins 5 -\> 6, although I'd expect it works for any combination of pins not including D0 / D3 / D4 / D8.)

However, a caveat here -- *it doesn't work well.* With an Arduino and a ~6m resistor, you can sense a change in capacitance from several inches away, with a nice continuous increase in capacitance as you get closer. At least for me, the 400k resistor had very low operational range, only maybe 1/2 in. or so, and even then the differences were subtle. But increasing to a 600k resistor replicated the initial problem -- I just got the "-2" error message consistently. And going down to a 200k resistor just decreased the range as you'd expect. So there seems to be a very narrow operational range of resistance for the D1 Mini, with less utility than the Arduino.
> 1 votes

---
Tags: esp8266, sensors, pins, esp32
---


# Question
Title: What's the newest way to use C++ stdlibs in Arduino 1.8.2?
(My Arduino version is 1.8.2.)

For example,if I want to `#include` `<vector>` or `<string>`, `<iostream>`, `<memory>` etc, the compiler always complains that such libs are not found.

So what's the newest/most efficient way to use C++ libs in Arduino 1.8.2?

# Answer
> 2 votes
Most Arduino Core don't include the Standard C++ Library, that's why headers like `<vector>` and `<string>` are missing. This decision makes a lot of sense because the STL relies heavily on heap allocation, which would ruin the little RAM of the microcontroller.

If you're looking for an alternative to the STL, you might check out the ETL, the Embedded Template Library.. However, the code will not be the same because all the containers of the ETL have a fixed capacity. Here is a string for example:

```
etl::string<32> s = "hello world";

```

In practice, I never saw a project using the ETL. Most projects use the standard Arduino classes (`String`, `Stream`, `Print`...) and learn to live with their flaws. Since there are no generic container classes in the Arduino core, the common usage is to use plain old C arrays.

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


# Question
Title: Conflict between SD card shield and accelerometer
I'm trying to get the SD card (Adafruit microshield SD card) and an MPU6050 accelerometer to work at the same time. When I connect the SD card to the Arduino (without the accelerometer), it's ok; When I connect the accelerometer to the Arduino (without the SD card), it's also ok. The codes for the accelerometer and SD card work fine separately. But when I connect the shield to the Arduino, and then connect the accelerometer, and try to run a combined code, it's problematic. I've included the code I'm currently working on below. I would really appreciate if you could help me find where the problem lies, and how to solve it.

```
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
//#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
//    #include "Wire.h"
//#endif

// A simple data logger for the Arduino analog pins

// how many milliseconds between grabbing data and logging it. 1000 ms is once a second
#define LOG_INTERVAL  1000 // mills between entries (reduce to take more/faster data)

// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0 // Wait for serial input in setup()

// the digital pins that connect to the LEDs
#define redLEDpin 4
#define greenLEDpin 3

// The analog pins that connect to the sensors
//(not sure which pins on the accelerometer are the analog pins that connect to the sensor. Insert here!!)

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;
#define OUTPUT_READABLE_YAWPITCHROLL
//#define OUTPUT_READABLE_QUATERNION
//#define OUTPUT_READABLE_EULER
//#define OUTPUT_READABLE_REALACCEL
//#define OUTPUT_READABLE_WORLDACCEL

RTC_DS1307 RTC; // define the Real Time Clock object

// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = HIGH;

// the logging file
File logfile;

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);

  // red LED indicates error
  digitalWrite(redLEDpin, HIGH);

  while(1);
}

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

  // use debugging LEDs
  pinMode(redLEDpin, OUTPUT);
  pinMode(greenLEDpin, OUTPUT);

#if WAIT_TO_START
  Serial.println("Type any character to start");
  while (!Serial.available());
#endif //WAIT_TO_START

  // initialize the SD card
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present");
  }
  Serial.println("card initialized.");

  // create a new file
  char filename[] = "LOGGER00.CSV";
  for (uint8_t i = 0; i < 100; i++) {
    filename[6] = i/10 + '0';
    filename[7] = i%10 + '0';
    if (! SD.exists(filename)) {
      // only open a new file if it doesn't exist
      logfile = SD.open(filename, FILE_WRITE);
      break;  // leave the loop!
    }
  }

  if (! logfile) {
    error("couldnt create file");
  }

  Serial.print("Logging to: ");
  Serial.println(filename);

  // connect to RTC
  Wire.begin();
  if (!RTC.begin()) {
    logfile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  logfile.println("Hello,World,!!!");
#if ECHO_TO_SERIAL
  Serial.println("Hello,World,!!!");
#endif //ECHO_TO_SERIAL

  // If you want to set the aref to something other than 5v
  analogReference(EXTERNAL);
}

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

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}
 #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(9600);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately
 // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

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

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

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

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

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

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

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

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}

void loop(void){

 if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }

  DateTime now;

  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

  digitalWrite(greenLEDpin, HIGH);

  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m);           // milliseconds since start
  logfile.print(", ");
#if ECHO_TO_SERIAL
  Serial.print(m);         // milliseconds since start
  Serial.print(", ");
#endif

  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
#if ECHO_TO_SERIAL
  Serial.print(now.unixtime()); // seconds since 1/1/1970
  Serial.print(", ");
  Serial.print('"');
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(" ");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
  Serial.print('"');
#endif //ECHO_TO_SERIAL

  analogRead(photocellPin);
  delay(10);
  int photocellReading = analogRead(photocellPin);

  analogRead(tempPin);
  delay(10);
  int tempReading = analogRead(tempPin);

  logfile.print(", ");
  logfile.print(photocellReading);
  logfile.print(", ");
  logfile.print(temperatureF);
#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(photocellReading);
  Serial.print(", ");
  Serial.print(temperatureF);
#endif //ECHO_TO_SERIAL

}

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

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

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

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

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

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

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

  logfile.println();
#if ECHO_TO_SERIAL
  Serial.println();
#endif // ECHO_TO_SERIAL

  digitalWrite(greenLEDpin, LOW);

  // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
  // which uses a bunch of power and takes time
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();

  // blink LED to show we are syncing data to the card & updating FAT!
  digitalWrite(redLEDpin, HIGH);
  logfile.flush();
  digitalWrite(redLEDpin, LOW);

}

```

# Answer
Based on the information that you've provided, it's quite likely that your problem lies with how your SD card and accelerometer connect via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high. The 'datasheet'/tutorial for the Micro SD Card Breakout Board (which is the device that I assume you mean when you say *Adafruit microshield SD card*), has the following schematic:

Which doesn't appear to include a tri-state buffer.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer (in that case, I used a 74HC125 4-channel tri-state buffer) in the MISO line for each of the SPI devices.

---

This page on Better SPI Bus Design in 3 steps is what finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).
> 2 votes

---
Tags: arduino-uno, sd-card, datalogging
---


# Question
Title: Attaching Microcontroller to DAC evaluation board
For an independent undergraduate research project I'm trying to construct a digital feedback loop. I have never used an Arduino, or done much electrical/computer engineering, so I'm just taking things one thing at a time. I've been given this microcontroller and this DAC eval board, and now I'm just trying to put them together.

From reading, I need to attach jumper cables from #16 here to  the pins on the Eval Board here,

but I don't know where to find information on them, so I don't know which to plug into what. Any advice?

# Answer
> 1 votes
Your DAC uses the SPI protocol. For that you want to connect it to the SPI header. That's the 6-pin (3x2) header numbered 11 on the uC32.

Connect:

* The uC32's SCK pin to the DAC's SCLK
* The uC32's SDO pin (MOSI) to the DAC's SDIN pin.
* The uC32's SDI pin (MISO) to the DAC's SDO pin.

The other pins (I am not sure what they all do off hand, but the datasheet details them) can connect to any GPIO pins you like (except pins 11-13 which duplicate the SPI header - so you could use those instead if you prefer - 11=MOSI, 12=MISO, 13=SCK).

---
Tags: pins, digital-analog-conversion
---


title: HTTP request as bytes

text:
# Question
Title: HTTP request as bytes
I need to send this line of HTTP request as bytes. What is the correct way?

```
client.write(byte(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>"));

```

To be more clear this is my C# code for the request

```
byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

```

This is my full C# working code

```
 ServicePointManager.Expect100Continue = false;
        ASCIIEncoding encoder = new ASCIIEncoding();
        byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");
        Uri a = new Uri("http://192.168.0.64");
        HttpWebRequest request = WebRequest.Create("http://192.168.0.64/ISAPI/System/Video/inputs/channels/1/overlays") as HttpWebRequest;
        request.Method = "PUT";
        request.Credentials = new NetworkCredential("admin", "12345qwerty");
        request.ContentLength = 888;
        request.ContentType = "application / x - www - form - urlencoded; charset = UTF - 8";
        request.ContentLength = data.Length;
        request.GetRequestStream().Write(data, 0, data.Length);
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        response.Close();

```

This is the Arduino version

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 0, 177 };
byte server[] = { 192,168, 0, 64}; // Google
String big_string="<?xml versiding='rlay>";
EthernetClient client;

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

  delay(1000);

  Serial.println("connecting...");

  if (client.connect(server, 80)) {
    Serial.println("connected");
    client.println("POST /ISAPI/System/Video/inputs/channels/1/overlays HTTP/1.0");
    client.println("Host: 192.168.0.64");
    client.println("User-Agent: arduino-ethernet");
    client.println("Authorization: Basic YWRtaW46MTIzNDVxd2VydHk=");
   client.println("Content-Type: application / x - www - form - urlencoded; charset = UTF - 8");

    client.println("content-length:888");
    // client.println();
    //client.println(big_string.length());
    client.write(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

     //client.println();
    //client.print(big_string);
    // client.println();

  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {

    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

```

# Answer
Characters are bytes. ASCII codes of characters are the values. There is no difference between `client.print(str)` and `client.write(str, strlen(str))`. And `client.write(str)` is the same too.

In C# or Java the constant string is of type String. It is an object. You must call a method of the object to get the raw char/byte array. In Arduino a constant string is of type `const char*` a.k.a. `const char[]` which is on low level the same as `const byte*` or `const byte[]`

Equivalent of C#

`byte[] data = encoder.GetBytes("some string");`

for ASCII characters (not UTF) in C is

`byte data[] = "some string";`
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to fix "expected ; before ) token" error?
I am in the early stages of writing my program, but I have run into a problem. I am fairly new to Arduino so I'm not sure if there is something I am trying to do that doesn't work, but I am getting an error message

> expected ; before ) token

on the line `for(count <= 10)`.

I would really appreciate if someone could let me know why I am getting this error.

```
#include<EEPROM.h>
const int LED = 12;
const int SWITCH = 4;

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

  pinMode(LED, OUTPUT);           //LED is always outputting information
  pinMode(LED_BUILTIN, OUTPUT);   //Built in LED is always outputting information
  pinMode(SWITCH, INPUT_PULLUP);  //Switch inputs value when in/out of ground
}

void loop() {
  // put your main code here, to run repeatedly:
  int addr = 0;     //Declaring variables
  int count = 0;
  int seconds;

  if (digitalRead(SWITCH) == LOW) {
Serial.println("----Recording----");

    for (count <= 10) {
      while (digitalRead(SWITCH) == LOW) {
        count = count + 1;
        digitalWrite(LED, LOW);
        delay(50);
      }
      else {
        count = count + 1;
        digitalWrite(LED, HIGH);
        delay(50);
      }
    } else {
      digitalWrite(LED_BUILTIN, HIGH);        //Internal LED blinks
      delay (300);
      digitalWrite(LED_BUILTIN, LOW);
      delay(300);
    }
  }
}

```

# Answer
Welcome to arduino.stackexchange.
Compiler informs you about the problems with your code. In your case there is a problem with **for** loop.
Remember, the for loop is one of basic concepts in c/c++ (and many others) programming language.
Syntax is:

```
for ( init-expression ; cond-expression ; loop-expression )
    statement;

```

Description of above:

*init-expression*:
Before any other element of the for statement, init-expression is executed only once. Control then passes to cond-expression.

*cond-expression:*
Before execution of each iteration of statement, including the first iteration. statement is executed only if cond-expression evaluates to true (nonzero).

*loop-expression:*
At the end of each iteration of statement. After loop-expression is executed, cond-expression is evaluated.

For example:

```
for(int count=0; count<10; count++){
    if (count%2) {
        digitalWrite(LED, LOW);
        }
    else{
        digitalWrite(LED, HIGH);
        }
    }

```

Add some extra code when needed.

To see more description of for loop see here.
> 2 votes

# Answer
Also, only 'if' statements have 'else' clauses; loop statements do not. If you didn't get an error for the 'else' at first, it is because the compiler got lost in the for-loop with only one argument.

'while()' statements have a boolean expression inside the parentheses. Each time the boolean evaluates TRUE, the statement or block following the loop executes once, until the loop evaluates FALSE. Regardless of how many times it executes, even zero, the following code will be executed.

'for()' statements have three expressions. Any of the three may be absent but the places for all three must be shown.

* The first expression is executed once at the beginning of the loop. It typically initializes a loop variable, but may do anything, or be absent.
* The second expression is a boolean expression that works exactly like the only argument in a 'while()' loop (the loop is only executed if, and for as long as, the expression is TRUE).
* The third expression is executed after all of the statements in the loop. It typically advances the loop variable, but may do anything.
* Like the 'while()' loop, whatever follows the 'for()' loop will be executed regardless of whether the loop did anything.

Though any of the 'for()' loop's expressions may be left out, both semi-colons must still be present to make it clear *which* expressions were left out.

Note that 'for(;;)' is an idiom in C that means "forever" - i.e., an infinite loop. Some other construct needs to be executed within the loop to cause it to end, if it not meant to execute perpetually.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: What's the function of this transistor on Arduino Mega?
I am trying to get information about the transistor on the Arduino Mega board below:

It says "340P" on the transistor. I want be able to know which model transition is this so that I can check its documentation. It also want to know what it is driving or its function on the Arduino board.

# Answer
It's a P-channel MOSFET. It's job is to act as a "dropless" diode.

The principle is this:

* MOSFETs have a built-in diode across them in reverse bias (an effect of the chemistry)
* The P-channel MOSFET is connected backwards in series with the incoming USB power.
* The internal diode conducts power when there is +5V in to the USB to give power to the board.
* The diode imposes a voltage drop, but there is enough voltage still to run the circuitry.
* An op-amp compares the incoming voltage from the barrel jack (divided by 2) against 3.3V. If it's less than 3.3V (6.6V incoming) or not there at all, it turns on the P-channel MOSFET
* The MOSFET then short circuits the internal diode removing the voltage drop, giving the full 5V from the USB to the rest of the board.

simulate this circuit – Schematic created using CircuitLab

Note: diode shown is internal to the MOSFET.

The MOSFET is designated T2 in the schematic, and is a FDN340P on the reference design, although the actual model is not that critical, as long as the threshold voltage is above about -3V and it can happily handle 500mA or more.
> 8 votes

---
Tags: arduino-mega, transistor, documentation
---


# Question
Title: Can I make the BT module disconnect with a BT module and connect with another in the code?
I am working on a project that requires a connection between two BT modules (HC-05) and a mobile phone. Later on, I encountered a problem: I can't connect two BT modules to one at the same time, So I thought about the possibility of ending a connection and starting the other one when needed. If that was possible, how can I do that in an arduino code?

One of the BT modules is a master which means it can't connect to the phone and it has to be a master because it must be connected to the other slave BT module.

# Answer
> 0 votes
Send `AT+ROLE=1` to BT module to set module into master role. To set module back to slave mode, send `AT+ROLE=0`

Also check this video, you have source code in the description. It will help you understand how to do it.

---
Tags: arduino-uno, bluetooth, wireless, hc-05
---


# Question
Title: Serial Communication between 2 Arduinos for analogRead value
I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.

**Transmitter Code:**

```
void setup() {
  pinMode(A0, INPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
}

```

**Receiver Code:**

```
void setup() {
        Serial.begin(9600);
}
void loop() {
        if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        Serial.print("I received: ");
        Serial.println(incomingByte, DEC);
        }
}

```

# Answer
You'll want to get familiar with the standard C function sscanf(). It does exactly what you're looking for, converts an ASCII string into whatever type you like.

sscanf() API

The code to read an integer from the serial port would look something like this:

```
  char recv_buf[10];  int recv_int;
  Serial.readBytesUntil('\n', recv_buf, 9);
  recv_buf[9] = 0;  // make sure it's null terminated
  sscanf(recv_buf, "%d", &recv_int);
  Serial.print("I received: ");
  Serial.println(recv_int);

```
> 1 votes

# Answer
One byte is 8 bits so 2^8 is equal to 255. One byte can hold value up to 255. Since you have value of 1023(max possible) you have to split value into two bytes. Here's an example:

```
unsigned byte highValueByte(int value)
{
    return (value >> 8);
}

unsigned byte lowValueByte(int value)
{
    return (value - (highValueByte(value) << 8));
}

int giveValue(unsigned byte highByte, unsigned byte lowByte)
{
    return ((highByte << 0) & 0xFF) + ((lowByte << 8) & 0xFFFF);
}

void loop()
{
    int senValue = analogRead(/* PIN NUMBER */);
    int byteOne = highValueByte(senValue);
    senValue = lowValueByte(senValue);
}

```

Your code Works for one byte(try it), but it doesn't for two bytes value. Because you have two bytes, you have to introduce some kind of buffer. Example: `unsigned byte buffer[2] = { 0, 0 };` Also be sure you connected pins properly. RX from Arduino #1 goes into TX from Arduino #2 and vice versa.

About serial communation sync
> 1 votes

---
Tags: serial, communication, serial-data
---


# Question
Title: Turn on Indicator LED if Moisture Sensor Value >= MaxDryness for longer than 20 min
Hi so I am making a self watering flower pot with a moisture sensor and a peristaltic pump, the code is as follows:

I want to add an indicator LED which turns on if the sensor value has been equal to or greater than MaxDryness for longer than twenty minutes.

How would I alter the code to do that?

# Answer
> 2 votes
Following is an example how it could be coded.

Remember that the soil is dry by setting `DrySoil = true`.

Register the time at which a dry period starts in DrySoilBegin.

Check at each 'dry' reading whether DrySoil was true for more than 20 minutes.

Set `DrySoil = false` at every 'not dry' reading.

The `ul` after the constant `1200000` makes it an unsigned long value. This because `millis()` returns a `unsigned long` result. I am not 100% sure this is necessary (maybe the compiler takes care of this automatically).

As I don't have a plant watering system I couldn't verify the proper working..

```
#define WATERPIN 10
#define READSOILPIN A0
#define LEDPIN 13

// higher number is more dry
#define MAXDRYNESS 700

#define WATERDELAY 10000
#define WATERPOSTDELAY 5000

bool DrySoil = false; // State of soil
unsigned long DrySoilBegin; // Time when DrySoil became true

void setup() {
  Serial.begin(9600);
  pinMode(READSOILPIN, INPUT);
  pinMode(WATERPIN, OUTPUT);
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  int SensorValue = analogRead(READSOILPIN); //take a sample
  Serial.print(SensorValue);
  Serial.print(" ־ ");

  if(SensorValue >= MAXDRYNESS) {
    // Soil is too dry
    // Check if soil was already in a dry state
    if(DrySoil){
      // If already in a dry state check the duration
      if((millis()-DrySoilBegin) > 1200000ul){
        // If duration is longer than 20 minutes switch LED on
        //   or keep LED switched on
        digitalWrite(LEDPIN, HIGH);
      }
    }
    else{
      // First 'dry' result after 'wet' result(s)
      DrySoil = true; // Set DrySoil in true state
      DrySoilBegin = millis(); // Set beginning of DrySoil period
    }
    // start watering for 10 seconds then
    //    wait for 5 seconds before monitoring again
    Serial.println("Soil dry start watering");
    digitalWrite(WATERPIN, HIGH);
    delay(WATERDELAY); // wait until WATERDELAY milliseconds have passed
    digitalWrite(WATERPIN, LOW);
    delay(WATERPOSTDELAY); // wait until WATERPOSTDELAY milliseconds have passed
  }
  else{
    // Soil is not too dry
    DrySoil = false; // Set or keep DrySoil in state false
    digitalWrite(LEDPIN, LOW); // Switch LED off, or keep it switched off
    delay(50); // Wait 50 ms before next sampling
  }
}

```

# Answer
> 0 votes
Here's a little example how to do it. Adapt this way(if you want) by yourself.

```
// GLOBAL VARIABLES
unsigned long lowSensorTick = 0;
bool dry = false;

void loop()
{
    if (analogRead(/* PIN */) > /* THRESHOLD VALUE */)
    {
        // DRY
        if (dry == false)
        {
            lowSensorTick = millis();
            dry = true;
        }
        else
        {
            if (millis() - lowSensorTick > 720000) // 720000ms = 12min * 60000ms (1s = 1000ms)
            {
                digitalWrite(LED_PIN, HIGH); // LED GOES HIGH/ON
            }
        }
    }
    else
    {
        // WET
        dry = false;
        digitalWrite(LED_PIN, LOW); // LED GOES LOW/OFF
    }
}

```

---
Tags: sensors, led
---


title: 7 segment display blinking

text:
# Question
Title: 7 segment display blinking
I want to display the DHT22 temperature and humidity sensor in a 3 digit 7 segments display. It's always showing the sensor value and after 2 or 3 sec the display turns off, and then the display turns on, and so on.
I need help to understand where is the mistake on the code to make the display always turned ON.

```
#include <SevSeg.h>
#include <EEPROM.h>
#include "DHT.h"
#define COMMON_ANODE 0
#define DHTPIN A0     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
int chk;
float hum;  //Stores humidity value
float temp; //Stores temperature value
SevSeg sevseg;

void setup(){

byte numDigits = 3;
byte digitPins[] = {1,2,3};
byte segmentPins[] = {4,5,6,7,8,9,10,11};
sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
 dht.begin();
}

void loop(){
   temp= dht.readTemperature();

   sevseg.setNumber(temp,1);
   sevseg.refreshDisplay();
}

```

# Answer
> 1 votes
A good way to avoid display flicker is to only update the display when needed. The display update is what causes it to flicker. If you change your main loop as below, the display will only update when needed (when the current reading is different than the last reading). It's probably also a good idea to only read the temperature every 2 seconds or so which can be controlled with a simple delay().

```
float temp, last_temp = 0;

void loop() {
    temp = dht.readTemperature();
    if (temp != last_temp)
    {
        sevseg.setNumber(temp,1);
        sevseg.refreshDisplay();
    }
    last_temp = temp;
    delay(2000);
}

```

# Answer
> 0 votes
You have a multiplexed display. Multiplexed displays have to be constantly updated, or they display the last displayed digit (if there was one) for an extended period.

The reading from the DHT will take time. That time will interrupt the display updates causing it to stop for a while as it reads.

Why does it do it every few seconds? All I can suggest is that the DHT library you are using limits the actual readings to every few seconds - and between those times it just returns the previously stored value.

To get around it you should consider doing your display updates from within a timer interrupt (assuming your DHT library doesn't disable interrupts).

---
Tags: display, temperature
---


title: Newbie question - Biltong Box Project

text:
# Question
Title: Newbie question - Biltong Box Project
I am a newbie to electronics, but I do have experience working with electrical wiring in the UK, so I am comfortable working with 240V reasonably safely. I have also built a camper including all the 12V electrics from scratch. I am fairly technically able, as a building physicist and academic researcher. However, my expertise is in mechanical engineering and physics rather than electronics or electrical engineering.

**The Project**

I am designing a new generation biltong box. My previous biltong boxes had electrical devices wired individually into plugs and then manually switched.

For those who dont know 'biltong' is the South African equivalent of US jerky. We simply dry the raw beef as opposed to light cooking.

*Image 1 - first generation manually switched biltong box*

The first generation boxes worked great - they were a test bed for the physics - airflow/heat and drying rates. However, they lacked finesse and were technologically challenged. So I have set myself the goal of building a new smaller box, laser cut from acrylic and packed with more intelligence.

My inspiration is drawn from this great project

**Technical details**

The biltong dryer design currently comprises of:

* 1no 240V AC 60W tubular heater - this one specifically. I might want to add another in the future.
* 2no 12V DC 14.4W axial fans - these ones
* 1no 12V LED strip light - not yet selected

**What I want to do / Problem Statement**

I would like to have an Arduino based system, to facilitate the following features:

1. 2no temperature and humidity sensors (one at the inlet at the bottom and one at the outlet at high level)
2. Touch screen to: 1. display temperature and humidity over time, 2. enable manual control of the heater, fans and LED light, 3. allow me to modify the temperature and humidity setpoints
3. The ability for the Arduino to control the heater (on/off) and the fans (ideally variable) based on setpoints for temperature and humidity. But also to allow me to operate the heater and fans individually from the touchscreen - on / off / auto for all.

**Please help**

I know all the kit I am trying to control and how I want to do it (conceptually). Now I need some advice on how to make this happen please.

To kick things off I have purchased an Arduino MEGA 2560 board and kit and have experimented with a few small projects. I now want to use this to control the above.

**Questions**

1. Is my idea sensible and achievable (technically)?
2. I know that I will need a 240V relay to control the heater. Is this safe and reliable? \** This is my biggest concern. What can you recommend for this - there are so many available on the market.
3. I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?
4. Can I control the speed of the proposed 12V fans? And how is this achieved?

Huge thanks in advance.

**First Edit**

My calculated current for the heater is 60W / 240V = 0.25A

Questions:

1. So for a SSR - this looks like a good option \- what do you think?
2. Found a four channel, four route MOSFET \- what do you think? Once I have the switching working, i will consider working out the PWM. But switching will be fine for now.
3. How do I go about designing the circuitry - are there any good online Arduino resources for this?

**Second Edit**

Not sure where to go from here!

Also, cannot find MOSFET's in Fritzing.

# Answer
> 3 votes
> Is my idea sensible and achievable (technically)?

Yep, sure is. It's not really much different to a DIY Reflow Toaster Oven.

> I know that I will need a 240V relay to control the heater. Is this safe and reliable? \** This is my biggest concern. What can you recommend for this - there are so many available on the market.

I would suggest an SSR instead of a mechanical relay. Easier to drive, and less electrical noise.

> I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?

No. Use MOSFETs for those. You can drive those with PWM to change the speed / brightness.

> Can I control the speed of the proposed 12V fans? And how is this achieved?

Yes - see above.

As far as control goes you may want to investigate PID as your calculation method.

---
Tags: arduino-mega, relay, electronics
---


# Question
Title: how to code LED turning signals on smart car
this question is regarding how to add turn led signals on arduino powered smart car. I have 4 leds to give turn indications on my smart car(line follower, obstacle avoider, Bluetooth mobile controlled and also IR remote controlled)

can someone help me to modify the code in such a way that I can add led turn signals?(I'm completely new to arduino)

want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time. i also need two right leds high at the same time when it turns right and I need two left leds high at the same time when it turns left .

this is the code

```
#include <IRremote.h>
#include <Servo.h>

//Pin assignments and global variables per function. Customize if needed
//*******Pin assignments Motor board and IR receiver********************
const int MotorRight1 = 7;
const int MotorRight2 = 8;
const int MotorLeft1 = 9;
const int MotorLeft2 = 10;
const int MotorRightPWM = 6;
const int MotorLeftPWM = 11;
const int irReceiverPin = A5;
const int servoPin = A4; //orange wire
int iSpeed = 255; //speed, range 0 to 255
const int LedPin=13;

//******Infrared key bindings********************************************
const long IRfront = 16730805;      //go straight: button up
const long IRback = 16718055;       //go back    : button down
const long IRturnright = 16734885;  //turn right : button right
const long IRturnleft = 16716015;   //turn left  : button left
const long IRstop = 16726215;       //stop       : button OK
const long IRcny70 = 16754775;      //CNY70 automatic mode: button EQ
const long IRAutorun = 16750695;    //Ultrasonic mode : button play/pause
//******Track following pin assignments and signals**********************
const int SensorLeft = 5;      //
const int SensorMiddle = 4 ;   //
const int SensorRight = 3;     //
IRrecv irrecv(irReceiverPin);  // IRrecv signal
decode_results infrared;       // decode result
//*******Ultrasonic pin assignments and signals**************************
const int echoPin = 12; // ultrasonic receive=echo pin
const int triggerPin = 13; // ultrasonic send=trigger pin
Servo myservo; // define myservo
const int degreesForward = 130; //nr degrees to look forward
const int degreesLeft = 60; //nr degrees to look left
const int degreesRight = 180; //nr degrees to look right
const int delay_time = 250; // servo motor delay
const int Fgo = 8; // go straight
const int Rgo = 6; // turn right
const int Lgo = 4; // turn left
const int Bgo = 2; // go back
//*****Bluetooth signals**************************************************
char val; //stores received character. Needs to be global to perform continuous movement

//*********General SETUP: activate pins***********************************
void setup() {
  //start receiving serial infor
  Serial.begin(9600);
  //motor connections
  pinMode(MotorRight1, OUTPUT);  //

  pinMode(MotorRight2, OUTPUT);  //

  pinMode(MotorLeft1,  OUTPUT);  //

  pinMode(MotorLeft2,  OUTPUT);  //
  pinMode(MotorRightPWM, OUTPUT); //enable for right side motor
  pinMode(MotorLeftPWM, OUTPUT); //enable for right side motor
  irrecv.enableIRIn();      // start infrared decode
  myservo.write(degreesForward);       // will make head look in front

  //black track following
  pinMode(SensorLeft, INPUT);
  pinMode(SensorMiddle, INPUT);
  pinMode(SensorRight, INPUT);

  //Ultra sonic
  //digitalWrite(2,HIGH); //what is this pin for?
  pinMode(echoPin, INPUT);
  pinMode(triggerPin, OUTPUT);
  myservo.attach(servoPin);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(ledrightfrontindicator, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(ledrightfrontindicator, LOW);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(ledleftfrontindicator, HIGH);
  digitalWrite(MotorLeft2, LOW);
  digitalWrite(ledleftfrontindicator, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void right(int d) { //turn right (single wheel)
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void left(int d) {//turn left(single wheel)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(MotorRight1, HIGH);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, HIGH);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void stopp(int d) { //stop
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, LOW);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, LOW);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}
void back(int d) { //go back
  digitalWrite(MotorRight1, LOW);
  digitalWrite(MotorRight2, HIGH);
  digitalWrite(MotorLeft1, LOW);
  digitalWrite(MotorLeft2, HIGH);
  analogWrite(MotorRightPWM, iSpeed);
  analogWrite(MotorLeftPWM, iSpeed);
  delay(d * 10);
}

//************Ultrasonic distance calculator*************************************
//detect distance for given angles and print char + direction
float getDistance(int degrees, char dir) {
  myservo.write(degrees);
  digitalWrite(triggerPin, LOW); // ultrasonic echo low level in 2us
  delayMicroseconds(2);
  digitalWrite(triggerPin, HIGH); // ultrasonic echo high level in 10us, at least 10us
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW); // ultgrasonic echo low level
  float distance = pulseIn(echoPin, HIGH); // read time
  distance = distance / 5.8 / 10; // turn time to distance
  Serial.print(dir); //
  Serial.print(" distance: "); //
  Serial.print(int(distance)); //  output distance (mm)
  Serial.print("\n");
  return distance;
}
//*************Ultrasonic direction decision making******************************
//measurements three angles (front, left, right
int getDirectionFromdetection() {
  int Fspeedd = 0; // front distance
  int Rspeedd = 0; // right distance
  int Lspeedd = 0; // left distance
  int delay_time = 250; //
  int directionn =0;

  //get front distance
  Fspeedd = getDistance(degreesForward, 'F');

  // if distance is less than 10mm
  if (Fspeedd < 10) {
    stopp(1); //  clear output
    directionn = Bgo;
  }
  // if distance less than 25 mm
  else if (Fspeedd < 25) {
    stopp(1); // clear output
    Lspeedd = getDistance(degreesLeft, 'L'); // detection distance on left side
    delay(delay_time); // waiting for the servo motor to become stable

    Rspeedd = getDistance(degreesRight, 'R'); // detection distance on right side
    delay(delay_time); // waiting for servo motor to be stable

    // if left distance greater than right
    if (Lspeedd > Rspeedd) {
      directionn = Lgo; // go left
    }

    if (Lspeedd <= Rspeedd) {//if left distance less than right
      directionn = Rgo; //go right
    }

    if (Lspeedd < 15 && Rspeedd < 15) { //if distance less 10mm both right and left
      directionn = Bgo; //go back
    }
  }
  else {
    directionn = Fgo; //go straight
  }
  return directionn;
}

void autoRunUsingUltraSonic() {
  bool stopPressed;
  int directionn = 0; // front=8, back=2, left=4, right=6
  while (IRAutorun) {
    myservo.write(80); // make the servo motor reset
    directionn = getDirectionFromdetection();
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
    else if (directionn == Fgo) { //go straight
      infrared.value = 0;
      advance(5); //
      Serial.print(" Advance "); //
      Serial.print(" ");
    }
    else if (directionn == Bgo) { //go back
      infrared.value = 0;
      back(8); //
      turnL(3); //
      Serial.print(" Reverse "); //
    }
    else if (directionn == Rgo) { //turn right
      infrared.value = 0;
      back(1);
      turnR(60); //
      Serial.print(" Right "); //
    }
    else if (directionn == Lgo) { //turn left
      infrared.value = 0;
      back(1);
      turnL(60);
      Serial.print(" Left ");
    }
  }
  infrared.value = 0;
}

//*************************Bluetooth functionality***********************
//Bluetooth commands
void bluetoothCommand() {
  if (Serial.available()) { //check if bluetooth command available
    val = Serial.read();
    Serial.write(val);
  }
  if (val == 'F') { // Forward
    advance(10);
  }
  else if (val == 'S') { // Stop Forward
    stopp(10) ;
    val = Serial.read(); //read value again, otherwise can't continu with infrared
  }
  else if (val == 'B') { // Backwards
    back(10);
  }
  else if (val == 'R') { // Right
    turnL(10);
  }
  else if (val == 'L') { // Left
    turnR(10);
  }
  else if (val == 's') { // Stop, not used though
    stopp(10 ) ;
  }
  else if (int(val) >= 49 && int(val) <= 57) { //set speed
    iSpeed = (int(val)-48)*26;
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'q') { //set speed
    iSpeed = 255;
    digitalWrite(LedPin,HIGH);
    Serial.println("Speed set to: " + iSpeed);
  }
  else if (val == 'W') {
    digitalWrite(LedPin,HIGH);
  }
  else if (val == 'w') {
    digitalWrite(LedPin,LOW);
  }
}

//Check if stop command on remote is pressed (button 5)
bool stopCommandPressed(){
  bool stopPressed = false;
  if (irrecv.decode(&infrared)) {
    irrecv.resume();
    Serial.println(infrared.value, HEX);
    if (infrared.value == IRstop) {
      stopp(10);
      stopPressed = true;
    }
  }
  return stopPressed;
}

void followBlackLine() {
  bool stopPressed;
  int SL;  //sensor left
  int SM;  //sensor middle
  int SR;  //sensor right
  while (IRcny70) {
    SL = digitalRead(SensorLeft);
    SM = digitalRead(SensorMiddle);
    SR = digitalRead(SensorRight);

    if (SM == HIGH) {//middle sensor in black area
      if (SL == LOW & SR == HIGH) {//left sensor in black area, right sensor in white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {//left white, right black, run right
        right(0);
      }
      else { // left and right both in white, go straight
        advance(0);
      }
    }
    // middle sensor in white area
    else {
      if (SL == LOW & SR == HIGH) { // left black ,right white, turn left
        left(0);
      }
      else if (SR == LOW & SL == HIGH) {
        right(0);
      }
      else {  //left and right both in white, stop
        stopp(0);
      }
    }
    stopPressed = stopCommandPressed();
    if (stopPressed) {
      break;
    }
  }
  infrared.value = 0;
}

//**************************************MAIN LOOP***************************************
void loop() {
  //bluetooth commands
  bluetoothCommand();
  //************************************normal remote control mode ********
  // decoding success 'receive infrared signal
  if (irrecv.decode(&infrared))  {
    if (infrared.value == IRfront) {
      advance(0); //go straigt
    }
    else if (infrared.value ==  IRback) {
      back(0); //go back
    }
    else if (infrared.value == IRturnright) {
      turnR(0); // go right
    }
    else if (infrared.value == IRturnleft) {
      turnL(0); // go left
    }
    else if (infrared.value == IRstop) {//stop
      stopp(0);
    }
    //********************follow black line********cny70 automatic mode********
    else if (infrared.value == IRcny70) {
      followBlackLine();
    }
    //***********************ultrasonic automatic mode***************************
    else if (infrared.value == IRAutorun ) {
      autoRunUsingUltraSonic();
      myservo.write(degreesForward);       // will make head look in front
    }
    //********************wait a little before continuing**************************
    irrecv.resume();
    delay(300);
  }
  else {
    stopp(0);
  }
}

```

# Answer
> 0 votes
Like chrisl suggested, add the led code to the functions advance, back, left, and right

```
const int LedFrontRight = 21;//change pin numbers
const int LedFrontLeft = 22;
const int LedBackRight = 23;
const int LedBackLeft = 24;

// ...

void setup() {
  // ...
  pinMode(LedFrontRight, OUTPUT);
  pinMode(LedFrontLeft , OUTPUT);
  pinMode(LedBackRight , OUTPUT);
  pinMode(LedBackLeft  , OUTPUT);
}

//**************Movement functions******************************
void advance(int d) { //go straight
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void right(int d) { //turn right (single wheel)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void left(int d) {//turn left(single wheel)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void turnR(int d) {//turn right (two wheels)
  digitalWrite(LedFrontRight, HIGH);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void turnL(int d) {//turn left (two wheels)
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , HIGH);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}
void stopp(int d) { //stop
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , LOW);
  digitalWrite(LedBackLeft  , LOW);
  //...
}
void back(int d) { //go back
  digitalWrite(LedFrontRight, LOW);
  digitalWrite(LedFrontLeft , LOW);
  digitalWrite(LedBackRight , HIGH);
  digitalWrite(LedBackLeft  , HIGH);
  //...
}

```

---
Tags: arduino-uno, code-review, code-optimization
---


# Question
Title: How to move Servo in between three positions
I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

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

void setup() {
  myservo.attach(12);  // attaches the servo on pin 9 to the servo object
}

void loop() {

  for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
    // in steps of 90 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

  for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

}

```

But the behavior of the servo is not correct. It moves few degree from initial position and then comes back.

What is wrong with the logic in my code ?

# Answer
> 1 votes
The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.

# Answer
> 0 votes
I think that the servo is too slow. When you ask it to go 90 degrees it starts, than after one second (while it maybe reaches 5 degrees) you ask it to go to 180 degrees it is probably reaching 10 degrees. There it waits again one second.

Than you ask it to go back to 0 (which it does in the same 2 seconds as it moved from 0 to 10 degrees).

Try to adjust the delay times, or use a faster servo.

Also note that in your example (if you wish it would behave like coded), it will end 2 seconds at 0 and 180 degrees, and 1 second at 90 degrees).

Try:

```
void move_servo(int pos)
{
    myservo.write(pos);
    delay(30000);
}

void loop()
{
    move_servo(  0);
    move_servo( 90);
    move_servo(180);
    move_servo( 90);
}

```

It will wait 30 seconds between each step, make this less when possible. To make the servo wait not more than needed, check the old and new servo position and wait as needed, it's probably reasonably linear.

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


# Question
Title: Arduino clone woks only with USB - NOT with external power
I have an Arduino UNO ch430 clone. It works with USB power supply, I can upload a Sketch and it works just fine. With external power supply, doesn't work. What do I mean? No LED lights up, *high* pins output ~ 0V. I'm using that barrel jack plug with 9V (6 x 1,5V batteries). Input voltage is measured OK. The AMS1117 regulator has Vin pin = Vout pin; i mean it gets no input Voltage. On the other hand, the M7F rectifier diode that comes between the jack and the regulator takes all voltage. I don't understan why, given that the anode is at higher voltage than the cathode (+9V). It shouldn't block current flow. I tried jumping the rectifier and getting the jack +pin directly to the Vin at the regulator: current starts to flow, but apparently so much that the ams1117 heats a lot and really fast. Well i don't know why it suddendly gets so much current, I have absolutely nothing pluged to the board and I couldn't find any stain or damaged spot on it.

I can't figure out what is happening. I hope you can help me, and thanks in advance.

---

This is an exact (i'm pretty sure) schematic of my board. Link

# Answer
> 2 votes
It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.

You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.

Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.

---
Tags: arduino-uno, power, clones
---


# Question
Title: Sketch talks to Android via BLE on Serial2 but times out after 5 seconds when Serial cable disconnected or not present
From an Android phone I am using the "Serial Bluetooth Terminal" app to communicate to an Arduino Mega 2560 with a Bluetooth Low Energy HM10 (Jaycar XC-4382) module connected via Serial2.

If the physical USB serial cable (Serial) is connected to Arduino the very simple sketch below works fine and runs continuously. When the cable is disconnected mid sketch or the power is cycle without the cable connected the sketch will run for about 5 seconds and then stop.

How can I prevent the sketch from timing out when the serial cable is disconnected?

```
int counter = 0;

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

void loop()
{
    Serial2.print(counter); Serial2.println();
    delay(1000);
    counter++;
}

```

# Answer
> -1 votes
The workaround is to switch to using SoftwareSerial, see code below. Data is continuously sent via Bluetooth from Arduino Mega to Android with or without the usb cable connected.

```
#include <SoftwareSerial.h>

// Connections
// Arduino HM10
// MEGA
// ----    ----
// 3.3v    VCC
// GND     GND
// 12      RX
// 13      TX

SoftwareSerial bte(12,13);    // RX, TX use (2,3) for UNO
int counter = 0;

void setup() {
  // set the data rate for the SoftwareSerial port
  bte.begin(9600);
  bte.println(counter);
}

void loop() { // run over and over
  bte.println(counter);
  counter++;
  delay(1000);
}

```

---
Tags: arduino-mega, bluetooth
---


# Question
Title: What components do I need to build Arduino based water pump controller?
I have situation at my home which is causing us a lot of headache. We get drinking water only at midnight and someone has to wake up and switch on electric pump. This electric pump will pump water from water tank present at ground floor to the water tank present on the terrace.

I want to automate this electric pump operation and I have come up with following rules for it:

1. When water tank at ground floor is almost full then automatically turn on the pump which will push water from ground floor to the tank on the terrace.
2. When water tank on the terrace is full then switch off motor.

I am a professional software engineer and I have vast experience in Java, Scala, REST API, Big Data and all but I am totally new to Arduino so I do not know which Arduino components I need to build the above mentioned system.

Any guidance will be deeply appreciated.

Thanks, Chandra

# Answer
If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful! http://www.powerswitchtail.com/
> 3 votes

# Answer
The easiest to build would be to use a real-time clock shield for time-keeping (examples: make or buy) and a relay- or solid-state switch shield (popular item - many choices) for switching the pump. A simple wall power supply providing 5volts to run the Arduino completes it. Oh, yes - an Arduino board, too!
> 1 votes

---
Tags: motor
---


title: How millis() resets itself to 0

text:
# Question
Title: How millis() resets itself to 0
Looking at the documentation for the `millis()` function , it says:

> Returns the number of milliseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days.

How's this possible? Is Arduino detecting when `millis()` overflow then resets the value to 0? If so, how does it do it? I just want to know what exactly is going on under the hood with the variable that is being returned by the `millis()` function.

# Answer
It is not an exclusive property of `millis()`. Any counter with a limited number of digits eventually returns to zero. For example, a 4 digit tally counter returns to zeros after `9999`.

Under the hood, the variable for `millis()` is of type `unsigned long`, which is 32 bits on the Arduino. In this case, the 32 bits (binary 0's and 1's) are similar to the digits (0 thru 9) on the tally counter.

The maximum is `11111111 11111111 11111111 11111111`. Once there, `millis()` returns to zero when you add `1`. The maximum (32 "ones") is `2^32 - 1`, which equals `4294967295` in the decimal number system. The maximum value for the counter is, therefore, 4,294,967,295 milliseconds. Converted to days you get approximately 49.71 days.
> 25 votes

---
Tags: millis
---


title: NRF51822 ± Arduino Uno / ATmegaXXX?

text:
# Question
Title: NRF51822 ± Arduino Uno / ATmegaXXX?
Hello I want to make a simple home automation project and I'd like to use an arduino uno for prototyping and later a atmega for deployment. I need some sort of a mesh communication method. I was thinking about the NRF51822 chip but I can't find any arduino libraries for it.

# Answer
> 0 votes
You can use the NRF51822 as module with AT firmware attached to Arduino. Then you need only the AT commands reference and some examples how to send AT commands and parse the response.

Or you can use the 32-bit ARM cortex-m0 micro-controller inside NRF51822 with Arduino nrf5 package. It requires a programmer/debugger hardware for sketch upload.

---
Tags: bluetooth, library, atmega328, wireless
---


title: how to simplify code

text:
# Question
Title: how to simplify code
I am as new as new can be to the Arduino world and have been playing around with them. I have a few "Arduino Uno" boards that I purchased and have successfully loaded sketches to them. However I am having problems figuring out how to write code in a simple manner.

I am using a LED strip of WS2812 LEDs (similar to this). Here is what I would like to achieve:

I would like to be able to light "lets say" LEDs `1, 3, 5, 7`. Then light LEDs `2, 4, 6, 8` or any other combination of "multiple LEDs", by that I mean maybe LEDs `0, 14, 15, 36, 37, 52, 54`. I am sure you get the idea.

Can I write a single line code to light these LEDs or do I have to write out each line.

Sorry if this is a simplistic question, but I have searched and have not seen anything that may accomplish this, or I just over looked it.

Thanks in advance for your help

# Answer
I have to say that I do not have any experience with the ws2812 led strip but basically it is used with the Adafruit\_Neopixel library where you have the function `pixel_obj.setPixelColor(pixel_number,pixel_obj.Color(R,G,B)` and the function `pixel_obj.show()`. Now you basically want to make the code in `void loop()` clean and there is a wide choice of possibilities and techniques to use. The simplest is not to do it, but if you want you can write a library to do it or write a function that takes the number of the pins and light 'em up (all with the same color), like this
`void light_pixel(int pixels[],int Red,int Green,int Blue){
 for(int i=0;i<NUMPIXELS;++i){
 pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
 }
 pixel_obj.show();
}`
This works assuming you have declared pixel\_obj in the outermost scope, and you will call the function like this:

```
#include <Adafruit_NeoPixel.h>
#define PIN //Whatever you pin is
#define NUMPIXELS //Thenumber of the pixels in your strip
Adafruit_NeoPixel pixel_obj = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
// You may have to modify the third parameter Rationale: You didn't
// specified anything about your led strip
void setup(){
pixel_obj.begin();
pinMode(PIN, OUTPUT);
}
void light_pixel(int pixels[],int Red, int Green, int Blue){
for(int i=0;i<NUMPIXELS && pixels[I]!=-1 ;++i){
    pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
}
pixel_obj.show();
}
void loop(){
int my_pixels[NUMPIXELS]={1,3,5,7,-1}; // Using -1 as terminator
// Initialize the array . Disclaimer: this is not optimised and you might use
// new opearator or better pass the reference of a vector to the function so
// that you can modify the range of the vector and have a more concise function
light_pixel(my_pixels,255,255,255);
delay(1000);
light_pixel(my_pixels,0,0,0);
}

```

Then you can change the number of my\_pixels with a smile array assignment This function is just a sample to get the job done but I'd recommend you to study further the C/C++ programming language in general in order to write better code
Good Luck!
> 2 votes

---
Tags: programming
---


# Question
Title: Reading values with HC-05 and sending commands at the same time working inconsistently
Not good at coding at all, so I'm at a total loss here.

But I'm doing a project that involves controlling a larger DC voltage through a mosfet. What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.

However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.

The code here is a short version of the project that I'm working on, but behaves similarly.

```
#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;

void setup() {
  delay(2000);
  pinMode(mosfet, gate);
  analogWrite(mosfet, 0);   //starts closed
  Serial.begin(9600);
}

void loop() {
  while(Serial.available() > 0){
    state = Serial.read();

    for (int y=0; y <= 5; y+=5){
      delay(500);
      Serial.println("testphase 1");
      delay(500);
    }

    for (int y=5; y >= 0; y--){
      delay(250);
      Serial.println("testphase 2");
      delay(250);
    }

    if (state == '0') {
    gate = gate + 1;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +1");
    state = 0;
    }

  if (state == '1') {
    gate = gate + 10;
    if(gate > maxgate) gate = maxgate;
    analogWrite(mosfet, gate);
    Serial.println(int(gate));Serial.print(", +10");
    state = 0;
    }
}
}

```

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.

I have no idea how I would interrupt a loop to execute the given command and then go back.

# Answer
> 2 votes
Actually got it working myself, but thank you so much for your help @chrisl

Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.

Basically just moved my measuring stuff outside the while loop\*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)\* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.

Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.

Here's a short version, should somebody bump into this thread in the future.

```
void loop() {
   while(Serial.available() > 0){
    state = Serial.read();

  if (state == '0') {stuff happens here,
    }
    }  //End of the while loop.

  sensors.requestTemperatures();
  delay(1000);
  Celcius=sensors.getTempCByIndex(0);
}

```

---
Tags: arduino-uno, hc-05
---


# Question
Title: Random characters generated by LCD during serial.read()
I am using the following codes to print characters on LCD display....

```
#include <LiquidCrystal.h>

const int rs = 8, en = 9, d0 = 4, d1 = 5, d2 = 6, d3 = 7;
LiquidCrystal lcd(rs, en, d0, d1, d2, d3);

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    delay(100);
    lcd.clear();
    while (Serial.available() > 0) {
      lcd.write(Serial.read());
    }
  }
}

```

but in the end it is generating an unwanted character also..

kindly help me with the problem

# Answer
> 2 votes
The character to the right of the 'A' on your LCD display does not correspond to any of the built-in character bitmap definitions (either on a EU or Chinese display). This random pattern is likely one of the 8 programmable character bitmaps supported by the LCD that has not been defined yet (ASCII codes 0 to 7).

So, you're likely sending the LCD a character with a value between 0 and 7. It's probably a good idea to filter out invalid characters before attempting to display them on your LCD.

Filtering Example:

```
char c = Serial.read();
if ((c >= 32) && (c <= 128))
  lcd.write(c);

```

---
Tags: arduino-uno, serial, lcd, shields
---


title: Why do the LEDs visibly flicker?

text:
# Question
Title: Why do the LEDs visibly flicker?
The aim of the project was to be able to show two "kinds" of LEDs in a 8x8 single color LED matrix. I used a MAX7219 chip to drive the LEDs using my Arduino UNO R3 as the driver (with the usual connections).

Despite the frequency of the `blackupdate()` function being near to a 100Hz, why do I see the LEDs corresponding to `currentblack()` flickering? 100Hz is much beyond the resolution of the eye, as I understand it. The multiplexing frequency of the MAX7219 chip is also much beyond resolution (800Hz). Why do the "white" LEDs not flicker?

Here's the code with `Serial.println()` added for debugging:

```
int DataPin = 2; // Pin 1 on MAX
int LoadPin = 3; // Pin 12 on MAX
int ClockPin = 4; // Pin 13 on MAX
int currentwhite[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};
int currentblack[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};

#define SCAN_LIMIT_REG 0x0B
#define DECODE_MODE_REG 0x09
#define SHUTDOWN_REG 0x0C
#define INTENSITY_REG 0x0A
#define DISPLAY_CHECK_REG 0x0F

void setup() {
  pinMode(DataPin, OUTPUT);
  pinMode(LoadPin, OUTPUT);
  pinMode(ClockPin, OUTPUT);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, SCAN_LIMIT_REG); // scan limit set to 0:7
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000111);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, DECODE_MODE_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, SHUTDOWN_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST,  B00000001);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, DISPLAY_CHECK_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
  digitalWrite(LoadPin, HIGH);
  digitalWrite(LoadPin, LOW);
  shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
  shiftOut(DataPin, ClockPin, MSBFIRST, 0);
  digitalWrite(LoadPin, HIGH);
  Serial.begin(9600);

  currentblack[3]=B00001000;
  currentblack[4]=B00010000;
  currentwhite[3]=B00010000;
  currentwhite[4]=B00001000;
}

void blackupdate() {
  digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
    shiftOut(DataPin, ClockPin, MSBFIRST, 0);
    digitalWrite(LoadPin, HIGH);
  for (byte row=0; row<8; row++){
    digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
    shiftOut(DataPin, ClockPin, MSBFIRST, (currentblack[row]));
    digitalWrite(LoadPin, HIGH);
  }
}

void whiteupdate() {
  digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
    shiftOut(DataPin, ClockPin, MSBFIRST, 15);
    digitalWrite(LoadPin, HIGH);
  for (byte row=0; row<8; row++){
    digitalWrite(LoadPin, LOW);
    shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
    shiftOut(DataPin, ClockPin, MSBFIRST, (currentwhite[row]));
    digitalWrite(LoadPin, HIGH);
  }
}

void loop() {
  Serial.print("A");
  Serial.println(millis());
  blackupdate();
  Serial.print("B");
  Serial.println(millis());
  whiteupdate();
  delay(5);
  Serial.print("C");
  Serial.println(millis());
}

```

And the Serial output was as follows:

```
A1
B3
C10
A10
B12
C19
A19
B21
C28
A28
B30
C37
A37
B39
C47
A47
B49
C56
A56
B59
C65
A66
B68
C75
A75
B77
C84
A84
B87
C94
A94
B96
C105
A105
B112
C123
A123
B131
C142
A143
B150
C161
A161
B168
C180
A180
B187
C198
A198
B205
C217
A218
B225
C236
A236
B243
C254
A254
B262
C273
A274
B281
C292
A292
B300
C311
A311
B318
C329
A329
B336
C348
A349
B356
C367
A367
B374
C386
A386
B393
C404
A404
B412
C422
A423
B431
C442
A442
B449
C460
A460
B467
C479
A480
B487
C498
A498
B505
C517
A517
B524
C535
A535
B542
C553
A555
B562
C573
A573
B580
C591
A591
B599
C610
A611
B618
C629
A629
B636
C648
A648
B655
C666
A666
B673
C685
A686
B693
C704
A704
B711
C722
A722
B730
C741

```

# Answer
> 0 votes
The hardware setup isn't clear. For example, do you have two matrix's or one? In any event, the effect of black update() stays on much shorter than the effect of white update() due to the delay inserted in the main loop.

# Answer
> 0 votes
You are correct that this is updating at about 100 Hz. The clue is in the serial output:

```
A1
B3  <<
C10 <<
A10
B12 <<
C19 <<
A19
B21 <<
C28 <<
A28
B30 <<
C37 <<
A37

```

There is always a big gap between the ms reading between `B` and `C`. This is due to the delay in after the `whiteupdate()`.

```
void loop() {
    Serial.print("A");
    Serial.println(millis());
    blackupdate();
    Serial.print("B");
    Serial.println(millis());
    whiteupdate();
    delay(5);    // <-- DELAY HERE
    Serial.print("C");
    Serial.println(millis());
}

```

There is no update between the `blackupdate()` and the `whiteupdate()`, so even though 5ms is just on the border of what your eyes can determine, due to the repeating pattern and persistence of vision, your eyes do notice it.

You will find that your flicker will dissapear if you split the delay so you have an equal delay between your `blackupdate()`-\>`whiteupdate()` and `whiteupdate()`-\>`blackupdate()`.

```
void loop() {
    Serial.print("A");
    Serial.println(millis());
    blackupdate();
    delay(2);    // <-- DELAY HERE
    Serial.print("B");
    Serial.println(millis());
    whiteupdate();
    delay(2);    // <-- DELAY HERE
    Serial.print("C");
    Serial.println(millis());
}

```

Removing the serial debug lines give you:

```
void loop() {
    blackupdate();
    delay(2);
    whiteupdate();
    delay(2);
}

```

# Answer
> 0 votes
There may be some more physiology at work here, too. Did you notice the flickering while staring fixedly at one LED, or while looking around your project area ("scanning" as it were, with your eyes)? If you scan your vision past a flickering LED, even one that flickers at a rate beyond our perception, you can see a streak of dots cross your vision, where a steadily lit one would make a solid streak. I noticed it driving at night, when LED tail-lights were still new and unusual. Those cars stood out because their tail-lights left the same trail of dots across my vision (although some people have told me they do not see this phenomenon or aren't aware of it...).

---
Tags: arduino-uno, led, time, multiplexer, max7219
---


# Question
Title: Transient buttons control non-transient behaviour of LEDs
Imagine a system where you have two transient non-exclusive buttons and two LEDs.

When you press button 1, the LED 1 is HIGH and LED 2 is LOW (and stays that way).

When you press button 2, the LED 1 is LOW and LED 2 is HIGH (also stays that way).

Which C++ code allow me, to keep the LED 1 turned on indefinitely (until button 2 is pressed)?

Basically, my problem is, that the buttons are transient and the behaviour of LEDs shouldn't be.

Here is code, that would work for pernament exclusive buttons, but doenst work for transient non-exclusive buttons.

```
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
}
else
{
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
}
else
{
    led2 = LOW;
}

```

# Answer
> 0 votes
Something like this:

```
if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
    led1 = LOW;
}

```

# Answer
> 1 votes
Don't react to the button by changing the LED; change a state-variable in memory, instead. That saves the information of which button was most recently pressed. Then, each time through your loop, set your LED's according to the contents of that persistent variable. Remember that it will have to be a static variable (global or static local), as an automatic one will disappear and reappear after each exit and re-entry to loop(), and you cannot count on its contents when that happens.

Update:

> How do I prevent overwriting the state variable with different input ?

You don't prevent it - you must over-write it. The purpose of the state variable is to remember which button was last pressed. I had in mind something like the following, where `lastButton` saves the number of the most recent button:

```
void setup(){
   pinmode(LED1PIN, OUTPUT);
   pinmode(LED2PIN, OUTPUT);
   pinmode(BUTN1PIN, INPUT_PULLUP);  // you might not want the pullup
   pinmode(BUTN2PIN, INPUT_PULLUP);  //  depending on your wiring.
}

void loop(){
   static uint8_t lastButton = 0;

   // Save the number of the last button pressed.
   if (digitalRead(button1) == HIGH)
      lastButton = 1;
   else if (digitalRead(button2) == HIGH)
      lastButton = 2;

   // Set the LEDs according to most recent button
   // Note that at program-start, when no button has
   // been pressed yet, this code leaves both LED's off.
   if (lastButton == 1)
   {
      digitalWrite(LED1PIN, HIGH);
      digitalWrite(LED2PIN, LOW);
   }
   else if(lastButton == 2)
      digitalWrite(LED1PIN, LOW);
      digitalWrite(LED2PIN, HIGH);
   }
}

```

---
Tags: c++, esp32
---


title: Library Compiler Error - ArduinoJson

text:
# Question
Title: Library Compiler Error - ArduinoJson
I have installed via the Arduino Library Manager a library called ArduinoJson. It seems to install fine and I have included the library in my sketch using:

```
#include "ArduinoJson.h"

```

But when I compile the sketch I get the following error:

```
"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\mega" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\HX711-0.1" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\ArduinoJson\\src" "C:\\Users\\jason\\AppData\\Local\\Temp\\arduino_build_7871\\sketch\\counting_machine.ino.cpp" -o nul

In file included from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/JsonBufferBase.hpp:7:0,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/DynamicJsonBuffer.hpp:7,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:9,

                 from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                 from G:\My Drive\Personal\jdeation\Arduino\counting_machine\counting_machine.ino:32:

G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/JsonParser.hpp:7:29: fatal error: ../JsonBuffer.hpp: No such file or directory

compilation terminated.

```

I'm very new to Arduino programming, can someone point me in the right direction.

Thanks.

# Answer
Go through the library manager and make sure your version is 5.14.3 and not higher. The higher ones are Beta versions and there has been changes that are not compatible with the previous non-Beta versions.

This is an annoyance because you would think that the latest would be the best. But that is not always the case.
> 1 votes

---
Tags: json
---