message:
ESP8266 always resetting after 65 second of running

I have a simple code where ESP8266 is asking MySQL database about actual state of LED (whether 1 or 0) and when DB has 1 ESP8266 turns LED on... But my problem is after 65-66 seconds of server running is still resetting... The program does what it is supposed to do, but after 65-66 seconds resets and trying to reconnecting to wifi

---- EDIT -----

After some experiments with code I have found, it doesn't matter the running time but, number of loop cycles... Every time no matter on delay or processing speed, it crash after 48 cycles....

.ino code
 ```
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

// Replace with your network credentials
const char* ssid     = "XXXX";
const char* password = "XXXX";
const char* host = "http://www.XXXX.XX/arduino_PHP/post_data.php";

// Set web server port number to 80
WiFiServer server(80);
HTTPClient http;

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output5State = "off";
String output4State = "off";

// Assign output variables to GPIO pins
const int output5 = 5;
const int output4 = 4;
byte green, red= 0;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
   WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
   WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
  delay(1000);
  pinMode(output5, OUTPUT);
  pinMode(output4, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output5, LOW);
  digitalWrite(output4, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
 delay(500);
DB_state("Green",green);
DB_state("Red",red);
 delay(500);
}

void DB_state(String component,int state){
  String postData =("component=" + String(component) + "&state=" + String(state));
  Serial.println(postData);
   http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
   http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  http.POST(postData);   //Send the request
  String payload = http.getString();    //Get the response payload
  Serial.println(payload);
  http.end();  //Close connection
  state_LED(payload,component);
  }

void state_LED(String str, String led){
  int x;
    if (led== "Green") {
      x = 4;}
    else if (led== "Red") {
       x = 5;}
    if (str == "State: 1") {
      digitalWrite(x, HIGH);}
    else if (str == "State: 0") {
      digitalWrite(x, LOW);}
  }

```
ESP8266 Stack debug
```
Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads
PC: 0x4020744a: ClientContext::state() const at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266WiFi\src/include/ClientContext.h line 364
EXCVADDR: 0x00000184

Decoding stack results
0x40203f10: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 164
0x40203f1c: HardwareSerial::write(unsigned char const*, unsigned int) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266/HardwareSerial.h line 165
0x40207512: HTTPClient::connected() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 475
0x40202d24: HTTPClient::disconnect(bool) at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 434
0x40203ac8: HTTPClient::end() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\ESP8266HTTPClient\src\ESP8266HTTPClient.cpp line 425
0x402012ba: DB_State(String, int) at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 87
0x40201334: loop() at C:\Users\XXXX\Documents\Arduino\ESP8266_php_DB_control/ESP8266_php_DB_control.ino line 73
0x40100175: esp_schedule() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 125
0x40205628: loop_wrapper() at C:\Users\XXXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\cores\esp8266\core_esp8266_main.cpp line 197
```

Thanks for any advice

body:
I don't know how, but finally I have found working solution... I have add ```HTTPClient http;``` at top of function and it works...
```
void DB_state(String component,int state){
HTTPClient http; // THIS IS ADDED
 String postData =("component=" + String(component) + "&state=" + String(state));
 Serial.println(postData);
  http.begin("http://www.XXXX.XX/arduino_PHP/DB_state.php");
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 http.POST(postData);   //Send the request
 String payload = http.getString();    //Get the response payload
 Serial.println(payload);
 http.end();  //Close connection
 state_LED(payload,component);
 }
```

Can anyone explain me how it's possible? Because I don't fully understand this procedure.


sender: user

message:
Arduino Nano stucks on uploading

I'm trying to upload an simple blink sketch to my Arduino Nano, which not used for a while.

As I remember, I uploaded an sketch to control RF module, at the last time I used. Now, when I connect my Arduino Nano, I 'm getting error message every second, from my serial monitor saying the the RF communication cant start, because I have disconnected all connections to the RF module.

It seems the Nano is working, and the Nano driver is working properly. I tried resetting manually, and uploading many times with random timings. But up to now, the sketch not uploaded, and waiting. When I press reset button while uploading, Arduino shows me the error it cant communicate.

I think the Arduino IDE not getting enough time to upload from serial, because it's busy all the time.

Is there any way to wipe out the existing sketch from Nano? or any working solution to upload my new empty sketch or simple blink sample? It's a big help if anyone can shed me some light to make my Nano work again.

sender: assistant

body:
I have solved the issue by selecting,

Tools > Processor > ATMega (Old bootloader)

@Juraj, Thank you for suggestion.


message:
Storing value in EEPROM in Arduino Uno

Hi I am a beginner in Arduino Uno. I wanted to store a value of 77880 in EEPROM and fetch it later. I made the code as follows to check my logic(I am using Arduino Uno) :

    #include <EEPROM.h>
    int addr = 0;
    byte value;
    void setup() {
      // put your setup code here, to run once:
      int val = 77880;
      EEPROM.write(addr, val);
      Serial.begin(57600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      value = EEPROM.read(addr);

      Serial.print(addr);
      Serial.print("\t");
      Serial.print(value);
      Serial.println();
      delay(1000);
    }

but I am not getting the value of 77880 when I read the EEPROM address. instead I am getting a value of  56 in my serial output. Can anybody pls explain how should I implement the same?

body:
EEPROM can only store the values 0-255 in any one address. That's the maximum range of an 8-bit value, and EEPROM "cells" are 8-bit in size.

You will have to split your value up into multiple 8-bit chunks and store each chunk at a different address - for example for 32-bit values you can use:

    uint32_t val = 77880; // In hex is 0x13038
    int addr = 0;
    EEPROM.write(addr, val & 0xFF); // Stores 0x38 in address 0
    EEPROM.write(addr + 1, (val >> 8) & 0xFF); // Stores 0x30 in address 1
    EEPROM.write(addr + 2, (val >> 16) & 0xFF); // Stores 0x01 in address 2
    EEPROM.write(addr + 3, (val >> 24) & 0xFF); // Stores 0x00 in address 3

Then to read you do the opposite and shift the values and OR them:

    uint32_t val = (uint32_t)EEPROM.read(addr) |
                   ((uint32_t)EEPROM.read(addr + 1) << 8) |
                   ((uint32_t)EEPROM.read(addr + 2) << 16) |
                   ((uint32_t)EEPROM.read(addr + 3) << 24);

Alternatively the EEPROM library has a "store anything" helper to do it for you:

    EEPROM.put(addr, val);

That will store the variable `val` across enough cells to fit it (4 in the case of a 32-bit variable), so you must know not to write to the other cells used by it (0, 1, 2 and 3 in this case) or you will corrupt your data.

You recall it with:

    EEPROM.get(addr, val);


body:
See Majenko's answer for why you have to problem. This is alternative solution to the problem.

Using the Arduino library for EEPROM is very limited. It can only read/write one byte at a time. Your variable `val` is of the type `int` which is a 16 bit integer on the uno. So two bytes, which is also called a `word`.

I use the [AVR EEPROM](https://www.nongnu.org/avr-libc/user-manual/group__avr__eeprom.html) "library" directly.

```cpp
#include <avr/eeprom.h>

EEMEM int eepVariable; // using EEMEM will make the compiler handle the location in EEPROM for you
                           // the compiler makes sure no data will ever overlap inside the EEPROM.

int value; //should be an `int` too.
void setup() {
  // put your setup code here, to run once:
  int val = 77880;
  eeprom_write_word(&eepVariable, val);
  Serial.begin(57600);
}

void loop() {
  // put your main code here, to run repeatedly:
  value = eeprom_read_word(&eepVariable);

  Serial.print(value);
  Serial.println();
  delay(1000);
}
```


message:
9 volt battery unable to power 2 plastic yellow motors

I am trying to build a robot using a kit I got from amazon:
https://www.amazon.co.uk/DFRobot-Tank-Mobile-Platform/dp/B014L1CF1K?th=1
(it uses plastic motors).

The main problem that I am having is that whenever I try to apply a battery with 9 volts to one of the motors it only moves the slightest amount. I am not sure if the voltage is too low or not because in the manual it is using 7.4 volts.

The motors are connected up to a motor driver, here is a diagram of what it looks like

[![enter image description here][1]][1]

Could the motors potentially be broken? (Hope not because it means I will have to dissect the whole robot)

The motors I am using look like this:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/D5mF5.png
  [2]: https://i.stack.imgur.com/56ITo.png

body: 9v batteries are incapable of supplying enough current for a motor; their best application is tiny-current, standby devices like smoke detectors. You need a power supply that can deliver much more current than the 9v brick can. 6 AA cells in series would do much better. 6 pairs of AA-cells would give you longer run time (each 2 cells in parallel; the 6 parallel pairs in series). You could accomplish the same thing using AAA-cells if your project values space over run-time.


message:
Why do we use bitwise operators to assign PORTx, DDRx and Pinx?

I have come accross a lot of examples using ways similar to the ones shown below to assign values to the pins.

 >  PORTB |= (1<<PORTB2); //set bit 2

 >  PORTB &= ~(1<<PORTB1); //clear bit 1

 >  DDRD = DDRD | B11111100;  //Sets up the pins for output

My question is why do we need to use bitwise operations to make assignements?

body:
> My question is why do we need to use bitwise operations to make assignements?

Because you're not assigning, you're modifying.

If you want to turn on just pin 3 (for example) you need to only control bit 3 of PORTB and leave the others alone.

That means you need to "or" the value of just bit 3 being on with the existing PORTB to turn the bit on, or AND it with the inverse (all pins on except bit 3) to turn it off.

To get the value of bit 3 you can remember that it's `4`, or you can just use `1<<3` to say "Bit 3" - or use the macro `PORTB3` to make it more readable instead of just the number 3.

The operation is commonly known as "Read Modify Write" and in some low-end microcontrollers you have to take special care when doing it.

For example, if you want to control the output pin 3 and currently you have pins 2, 5 and 6 on and the rest of pins 0-7 off (those are the ones on port B on the Uno) the sequence may be like:

```
Turn on:

Calculate bit value 1<<3    => 0b00001000
Read PORTB                  => 0b01100100
OR the two values together  => 0b01101100
Write to PORTB              <= 0b01101100

Turn off:

Calculate bit value 1<<3    => 0b00001000
Invert it                   => 0b11110111
Read PORTB                  => 0b01101100
AND the two values together => 0b01100100
Write to PORTB              <= 0b01100100
```


body:
The registers are 8 bits in size. And in the above two cases you want to set/clear 1 bit, while leaving the others the same.

In the last example you want to set pins D2-D7 to output, while leaving pins D0 and D1 unchanged.


body:
**It makes code easier to write and re-use.**

Let's say your program needs to do 3 unrelated things on different pins. Control a motor, flash a light, count some input pulses.

Since this bitwise technique allows you to read/change only the bits you need to, _and leave the others alone,_ you can totally separate the code for the 3 tasks. It can even be written in separate files by separate people, and without knowing what other pins in the project are being used for. The code for one of the 3 tasks could be copy-pasted into a separate project, without needing to untangle it from project 1 nor make major changes to project 2. In software engineering lingo this is called making code "more maintainable" and also "modular."


body:
### If you want to change all pins on a port at once, you don't have to. ###

The point isn't just that you want to set/clear the pins you want, it's that you want to *not* change the state of the other pins.  To do that, you need to modify only the bits for the pins to be changed, and leave all the other bits as they are.  The only way to do this is with bitwise operators.

But if you do want to change all the pins at once, then you can perfectly well just set the port register to a value.  Outputting a value on an 8-bit bus would be a classic case where you'd do this.

I do need to pick you up on one thing in your question though.  In many cases, it is a bad idea to read the state of the port, modify the bits, and write the value back.  The reason is that almost all microcontrollers use the same port address for setting the output state and reading the input state.  So by reading back the port state, you aren't necessarily reading the actual outputs you set.  Logic-high outputs are generally weaker than logic-low, so it's entirely possible for your connected electronics to pull down a logic-high.  The sequence of faults for the bug goes:-

* Your program sets a bit (pin) to 1.
* Another component pulls that pin down to logic-low.
* The next time you read that port back to change another pin, the input for the pin reads 0.
* You modify the value for the pin you intended to change.
* You write the value back.  Now not only has the intended pin changed state, but so has the pulled-down output.
* The other component stops pulling the pin down.  But your micro keeps outputting 0 (logic-low) for that pin.

The solution is that you don't do bitwise operations directly on the register.  Instead, you keep a "shadow" variable containing the state you want the outputs to be.  You do all your bitwise operations on that shadow variable, and then you write the shadow variable directly to the register.  And the bug goes away.


message:
Stepper motor slow when reading from MPU 6050 sensor

I'm trying to get an inverted pendulum project working (following the instructions [here][1]), 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][2]. 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;
}
```

  [1]: https://www.instructables.com/Inverted-Pendulum-Control-Theory-and-Dynamics/
  [2]: https://www.amazon.com/Aukru-Arduino-Accelerometer-6050-Gyroscope/dp/B019SX74TE/ref=as_li_ss_tl?keywords=MPU6050&qid=1583927362&sr=8-10&linkCode=sl1&tag=howto045-20&linkId=de53fe380c95f93863eee585fcf2f2fb&language=en_US

body:
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.


message:
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.

body:
You'd usually use a transistor to do that.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/8hJAC.png)

<!-- End schematic -->

SW1 is your microcontroller creating the PWM signal.


body:
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.
[![How to connect mosfet to arduino pin][1]][1]

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:

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/kJkCp.jpg
  [2]: https://i.stack.imgur.com/HZJ3c.png


body:
**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]: https://i.stack.imgur.com/aJwdy.png


body:
<!-- language-all: lang-arduino -->

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][2]. 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][2], 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:

- brushed, NOT brushless, DC motors
- high-power LEDs, assuming you have a means of current-control too, such as a large passive power resistor, or current feedback control loop and control code
- speakers (for tone's, beeps, or digital PWM-based [NOT analog-amplifier-based] music, voice, or rich audio). Ex:
    - tone library
        - [ok] [`tone()` library][3]
        - [best] [`toneAC()` library][4]
            - Example siren project I did with `toneAC` library, a large speaker, and a custom driver or H bridge:
                - https://www.electricrcaircraftguy.com/2016/01/arduino-playing-siren-sound.html
                - https://www.youtube.com/watch?v=anuan0oEOQw&feature=emb_logo
                - _https://www.youtube.com/watch?v=y31gM3m3VJI - final project video demo: siren_
    - music/rich audio PWM-based library
        - [excellent] [`TMRpcm` library][5]

### 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"](https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2334524.m570.l1313&_nkw=arduino+h+bridge&_sacat=0&LH_TitleDesc=0&_osacat=0&_odkw=h+bride)
    1. [L9110 datasheet](https://www.elecrow.com/download/datasheet-l9110.pdf)
        1. 2.5V to 12V supply
        1. 800mA max continuous current per channel
1. Cheap $3 L298N H-bridge (much more powerful):
    1. [Ebay search for "arduino h bridge L298"](https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2334524.m570.l1313&_nkw=arduino+h+bridge+L298&_sacat=0&LH_TitleDesc=0&_osacat=0&_odkw=arduino+h+bridge+l298)
    1. Example specs sheet: http://www.handsontec.com/dataspecs/L298N Motor Driver.pdf
        1. 3.2 to 40V supply
        1. 2A peak current
        1. 20W max power
1. 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
    1. Ex: [$40 Pololu G2 High-Power Motor Driver 18v25](https://www.pololu.com/product/2994)
        1. 6.5V to 30V supply
        1. 1.8V, 3.3V, or 5V logic signals
        1. 25A max continuous current
        1. up to 100kHz PWM operation, because they have excellent MOSFET gate drivers to minimize MOSFET time in the ohmic region, and therefore MOSFET heating!
        1. If you're in a hurry and want high-quality, Pololu is an _excellent_ choice!
        1. 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][6], 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.

- HobbyKing:
    - [_Brushed_ RC CAR ESCs on HobbyKing][7]
        - $12 45A ESC, 2S LiPo (6V to 8.4V) max [here][8]
        - $40 80A continuous, 400A split-second peak (yes, these numbers seem legit to me), 2-3S LiPo (6V to 12.6V) [here][8]

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]  https://arduino.stackexchange.com/questions/77600/switching-a-solenoid-using-arduinos-5v-output/77602#77602
    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](https://www.adafruit.com/product/976) in place of the 2N3904 in my circuit, and be sure to redo the calculations to size your base resistor, R1.
    1. 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.
    1. [![enter image description here][9]][9]

  [added 713 characters in body7]: https://hobbyking.com/en_us/hobbyking-x-car-45a-brushed-car-esc.html?queryID=917d3f2440f14105c354b8f540ae8c06&objectID=48605&indexName=hbk_live_magento_en_us_products

  [1]: https://www.adafruit.com/product/395
  [2]: https://arduino.stackexchange.com/a/78549/7727
  [3]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
  [4]: https://playground.arduino.cc/Code/ToneAC/
  [5]: https://github.com/TMRh20/TMRpcm
  [6]: https://www.arduino.cc/reference/en/libraries/servo/writemicroseconds/
  [7]: https://hobbyking.com/en_us/cars/cars/esc.html#q=brushed&idx=hbk_live_magento_en_us_products&dFR[warehouses][0]=USA&dFR[warehouses][1]=Global&dFR[warehouses_stock_data][0]=USA|1&dFR[warehouses_stock_data][1]=USA|2&dFR[warehouses_stock_data][2]=USA|3&dFR[warehouses_stock_data][3]=Global|1&dFR[warehouses_stock_data][4]=Global|2&dFR[warehouses_stock_data][5]=Global|3&hFR[categories.level0][0]=Vehicles /// Cars /// ESC&is_v=1
  [8]: https://hobbyking.com/en_us/quicrun-wp-crawler-brushed-1.html?queryID=917d3f2440f14105c354b8f540ae8c06&objectID=62441&indexName=hbk_live_magento_en_us_products
  [9]: https://i.stack.imgur.com/INI2q.png


body:
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.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/EEBMi.png)

<!-- End schematic -->


message:
Wiring up an ESP 01 to Nano

I've been at this for over a week now and still cant get things working. Im attempting to wire up an ESP-01 chip to a Nano to send AT commands over Serial. I've followed many different tutorials, but the best (and my current) setup seems to be this one:

https://www.youtube.com/watch?v=YKn2ZXYb_EI (Wiring)
https://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html (Wiring & Code)

My breadboard has that exact wiring as shown in the video and the website. I understand that the 3.3v pin doesnt provide enough power, so I've used a DC Voltage regulator to step the 5v pin down to 3.3v, and I'm using that as my main power line.

When I plug the Arduino in, I get a quick couple of flashes from the blue light on the ESP, as well as a solid bright red light. The light is brighter than when it is directly from the 3.3v, so I'm pretty sure it's powered enough.

I then open Serial monitor and get no response when I type `AT`:

[![enter image description here][1]][1]

I have tried at both 9600 and 115200 baud, and tried many different wiring setups, all to no avail.

If someone could help with this I'd be forever appreciative

- After taking some readings with my multimeter - I see the output of my regulated 3.3 rail drops to 2.55 with the ESP plugged in... Do I want to bring this up even more so it's 3.3 WITH the ESP plugged in?

- I don't think the above edits suggestion will work since I've also wired the chip to a 3.3 breadboard power supply powered by a barrel jack - still no avail

- I understand I can write firmware directly to the ESP-01, this is not my goal here. I require it as an add-on to the Nano, since I need its analog pins, amongst other things'

  [1]: https://i.stack.imgur.com/3ptXf.png

body:
Wowwww i finally figured it out after a week of messing around, and 20 mins after posting my question.

To anyone else who stumbles across this: Please understand if you're following this tutorial [here][1] or [here][2]. There is a bug in the code:

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

should be

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

Also the suggested baud rate of 9600 doesnt seem to work, adjust to 115200 and go from there. Once you get a receiving signal, run the following to adjust the 01's baud to 9600:

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

After this, reflash your nano with serial bauds set to 9600 and you should be able to send AT commands over your Nano to the ESP-01 via 9600 baud

In addition to this. You will read online that you might be able to get away with stepping the Nano's 5v pin down to 3.3 to power the module. This didnt work for me, and i suggest you get a breadboard power supply

Good luck to all!

  [1]: https://www.instructables.com/Learn-How-to-Setup-the-Wifi-Module-ESP8266-by-Usin/
  [2]: https://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html


message:
Leds become dimmer after they reach a certain brightness, why?

**Even if I don't use buttons and I do an automated thing that makes the led brighter(Even the non-rgb one)after sometime it resets itself to a dimmer light, why?***

```int Rled = 3;
int Gled = 5;
int Bled = 6;
int Rv;
int Gv;
int Bv;

int b1 = 7;
int b2 = 8;
void setup()
{

  pinMode(b1, INPUT_PULLUP);
  pinMode(b2, INPUT_PULLUP);
  Rv = 0;
  Gv = 0;
  Bv = 0;
  analogWrite(Rled, Rv);
  analogWrite(Gled, Gv);
  analogWrite(Bled, Bv);

}

void loop()
{

  if(digitalRead(b1) == LOW)
  {
    Rv += 10;
    analogWrite(Rled, Rv);
  }
  if(digitalRead(b2) == LOW)
  {
    Gv += 10;
    analogWrite(Gled, Gv);
  }

}

body:
The described behavior stems from 2 important facts:

1. The `loop()` function will run very fast (microsecond range), while the button presses of a normal human will be rather slow (in the tens or even hundreds of milliseconds). That means, that with only one button press you will enter the corresponding if statement many times, everytime adding 10 to the value. You don't have control how many times exactly the if statement will be entered, so the value, that comes out after your button press is somewhat randomly growing.

2. While the `analogWrite()` function takes an `int` as the value parameter (16 bits on AVR), internally it assigns that value to the corresponding Timer register, which is only 8 bits big. So it can only hold values between 0 and 255 anyway. If you provide a bigger number as a parameter, the higher part will just be cut off. For example: Providing 257 will result in a value of 1 (= 257 % 256 = 257 % 2^8 --> 257 modulo 256). The higher values get wrapped around back into the range of 0 to 255.

So together you have a value, that is growing very fast and somewhat randomly, while the `analogWrite()` function will only take the lower 8 bit of that value. The outcome is a rather erratic, somewhat random LED brightness, which is difficult to control.

**What to do now?** That depends on what behavior you want to have exactly:

- One button click (press + release) should increase the value of the corresponding LED by 10:
    - Currently you are checking, if the button is being pressed. Instead you have to look for the transition between not-pressed and pressed, so a HIGH to LOW transition. You can do that by saving the last read value in a variable at the end of the button reading part and comparing this previous value to the newly read value at the start of it. Though that still leaves you with the bounce problem. There are many measurements, that you can do, to debounce the button (you can google that easily), though here I just will suggest using the `Bounce2` library. You can find it [here on github][1] or in the library manager (I think). It makes it much easier to read buttons reliably. It has good examples to learn how to use it.

- The value should rise, while the button is pressed, and stopping to rise, when it is released again:
    - Here you should limit the rate in which the if statement is entered. You can do this by limiting the execution rate of the `loop()` function with a simple call to `delay()`, though that isn't a good coding practice and can limit you, when adding more functions to your code (because it's blocking the execution of other code). Instead you can use the non-blocking coding style involving the `millis()` function, that you can see in the `BlinkWithoutDelay` example. You use a timestamp variable to save the last time, when the if statement was executed. The if statement should then check (additionally to the button state), if enough time has passed, meaning if the difference between `millis()` and the timestamp is high enough. You can change the interval for this comparison to change the rate, in which the value is increased.

  [1]: https://github.com/thomasfredericks/Bounce2


message:
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?

body:
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.


message:
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);
    }
    }

body:
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.


body:
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.

[![Path to cut.][1]][1]

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

  [1]: https://i.stack.imgur.com/7SPQI.jpg


message:
U-Blox Neo M8N GNSS-GPS interface with ESP32-TTGO-T-CALL

I have tried contacting the manufacturers as well as many Google searches.
I have tried many different libraries to get this GNSS-GPS working.

**Libraries I've Tried:**

- Arduino_GPS

- Arduino_Parser_Ublox_Neo_M8N

- esp32-ublox

- MicroNMEA

- NEO-M8N

- NeoGPS

- UBLOX-NEO-M8N

**The library I am trying now:**
- Parser_Ublox_Neo_M8N
*with:*
- ESPSoftwareSerial

(I have a non-AVR board so NeoSWSerial and SoftwareSerial didn't work for me.)

**Link to files on GitHub:**
https://github.com/toskyRocker/Arduino_Parser_Ublox_Neo_M8N

**My questions for someone who has done this before with a U-Blox M8N:**
- Must I use U-Center software to configure the gps before it will output data?
- Does my code look to be functional? I can compile but then when attaching GPS I get the output (as my psuedo error message) that lets me know the serial connection between my TTGO T-Call V1.3 and U-Blox-M8N is not valid.
Here is a link to the board I have and the GNSS-GPS:

**Board:**
https://www.ebay.com/i/284030711638?chn=ps&norover=1&mkevt=1&mkrid=711-213727-13078-0&mkcid=2&itemid=284030711638&targetid=4580840328168117&device=c&mktype=&googleloc=&poi=&campaignid=403206339&mkgroupid=1235851284533722&rlsatarget=pla-4580840328168117&abcId=9300372&merchantid=51291&msclkid=52c16af1ba571d52ddfe35755ba68854

**GPS:**
https://www.bidorbuy.co.za/item/319275677/GYGPSV5_NEO_M8N_NEO_M8N_001_GPS_Chip_Module_for_APM2_6_Flight_Control.html

(The "<#include SoftwareSerial.h>" in the code below is what was added when I used the Arduino IDE's drop down libraries menu when I selected espsoftwareserial to include.)

**Here is the (.ino) code:**

    #include <SoftwareSerial.h>

    #include "Ublox.h"
    #define SERIAL_BAUD 115200
    #define GPS_BAUD 9600
    #define N_INTS 4
    //gpsSerial(3,1);
    Ublox M8_Gps;
    // Altitude - Latitude - Longitude - N Satellites
    int gpsArray[N_INTS] = {0, 0, 0, 0};
    SoftwareSerial gpsSerial;

    /////////////////////////////////////////////////////////////

    void setup() {
    Serial.begin(SERIAL_BAUD);
    gpsSerial.begin(GPS_BAUD,SWSERIAL_8N1,3,1);
    //gpsSerial.begin(GPS_BAUD);
    pinMode(0,OUTPUT);
    }
    ///////////////////////////////////////////////////////////
    void loop() {
    digitalWrite(0,LOW);
    if(!gpsSerial.available()){
  Serial.print("Problem with GPS ");
    }
    while(gpsSerial.available()){
        char c = gpsSerial.read();
         if (M8_Gps.encode(c)) {
          gpsArray[0] = M8_Gps.altitude;
          gpsArray[1] = M8_Gps.latitude;
          gpsArray[2] = M8_Gps.longitude;
          gpsArray[3] = M8_Gps.sats_in_use;
        }
     }
     for(byte i = 0; i < N_INTS; i++) {
     Serial.print(gpsArray[i], 10);Serial.print(" ");
     }
     Serial.println("");
     }

body:
> Must I use U-Center software to configure the gps before it will
> output data?

No, but it is HIGHLY recommended.  It's the only (easy) way to change the baudrate, and the only (easy) way to change what messages are output over serial.

> Does my code look to be functional?

I can't answer 100%, as I have not used that library before, but the problem I did run into with the NEO-M8N and multiple libraries I tried (MicroNMEA, TinyGPS, TinyGPS++, ...) was that as a multi-constellation GNSS receiver that can receive more satellite constellations than just GPS, it by default outputs $GNGGA.  These libraries I had tried using only decoded the old standard $GPGGA, and ignored the more universal ones.

Here is how you can use U-Center to verify this is the problem, and if so how to configure your module to output GPGGA messages that these libraries will parse:

 1. Connect to your NEO-M8N using U-center.  (Usb is pprefered, but serial will work fine too)
 2. Confirm that this is the problem by clicking View -> Messages View.
 3. You should see either GPGGA or GNGGA messages being received.

If you are currently getting GNGGA, here is how to switch them to GPGGA:

 1. View -> configuration View
 2. Click on "NMEA (NMEA Protocol) config entry
 3. Click "Poll" at the bottom to pull the current settings from your device.
 4. Change the "Main Talker ID" to "1 - GP (GPS)"
 5. Change the "GSV Talker ID" to "1 - Use main talker ID"
 6. Click "Send" at the bottom to upload your changes.
 7. Click on the "CFG (Configuration)" config entry
 8. Choose "Save current configuration" and then "Send" at the bottom.

Now just use the method above to verify what NMEA packets you are receiving!

Now that you're in U-Center, I'd recommend also checking out the GNSS config, to enable the use of more satellites (GPS, Glonass, Galileo) and set the SBAS config depending on your location.  (In the US, setting to WAAS may help it lock on quicker as it won't bother searching for other SBAS sources)  You can also change the baud rates for different ports under "PORTS", increase or decrease the frequency of sending location updates under "RATE" and enable or disable individual NMEA messages for each port under "MSG"


message:
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 :)

body:
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](https://majenko.co.uk/blog/reading-serial-arduino), and the same principle can be applied to any other language.


message:
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...

body:
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.


body:
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][1], and Pro Minis ([not as good--here I recommend the Nano][2]) [are about the same][3], 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][4].

    **For designing your own board**, I recommend [KiCad][5], 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](https://www.kicad.org/about/kicad/) (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][6], Arduino, and [DigiKey][7] 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](https://www.kicad.org/sponsors/sponsors/)
    1. [In Kind Sponsors](https://www.kicad.org/sponsors/inkind/)
    1. [Historical Sponsors](https://www.kicad.org/sponsors/historical/)

    The [CERN Open Hardware Repository states here][8]:

    > 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][9], 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][10]. 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][11]. 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][12]. 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?][13]

    > 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?][14]

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

1. **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][15].

    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][16], 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][16]:

    > 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][17], which is the owner of the copyrights on the license _text itself_, and the author of the GNU [GPL][18] and [LGPL][19] and other free and open source licenses, has [this _official guidance about selling and even reselling free software_ (they strongly _encourage_ it!)][20] (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][20].

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. https://arduino.stackexchange.com/questions/9163/using-arduino-for-industrial-process
1. https://arduino.stackexchange.com/questions/51376/lgpl-and-arduino-in-commercial-products

  [1]: https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=arduino nano&_sacat=0
  [2]: https://arduino.stackexchange.com/a/78376/7727
  [3]: https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=atmega328 pro mini&_sacat=0
  [4]: https://arduino.stackexchange.com/a/9197/7727
  [5]: https://www.kicad.org/
  [6]: https://cernandsocietyfoundation.cern/projects/kicad-development
  [7]: https://www.digikey.com/en/resources/design-tools/kicad
  [8]: https://ohwr.org/project/cern-kicad/wikis/home
  [9]: https://www.autodesk.com/products/eagle/overview?plc=F360&term=1-YEAR&support=ADVANCED&quantity=1
  [10]: https://www.autodesk.com/products/eagle/free-download?plc=F360&term=1-YEAR&support=ADVANCED&quantity=1
  [11]: https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf
  [12]: https://creativecommons.org/licenses/by-sa/1.0/
  [13]: https://support.arduino.cc/hc/en-us/articles/360016912680-Since-Arduino-uses-Creative-Commons-licenses-do-I-also-need-to-do-that-on-my-product-
  [14]: https://support.arduino.cc/hc/en-us/articles/360016785120-Can-I-design-my-own-Arduino-board-and-sell-it-
  [15]: https://github.com/arduino/arduino-cli
  [16]: https://github.com/arduino/Arduino/blob/master/license.txt
  [17]: https://www.fsf.org/
  [18]: https://www.gnu.org/licenses/gpl-3.0.en.html
  [19]: https://www.gnu.org/licenses/lgpl-3.0.en.html
  [20]: https://www.gnu.org/philosophy/selling.en.html


message:
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.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/maigg.png

body: 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.


body:
A better solution would be to get a [Pololu Wixel][1] 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][2] 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][3] rather than a proprietary protocol, but they aren't as easy to implement as the Wixel method.

  [1]: https://www.pololu.com/product/1336
  [2]: https://www.fpaynter.com/2015/12/new-battery-and-wireless-for-wall-e2/
  [3]: https://www.fpaynter.com/wp-admin/post.php?post=3612&action=edit


message:
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.][1] 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.

  [1]: https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

body:
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.


message:
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][1].

      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...**

  [1]: https://forum.arduino.cc/index.php?topic=520674.msg4123985#msg4123985

body:
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.


body:
> 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.

> ```c++
> 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:

```cpp
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


body:
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!