# Question
Title: Stepper motor slow when reading from MPU 6050 sensor
I'm trying to get an inverted pendulum project working (following the instructions here), and while my stepper motor moves the cart just fine when that's the only code in the Arduino sketch, as soon as I add the MPU 6050 sensor for detecting the angle of the pendulum, the cart moves much slower, far too slow to be useful for keeping the pendulum upright.

I imagine the timing of the motor commands is messed up by the sensor reads, but I'm not sure how to avoid the problem. Also, the author of the example posted essentially the same code as his working solution for proportional control, so there may be something else that I'm missing that messes my motor performance up.

Does anyone have any suggestions for how to get the stepper motor turning fast enough while also reading data from the MPU 6050?

My code is below. I'm using a Nema 17 stepper motor with an A4988 driver, a 12 V 10 A power supply, and this Aukru MPU-6050. To be sure that updates to the speed and Serial prints aren't the problem, I use an interval of 500 ms between updates/printing.

```
#include "I2Cdev.h"
#include <AccelStepper.h>
#include "MPU6050_6Axis_MotionApps20.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// 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

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

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

// Defines pins numbers
const int stepPin = 3;
const int dirPin = 4;
AccelStepper stepper(1,stepPin,dirPin);

int motorSpeed, currentPos;
unsigned long t_start, t_elapsed;
int interval = 500; // ms between printing speed

int speedMax = 4000;
float k_proportional = 4;

float angleCurrent, speedSet;

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  #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(115200);

  // 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"));

  // 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.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
      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(")"));
  }

  stepper.setMaxSpeed(speedMax);
  stepper.setAcceleration(10000);
  stepper.setSpeed(2000);
}

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

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

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

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

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

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

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

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

      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    }

  t_elapsed = millis() - t_start;

  if (t_elapsed >= interval) {
    t_start += interval;
    motorSpeed=setMotorSpeed();
    stepper.setSpeed(motorSpeed);
    Serial.print("Roll ");
    Serial.print(ypr[2] * 180/M_PI);
    Serial.print("Motor speed: ");
    Serial.println(motorSpeed);
  }

  stepper.runSpeed();
}

int setMotorSpeed() {
  // Proportional control
  angleCurrent = ypr[2];
  speedSet = constrain(-angleCurrent*k_proportional*speedMax, -speedMax, speedMax);
  return speedSet;
}

```

Edit: Adding my code which limits the sensor logic to the same interval as the speed update, based on the answer by chrisl. The cart moves quite a bit faster, though still not fast enough to keep the pendulum upright.

```
#include "I2Cdev.h"
#include <AccelStepper.h>
#include "MPU6050_6Axis_MotionApps20.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

// 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

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

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

// Defines pins numbers
const int stepPin = 3;
const int dirPin = 4;
AccelStepper stepper(1,stepPin,dirPin);

int motorSpeed, currentPos;
unsigned long t_start, t_elapsed, t_mpu, t_start_mpu;
int interval = 50; // ms between printing speed
unsigned long count = 0;

int speedMax = 800;
float k_proportional = 3;

float angleCurrent, speedSet;

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  #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(115200);

  // 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"));

  // 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.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
      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(")"));
  }

  stepper.setMaxSpeed(speedMax);
  stepper.setAcceleration(10000);
  stepper.setSpeed(100);
}

void loop() {

  t_elapsed = millis() - t_start;
  count += 1;

  if (t_elapsed >= interval) {
    t_start += interval;

    // wait for MPU interrupt or extra packet(s) available
    // Slows down cart tremendously, but code freezes without it
    while (!mpuInterrupt && fifoCount < packetSize) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }
    }

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

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

    // check for overflow (this should never happen unless our code is too inefficient)

    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

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

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

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

      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    }

    motorSpeed=setMotorSpeed();
    // Use one potentiometer to turn system on or off (A0)
    int A0val = analogRead(A0);
    // Use another potentiometer to tune response time (or max speed)
    int A1val = analogRead(A1);
    //speedMax = 2*A1val;
    interval = A1val/2;
    Serial.print("Roll: ");
    Serial.print(ypr[2] * 180/M_PI);
    Serial.print(", motor speed: ");
    Serial.print(motorSpeed);
    Serial.print(", A0: ");
    Serial.print(A0val);
    Serial.print(", interval: ");
    Serial.print(interval);
    //Serial.print(", speedMax: ");
    //Serial.print(speedMax);
    Serial.print(", iterations: ");
    Serial.println(count);
    count=0;
    if (A0val > 512)
      stepper.setSpeed(motorSpeed);
    else
      stepper.setSpeed(0);
  }

  stepper.runSpeed();
}

int setMotorSpeed() {
  // Proportional control
  angleCurrent = ypr[2];
  speedSet = constrain(-angleCurrent*k_proportional*speedMax, -speedMax, speedMax);
  return speedSet;
}

```

# Answer
> 1 votes
I cannot say, why that principle works for the author of that tutorial. Though I can guess the reason, why your motors runs so slow.

The function, that actually drives the motor, is `stepper.runSpeed()`. You call it exactly once at the end of the `loop()` function. Though that function is designed to be called very often, as it only checks, if it is time to do a step, and then do so. It just an do max 1 step per execution. So you get 1 step per `loop()` iteration.

And at the start of the `loop()` you wait for the MPU data to be ready with this line:

```
while (!mpuInterrupt && fifoCount < packetSize)

```

So you do the steps at max with the same rate, that you read the MPU. That seems to be not enough for your setup.

You can try calling the `runSpeed()` function more often (and with that removing the limit on the steps). Either rewrite your code to only do the MPU communication, if the MPU data is ready, and proceed with the other code otherwise. Or you can insert the `runSpeed()` function into the while loops, that are waiting for the MPU data. The first option would be cleaner and would make the code easier to extent.

---
Tags: mpu6050, stepper, stepper-motor, a4988
---


# Question
Title: How to find out if HX711(amplifier and 24-bit ADC) is damaged or not?
I'm using this ADC with a load cell for weight measurement, I had 4 strain gauges and mounted them on a cantilever structure that I made out of acrylic sheet, used calibration program from here: https://github.com/olkal/HX711\_ADC/blob/master/examples/Calibration/Calibration.ino,

followed the steps but it gave `calibration factor as 0.00` and the output was `NaN` or `inf` . I used another program from here: https://github.com/queuetue/Q2-HX711-Arduino-Library/tree/master/examples/simple\_scale and the output was just hovering around `83868`. So I thought that the mounting was the problem and used a load cell (green label, CZL 601) with the above and found the same results by doing the above.

Then I thought maybe the ADC is at fault , measured the power output from Arduino to the board and it was around 5 V , but when I measured between the `E+` and `E-` , I got `0 V`. Since it is the excitation voltage to the bridge, it should be around 5V too right?

Is this the right way of checking the board?

P.S. I measured the four wires of the load cell and connected the opp. ends of the bridge to the E+ , E- , A+ , A- (order doesn't matter here right? connected the pairs that showed the rated resistance to E's and A's separately)

Here's a \[pic\]\[1\] of the connections

Between White and green wire the Resistance is 350 ohm Between Bk( connected in the board ) and the red it is 408 ohm Between White and red it was 263 ohm Between white and bk it is 320 ohm

Between bk(not connected in the board) and all others it is around 1 MOhm (so ignored that) \[1\]: https://photos.app.goo.gl/4HEmZaN1EwZ7Mjur7

# Answer
> 2 votes
Looking closely at the photo of your setup I can see that you haven't soldered the header to the breakout board. Whilst there are headers available that don't require soldering, and ways of making header connections that don't require soldering, this isn't either of those.

Without solder the connection to the board will be intermittent at best and non-existent in general.

---
Tags: hardware, adc
---


# Question
Title: storing 600 unsigned int values in an array and find minimum and maximum values
I am reading an ASCII serial data values from a sensor and storing it in an unsigned integer variable. The values are ~45000 to 50000 range. I need to store 600 values and then find the minimum and maximum. after 600 values reached the oldest value is being replaced with the new value. The array size required is 600 which is approx.1200Bytes of the size of storage. I'm using Atmega 2560. I would like to know is it possible to store all 600 values in SRAM or do I need to use EEPROM memory?

# Answer
> 1 votes
The Atmega 2560 has 8K of static ram, more than enough for your 1200-byte array.

Reading-, and especially, writing EEPROM are very slow, and EEPROM has a rather limited lifetime-number-of-write-cycles, so it is not a good candidate for active use but rather for storing data that change infrequently and need to survive a power-down. These would typically per-system preferences, or data that needs to be stored to let the system resume at the next power-up, where it had left off when the power went down. This latter function requires that the system store enough power (capacitor or tiny battery) to keep it running long enough to sense the main power failing and still have run-time enough to write to EEPROM.

---
Tags: arduino-mega, datalogging, data-type, serial-data
---


# Question
Title: Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?
I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...

```
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

```

I think am following the recommendations and template in the official spec here... https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

My "vendor/maintainer" is `move38` and my platform is `avr`, so the path to the `boards.txt` is...

```
Arduino\hardware\Move38\avr\boards.txt

```

Here is my `boards.txt` that defines the `blink` board...

```
blink.name=Blinks Tile
blink.upload.tool=avrdude
blink.upload.protocol=avrisp
blink.upload.maximum_size=15872
blink.upload.maximum_data_size=1024

blink.build.core=blinks
blink.build.board=AVR_Blink

blink.build.mcu=atmega168pb

blink.c.extra_flags=-Wextra -flto
blink.c.elf.extra_flags=-w -flto
blink.cpp.extra_flags=-Wextra -flto
blink.ltoarcmd=avr-gcc-ar

# set F_CPU to 1Mhz for all boards on this platform
build.f_cpu=1000000L

```

...which would seem to define `build.board` as `AVR_BLINKS`.

I think am following the recommendations and template in the official spec here... https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

...but nonetheless the warning persists.

I am using Arduino IDE version 1.8.3 on Windows.

What am I missing here? Is there something special about the value, format, or position of the `build.board` key that I am missing here?

Thanks!

## More notes

Adding the following lines to a working `boards.txt` file...

```
build.name=testname
build.f_cpu=4000000L
build.core=blinks
build.board=AVR_BOARD

```

Will create a menu entry for a new phantom board called `testname`, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...

```
Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

```

...despite the fact that the key `build.board` is explicitly defined.

# Answer
> 1 votes
It appears that you can no longer set a global property in the `boards.txt` file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

> The other properties will override the corresponding global properties of the IDE when the user selects the board.

Further, if any global key is set directly, then *both* the board specific keys *and* the global keys are ignored.

So in my above `boards.txt`, setting the the global key `build.f_cpu` at the end of the file seems to cover the `blink.build.board` key and prevent it from being copied to `build.board` when the board is selected. Even if you set the global key `build.board` directly, this setting is ignored.

# Answer
> 1 votes
In my case: I erase the board configurations that was with problem in the file boards.txt. These configurations appears between #### ... board configurations... #####.

# Answer
> 0 votes
The line in your boards.txt:

```
build.f_cpu=1000000L

```

created a separate board entry with the board ID `build`, thus the error message:

```
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

```

From your comment:

```
# set F_CPU to 1Mhz for all boards on this platform

```

and your answer I see that you expected that line to define a global value for the `build.f_cpu` property but the Arduino IDE has no mechanism for doing this in boards.txt and I don't believe it ever has. You need to define the properties for each board individually in boards.txt, where they will override previously defined properties of the same name. However, you can define default property values for the hardware package in your platform.txt just as you attempted to do in boards.txt.

---
Tags: arduino-ide, build, custom
---


# Question
Title: Reading Serial String Gives Null Lines with JSSC
I need to send serial data to my Arduino UNO from within a java application. I am using JSSC for this.

I wanted to verify that my data actually arrives correctly to the arduino before going to the next step of my application. For this I tried to just return the string I am sending, however when I send "test", this is what is returned:

```
t
null
est

```

I am wondering if this is a problem on the Java side with sending/reading the string, or that it's a problem with sending/reading on the arduino, and how I could possibly fix this.

This is my java code to read the data:

```
try {
    port.addEventListener(event -> {
        try {
            System.out.println(port.readString());
        } catch (SerialPortException e) {
            e.printStackTrace();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

```

This is my java code to send the data:

```
try {
    port.writeString("test");
} catch (SerialPortException e) {
    e.printStackTrace();
}

```

And this is the code on my arduino:

```
void loop() {
  while (Serial.available() > 0) {
    Serial.print(Serial.readString());
  }
}

```

I hope someone can help :)

# Answer
> 0 votes
This is a common misconception about how serial communication works.

You're "sending" the "string" `test`. Except you're not.

What you're actually doing is you're placing the string `test` into the send buffer. Another routine then takes each byte from that send buffer in turn and sends it out through serial.

The Arduino then receives that byte and places it into its internal receive buffer.

You then get around to reading from the serial and you just get whatever is in the receive buffer at that moment in time - however many bytes that happens to be.

Then you "send" those bytes back - except again, you don't. You place those bytes into the internal transmit buffer in the Arduino and another routine takes each byte in turn from that transmit buffer and sends it out through the serial.

Again the Java program gets around to reading from the serial, and all it gets is what happens to be in its receive buffer at the time, however many bytes that may be at the time.

There is no such thing as "a string" or "a line" in serial. All there is is bytes - one after another.

It is up to *you* to receive those bytes and reconstitute them back into the form you want as each byte happens to arrive.

As it stands you have no way of knowing what that form should be, since you just send four bytes with no meaning attached to them.

It's common to add a "terminator" to a string when sending so that the receiver knows when all the bytes have arrived. For us humans the simplest to use is a "line feed" or `\n` character.

Your receiving routine would then receive each character in turn appending it to the target String up until it receives the terminating character, at which point it knows that it has finished receiving this chunk of data and can act on it.

I have a popular blog post all about reading serial on the Arduino here, and the same principle can be applied to any other language.

---
Tags: serial, string, java
---


# Question
Title: How do I convert 0-5v PWM to a 0-12v PWM
I have a Arduino which I would like to use to control a 12v PWM fan for speed control.

I know about the 0-3.3v to 0-5v logic level shifter, is there a similar option for 0-5v to 0-12v? Or is there a circuit using a IC that I need to make?

Thanks in advance for your help.

# Answer
I advice you to learn about basics of how to connect external components to MCU. Anwser to your question is simple transistor amplifier... So you can use bipolar transistor (NPN/PNP) or MOSFET... MOSFETs is better for switching like your case, switching via PWM.

If you switching inductive load with MOSFET like motors or coils, don't forget add antiparallel flyback diode. Otherwise your MOSFET will burn out.

If you need switching with higher frequency or load with more voltage or power I advice to use push-pull logic to drive mosfet gate.

Something like this:
> 6 votes

# Answer
As far as I can tell the Arduino does not have open collector outputs, so you can mimic one as follows. The following inverts the Arduino output signal, so some adjustment is needed there when generating the PWM signal.

Excuse the rather gross schematic. I can't find any scaling parameters.

The particular resistors values are not terribly important, mainly to limit current.

simulate this circuit – Schematic created using CircuitLab
> 2 votes

# Answer
**Use MAX232**

**Advantages of MAX232:**

* It has low rise/fall times. A good PWM needs to be sharp. Since MAX232 is designed for serial port communications, i.e., TTL to RS232 and RS232 to TTL, it has to perform reliably. Reliability ensures low rise/fall times.
* It operates at low currents. The OP suggested that the fan only needs a PWM to drive, i.e., it has its internal current amplifiers.
* It is cheap. Engineering solutions require to be no more expensive than it has to be, and MAX232 is half the price of L298.

**Shortcomings of MAX232:**

* Since the computer serial port is used much less, the primary use of MAX232 is over. Therefore, it is not in all hobby kits and it might be harder to find MAX232. Mostly older engineers who used to play with PIC16F877A before ardunios become popular remembers such ICs.

**Shortcomings of L298:**

* *L298 is a current amplifier*, not a voltage booster. Using it for a purpose other than its primary purpose is *suboptimal*.
* *L298 has a huge current output*. It might exceed the threshold currents of the fan, and cause malfunction. It is very unwise to connect a 1A rated L298 to 0.5 mA rated signal pin.
* L298 has a weird pin diagram. It has a ZIP package rather than the regular DIP to allow attachment of heatsinks, which increases the size of the circuit.
* L298 has high rise/fall times. Its purpose is to generate large currents, not PWMs. Therefore, its rated rise/fall times are not only high, but also unreliable.
* L298 requires four high current rated Schottky diodes. The cost of these diodes will be more than that of the L298 and they are very large, resulting in a much larger circuit area.

Do you really want to use an H-Bridge? **Use L293D**.

* L293D is still a current amplifier but not an overkill like L298. Its current output is four times as low as L298 so chance of malfunction is reduced.
* L293D has a DIP layout. Most hobby electronics application uses DIP sockets to mount the ICs later on and you can do it with L293D.
* L293D has the flybacks diodes internally. So you neither need to buy nor place them on your circuit.

Do you want to design your own circuit? **Use a gate/base recharge/discharge transistor.**

Basically, all transistors have a gate/base capacitor which needs to be charged before the transistor switches to ON and discharged before it switches to OFF. Power amplifiers normally do not care about the rise/fall times, with a notable exception that comes to my mind is musical amplifiers.

**What about a discharge resistor?**

Replacing discharge transistor with a simple resistor works but it would increase your drain from the PWM source. It has a simplicity vs performance trade-off.

**Commenting about relays**

Relays usually have a higher switching time because their input module consists of a diode and output module consists of a transistor, i.e., you have add their reaction times together. This results in distortion in the PWM output. Furthermore, there is no need to use SSR in a low power operation, an opto-isolater would suffice.

**Final comment about designing circuits**

Circuits have many trade-offs. Cost, availability, complexity, size, performance are just to name a few. A good design needs to take everything into account. To rate my above suggestions:

* MAX232: Cheap, simple, small, good performance, **not available**
* L298: **Expensive, complex, large, low performance**, available
* L293D: Cheap, simple, small, **mediocre performance**, available
* Simple transistor: Cheap, simple, small, **mediocre performance**, available
* Modified transistor with base recharge/discharge: **Expensive, complex, large**, good performance, available

So, I would rate L298 as the worst possible solution that actually works.
> 1 votes

# Answer
You'd usually use a transistor to do that.

simulate this circuit – Schematic created using CircuitLab

SW1 is your microcontroller creating the PWM signal.
> 0 votes

# Answer
Note: my entire answer below assumes you need to drive a 2-wire brushed DC motor (or similar load, such as an audio speaker) *directly*, with real power and real current. That is what my entire answer is based on. However, after I wrote my answer, the OP posted this in a comment under his question (emphasis added):

> I didn't have the serial number of the fan until today, now I have that I have checked the spec, and **a low powered option is suitable as it only requires a PWM signal to control the speed the rest is done with its on-board controller - no more than a 0.5mA signal is required.**

So, although my answers below will still work to provide an output PWM at, lets say, 12V, from an input PWM at 5V, they are intended to drive a 2-wire brushed DC motor *directly* with real power and real current. The fact that they can also provide an output PWM *signal* at 12V is incidental, but just as applicable.

Also, it is important to note that all my answers below are expected to be usable up to a few dozen kHz max PWM frequency, unless otherwise stated on the product datasheets--Ex: many high-end Pololu brand motor drivers (H-bridges) I recommend below can be driven with up to 100kHz PWM frequency since they use such high-quality and fast MOSFET Gate driver circuits with both high-power active Gate drive HIGH *and* active, high-power Gate drive LOW in their H-bridges.

---

## TLDR;

Jump straight down to the section titled "Here's some H-bridges you can buy", in the "Option 2" section below. Buy one of those and be done.

Reminder: on any H-bridge, when you drive a PWM to the *input* at 5V with a certain duty cycle and frequency, an equivalent or almost-equivalent PWM output at voltage level `Vsupply` will occur on the H-bridge *output*. *This is the exact purpose of the half-H-bridge.* And, *this, in addition to allowing bi-directionality of power, current, and voltage,* is the exact purpose of the *full H-bridge.* PWM *output freq* from the H-bridge will be *exactly identical* to the input PWM, and PWM *duty cycle* will be *almost identical*, with output PWM waveform distortion increasing as PWM frequency is increased.

## Option 1 of 3: \[custom circuitry\] The Electrical Engineer / "very curious hobbyist with lots of time" answer:

I've upvoted @Sahasrar's answer. If you haven't taken a look at it, you should. It fits squarely into this "Option 1" category.

However, in his first image, when controlling pin `D7`, the MOSFET gate is **actively driven** both HIGH and LOW with a max (initial) current of I = V/R = 5V / 100 Ohms = 0.05A = 50mA, which is good, but kind of weak (a good MOSFET gate driver is more like 500~1000mA drive current). This is also exceeding the 40mA max current rating of the Arduino pin, so I recommend you choose a slightly bigger resistor. The resistor here is to limit current to not damage your Arduino pin when charging and discharging the Gate capacitance of the MOSFET, which capacitance is significant enough for MOSFETS (but NOT BJT transistors), that it is even listed as a parameter in a MOSFET transistor datasheet (but not in a BJT transistor datasheet). WithOUT this Gate resistor, each time you drive the Gate HIGH or LOW, you'd otherwise have the equivalent of a momentary instantaneous short through the Arduino pin, which could damage the pin.

Also, you have to be sure to use a **Logic-Level** N-Channel MOSFET which can be driven with a gate voltage as low as 3.3V~5V instead of requiring more like 10V~12V.

So, with @Sahasrar's first circuit, the max PWM frequency you can use is probably a few dozen kHz.

If you need to drive higher PWM frequencies, the solution is to use the push-pull logic circuit which @Sahasrar shows next instead. But, you have to fill in the blanks: choosing parts, doing calculations, having advanced knowledge.

In both cases, you must also be sure to use a flyback diode to snub inductance-induced voltage spikes!

## Option 2 of 3: \[just buy an H-bridge DC motor driver\] The normal hobbyist / time-constrained-individual answer:

So, the quick solution is to just buy a motor driver instead and be done!

You can use any **H-bridge** for a 1-channel (1 device) bi-directional drive, or for a 2-channel (2 separate devices) uni-directional drive.

Or, you can use a **half H-bridge** for a 1-channel uni-directional drive.

H-bridges are frequently called "brushed motor drivers". They handle all the fancy Electrical Engineering circuitry for you.

### H-bridges are **excellent** for driving things like:

### Here's some H-bridges you can buy:

When searching for these things, recommended search terms include "DC motor driver" or "h bridge". Even if you plan to drive an LED or speaker with it, these are still the correct search terms and parts. Just make sure what you buy accepts *PWM input* as the control signal is all, and that this PWM input means *true PWM*, NOT a servo "PWM" signal, which is very different.

Just buy one of these and be done:

1. Cheap $1 L9110S H-bridge:
    1. Ebay search for "arduino h bridge"
    2. L9110 datasheet
        1. 2.5V to 12V supply
        2. 800mA max continuous current per channel
2. Cheap $3 L298N H-bridge (much more powerful):
    1. Ebay search for "arduino h bridge L298"
    2. Example specs sheet: http://www.handsontec.com/dataspecs/L298N%20Motor%20Driver.pdf
        1. 3.2 to 40V supply
        2. 2A peak current
        3. 20W max power
3. High-end, reliable, very-well-engineered DC motor drivers/H-bridges by Pololu robotics company:
    1. See the full list of motor drivers here! https://www.pololu.com/category/11/brushed-dc-motor-drivers
    2. Ex: $40 Pololu G2 High-Power Motor Driver 18v25
        1. 6.5V to 30V supply
        2. 1.8V, 3.3V, or 5V logic signals
        3. 25A max continuous current
        4. up to 100kHz PWM operation, because they have excellent MOSFET gate drivers to minimize MOSFET time in the ohmic region, and therefore MOSFET heating!
        5. If you're in a hurry and want high-quality, Pololu is an *excellent* choice!
        6. Tiny! 1.3" x 0.8", and no heat sink required, again, because of their excellent MOSFETS and MOSFET gate driver circuits.

## Option 3 of 3: \[Radio Control brushed ESC (Electronic Speed Controller)\] (easiest of them all!)--preferred by people with RC vehicle experience and/or who need *really high power*

*Important*: since this option does NOT give you the low-level control over the PWM output directly, these controllers can NOT drive speakers for audio, whereas Option 1 and Option 2 drivers above *can*!

I'd be remissed if I didn't include this answer as well, since this is one of my specialties. This is the easiest by far! Its only downside is it gives you less fine-tuned control than controlling the low-level PWM output to the motors directly, as you can do with the motor *drivers* above, versus the motor *controllers* below. Another advantage of the hobbyist RC brushed ESCs below over the Pololu-type robotics motor drivers above is *power* and *current*: the above *motor drivers* from Pololu peak out at 25A continuous, for instance, whereas some RC *brushed motor controllers*, some less-powerful examples of which are shown below, can drive as much as 100~200A continuous, which is HUGE.

Just buy a Radio Control (RC) brushed ESC and feed it a **servo PWM signal** via the Arduino `servo` library, NOT a true PWM signal with `analogWrite()`!

You give it a servo signal, and it generates the low-level PWM to the motor automatically using its internal microcontroller and MOSFET driver circuitry, usually on the order of 8kHz~16kHz PWM output frequency. Many of these types of ESCs use the ATmega168 mcu internally.

For a single-direction ESC, such as for RC airplanes, a microsecond servo value between 700~1300us is 0% throttle, and a microsecond servo value between 1700~2100us is 100% throttle.

For a dual-direction ESC, such as for RC cars, with both forward and reverse, a microsecond value of ~1500us is 0% throttle, with ~2000us or so being 100% forward throttle and ~1000us or so being 100% reverse throttle.

Sample code:

```
#include <Servo.h>

Servo brushed_motor;

void setup()
{
  brushed_motor.attach(9); // pin 9

  // ~0% throttle (0% output PWM duty cycle), depending on ESC
  // calibration, and assuming a forward-only ESC for RC airplanes
  brushed_motor.writeMicroseconds(1000);

  delay(2000);

  // ~100% throttle (100% output PWM duty cycle), depending on ESC
  // calibration, and assuming a forward-only ESC for RC airplanes
  brushed_motor.writeMicroseconds(2000);
}

void loop()
{
    // whatever you need here
}

```

To calibrate one of these ESCs to whatever throttle values you want, just set it to 2000us (full throttle) BEFORE you turn it on (careful--just in case it decides to go full throttle instead), then power it up, and it will register that as "full throttle". Next, withOUT powering it off, set it to 1000us (0% throttle), and it will register that as 0% throttle. Now, it is calibrated to have 1000us be 0% throttle and 2000us to be 100% throttle. If using an RC car brushed ESC instead of an RC airplane brushed ESC, you may have to play with it, do some research, and read its manual to get what you want, since 1500us might be considered 0% throttle, with 2000us being 100% *forward* throttle and 1000us being 100% *reverse* throttle. So, do the research.

In either case, here's some brushed RC ESCs which can drive motors and blowers or whatever just fine too.

These are just a couple examples. RC ESCs like these are designed to be really high power for high-end RC vehicles which can go up to 25~100mph sometimes, and be quite large. Do some research. Brushed RC ESCs are sold in many places. HobbyKing has the best prices in the industry for these types of things, with generally good to very-good quality parts.

## Related:

1. \[my answer\] Switching a Solenoid Using Arduino's 5V Output?
    1. Here's my answer to another question which answers your question. In the diagram below, from this other answer, *the relay + R2* **is the load**. Replace this load (relay + R2) with your motor as the load instead, and this is also a perfectly legitimate circuit to solve your problem. The 5V here in this circuit to the transistor base would be replaced by your 5V logic level PWM signal coming from your Arduino. I also go over calculations and how to size all components. Try a high-current TIP120 NPN BJT 5 Amp continuous transistor in place of the 2N3904 in my circuit, and be sure to redo the calculations to size your base resistor, R1.
    2. Note that this circuit allows your Arduino pin to *actively drive* the output both HIGH *and* LOW, but since its through this (relatively small) base resistor, it's probably only good for PWM frequencies up to a few dozen kHz or so. An oscilloscope used to look at the output would make this clear. Increase input PWM frequency until output PWM waveform distortion becomes significant.
    3.
> 0 votes

---
Tags: pwm, speed
---


# Question
Title: How can I increase the torque or speed of the stepper motor with Arduino
I run 28BYJ-48 12 Volt Motor with ULN 2003 Driver using Arduino UNO. I am also using external 12 volt power outside. I aim for the syringe pump to move back and forth with the rotation of the motor. I'm using the code below. The code is running but the motor cannot move the syringe back and forth. How do I change to be able to move the syringe pump

```
const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2
;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i < 2048 ; i++)
{
adim1();
adim2();
adim3();
adim4();
}
{

exit(0);
}
}

```

---

```
İleri
// Meraklı Mühendis Sayfasının hazırlığı kodlar kullanılmıştır.
//Dilerseniz farklı fonksiyonlar kullanabilirsiniz.

const int motorPin1 = 8;
const int motorPin2 = 9;
const int motorPin3 = 10;
const int motorPin4 = 11;

int bekleme =2;
// bekleme süresini değiştirerek step motorun hızlı veya yavaş ilerlemesini sağlayabilirsiniz.
//1sn=1000

void adim1() {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim2() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, HIGH);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim3() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, HIGH);
digitalWrite(motorPin4, LOW);
delay(bekleme);
}

void adim4() {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
digitalWrite(motorPin3, LOW);
digitalWrite(motorPin4, HIGH);
delay(bekleme);
}

void setup() {

pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorPin3, OUTPUT);
pinMode(motorPin4, OUTPUT);

}

void loop() {

for (int i = 0; i <2048; i++)   // buradaki 512 değerleri step motorun tam bir tur dönmesini sağlıyor. dilerseniz bu sayıyı değiştirebilirsiniz
{
adim4();
adim3();
adim2();
adim1();

}
{

exit(0);
}
}

```

# Answer
To increase torque of 28BYJ-48 you have to perform a simple mod (cup one path on the PCB) to change it from unipolar to bipolar and then use it with an H-bridge like the A4988 or the DRV8825 driver.

Sources:

1. https://ardufocus.com/howto/28byj-48-bipolar-hw-mod/
2. https://coeleveld.com/wp-content/uploads/2016/10/Modifying-a-28BYJ-48-step-motor-from-unipolar-to-bipolar.pdf
3. https://everythingsmarthome.co.uk/howto/converting-the-28byj-48-stepper-motor-for-more-torque/
4. http://www.jangeox.be/2013/10/change-unipolar-28byj-48-to-bipolar.html
5. https://www.youtube.com/watch?v=hkxnQIKybiI
6. https://www.youtube.com/watch?v=jHLyJbNgcDo
> 2 votes

# Answer
Assuming you are driving your motor correctly (And it sounds from Chris like you are not) and that you are using a power supply with enough current and a motor driver with a low internal resistance, you could put a reduction gear on the motor to reduce the rotation speed and increase the torque. It would take more rotations to push the syringe the same distance, but it will have more force.

If you use a 4:1 reduction gear, for example, you'd need 4 times more rotations, and you'd get 4 times as much force.
> 0 votes

---
Tags: power, motor
---


title: Measure Vcc on ATtiny13a?

text:
# Question
Title: Measure Vcc on ATtiny13a?
I am trying to figure out if I can measure the Vcc of attiny13a, but the code I use for arduino's and attiny85 does not work. This is where I got the code from. I know that it works by using the 1.1v reference and the ADC, and in the attiny13a datasheet it says that it has these, but I can't get it to work.

# Answer
> 6 votes
The code you linked to measures the 1.1 V internal reference using Vcc as a reference. The ATtiny13A cannot do that. It does have a 1.1 V internal reference, but it can only use it as a reference for the ADC, not as a measured channel.

What you can do, if you don't mind adding extra hardware, is divide Vcc with some resistors in order to get a voltage proportional to Vcc but lower than 1.1 V. Then use the 1.1 V reference to measure that voltage. In other words, measure a scaled-down Vcc against the 1.1 V reference instead of measuring the 1.1 V reference against Vcc. The datasheet should help you with the details.

---
Tags: attiny, code-review, adc, voltage
---


# Question
Title: NodeMcu 1.0 resets automatically after sometime
I want to show some digits in a 3x3 p10 red led pannel where the number will come from the cloud and the number keeps updating. For this I have used esp8266 based Nodemcu. I have used WiFi Manager library and DMD2 library for this and I am requesting the server every 5 seconds to get the number in response. Everything is working fine but it keeps restarting after some time and there is no fixed timing for this but it keeps restarting. It provides a message that "reset cause 4 boot mode(3,6)" wdt reset... I have tried different hardware and esp board version but nothing is working. I am currently using arduino 1.8.9 and esp8266 board version 2.5.2

please look into my code and suggest me what is wrong....

```
#include <Arduino.h>

```

#include \<WiFiManager.h\>
#include \<math.h\> #include \<WiFiClient.h\> #include \<ESP8266HTTPClient.h\> #include \<EEPROM.h\> #include \<ESP8266WiFi.h\>

WiFiManager wifiManager; int countT;

HTTPClient http; String svrHost = ""; unsigned int svrPort = 80; String svrURL = "";

//DMD #include \<SPI.h\> #include \<DMD2.h\> #include \<fonts/Arial\_Black\_16.h\> #include \<fonts/Droid\_Sans\_36.h\> #include \<fonts/Droid\_Sans\_12.h\> #include \<fonts/Arial\_New\_56.h\> //#include \<fonts/Dmd13x20ClockX.h\> //DMD PIN #define pin\_A 16 #define pin\_B 12 #define pin\_sclk 0 #define pin\_clk 14 #define pin\_r 13 #define pin\_noe 15

int respin = D2; int btnstt = 0;

int wlcmgs = 1; String ssid;

String dmdText = "0"; SPIDMD dmd(3, 3, pin\_noe, pin\_A, pin\_B, pin\_sclk); // Number of P10 panels used X, Y //DMD\_TextBox box(dmd,0,0,32,5); // Set Box (dmd, x, y, Height, Width)

//const char \*MESSAGE = "iTrack LIVE InWard";

void setup(){ Serial.begin(115200); EEPROM.begin(512); pinMode(respin, INPUT);

```
//Reset Val
String doResetWifi = "0";
doResetWifi = readESP(257,1);

if(doResetWifi == "1"){
    writeESP(257,1,"0");
    wifiManager.resetSettings();
}

Serial.println("\nReset Val "+doResetWifi);
//wifiManager.resetSettings();
countT = 0;
wifiManager.autoConnect("LED-1");
Serial.println("connected...yeey :)");

//Read/Write EPROM
if(wifiManager.svrURL != ""){
    svrHost = wifiManager.svrHost;
    svrPort = wifiManager.svrPort;
    svrURL = wifiManager.svrURL;
    //HOST
writeESP(0,50,svrHost);

    //PORT
writeESP(51,5,String(svrPort));

    //URL
    writeESP(56,200,svrURL);

}else{
    //HOST
    svrHost = readESP(0,50);

    //PORT
    svrPort = readESP(51,25).toInt();

    //URL
    svrURL = readESP(56,200);
}

//DMD Setup
    dmd.setBrightness(255); // Set brightness 0 - 255
    //dmd.selectFont(Droid_Sans_36); // Font used
    dmd.begin();     // Start DMD

```

}

void loop(){

```
btnstt = digitalRead(respin);

```

if (btnstt == 1){ flashESP(); ESP.reset(); } doRequest();

```
  //box.print(dmdText);

```

if(wlcmgs==1){ dmd.selectFont(Droid\_Sans\_12); dmd.drawString(0,0,"Connected"); delay(5000); dmd.clearScreen(); //scrlssid(); delay(5000); wlcmgs=0; }

dmd.clearScreen(); dmd.selectFont(Arial\_New\_56); int padingTop = 2;

dmd.drawString(round((96 - (dmdText.length() * 24)) / 2), padingTop, dmdText);

delay(1000 * 5);

//dmd.selectFont(Arial\_Black\_16); //scrtxt(); }

void doRequest(){
Serial.print("\[HTTP\] begin: "+svrHost+" "+svrPort+" "+svrURL+"\n"); String response; if (httpRequest(svrHost, svrPort, String("GET /") + svrURL, "", response)) { if (response.length() != 0) {

```
        response.trim();
        dmdText = response;
        Serial.println(response);
        Serial.println(countT);
        countT++;
    }
}

```

}

bool httpRequest(const String svrHOST, unsigned int svrPORT, const String& method, const String& request, String& response) { WiFiClient client;

```
if (client.connect(svrHOST, svrPORT)) {
    Serial.println("HTTP Connected");
} else {
    Serial.println("failed");
    return false;
}

client.print(method);
client.println(F(" HTTP/1.1"));
client.print(F("Host: "));
client.println(svrHOST);
client.println(F("Connection: close"));
if (request.length()) {
    client.println(F("Content-Type: application/json"));
    client.print(F("Content-Length: "));
    client.println(request.length());
    client.println();
    client.print(request);
} else {
    client.println();
}

//Serial.println("Waiting response");
int timeout = millis() + 5000;
while (client.available() == 0) {
    if (timeout - millis() < 0) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return false;
    }
}

//Serial.println("Reading response");
int contentLength = -1;
while (client.available()) {
    String line = client.readStringUntil('\n');
    line.trim();
    line.toLowerCase();
    if (line.startsWith("content-length:")) {
        contentLength = line.substring(line.lastIndexOf(':') + 1).toInt();
    } else if (line.length() == 0) {
        break;
    }
}

//Serial.println("Reading response body");
response = "";
response.reserve(contentLength + 1);
while (response.length() < contentLength && client.connected()) {
    while (client.available()) {
        char c = client.read();
        response += c;
    }
}
client.stop();
return true;

```

}

void writeESP(int start, int len, String text){ EEPROM.begin(512); int ind; for(ind = 0; ind \< len; ind++){
EEPROM.write(ind+start,text\[ind\]); } EEPROM.write(ind+start+text.length(),'\0');

```
EEPROM.commit();

```

EEPROM.end(); }

String readESP(int start, int len){ EEPROM.begin(512); char dataS\[len\]; int ind; for(ind = 0; ind \< len; ind++){ if(EEPROM.read(ind+start) != '\0'){ dataS\[ind\] = EEPROM.read(ind+start); }else{ break; } } dataS\[ind\]='\0'; EEPROM.end(); return String(dataS); }

void flashESP(){ Serial.print("\nResetting ESP\n"); writeESP(257,1,"1"); ESP.reset(); delay(2000); }

/\* void scrtxt(){ const char \*next = MESSAGE; while(\*next) { Serial.print(\*next); box.print(\*next); delay(200); next++; } } */ /* void scrlssid(){ dmd.drawString(5,0,"Connected With"); DMD\_TextBox box(dmd,0,20,96,16); ssid = WiFi.SSID(); const char \*ssidNext= ssid.c\_str(); int len = 0; while(ssidNext && len \< ssid.length()){ Serial.print(\*ssidNext); box.print(\*ssidNext); delay(200); ssidNext++; len++; } } \*/

# Answer
From your description it sounds like a Watchdog Timer reset.

The ESP8266 needs to regularly run internal householding tasks outside of your own code, such as Wifi/network related tasks. It will normally take some processing time for those tasks with every `loop()` iteration and with every `delay()` command.

If your code is doing things that take longer than about 3.2 seconds, the internal "watchdog timer" will time out and reset the ESP, which is what you observed.

To ensure this does not happen, you should put a `yield();` command inside pieces of your code that can potentially take longer than 3 seconds, like waiting loops (for example the "Waiting response" `while()` loop and similar pieces of your code). Try this and see if this solves your problem.
> 2 votes

---
Tags: esp8266, arduino-ide, nodemcu, espressif, esp
---


# Question
Title: How to change colors and theme settings in 'Windows Store app' version of Arduino IDE?
In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.

For the *Windows Store app* version of the IDE the theme files are stored in protected app storage space.

Is there a simple/safe way to change theme settings for the *Windows Store app* version of the IDE without messing up security settings and inadvertently lowering Windows security?

*(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)*

# Answer
I think rrz0's answer skipped the part of the question: "For the Windows Store app version of the IDE the theme files are stored in protected app storage space."

The only way is to take control of the windows app folder but I believe this is risky and M$ suggests that this can brick your pc (take that with a grain of salt).

There is an offline windows installer and zip link on the downloads page which I used to replace the windows store version. I see no advantage to the store version.
> 2 votes

# Answer
Working from what Ignacio Soler Garcia wrote (which didn't work for me), I tried around and came up with a solution for my case (I downloaded the OneDarkArduino Theme from GitHub):

* Unpack the theme if it came in a ZIP file
* copy the folder called "theme" (there should be a bunch of .txt and .svg files in there)
* paste it into the folder where all your projects are (usually something like C:\User\Documents\Arduino) - it needs to be named "theme"
* (re)start the Arduino IDE and now it should start with the new theme already loaded
> 2 votes

# Answer
I can confirm that changing ownership/security on the WindowsApps folder half-bricked my machine... it still ran classic windows but every single store App wouldn't run and the store itself stopped working... and I couldn't reset the security back again - 4 hours later and a complete restore with Microsoft's recovery download and a 16GB USB boot load , I'm older and wiser.
> 1 votes

# Answer
There is a way, but not necessarily simple. You basically need to replace the current theme files with the new ones.

1. Rename `{Arduino IDE installation folder}/lib/theme` to `{Arduino IDE installation folder}/lib/theme.bak`
2. Download https://github.com/jeffThompson/DarkArduinoTheme/archive/master.zip
3. Copy the theme folder from the downloaded file to {Arduino IDE installation folder}/lib
4. Restart the Arduino IDE if it's running.
> 0 votes

# Answer
I found the solution, based on a new functionality for themes that I wasn't aware of.

You need to create a themes folder in the folder where your projects are (the one that appears in the preferences section) and put inside it the theme in a zip file. After restarting it will appear as a new theme in the combobox themes.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: What is the default setting for a digital output pin
With `digitalWrite(pin_number,value)`, we can set an output pin as `HIGH` or `LOW`. But if only coding `pinMode (pin_number, OUTPUT)`, what is the default state for the pin `pin_number`, `LOW` or `HIGH`? It is noted that: `Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state`. Does that mean the pin will be in the state `LOW`?

# Answer
On the AVR-based Arduinos at least, pins start in the `INPUT`, i.e. high impedance state. If you then `pinMode(pin, OUTPUT);`, the pin turns to `OUTPUT` `LOW`. Note, however, that if you first set the pin to `INPUT_PULLUP`, and **then** to `OUTPUT`, the pin ends up in the `OPUTPUT` `HIGH` state.

Sometimes you want to control the state the pin will have right when it's turned to `OUTPUT`. You may for example simulate an open collector output by switching between `INPUT` (or `INPUT_PULLUP`) and `OUTPUT` `LOW`, while avoiding the `OUTPUT` `HIGH` state. In this case, a safe idiom is to set the output level *before* switching the pin to `OUTPUT`, e.g.

```
// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);

```

A side effect of performing a `digitalWrite()` on a pin that is not set to `OUTPUT` is that the pin gets switched to either `INPUT` (if writing `LOW`) or `INPUT_PULLUP` (if writing `HIGH`). This is an idiosyncrasy of the AVR IO ports you should probably not rely on if you want your code to be readable or portable.

Reference: the source code of `pinMode()` in the Arduino core, and the datasheet of the relevant MCU. See for example the section Ports as General Digital I/O in the ATmega328P’s datasheet.
> 18 votes

# Answer
I've had a similar issue with an ATTINY85 powered DIGISPARK board.

I was getting a glitch when setting a pin to `OUTPUT` and the driving it `HIGH` immediately. Looked something like this:

`CH1:`

`pinMode(ch1, OUTPUT); // it is at this line that ch1 becomes LOW`

`digitalWrite(ch1, LOW); // technically redundant since ch1 pin already driven LOW`

`CH2:`

`pinMode(ch2, OUTPUT); // at this point ch2 goes LOW`

`digitalWrite(ch2, HIGH); // and only goes HIGH once this instruction executes`

The solution that mitigated the above glitch in my case (ATTiny85 / Digispark Board) was, as Edgar Bonet pointed out above, going through the INPUT\_PULLUP phase:

`pinMode(ch2, INPUT_PULLUP);`

`pinMode(ch2, OUTPUT);`

`digitalWrite(ch2, HIGH);`
> 6 votes

---
Tags: arduino-uno
---


# Question
Title: Measuring li-ion that arduino is running from
I am using a 5v Arduino pro mini (with regulator and power led removed).

I have been reading how to accurately measure Li-ion batteries when powering from the same battery you are trying to measure from. Using the 1.1V internal analog reference to measure a draining VCC source by using a voltage divider on it, and math to show that converted reading.

Reading the Arduino forums I came across this answer.

```
  long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

```

However, I cant see a analogRead anywhere in this sketch. (Is this a strictly internal reference?) At the bottom of the thread someone is saying that you can do this without a voltage divider on the analog pin.

Can someone confirm or explain this? **I don't want to fry my Arduino...**

# Answer
> Using the 1.1V internal analog reference to measure a draining VCC source by using a voltage divider on it

You could indeed use a voltage divider, and measure a scaled-down Vcc against the internal 1.1 V reference. This is, however, not what the code you posted is doing. It is instead measuring the internal reference against Vcc, as stated in the comment within the code. The REFS0 bit selects Vcc as the reference for the ADC. The bits MUX1...MUX3 select the internal reference as the input channel.

> ```
> result = ADCL;
> result |= ADCH<<8;
>
> ```

This idiom dates back from a time when the compiler did not know how to read 16-bit I/O registers: you had to explicitly read one byte at a time and then put these together into a 16-bit word. This time is long gone, and you can now just access the 16-bit register as `ADC` directly. I would even get rid of the `result` variable and just:

```
return 1126400L / ADC;  // Vcc in mV

```

**Edit**: As suggested by the busybee, here is the explanation of the factor 1126400: The ADC meaures the ratio of its input voltage to its reference voltage, and returns this ratio scaled by a factor 1024. In this case,

ADC = 1024 × (Vbg ÷ Vcc)

where Vbg is the voltage of the 1.1 V bandgap reference. Thus,

Vcc = 1024 × Vbg ÷ ADC

If we want Vcc in millivolts, we plus the Vbg voltage in millivolts in the above equation and get

Vcc (in mV) = 1024 × 1100 ÷ ADC = 1126400 ÷ ADC
> 5 votes

# Answer
If anyone else is confused by this:

**Will it hurt your Arduino?**

* **No**, this is a internal voltage reference between VCC & the 1.1v internal analog reference.

**Is a voltage divider necessary?**

* Not unless you have something external of the Arduino to measure!

**Is the internal reference actually 1.1v?**

* No, it seems like each pro mini I have the the 1.1v reference is slightly different. My pro minis do not have a break out for the AREF pin, so you need to figure out what the value is for **each individual Arduino**.

I used this,

```
1.15 x 1023 x 1000 = [value in quotation from second to last line in the Function]

return "1125300L" / ADC;

```

I just incremented the 1.1v reference by 0.01 a couple of times until the output matched the voltage reading on my digital multi-meter. I would think with a known voltage you could do this math backwards to find what AREF actually is. I am sure that would be easier.

A big thanks to JRobert & @ EdgarBonnet for your answers!
> 3 votes

# Answer
Instead of calling `analogRead()`, this sketch performs the equivalent actions by directly manipulating the hardware registers to begin a conversion, wait until the conversion is complete, and collect the converted value.

Just reading the final value is accomplished by the statements:

```
result = ADCL;
result |= ADCH<<8;

```

All of the statements following `delay(2)` up to and including the above 2, taken together, do what `analogRead()` does.
> 2 votes

---
Tags: power, atmega328, arduino-pro-mini, voltage, voltage-divider
---


# Question
Title: Servo doesn't move if I detach it AFER the write?
So this is a bit weird, and I don't understand anything. Basically, I'm just playing with my servo. I wrote a small program, which can be found at this link: https://pastebin.pl/view/8e9c9573 (Note: It's three files, I left some comments there, and the `idk` function is just my last resort, trying to separate myself from `loop`, I really don't know :/ ).

So I run `controller.Setup()` in the `setup` function, and then in loop I just move it to 180 and detach it, then I run into an infinite loop. Note: I know it's not very good code, but that's not what concerns me right now.

The problem is, when I add the call to detach (line 22), the previous move doesn't run! I think I'm going crazy, cause as soon as I remove the line and recompile, it actually moves.

I tried to remove the lock(`Controller::m_Attached`), and it still doesn't work. Please let me know if I didn't notice something, but I really don't understand.

Notes:

EDIT: Someone told me to post the code in the question, so here I go:

```
//Main.ino
#include <Servo.h>
#include "Controller.h"

Controller controller(3);

void idk();

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

void loop() {
    idk();
    while(true);
}

void idk() {
    controller.Move(180);
    controller.Unlock();
}

// Controller.h
#pragma once
#include <Servo.h>

class Controller
{
public:
    Controller(int servoPin)
        : m_ServoPin(servoPin), m_Attached(false) {}

    void Setup();
    void Move(int angle);

    void Lock();
    void Unlock();

private:
    Servo m_Servo;
    bool m_Attached;
    const int m_ServoPin = 3;
};

// Controller.ino
#include "Controller.h"

void Controller::Setup()
{
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
    Serial.print("[CONTROLLER] Attached Servo\n");
}

void Controller::Move(int angle)
{
    if (m_Attached)
        m_Servo.write(angle);
}

void Controller::Lock() {
    m_Servo.attach(m_ServoPin);
    m_Attached = true;
}

void Controller::Unlock() {
    m_Servo.detach();
    m_Attached = false;
}

```

# Answer
The detach() function probably stops the data pin from outputting the servo control signal.

Your code disables the control signal a few microseconds after it is enabled.

The cotrol signal is never generated.

Furthermore, a servo requires the signal to be present at all times for it to keep its position.

When your programming includes real-world events, you have to think about the time frame of the events, and about the time frame of the running program.

Think in the terms that the program can loop 100,000 times before the servo has finished moving.
> 2 votes

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


# Question
Title: How can I declare an array of variable size (Globally)
I'd like to make three arrays of the same length. According to the documentation, Arrays must be defined as `int myArray[10];` where 10 can be substituted for a known length (another integer), or filled with an array `{2, 3, 5, 6, 7}`.

However, when I attempted to declare a value `int arrSize = 10;` and then an array based on that size `int myArray[arrSize];`, I get the following: `error: array bound is not an integer constant`.

Is there a way to variably determine array sizes, or do I just need to hardcode them? (I was taught hardcoding is bad and something to avoid at all costs.)

# Answer
Your question has 2 parts actually.

**1/ How can I declare the constant size of an array outside the array?**

You can either use a macro

```
#define ARRAY_SIZE 10
...
int myArray[ARRAY_SIZE];

```

or use a constant

```
const int ARRAY_SIZE = 10;
...
int myArray[ARRAY_SIZE];

```

if you initialized the array and you need to know its size then you can do:

```
int myArray[] = {1, 2, 3, 4, 5};
const int ARRAY_SIZE = sizeof(myArray) / sizeof(int);

```

the second `sizeof` is on the type of each element of your array, here `int`.

**2/ How can I have an array which size is dynamic (i.e. not known until runtime)?**

For that you will need dynamic allocation, which works on Arduino, but is generally not advised as this can cause the "heap" to become fragmented.

You can do (C way):

```
// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source)
if (myArray != 0) {
    myArray = (int*) realloc(myArray, size * sizeof(int));
} else {
    myArray = (int*) malloc(size * sizeof(int));
}

```

Or (C++ way):

```
// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source or through other program logic)
if (myArray != 0) {
    delete [] myArray;
}
myArray = new int [size];

```

For more about problems with heap fragmentation, you can refer to this question.
> 29 votes

# Answer
I know I'm a little late here, but in theory regular arrays can't be created using a variable to define the amount of elements the array is going to have as in:

```
int arrSize;
int myArray[arrSize];

```

This will display an error since when declaring the array, the program expects for the value between the brackets to be a constant. Yet, there is a way in which you could create an array with a variable defining the amount of values this arrays is going to have through dynamic memory allocation for value sets (this method has been tested with monodimensional arrays only, haven't tried for multidimensional yet), and it goes something like this:

```
//First you create a pointer for the memory space to be separated for the set you're creating
int* myArray;
int arrSize; //Then you define the variable that will determine the amount of elements the array is going to have, you can give it a value whenever you want as long as this int is defined before the values in myArray are set
myArray=(int*)calloc(arrSize,sizeof(int)) //Here, you establish that the instance myArray (whose memory space has already been separated through the creation of the pointer) will be separated into arrSize amount of elements of type int with a maximum memory value (in bytes) equal to the maximum available for the int type variables

```

After this, all that's left to do is assign a value for every element created in the instance myArray (which is already an Array by now) as you would for a normal array created as myArray\[arrSize\].
> 2 votes

# Answer
If you know the maximum length of array, just initialize the array to that length and use an integer to tell the program how much of that array to use. If it's the difference between 7,10 bytes then you are not wasting that much memory allocation.
> 1 votes

# Answer
The size of the array must be known at compile time. Otherwise you should allocate memory dynamically using:

```
char *chararray = malloc(sizeof(char)*x);

```

where x(an integer) can be set in the application code (you could load it from eeprom if you wanted it be a persistent but configurable setting).

---

However if you just want to declare some arrays of the same size, you just have to declare the number a constant like this:

```
const int arrsize = 10;
char array1[arrsize];
int array2[arrsize];

```

---

I think not hardcoding things only makes sense if you would reasonably expect the user to want to change the setting at some point. I don't know if that's the case.
> 0 votes

# Answer
The coderwall explains in Some detail the theory of how best to get the size of an array in C++ https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c
> 0 votes

---
Tags: programming, variables, code-optimization
---


# Question
Title: Switched from 3ft to 10ft connection wires. My setup doesnt run correctly now. Timing issues?
Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and Arduino Mega. I am stabilizing an object with an accelerometer as my sensor. I switched to longer wires so I can have my board next to me and the stabilized object far away. Now I believe there are timing issues because of this. How would I fix this? How would i test to see how long it takes to travel through my wires?

I can add my code if that helps.

# Answer
The pins of logic chips and processors are not line drivers and will not operate properly when used as such. Sometimes you may get lucky but that generally would be intermittent in operation. They make drivers to drive wires off board from the controller and other chips that are receivers on the other end. This needs to be done with each digital line. There are some specialty drivers such as I2C repeater chips, RS485 etc. Remember the wires are antennas and the system is operating at a high enough frequency to be a great radio transmitter. The main thing is to isolate the controller wires from the world.
> 2 votes

# Answer
A better solution would be to get a Pololu Wixel and companion shield for your Mega, and then put the Mega near the object. You can then program the Mega wirelessly and completely avoid problems with long signal lines. See this post for how I used it on one of my wall-following robots. You'll need two Wixels and one Wixel shield. They aren't particularly cheap, but you won't regret getting them.

There are other options for wireless control and programming, using Bluetooth rather than a proprietary protocol, but they aren't as easy to implement as the Wixel method.
> 2 votes

---
Tags: pwm, wires, timing
---


title: 2 stepper drivers speed control

text:
# Question
Title: 2 stepper drivers speed control
I'm using two tb6600 to control two step motors. It's for letter writing cnc machine. Moving single axis works fine.

I want to push 2 steppers in the same time along a diagonal.

I tried to calculate ratio x:y, so if x is making more steps than y for 1 y do n x steps. This worked, but machine was shaking no mater how i adjusted delays between step high and low. When i use PWM there is no shaking, but i can't figure out how to make it follow diagonal.

Second try was to use PWM with analogWrite.

```
if(delayX > delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayY);
      analogWrite(stepPinY, 0);
      delay(delayX - delayY);
      analogWrite(stepPinX, 0);

    }else if(delayX <= delayY){
      analogWrite(stepPinX, 128);
      analogWrite(stepPinY, 128);

      delay(delayX);
      analogWrite(stepPinX, 0);
      delay(delayY - delayX);
      analogWrite(stepPinY, 0);
    }

```

This doesn't works obviously. It reaches end point, but it doesn't follow diagonal. If i set duty cycle to 2 or 128 it doesn't matter. Isn't duty cycle supposed to change speed of stepper motor?

What am i missing here and how can this be done?

# Answer
Changing the duty cycle does not change the frequency of the PWM signal.

The tb6000 needs a pulse to trigger a step of the motor. If the frequency does not change the pulses per second do not change too and thus the speed is constant.

If you control just one motor the method of using delays to control the frequency works.

But in the case of two motors with different speed you need counter variables to immetate two frequencies (speeds) you need to control each speed of the motors.

First you caculate the ration of the speeds (you said y=1 and x=n steps. Then, the ratio is n:1, i.e the X Motor is faster then the Y Motor by factor n).

The following is just an incomplete example to explain my idea.

```
int cntX = 0;
int cntY = 0;

// I don't know you value n
// Let's say n=5
int ratioX = 5;
int ratioY = 1;

// One step per second at max speeed
// choose whatever fits your needs
int delayForMaxSpeed = 1000;

const int stepPinX = 5;
const int dirPinX = 2;
const int stepPinY = 6;
const int dirPinY = 3;
const int enPin = 8;

void setup()
{

  pinMode(stepPinX,OUTPUT);
  pinMode(dirPinX,OUTPUT);
  pinMode( stepPinY, OUTPUT );
  pinMode( dirPinY, OUTPUT );

  pinMode( enPin, OUTPUT );
  digitalWrite( enPin, LOW );

}

void loop()
{
  // Enables the motor to move in a particular direction
  digitalWrite( dirPin, HIGH );

  countx++;
  county++;

  if ( countX >= ratioX )
  {
     countX = 0;
     digitalWrite( stepPinX, HIGH );
  }

  if ( countY >= ratioY )
  {
    countY = 0;
    digitalWrite( stepPinY, HIGH );
  }

  delayMicroseconds( 500 );

  digitalWrite( stepPinX, LOW );
  digitalWrite( stepPinY, LOW );

  delay( delayForMaxSpeed );
}

```
> 3 votes

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


# Question
Title: Is it possible to gather data while the Arduino is being powered with a battery, connect to comp, and then read off the values in Serial Monitor?
I want to do a project where I gather data such as sunlight hours per day, as well as temperature highs/lows. Once I have gathered 24 hours worth of data, I want to hook it up to the computer to read off the values in Serial monitor. When I try and open the Serial monitor, it restarts the program wiping all the memory. I tried doing something with PROGMEM, but that didn't seem to help as it is only for constants. I want to avoid using an LCD to display data if possible.

# Answer
Yes, this is perfectly possible. You will need to write a routine that you can trigger via Serial. For example you will listen on Serial until you get the `dump` command. Then run a function that spits your variables out to Serial.

You just have to be careful where you save your 5 variables.

If stored in memory (RAM), you should avoid power loss. Therefore I'd suggest a FTDI USB-to-Serial adapter. There you just connect the TX, RX and GND wires and proceed with the Arduino IDE's Serial Monitor.

If stored in EEPROM, you can use the regular USB connector of Arduino.
> 1 votes

---
Tags: serial, battery, data
---


# Question
Title: Can Arduino Sketch be used for production
There are lot of device support with the help of Boards Manager today and is on going in Arduino IDE.

So I am curious to know about can one use those for production purpose. Or it is recommended for quick prototyping purposes only...

# Answer
> 4 votes
There's a lot of controversy on this issue, but if it works for your needs, absolutely do it!

Basically, there are 2 questions you have to answer:

1. **Should I use actual Arduino *boards* in production?**

The answer is generally "no", simply because you need to customize the boards to add components to support your project, and to make them more robust, and cheaper, if possible. So, use an Arduino schematic as a guideline, then modify it to suit your needs.

One big exception to this, however, could be if you create a "mother board" onto which you will plug in a "daughter board" such as an Arduino Nano, Pro Mini, Pro Micro, or similar. You could make the Nano removable by soldering male headers onto it, and female headers onto the main "mother board", then you just plug in the Nano into the headers on the main board. Or, you could make it permanent by soldering male headers onto the Nano and then also solder that straight onto the "mother board" directly into the holes where female headers would otherwise be soldered. Both of these are great options, and this vastly simplifies your design and assembly process as you learn to get started manufacturing. Legal Arduino Nano clones are ~$1~$4 each, with shipping, on Ebay, and Pro Minis (not as good--here I recommend the Nano) are about the same, so buying a pre-made Nano is generally cheaper than buying just the raw chips on the Nano anyway, oddly enough. And again, this vastly simplifies your design and makes designing and assembling boards and products much much easier for the beginner/entry-level manufacturer (you) or micro business. It also allows you to make hand-made boards using perf-boards or proto (prototyping) boards, as I show in my other answer here.

**For designing your own board**, I recommend KiCad, which is Free and Open Source, and no cost (`"free" == "free to modify"; "free" != "no cost"`!), and actively developed by a volunteer team of about 6 people on a daily basis (I'm on their mailing lists and see this daily). It is a great product and is highly-capable. It is used by hobbyists and professionals alike, and has been used on many professional products world-wide. CERN, Arduino, and DigiKey have all contributed to KiCad in one way or another. See the lists of sponsors under the "Sponsors" tab at the top of the KiCad website, here:

1. Corporate Sponsorship
    2. In Kind Sponsors
    3. Historical Sponsors

The CERN Open Hardware Repository states here:

> We think that KiCad can do to PCB design what the gcc compiler did to software: ensure there are no artificial barriers to sharing so that design and development knowledge can flow more freely.

That's an incredibly exciting mission!

There is also Autodesk Eagle, which is also popular among hobbyists and small businesses. It is a paid product, but has a no cost version for hobbyist, non-commercial use. It is also actively developed, by a tiny team of paid software developers on a pier in San Francisco. I've been to their office, and they are very excited about their work on it. They are doing a great job at making it a more-professional product. They've made some great improvements to Eagle over the last few years, hence why its price has gone up. It is also a great product.

Both products work on Windows, Mac, and Linux.

**The Arduino board schematics are open-source hardware**, so follow the licenses and provide attribution to where your design stemmed from. Ex: here's the Uno schematic. It shows the CC BY SA license logo at the bottom. I don't see a license version, but if it's 1.0, here's that license in plain terms. So, if you copy parts of the original schematics, release your design under the same license, and give credit to the original design.

You can NOT, however, use the Arduino logo or name. Those are trademarked and copyrighted, respectively. Arduino clones which do NOT use the Arduino name or logo are *legal*, and any clones which DO use the Arduino name or logo are *illegal.* There's no excuse for making an illegal Arduino clone. The schematics are intentionally open-source.

See also: Since Arduino uses Creative Commons licenses, do I also need to do that on my product?

> Deriving the design of a commercial product from the Eagle files for an Arduino board requires you to release the modified files under the same Creative Commons Attribution Share-Alike license. You may manufacture and sell the resulting product.

And: Can I design my own Arduino board and sell it?

> Since the hardware designs of Arduino are open source it is allowed to copy and further develop them. However this is not the same thing as making an Arduino board, only the company Arduino can design and produce Arduino products.
>
> Your finished product is a product compatible with Arduino which should have its own name and brand. In case a copy uses the Arduino name and/or logo on it, this board is no longer a copy but a counterfeit which is illegal to manufacture and produce.
2. **Should I use the Arduino *software* (*build system* and core libraries, and my program / "sketch") in production?**

The answer is generally, "yes". This may be using the IDE for building or using the Arduino CLI command-line build interface.

The Arduino core and build system works great and has tons of internal and 3rd-party library support. The Arduino IDE itself is released under the GPL license (see below), and the core libraries are LGPL-licensed, which means if you modify them for your project, and put your project result into someone else's hands, you MUST release your modifications you made to the core code and libraries to those who have your project in their hands. See the main license file here:

> this file includes licensing information for parts of arduino.
>
> first, the gnu general public license, which covers the main body of the processing/arduino code (in general, all the stuff inside the 'app' and 'core' subfolders).
>
> next, the gnu lesser general public license that covers the arduino core and libraries.

**But, you can keep your programs/"sketches" and main bits of project closed-source if you wish. Your programs are your own. They are copyrighted solely by you and you can license, use, and/or sell them however you wish.** This includes the right to sell your Arduino/C and C++ programs as software or as firmware within a commercial product.

As a matter of fact, the GPL and LGPL licenses on the Arduino IDE and source code *even allow you to sell the Arduino IDE and source code itself if you wish!* This is really important, and is a fundamental right that "free and open source" software grants you. The Free Software Foundation, which is the owner of the copyrights on the license *text itself*, and the author of the GNU GPL and LGPL and other free and open source licenses, has this *official guidance about selling and even reselling free software* (they strongly *encourage* it!) (italics added):

> **Selling Free Software**
>
> Some views on the ideas of selling exceptions to free software licenses, such as the GNU GPL are also available.
>
> Many people believe that the spirit of the GNU Project is that you should not charge money for distributing copies of software, or that you should charge as little as possible—just enough to cover the cost. This is a misunderstanding.
>
> *Actually, we encourage people who redistribute free software to charge as much as they wish or can. If a license does not permit users to make copies and sell them, it is a nonfree license.* If this seems surprising to you, please read on.
>
> The word “free” has two legitimate general meanings; it can refer either to freedom or to price. When we speak of “free software”, we're talking about freedom, not price. (Think of “free speech”, not “free beer”.) Specifically, it means that a user is free to run the program, study and change the program, and redistribute the program with or without changes.
>
> Free programs are sometimes distributed gratis, and sometimes for a substantial price. *Often the same program is available in both ways from different places. The program is free regardless of the price, because users have freedom in using it.*
>
> Nonfree programs are usually sold for a high price, but sometimes a store will give you a copy at no charge. *That doesn't make it free software, though. Price or no price, the program is nonfree because its users are denied freedom.*
>
> Since free software is not a matter of price, a low price doesn't make the software free, or even closer to free. *So if you are redistributing copies of free software, you might as well charge a substantial fee and make some money. Redistributing free software is a good and legitimate activity; if you do it, you might as well make a profit from it.*
>
> Free software is a community project, and everyone who depends on it ought to look for ways to contribute to building the community. *For a distributor, the way to do this is to give a part of the profit to free software development projects or to the Free Software Foundation.* This way you can advance the world of free software.
>
> **Distributing free software is an opportunity to raise funds for development. Don't waste it!**
>
> *In order to contribute funds, you need to have some extra. If you charge too low a fee, you won't have anything to spare to support development.*

This is only the first portion of their stance on the topic. Read the rest of the Free Software Foundation's encouragement to sell free software here.

That's the gist of it.

*I am not a lawyer, and even if I was, none of my words herein are official legal advice.*

When words come from the Free Software Foundation, who authors the GPL and LGPL licenses, however, those words are automatically extra legitimate.

## Related:

1. Using Arduino for Industrial process
2. LGPL and Arduino in Commercial Products

# Answer
> 2 votes
There is two cases. First you use arduino boards. I would avoid this because it will be more expensive and harder to assemble the product. There is one exception, the new arduino nano family. These boards are made to be easily use in production (they can be soldered as a SMD components) but it's always expensive.

The second case is to use arduino software on custom microcontroller setup. It cheaper and easier tu put in production. The limitations are the choice of microcontroller (mostly Atmel) and speed and memory usage of microcontroller. As you use an extra layer of software (the Arduino bootloader) there is a risk of bug.

To conclude : it's possible but as most of the people that put projects in production know how to use microcontrollers without Arduino hardware or software and there is limitations to Arduino software there is not a lot of case of uses and it's not reccomended.

---
Tags: arduino-ide, sketch
---


# Question
Title: Serial doesent work when calling function from timer
You can try the code on your arduino UNO to better understand what is hapening in serial monitor!

I want to calculate jacobian matrix from rotation matrix!

```
float jakMATB[3][3] = {
{0, 0, 0},
{0, 0, 0},
{0, 0, 0}
     };
float POKUS = 0;
float k = 0.000001;
float dt = 0.001;
float b = 90 * (PI / 180);
float vnB[3] = {0, 1, 0}, vpB[3] = {0, 1, 1};
float nB[3] = {0, 1, 0};
float nBplus[3] = {0 , 1, 0};
float nBminus[3] = {0, 1, 0};
void setup() {
Serial.begin(9600);
Serial.print("init ok");
cli();//stop interrupts
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1  = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = (16000000) / ((1 / dt) * 1024) - 1; // 15624 = (16*10^6) / ((1)*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12 and CS10 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
}

```

when I call the function in loop everithing works fine and I get 1 2 1 in serial monitor

```
 void loop() {
 izracunJAKOB();
 for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  Serial.print(jakMATB[j][i]);
  Serial.print(" ");
}
Serial.println("");
}
}

```

when I call izracunJAKOB() with timer interupt Serial monitor stops working and doesent event write "init ok"

```
ISR(TIMER1_COMPA_vect) {
  //izracunJAKOB();
 }
void izracunJAKOB() {
for (int j = 0; j <= 2; j++) {
for (int i = 0; i <= 2; i++) {
  nBplus[j] = nB[j] + k;
  nBminus[j] = nB[j] - k;
  float matricaBplus[3][3] = {
    {cos(b) + nBplus[0]*nBplus[0]*(1 - cos(b)), nBplus[1]*nBplus[0]*(1 - cos(b)) - nBplus[2]*sin(b), nBplus[0]*nBplus[2]*(1 - cos(b)) + nBplus[1]*sin(b)},
    {nBplus[1]*nBplus[0]*(1 - cos(b)) + nBplus[2]*sin(b), cos(b) + nBplus[1]*nBplus[1]*(1 - cos(b)), nBplus[1]*nBplus[2]*(1 - cos(b)) - nBplus[0]*sin(b)},
    {nBplus[0]*nBplus[2]*(1 - cos(b)) - nBplus[1]*sin(b), nBplus[1]*nBplus[2]*(1 - cos(b)) + nBplus[0]*sin(b), nBplus[2]*nBplus[2]*(1 - cos(b)) + cos(b)}
  };
  float matricaBminus[3][3] = {
    {cos(b) + nBminus[0]*nBminus[0]*(1 - cos(b)), nBminus[1]*nBminus[0]*(1 - cos(b)) - nBminus[2]*sin(b), nBminus[0]*nBminus[2]*(1 - cos(b)) + nBminus[1]*sin(b)},
    {nBminus[1]*nBminus[0]*(1 - cos(b)) + nBminus[2]*sin(b), cos(b) + nBminus[1]*nBminus[1]*(1 - cos(b)), nBminus[1]*nBminus[2]*(1 - cos(b)) - nBminus[0]*sin(b)},
    {nBminus[0]*nBminus[2]*(1 - cos(b)) - nBminus[1]*sin(b), nBminus[1]*nBminus[2]*(1 - cos(b)) + nBminus[0]*sin(b), nBminus[2]*nBminus[2]*(1 - cos(b)) + cos(b)}
  };
  jakMATB[i][j] = (matricaBplus[i][j] - matricaBminus[i][j]) / (2 * k);
  nBplus[0] = 0;
  nBplus[1] = 1;
  nBplus[2] = 0;
  nBminus[0] = 0;
  nBminus[1] = 1;
  nBminus[2] = 0;
}
}
}

```

////////////////////////////// when I comennt out

```
   nBplus[j] = nB[j] + k;
   nBminus[j] = nB[j] - k;

```

and

```
   nBplus[0] = 0;
   nBplus[1] = 1;
   nBplus[2] = 0;
   nBminus[0] = 0;
   nBminus[1] = 1;
   nBminus[2] = 0;

```

Serial works just fine

when I coment out only matricaBminus and matricaBplus serial works fine

Please help! It surely is a stupid solution!

# Answer
> 1 votes
Timer was to fast! When I decreased frequency everithing worked fine.

---
Tags: timers, functions
---


# Question
Title: AMIS30543 - Library code | Order of pinDirection and pinOut
This piece of code was taken from AMIS30543- Arduino library,

```
void init(uint8_t slaveSelectPin) {
    ssPin = slaveSelectPin;
    digitalWrite(ssPin, HIGH);
    pinMode(ssPin, OUTPUT);
}

```

Facts I know

* digitalWrite - makes the pin to the corresponding voltage level
* pinMode - makes the pin either input or output
* ssPin is active low pin usually.

So I was wondering before setting the pinDirection why the pin is made HIGH, Then immediately after that the pinDirection was declared as OUTPUT

Also I know , if a pin was made HIGH and on the next line if the direction of the same is set as INPUT will bring the internal pull up resistor in action .

So what am I missing here. More over in Arduino does the order of pinMode/digitalWrite matter.? if So what is the meaning of this particular lines of code Github link to the library

# Answer
> 0 votes
The library is doing this to make sure, that the pin will never go low during initialization.

Imagine doing it the other way round:

```
pinMode(ssPin, OUTPUT);
digitalWrite(ssPin, HIGH);

```

If the corresponding PORT bit is set to zero (LOW) previously (which is also the standard after reset/power cycle), the pin will go LOW for a very short time, until `digitalWrite()` sets it HIGH again. That LOW time is short, but it might needlessly activate the slave. If you first use `digitalWrite(ssPin, HIGH)`, you activate the internal pullup (as standard mode after reset/power cycle is INPUT) and set the corresponding PORT bit to 1. Thus, when you now change the pin mode, the pin is HIGH immediately, without ever going to LOW in between.

Internally the Arduino uses 3 SFRs (Special Function Registers), which are directly connected to the IO hardware of the pins. The `DDR` register of each port controls the "pin mode" aka direction of the pin (input or output). The `PORT` register controls the output value (HIGH or LOW; or turning the pullup resistor on or off in input mode). The `PIN` register reflects the current state of the pin (for reading it). In this case the double function of the `PORT` register is important, as it activates the internal pullup resistor, when set while in input mode.

# Answer
> 1 votes
This initialization will work with spi communication for PIC32 microchip too?

---
Tags: arduino-uno, arduino-mega, spi, electronics, stepper-motor
---


# Question
Title: AMIS30543 | Data-Sheet understanding Status register
I was reading the data Sheet of AMIS-30543 stepper motor driver and I was not able to understand how to combine the result of the Micro step position status register MSP\[8:0\]. I know that its a 9 bit value . Help me understand how to get the value.

In the data sheet it is given like

in SR3 -\> MSP\[8:2\], and in SR4 -\> MSP\[6:0\]. How I am I suppose to get the 9 bit out of these.

---

In the library I have seen that , `(sr3<<2) | (sr4 & 3)`  . I don't understand why they are doing and `&` here.

Please explain . also If there was no library how am I suppose to know how to combine these registers from the dataSheet .

Link to DataSheet

# Answer
Most of the data is duplicated between the registers. Both registers contain MSP\[6:2\].

If MSP contains `111001001` the registers (ignoring the MSB "PAR" bit) would look like:

```
SR3: 1110010
SR4: 1001001

```

If we line those up it's then like:

```
SR3: 1110010
SR4    1001001

```

You can now see the overlap.

So taking SR3 and shifting it left two places (`sr3 << 2`) gives you:

```
SR3:   1110010
<<2: 111001000

```

Taking the lowest two bits of SR4 with `& 3` gives you:

```
SR4:   1001001
& 3:   0000001

```

Then ORing the two results together:

```
SR3<<2: 111001000
SR4 &3: 000000001
-----------------
MSP   : 111001001

```
> 3 votes

---
Tags: arduino-uno, programming, spi, electronics, stepper
---


# Question
Title: Selection of module for person following shopping cart
I'm building a person following shopping cart with Arduino for my final year project. The cart is supposed to be able to follow its user while shopping use of Bluetooth module or wifi module will be feasible or not?or I should use IR sensors ?

# Answer
Bluetooth beacon. Use "bluetooth positioning arduino" as search terms.

Bluetooth beacon is a way to achieve the same as a GPS can do outdoor. By placing beacons around the room you can find your position in 3D space.

So a beacon locator on the shopping cart (Arduino with BLE module or a ESP32) and one on you (mobile phone) and then some central unit that can coordinate the two positions.

Just as a concept it would be feasible.
> 2 votes

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