# Question
Title: Why do you need to shift bits when reading from an analog sensor?
I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go \- this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val\[1\]) \<\< 8) | int(val\[2\])" before getting the result.

Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

# Answer
> 1 votes
You read bytes in the order:

* Most significant byte (let's call this msb)
* Least significant byte (let's call this lsb)

The formula to get to real value is msb * 256 + lsb 256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).

However, a CPU is normally faster in bit operations than in arithmetic operations.

```
Assume msb is 10101010
and lsb is    11001100

```

Now below is the table with the calculation order

```
sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

```

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.

---
Tags: sensors, analogread, raspberrypi
---


# Question
Title: NodeMCU successfully uploaded sketch but it does not work from Arduino IDE
NodeMCU successfully compiled and uploaded a simple blink sketch on board, no errors at all, but the LED stays on constantly and does not blink. Also I have checked the power is enough. I have checked this with all pins but the red LED only stays on and doesn't blink. I have no idea what could have gone wrong. And how to fix this?

# Answer
> 1 votes
Fixed it.... turns out that in the tools, the board was selected to be NodeMCU 0.9 when it should actually have been NodeMCU 1.0 so i just changed it to NodeMCU 1.0 and it worked!

---
Tags: esp8266, nodemcu, ide, iot
---


# Question
Title: Will I destroy my Arduino Uno if I connect a 600-mA DC motor to the +5V pin?
I know that if I connect an electronic component that consumes more than 20 mA, my Arduino Uno will be destroyed. I don't know if that refers only to digital pins or refers to +5V pins too.

# Answer
If you connect a motor to the +5V pin, it will always be on. Is that what you want?

The +5V pin on the Arduino Uno gets power from the on-board 5V linear voltage regulator **OR** from the USB jack, and thus the host computer. This allows the board to have a fixed 5V source even when applying 9 or 12 V to the barrel jack or the RAW pin, and to be powered by a USB host.

When you draw 600mA for your motor (ignoring what the other devices on the Arduino draw), you are drawing 600mA from the regulator's output. You are also drawing 600mA from the regulator's input, which supplies a higher voltage. Excess power is dissipated as heat. 5V * 600mA is 3W. If you power the board from 9V, you are discarding \[(9V-5V)=4V\] * 600mA = 2.4W of power. 2.4 Watts is probably too much for the little regulator to handle. It will get too hot and burn up.

If you do this, you will *probably* be able to still operate it powered by the USB port, as only the 5V regulator is damaged.

However, if you try to draw 600mA and power the board from a USB device like a computer, you may burn up the computer's USB chip and make it useless forever.

For high-power devices like motors, always power them from a sufficient external supply of the appropriate voltage. Be sure to connect the ground of the external power supply to the GND pin of the Arduino. Don't send high current through the Arduino board. The Arduino should handle *signals*, not power.

Use the signals to activate switching devices like MOSFETs, which are designed to control higher currents by low-power signals.
> 5 votes

# Answer
No, it shouldn't destroy it. Although you are getting close to the current limit.

The on-board regulator (depending on the board version) can supply up to about 800mA to 1A.

However, the actual maximum current is dependent on the voltage you are supplying the board with - the higher the voltage the hotter the regulator gets and the lower the current that it can supply without shutting down (or burning out).

As long as you run the board from the lower end of the input voltage (7V, say) it should be fine.

It would be better, though, to use an external power supply for the motor anyway, just to reduce the amount of heat the regulator will pump out.

Powering from the USB won't be possible, however: the USB port has a 500mA fuse in the supply circuit.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Uno R3 connected via Ethernet shield becomes unreachable after a few minutes
I'm setting up an Elegoo Uno R3 with a Seeed 5200 ethernet shield to monitor water flow and temperature. It needs to run unattended for weeks at time (being called several times a day by a remote script).

I'm normally able to send and receive UDP packets for a few minutes when I've just reset/power-cycled the Arduino. After that, it stops responding to UDP messages. By adding some serial output I can see that it hangs unpredictably at different parts of loop(). Sometimes it seems that physically shifting the device will get it to wake up; or it will wake up on its own after a minute or two. Most of the time it works until it quits, then doesn't work until I reset it.

It does respond to ping while it's otherwise unresponsive.

Is there anything wrong with my code? This is my first Arduino project. Otherwise could it be a hardware problem? If I buy another, I'll buy a genuine Arduino. Is Seeed a reliable source for the ethernet shield?

(By the way--I think it's safe to disregard the PACKETLEN thing, which is a leftover artifact. In the end it's unnecessary to read the incoming message anyway, so the packetBuffer array is superfluous but doesn't seem to change anything one way or another.)

Thanks in advance. Best wishes, Dan

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

#define PACKETLEN 48

//Flow and temp globals
byte sensorInterrupt = 0;  // 0 = digital pin 2
byte flowPin       = 2;
byte tempPin = 0;

float calibrationFactor = 45; // we're going to measure for 10s intervals
float minFlow = 270;          // minimum 6 L/min, measured for 10 s
volatile byte pulseCount;
unsigned long startTime, timeDelta;

int tempReading;
float tempVoltage;
float temperature;

//Communication globals
IPAddress ip(xxx, xxx, xxx, xxx);
byte mac[] = {
  0xxx, 0xxx, 0xxx, 0xxx, 0xxx, 0xxx
};
EthernetUDP Udp;

unsigned int localPort = xxxx;
char packetBuffer[PACKETLEN+1];  //buffer to hold incoming packet,

int packetSize;
byte flowOk, tempOk;
IPAddress remoteIP;
unsigned int remotePort;

void pulseCounter()
{
  pulseCount++;
}

void setup()
{

  //Serial.begin(9600);
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);

  pinMode(flowPin, INPUT);
  digitalWrite(flowPin, HIGH);

  // attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}

void loop()
{

    delay(2000);

    if(packetSize = Udp.parsePacket())
    {
        remoteIP = Udp.remoteIP();
        remotePort = Udp.remotePort();

        //Measure the flow for 10 seconds
        flowOk = 0;
        pulseCount = 0;
        startTime = millis();
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
        while((timeDelta = millis() - startTime) <= 10000) ;
        detachInterrupt(sensorInterrupt);
        if (pulseCount >= minFlow)
            flowOk = 1;

        //Check the temperature
        tempOk = 0;
        tempReading = analogRead(tempPin);
        tempVoltage = tempReading * 5.0 / 1024.0;
        temperature = (tempVoltage - 0.5) * 100;
        if (temperature < 35.0)
            tempOk = 1;

        Udp.beginPacket(remoteIP, remotePort);
        if (flowOk && tempOk)
            Udp.write("Ok");
        else
            Udp.write("Not ok");
        Udp.endPacket();
    }

}

```

# Answer
I don't know where my compiler was finding the UDP code in the above sketch, because it's not in EthernetV2\_0.h. The problem was fixed by adding the following lines, from the example sketch UDPSendReceiveString written by Michael Margolis and included with the Ethernet\_Shield\_W5200 library:

```
#include <EthernetUdpV2_0.h>

#define SDCARD_CS 4

void setup():
    //...//
    pinMode(SDCARD_CS, OUTPUT);
    digitalWrite(SDCARD_CS, HIGH);

```
> 1 votes

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


# Question
Title: Arduino-compatible micro-controller with both I2C and CAN
I am looking for a controller that works with Arduino (i.e. there is official or third-party support for the controller in the Arduino IDE and core libs) and has both built-in CAN and I2C buses. I was looking at the ATMega automotive series (16M1, 32M1, 64M1, 32C1, 64C1) but it does not mention I2C/TWI in the datasheet at all.

(I know I can bitbang I2C, I know there is MCP2515 for CAN over SPI.)

Thanks!

**EDIT:** The application in mind is a bridge between a few I2C sensors and CAN, no complex logic. High performance is not necessary, plus it will drive costs upwards.

# Answer
Many options come to mind:

A Bluebill board is programmable with mbed, STM32HAL (CubeMX) and Arduino, all of which have either CAN libraries for the CAN peripheral or have it even built-in in the OS (mbedos).

The Bluepill board is extremely low cost ($1.81 with free shipping from aliexpress) and features an STM32F103C8 microcontroller with 128kB Flash and 20kB RAM. Its peripherals include two I2C and one CAN bus.

Infos & Datasheet: http://www.st.com/en/microcontrollers/stm32f103c8.html, http://wiki.stm32duino.com/index.php?title=Blue\_Pill

For flashing and debugging the chip you should have one cheap ST-Linkv2 clone (~3$ from china).

For programming environments you can use:

As frameworks you can use:

* Arduino (see above)
* ARM mbedos (builds upon STM32HAL, natively supported by PlatformIO)
* STM32HAL (e.g. with project files for an IDE generated by STM32CubeMX)

Documentation references:

8 Bit microcontrollers from STM8AF series have a few micros with 1 I2C and 1 CAN bus: See http://www.st.com/en/microcontrollers/stm8af-series.html?querycriteria=productId=SS1583

Ready buyable evaluation board: http://www.st.com/en/evaluation-tools/stm8a-discovery.html (you want the STM8AF5288 one)

The toolchain changes then, of course. See https://my.st.com/content/my\_st\_com/en/extended-query.html?querycriteria=productId=LN1759$$associatedTo=SS1584
> 2 votes

---
Tags: i2c, can-bus
---


# Question
Title: Detect button press inside a for() cycle
I was working on a project with an LED strip, where I'd like to cycle through various effects with just a press of a button. The problem is that I don't know how to detect the press of the button to change effect while in for() cycling colors to have a rainbow effect (so it's a multitasking problem, I think). Could you help me? :)

```
#include <Adafruit_NeoPixel.h>

#define pin 5
#define led 15
#define button 7
Adafruit_NeoPixel strip = Adafruit_NeoPixel (led,pin,NEO_RGB+NEO_KHZ800);

int doggo=0;

void setup(){
 strip.begin();
 pinMode(button,INPUT);
}
void loop(){

 int buttonVal=digitalRead(button);

 if(buttonVal==HIGH){
  doggo++;
  delay(300);
 }
 if (doggo>2){
  doggo=0;
 }
 while (doggo==0){
  //whole strip red
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,255,0,0);
   strip.show();
  }
 }
 while (doggo==1){
  //rainbow effect
  uint16_t i, j;
  int rainbowSpeed=10;
  for(j=0; j<256*5; j++) {

   for(i=0; i< strip.numPixels(); i++) {

    strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    strip.show();

   }

  }

 delay(rainbowSpeed);

 }

 while (doggo==2){
  //whole strip blue
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,0,0,255);
   strip.show();
  }
 }

}

uint32_t Wheel(byte WheelPos) {
 WheelPos = 255 - WheelPos;

 if(WheelPos < 85) {
  return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
 }
 if(WheelPos < 170) {
  WheelPos -= 85;
   return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
 }
 WheelPos -= 170;
 return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

```

# Answer
You could use the Bounce2 library.

Call the update() method regularly and then check the state with read().

e.g.

```
for (...) {
  button.update();
  if (button.read() == HIGH) {
     //change pattern
     break;
  }
  // Do strip stuff.
}

```

As an added bonus the bounce library will debounce your button.
> 1 votes

# Answer
You should use a hardware interrupt. Depending on your microcontroller, you have different pins available.

Here is a reference for more details and syntax
> 0 votes

# Answer
I finally solved!

I tried the Bounce2 library, but it acted really strange (the effects passed from the first one, then the third one, then the first one again for a fraction of second and automatically to the second one, plus other things :/ )

It looks like I just needed to add a normal digitalRead inside for() and a return, I don't usually make those errors xD
> 0 votes

---
Tags: button
---


# Question
Title: One of the LEDs on my Arduino is very dim
I made a vibration sensor using an Arduino. It is connected to an Android app. When the start button is pressed on the app, a red light LED turns on (stand by), and after 2 - 5 seconds, the red LED turns off and a green LED turns on (meaning the system is ready). The green LED turns off if the sensor detects a vibration. The green LED works perfectly. However, the red LED is always dim. I've tried testing the red LED separately, it works fine. I've tried changing the pin it's connected to, it's still dim. I've included my code below if it helps.

Thanks in advance.

```
int ledPin = 13;
int ledPin2 = 9;
int EP = 7;
int cal = 500;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT); //set EP input for measurement
  Serial.begin(9600); //init serial 9600
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();
    if (c == '1') {
      cal = 100;
    }
    if (c == '2') {
      cal = 200;
    }
    if (c == '3') {
      cal = 300;
    }
    if (c == '4') {
      cal = 400;
    }
    if (c == '5') {
      cal = 500;
    }
    if (c == '6') {
      cal = 600;
    }
    if (c == '7') {
      cal = 700;
    }
    if (c == '8') {
      cal = 800;
    }
    if (c == '9') {
      cal = 900;
    }
    if (c == '0') {
      int randm = random(2, 6);
      int x = randm * 1000;
      digitalWrite(ledPin2, HIGH);
      delay(x);
      unsigned int tm = millis();
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, LOW);
      while (1) {
        long measurement = TP_init();
        char br = Serial.read();
        if (br == 'x') {
          break;
        }
        if (measurement > cal) {
          digitalWrite(ledPin, LOW);
          unsigned int out = millis() - tm;
          unsigned char i = out;
          Serial.print(out);
          break;
        }
      }
    }
  }
}

long TP_init() {
  delay(0);
  long measurement = pulseIn (EP, HIGH);
  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

```

# Answer
> 4 votes
You need to add this line for the other LED pin:

```
pinMode(ledPin2, OUTPUT);

```

# Answer
> 1 votes
You need this same line for the other LED pin:

pinMode(ledPin**2**, OUTPUT);

---
Tags: led, bluetooth, arduino-duemilanove
---


# Question
Title: Merge two Arduino projects (change build process)
I'm working on a big software project consisting of several Arduino sketches. I have one Arduino project providing general functionality, such as TCP/IP communication, parsing queries, handling errors, and some more. This part is fundamental for several devices, which extend this fundamental part by specific functionalities. E.g. one device needs to read temperature sensors and manage a loop to control the temperature and has its own sketch. Another device is driving a servo motor and measuring sun light and also has its own sketch. (And there are some other devices with specific sketches.)

I want to maintain the fundamental part in ONE sketch and the specific parts of the different devices each in OTHER sketches, so I can code both separately.

The problem is, those specific parts can not be compiled if not merged with the fundamental sketch, as this provides basic functions. So if I compile any specific part, I want the fundamental part to be added to the specific one and afterwards the whole code should be compiled.

Is there a way to manipulate the makefile used by the Arduino IDE? Then I could use whatever I want (bash or Python script) to merge in the desired way first.

# Answer
> 5 votes
Assuming that each separate hardware device (ESP32?) must run self-contained with both the fundamental parts, and the use-specific parts, then you would do well to separate out the fundamentals into a library, and then include that library in each use-specific sketch.

The Adafruit Unified Sensor Driver would be one project that shows this. Each of the sensor libraries based on this driver must `#include` the unified sensor driver library, and that provides some basic properties and interfaces, while each sensor's individual code handles the specifics for communicating to/from that particular unique hardware device.

# Answer
> 1 votes
In my opinion, you don't need another Arduino. Most of the time, Arduino is fast enough to handle all the things you mentioned. It highly depends on your programming skills. For example, don't make your Arduino do nothing while waiting for a communication to complete and so on. The techniques you require are:

1) No delay functions at all in your programming. Go Arduino's examples and look for 'blink without delay' sketch.

2) Organize your programming. Make use of creating your own functions. Your void loop() should be a to-do-list.

---
Tags: esp8266, arduino-ide, esp32
---


# Question
Title: No Matching Function for call to Ultrasonic:Ultrasonic(int,int)
Good Day! I am trying to code the distance of Ultrasonic Sensor but the problem is it gives me this error. Any idea? Please help.

```
#include <Ultrasonic.h>

// HR-SC04 SENSOR
#define TRIGGER_PIN   5
#define ECHO_PIN      6

Ultrasonic ultrasonic(TRIGGER_PIN, ECHO_PIN);

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

// Global variables
int lastDistance = 0;
int thisDistance = 0;

void loop()
{
  // Copy over last distance
  lastDistance = thisDistance;

  // Get new this distance
  thisDistance = ultrasonic.Ranging(CM);

  if (outlierCheck(lastDistance, thisDistance)) {
    Serial.println("Outlier found: " + String(thisDistance));
  } else {
    Serial.println(String(thisDistance) + " cm");
  }

  delay(10);
}

// Check for significant jumps and outliers in sensor reading
bool outlierCheck(int lastDistance, int thisDistance) {

  // if the difference between measures is greater then 20cm, outlier found
  if ((lastDistance - thisDistance) > 20) {
    return true;
  } else {
    return false;
  }
}

```

# Answer
> 1 votes
You are very likely to have confused the libraries.

When using your code with the library at https://github.com/JRodrigoTech/Ultrasonic-HC-SR04, the code compiles perfectly fine. The constructors match up with your code.

```
//Constructor 1
Ultrasonic(int TP, int EP);
//Constructor 2
Ultrasonic(int TP, int EP, long TO);
//methods.. (used in your source)
long Timing();
long Ranging(int sys);

```

I think you have installed this Ultrasonic library: https://github.com/ErickSimoes/Ultrasonic. It has the same header file and class name but the class is constructed differently

```
//Constructor 1
Ultrasonic(uint8_t sigPin) : Ultrasonic(sigPin, sigPin) {};
//Constructor 2
Ultrasonic(uint8_t trigPin, uint8_t echoPin, unsigned long timeOut = 20000UL);
//Note that a constructor with only 2 arguments is not directly visible

```

You should go into the Arduino IDE and uninstall your current "Ultrasonic" library from the library manager. Then download the zip file from the first given github repository and add that ZIP file to your libraries.

Alternatively of course, you can use the second library and its correct example code.

Also note that your Arduino IDE 1.0.6 is extremely outdated, current one is 1.8.5

---
Tags: sensors, arduino-ide
---


title: How to get location of the hand indoors

text:
# Question
Title: How to get location of the hand indoors
I made a glove that tracks the positions of the fingers, but I don't know how to get the location of the hand relative to the person using them. Any suggestions? It should be quite accurate but I would really like to make even a rough prototype of it.

Ps. I'm using a Arduino Nano (atmega328p) to send and process the positions of the finger to a Java application through serial if you wanted to know.

# Answer
> 1 votes
The only way to check the relative position is, first to define, what is the absolute position of a person, is it his other hand, his heart, his head, his foot?

When you defined the absolute position of the person, then you need to use a sensor at that absolute position that can measure the current position, e.g. GPS (if outside), but this is not accurate.

You also can use a gyroscope or device similar to what you use for the glove. When you initially keep them together you now the relative position (around 0.0). Than you can track movement differences of both the glove and the absolute position, send it to the glove (or vice versa) and calculate the difference. There might be calibration issues.

Another way is to use a camera and continueously check for a line of sight signal (IR, led), but this also can have issues (like distance measurement, what if there is no line of sight etc).

---
Tags: atmega328, gyroscope
---


title: Get UUID from Arduino Nano, ATmega328

text:
# Question
Title: Get UUID from Arduino Nano, ATmega328
I need to know how to obtain the UUID from an Arduino Nano ATmega328 for a project.

# Answer
You don't have a UUID.

You only get a UUID in the USB-enabled chips, like the ATMega32U4.

You would have to create your own UUID and store it in EEPROM, or embed it within your sketch.
> 2 votes

---
Tags: arduino-nano
---


# Question
Title: Is it possible to use LCD (the 16 pins) without potentiometer?
look, I don't have any potentiometer lying around, and I don't have any variable resistor. So is it possible to instead use a fixed resistor for the LCD display ?

# Answer
Sure. You can use two resistors in series to be a "fixed value" potentiometer.

The "wiper" of the potentiometer is the junction between the two resistors.

I can't tell you what values to use, so you'll have to experiment. You want them to add up to somewhere in the tens of kilo-ohms though, ideally, though the value isn't that critical - it's the ratio between the two values that is of interest, and it's that which gives you your contrast setting.
> 2 votes

---
Tags: lcd
---


# Question
Title: this code is not printing anything on the serial moniter. the code is in setup()
```
Serial.println("CLEARDATA"); //clears up any data left from previous projects
Serial.println("LABEL,time,load reading(gm),microwave output,CO sensor,sound data,magnetic sensor "); //always write LABEL, so excel knows the next things will be the names of the columns (instead of Acolumn you could write Time for instance)
Serial.println("RESETTIMER"); //resets timer to 0

//pinMode(AOUTpin, INPUT);//sets the pin as an input to the arduino
// pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
Serial.println("HX711 calibration sketch");
Serial.println("Remove all weight from scale");
Serial.println("After readings begin, place known weight on scale");
Serial.println("Press + or a to increase calibration factor");
Serial.println("Press - or z to decrease calibration factor");

```

# Answer
> 4 votes
There can be different reasons, among:

* The speed of the serial port does not match with the serial 'monitor'
* The speed of the serial port is not set at all (can cause first problem)

# Answer
> 2 votes
I don't see this before the print statements: Serial.begin(9600); // or some other speed

That will prevent anything from printing.

---
Tags: arduino-uno
---


# Question
Title: Digital Pins reads 1 when configured with internal_pullup
I work with Arduino DUE. I would like to configure few of my digital pins as INPUT pins. When the µc sets these particular 4 pins , the DUE must be activated. Something like a DATAREADY pin in the SPI,where the data will be sent to the slave only,when it sets the pin to 1.

According to the datasheet , the external µC would set the pin state from 0 to 1. I tried this program for experimenting the effect of digital pins,

```
int RDY = 52;
void setup() {

 Serial.begin(9600);
pinMode(RDY,INPUT_PULLUP);
pinMode(50,INPUT);
digitalWrite(RDY,HIGH);

}

void loop() {

digitalRead(RDY);
digitalRead(50);
digitalRead(11);
digitalRead(12);

Serial.println(digitalRead(RDY));
Serial.println(digitalRead(50));
Serial.println(digitalRead(11));
Serial.println(digitalRead(12));

delay(100);
}

```

Results obtained are; 1,1,0,0 as expected. I cannot find a proper way to detect the change of state of the pin (from 0 to 1). To make detect changes, I connected/disconnected the 5V output pin of DUE to the particular digital pins. The results never changed with connection and disconnection of the 5V wire for any pin.

Is there any possible way to detect the change of the pin state as in INPUT mode in Arduino DUE? Most examples are dealing with switches,but in my case I need a pin as a input.

Thanks

# Answer
> 4 votes
There is no difference between a switch and a "pin" for input. All are either HIGH or LOW. You tie it HIGH with the pullup, and then try giving it a HIGH with +5V (**Caution: The Due is a 3.3V device, not 5V!**).

At no point do you ever give it a LOW signal (connect the input to GND), so how can it ever read LOW?

---
Tags: arduino-due, pins, digital-in
---


title: Strange behavior on bitwise operation

text:
# Question
Title: Strange behavior on bitwise operation
i am trying to write a simple program that writes the outputs of an accelerometer (which comes down to 3 analog inputs) onto an SD-Card.

I got the hole thing working fine (sending the values as simple strings), however i wanted to increase the frequency at wich the data is taken and therefore tried to send the data to the SD card encoded in binary, and therefore i am doing some bitwise manipulation.

Unfortunately some (as i think) strange things happen. When i add a simple bitwise manipulation the data on the SD card is pretty messed up. (I was unable to detect a pattern but it seems some Bytes are missing or or are there twice without any regularity):

Here is an example of a working version:

```
// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = (byte) (rawX>>2);
byte b2 = (byte) (rawY>>4);
b2 = b2 + (byte) (rawX<<6);
byte b3 = (byte) (rawZ>>6);
b3 = b3 + (byte) (rawY<<4);
byte b4 = (byte) (rawZ);
b4 = (byte)b4*4;
//b4 = (byte)b4<<2;

// get pressure
//temp = BMP180_getTemp();
//float a = 0;
//float a = pressure.altitude(BMP180_getPressure(), baseline);

unsigned long t = millis();

byte writeB[] ={
    b1,
    b2,
    (byte) (rawZ>>6), //replacing this with '(byte) ((rawZ>>6)|(0b11110000 & rawY))' will cause the error
//also replacing with b3 creates the error as well
    b4,
    (byte) (t>>16),
    (byte) (t>>8),
    (byte)t, (byte)0};

dataFile.write(writeB,8);

dataFile.flush();

```

As mentioned as a comment in the code changing the way the byte is calculated messes up my data on the SD card. I tried several other things however it seems that the following operations are causing the error: | & \<\< \>\> (However i am using some of them to calculate e.g. b2)

What i don't get is how changing how a byte is calculated affect the data output.

Maybe (probably) i overlooked some easy mistake but i cant figure out what is happening. Any help would be greatly appreciated since im working on this since quite a while.

(I am aware that the program does currently not transmit all necessary data but i startet from scratch and programmed step by step to locate/identify the error)

# Answer
> 1 votes
Your way of sharing the bits between the three values seems a bit confusing. Your code for saving the bits is correct in the meaning of that you save all relevant information. Your bytes are shared in this way (H means high portion of value, L is the low portion of value):

```
     ____HX_____
b1: | 0000 0000 |
     _LX_ ___HY___
b2: | 00 | 000000 |
     __HZ__ __LY__
b3: | 0000 | 0000 |
     __LZ____
b4: | 000000 | XX |

```

This is a rather complex way of dividing the space. Also, since you are not using the remaining 2 bits of `b4` you don't have to shift there.

When you are getting garbled values from your SD card, it wildly depends on how you are reading the bytes (you haven't shown us the code for that). As a suggestion I will explain how I would do it.

---

We have 3 values from `analogRead()`, which each have 10 bits. So in total we have 30 bits, which can be transmitted in 4 bytes (or 32 bits). When adding bits from another value, I think you can use the `+` operator (opposing to my comment) if the bits of the different values don't overlay (which should be anyway). For my part I like to use the bitwise or `|` to show more clearly, what is done there and to easier check for errors in alignment (easy to see in binary representation). Do as you like. I will use the `|` operator for now.

```
// Get raw accelerometer data for each axis
unsigned int rawX = analogRead(A0);
unsigned int rawY = analogRead(A1);
unsigned int rawZ = analogRead(A2);

byte b1 = rawX & 0xFF;
byte b2 = rawY & 0xFF;
byte b3 = rawZ & 0xFF;
byte b4 = (rawX & 0x0300) >> 2
          | (rawY & 0x0300) >> 4
          | (rawZ & 0x0300) >> 6;

```

The low portion of the values are saved in the bytes `b1` to `b3`. The upper 2 bits of every value is saved left-aligned to `b4` (The `& 0x0300` isolates the upper portion, bit 9 and 10, in the values.).

You can read these values in this way:

```
rawX = b1 | (( b4 & 0b11000000) << 2);
rawY = b2 | (( b4 & 0b00110000) << 4);
rawZ = b3 | (( b4 & 0b00001100) << 6);

```

`b1` to `b3` are the start for our retrieved raw values. Then we add the other 2 bits to the raw values. For this we first isolate the bits from `b4` from the positions we used in the upper code. Then we shift them to the left, until they are directly above the 8 bits of the start values.

---
Tags: analogread, sd-card, arduino-pro-mini, accelerometer, sd
---


title: Button isn't working properly

text:
# Question
Title: Button isn't working properly
I am new in arduino trying to make race game. My problem is that my button (all buttons) is working sometimes and sometimes not. I am pretty sure that it's because of my code. Could you please help me with it? Here is my code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int pausebetween = 1;
int spaceBetween = 1;
int maxElemnets = 4;
int obstacleArray[4][2];
int obstacles[4] = {3,3,2,3};
bool gameStart = false;
byte player[8] =
{
 B00000,
 B00000,
 B10100,
 B11110,
 B11111,
 B11110,
 B10100,
 B00000
};
byte obstacle[8] =
{
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111
};
byte enemy[8] =
{
 B00000,
 B00000,
 B00101,
 B01111,
 B00101,
 B00000,
 B00000
};
byte empty[8] =
{
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000
};
byte fire[8] =
{
 B00000,
 B00000,
 B00000,
 B11111,
 B00000,
 B00000,
 B00000
};
int mat[2][24] = {
  {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
  {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
  };
int up = 0;
int down = 0;
int reset=0;
int atack=0;
void setup() {
 pinMode(9, INPUT);
 pinMode(8, INPUT);
 pinMode(7, INPUT);
 pinMode(6, INPUT);
 Serial.begin(9600);
 lcd.createChar(0, player);
 lcd.createChar(1, empty);
 lcd.createChar(2, enemy);
 lcd.createChar(3, obstacle);
 lcd.createChar(4, fire);
 lcd.begin(16, 2);
}
void loop() {
  up  = digitalRead(9);
  down  = digitalRead(8);
  atack  = digitalRead(7);
  reset  = digitalRead(6);
  if(atack){
    for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(mat[j][i]==1){
              mat[j+1][i]=4;
              Serial.println(mat[j+1][i]);
            }
        }
      }
  }
  if(reset){
    clearStage();
    gameStart = true;
  }
  if(gameStart){
    generateObstacles();
    redrawGame();
    moveObstacles();
  }
  delay(1000);

 }

void generateObstacles(){
  int obscount = random(1,4);
  int types[4][2] = {{1,3},{2,1},{1,1},{2,1}} ;
  int type = random(0,4);
  for(int i = 0; i< obscount; i++){
    mat[0][16+i] = types[type][0];
    mat[1][16+i] = types[type][1];
  }
  int spacecount = random(2,5);
  pausebetween = obscount + spacecount;
}
void redrawGame(){
   for(int j = 15; j >= 0; j--){
    for(int i = 0; i < 2; i++){
      lcd.setCursor(j,i);
      lcd.write(mat[i][j]);
    }
  }
}
void clearStage(){
  for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(i!=1 && j!=1){
               mat[i][j] =1;
          }
        }
      }
}
void moveObstacles(){
   for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
           if(mat[i][j]!=0){
            mat[i][j] = mat[i][j+1];
          }else{
            mat[i][j-1]=1;
          }
          if(mat[i][j]==4){
            mat[i][j-1]=0;
            mat[i][j-2]=1;
           }
        }
      }
}

```

Scheme:

# Answer
> 0 votes
I have two suggestions.

1. Get rid of the delay(1000); in the loop and replace it with code from the BlinkWithoutDelay example that comes with the Arduino IDE: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
2. Debounce the buttons. There are several libraries on Github that simplify this, for example: https://playground.arduino.cc/Code/Bounce.

---
Tags: arduino-uno, lcd, button, potentiometer, resistor
---


# Question
Title: How can I declare global array with its length stored in EEPROM?
I am working with Arduino UNO connected with BV4612 display. I am working on a simple code that controls several water pumps. Each pump has several modes it can run in. I store these modes in an array. The number of water pumps may vary, and I'd like to store that value in EEPROM (either arduino's or display's).

When the pump count is fixed, I use fixed value, defined by macro:

```
#define     PUMP_COUNT      18      //How many pumps we have

uint8_t pumpModes[PUMP_COUNT];

void setup(){...}
void loop(){...}

```

I'd like to get rid of fixed defined value of PUMP\_COUNT, and rather load it from EEPROM, or save the new pump count into the EEPROM if needed. However, I can't declare an array if I can't read from EEPROM before setup() function like this (from address 32 for example):

```
uint8_t pumpModes[EEread(32)];

void setup(){...}
void loop(){...}

```

Is there a solution to get the value from EEPROM so I can declare global array's length with it?

Thanks.

# Answer
You can't create variable length arrays in C. That's not how C works.

Instead you have to create an array that is big enough to store the *maximum* number of pumps you want to be able to deal with.

The array "size" is then just a number in a variable obtained from wherever you like (including EEPROM).

It doesn't matter if you don't use all of the array. The rest just sits there twiddling its metaphorical thumbs.

The other option, if you are only going to define the array once at startup, or very rarely change the size, is to use `malloc()`:

```
uint8_t *pumps;
uint8_t nPumps = 0;

void setup() {
    nPumps = EEPROM.read(32);
    pumps = (uint8_t *)malloc(nPumps);
}

```

You can change the array size then with:

```
nPumps = 8; // for example
pumps = realloc(pumps, nPumps);

```

And dispose of the array with:

```
nPumps = 0;
free(pumps);

```

It's best to try not to change the array size once created, since that can make swiss cheese of your heap, and is not a friendly thing to do on a small microcontroller. If you can decide the array size once in setup and keep it the same all the time the program is running this is a safe operation. Otherwise it becomes risky.
> 1 votes

# Answer
It is possible to use a dynamically allocated array, with malloc and free.

To create such an array use:

```
uint8_t* pumpModes;

```

Somewhere in setup (preferably):

```
pumpModes = malloc(sizeof(uint8_t) * PUMP_COUNT);

```

Freeing the memory is not needed if you need it throughout the entire program, otherwise you can use

```
free(pumpModes);

```

However, take in mind that if you continuously malloc and free memory in the loop() function, you can get memory 'gaps' and you run out of memory really quickly since the Uno has only a few KB of RAM memory.
> 0 votes

---
Tags: arduino-uno, array, display, eeprom, variables
---


title: GPS(Incorrect time showing)

text:
# Question
Title: GPS(Incorrect time showing)
Anyone help? It shows incorrect time. Please help.

```
  /* Conexion pines
     Arduino        GPS
        D3           RX
        D4           TX
  */

  #include <SoftwareSerial.h>  //incluimos SoftwareSerial
  #include <TinyGPS.h>         //incluimos TinyGPS

  TinyGPS gps;  //Declaramos el objeto GPS
  SoftwareSerial serialgps(10,11);      //Declaramos el pin 4 (Tx del GPS) y 3 (Rx del GPS)

  //Declaramos la variables para la obtención de datos
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned long chars;
  unsigned short sentences, failed_checksum;

  void setup()
  {
   Serial.begin(9600);  //Iniciamos el puerto serie
   serialgps.begin(9600); //Iniciamos el puerto serie del gps

   //Imprimimos en el monitor serial:
   Serial.println("");

  }

  void loop()
  {
   while(serialgps.available())
   {
    int c = serialgps.read();
    if(gps.encode(c))
    {
     float latitude, longitude;
     gps.f_get_position(&latitude, &longitude);
     Serial.print("Latitud/Longitud: ");
     Serial.print(latitude,5);
     Serial.print(", ");
     Serial.println(longitude,5);
     gps.crack_datetime(&year,&month,&day,&hour,&minute,&second,&hundredths);
     Serial.print("Date: "); Serial.print(day, DEC); Serial.print("/");
     Serial.print(month, DEC); Serial.print("/"); Serial.print(year);
     Serial.print(" Time: "); Serial.print(hour, DEC); Serial.print(":");
     Serial.print(minute, DEC); Serial.print(":"); Serial.print(second, DEC);
     Serial.print("."); Serial.println(hundredths, DEC);
     Serial.print("Altitud (metros): "); Serial.println(gps.f_altitude());
     Serial.print("Rumbo (grados): "); Serial.println(gps.f_course());
     Serial.print("Velocidad(kmph): "); Serial.println(gps.f_speed_kmph());
     Serial.print("Satelites: "); Serial.println(gps.satellites());
     Serial.println();
     gps.stats(&chars, &sentences, &failed_checksum);

     delay(10000);
    }
   }
  }

```

# Answer
Like Majenko's comments suggested, you must shift the UTC time to your local time. The Time library can help you do this.

There are some other problems:

* You cannot wait 10 seconds without processing the characters. The Arduino receive buffer only has room for 64 characters. The GPS device could have sent 10000 characters during that time, so most of them will get dropped. This prevents the GPS library from parsing a GPS data successfully. It will eventually "see" a complete set of data, sometime after the 10 seconds. You may see data once every 11 seconds, not 10.
* You are printing the several values even though they may not be valid. For example, if you are not moving, or you do not have good satellite reception, the GPS device may not provide a speed.
* The Arduino `millis()` clock will not be synchronized with the GPS clock. You could use the GPS updates as an exact 1-second clock. Simply count 10 fixes as they arrive, and this will mean that 10 seconds have elapsed.
* You should use a different serial port and/or library. This answer describes the various choices: HardwareSerial (i.e. Serial on pins 0 & 1), AltSoftSerial (8 & 9 on an UNO) or NeoSWSerial (any two pins).

Here is a NeoGPS version of your sketch that addresses these issues:

```
#include <NeoSWSerial.h>
#include <NMEAGPS.h>

NMEAGPS gps;  //Declaramos el objeto GPS
gps_fix fix;  // all GPS fields, including date/time, location, etc.
uint8_t fixCount;
NeoSWSerial serialgps(10,11);

void setup()
{
 Serial.begin(9600);  //Iniciamos el puerto serie
 serialgps.begin(9600); //Iniciamos el puerto serie del gps

 //Imprimimos en el monitor serial:
 Serial.println( F("Test") );

}

void loop()
{
 // Check for GPS characters and parse them
 if (gps.available( serialgps ))
 {
  // Once per second, a complete GPS fix structure is ready.  Get it.
  fix = gps.read();

  // Count elapsed seconds
  fixCount++;

  if (fixCount >= 10)
  {
    fixCount = 0; // reset counter

    // adjust from UTC to local time
    if (fix.valid.time)
      adjustTime( fix.dateTime );

    printGPSdata();
  }
 }
}

void printGPSdata()
{
  Serial.print( F("Latitud/Longitud: ") );
  if (fix.valid.location) {
    Serial.print( fix.latitude(), 5 );
    Serial.print( F(", ") );
    Serial.print( fix.longitude(), 5 );
  }
  Serial.println();

  Serial.print( F("Date: ") );
  if (fix.valid.date) {
    Serial.print( fix.dateTime.date  ); Serial.print('/');
    Serial.print( fix.dateTime.month ); Serial.print('/');
    Serial.print( fix.dateTime.year  );
  }

  Serial.print( F(" Time: ") );
  if (fix.valid.time) {
    Serial.print( fix.dateTime.hours ); Serial.print(':');
    if (fix.dateTime.minutes < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.minutes); Serial.print(':');
    if (fix.dateTime.seconds < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime.seconds );
    Serial.print('.');
    if (fix.dateTime_cs < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime_cs );
  }
  Serial.println();

  Serial.print( F("Altitud (metros): ") );
  if (fix.valid.altitude)
    Serial.print( fix.altitude() );
  Serial.println();

  Serial.print( F("Rumbo (grados): ") );
  if (fix.valid.heading)
    Serial.print( fix.heading() );
  Serial.println();

  Serial.print( F("Velocidad(kmph): ") );
  if (fix.valid.speed)
    Serial.print( fix.speed_kph() );
  Serial.println();

  Serial.print( F("Satelites: ") );
  if (fix.valid.satellites)
    Serial.println( fix.satellites );
  Serial.println();
  Serial.println();
}

//--------------------------

void adjustTime( NeoGPS::time_t & dt )
{
  NeoGPS::clock_t seconds = dt; // convert date/time structure to seconds

  // Offset to the local time
  const int32_t          zone_hours  = +8L;
  const NeoGPS::clock_t  zone_offset = zone_hours * NeoGPS::SECONDS_PER_HOUR;
  seconds += zone_offset;

  dt = seconds; // convert seconds back to a date/time structure

} // adjustTime

```

If you want to try it, NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**. NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.

Even if you don't use it, there are many suggestions on the Installation and Troubleshooting pages.
> 1 votes

---
Tags: arduino-uno, gps, tinygps
---


# Question
Title: ESP8266 Wifi.setOutputPower - original/default value?
I'm working on dynamically adjusting the ESP8266 WiFi power using the following function, such that it's as low as possible, yet sufficiently reliable:

```
WiFi.setOutputPower(x)

```

I've been trying unsuccessfully to find out what the original/default value is before that function is called? There is no function WiFi.getOutputPower(). I know the range of values is 0 to 20.5, but I'm curious to know what it is initially? I guess it could depend on the particular Arduino? I have the following: ESPduino, Wemos D1R2/D1R1/D1R1 mini, NodeMCU, Yun sheild.

I plan to use iwconfig & iwlist on a Pi3 to measure the RSSI, but I'd like to know the baseline if possible.

The best similar idea is expressed in here: : How to optimise TX power for ESP8266?

Thanks in advance ;-) Geoff

# Answer
I was looking for the same answer. I found this link: https://gitlab.com/painlessMesh/painlessMesh/issues/51

Someone dug deeper into the code and found it's set to the max value on init
> 1 votes

---
Tags: esp8266, wifi
---


title: Arduino Serial Output Gone Wild!

text:
# Question
Title: Arduino Serial Output Gone Wild!
I'm having a slight problem that I'm unable to work out. I am using an arduino Uno to print an incremental, but predefined wheel circumference. This is all working beautifully except it gives a negative reading during execution, and then runs into the positive etc. Without being exact, the output is something like the following:

1.85, 3.71, 5.56, 7.41, 9.27, 11.15....

When this multiple reaches 32.00 or greater, it then counts negatively back down to zero, then positively up to 32.00 again.

I can't quite work out why this would be, so hoping that one of you guys would be able to shed some light. The code is as follows:

```
#include <Arduino.h>

int InterruptPin = 2;
int circ = 1854; //mtrs
int km = 0;

void calculate(){
    km = km + circ;
    //float temp = km / 1000;
    float temp = (float)km / (float)1000;
    Serial.println(temp);
}

void setup(){
    pinMode(InterruptPin, INPUT);
    attachInterrupt(digitalPinToInterrupt(2), calculate, RISING);
    Serial.begin(9600);
}

void loop(){

}

```

# Answer
`km` is never reset but continously incremented.

```
km = km + circ;

```

This leads to an overflow of the value after some time.

When you declare `int km;`, then `int` on an Arduino Uno is `int16_t`, it thus has a maximum positive value of `2^15 - 1 = 32767`. Since `circ` is constant `1854`, after executing the ISR a total of `CEIL(32767 / 1854) = 18` times, `km` becomes greater than that maximum positive value. Thus an integer overflow occurs which takes you back to the maximum negative value of the `int16_t`. (See https://en.wikipedia.org/wiki/Integer\_overflow)

You might want to use `uint32_t` or similiar from `stdint.h` if you want to cover a greater value range. I think however your underlying algorithm is flawed, since even then `km` *will* overflow after some later time. You must reset it at some point or only store the number of **revolutions**, which is a much smaller number. If you want to get the traveled distance then, you take the number of revolutions and multiply it by the circumference.

Also you should not not use any `Serial` printing within in interrupt service routine! And you should also declare your used interrupt variables as `volatile`. Read this article for more info.
> 4 votes

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


# Question
Title: Fail to retrieve the value from gsm sim 900A by using AT Command to PHP script
I am currently trying to establish a connection between my gsm sim900A to one of my test server. The connection seems pretty good so far, though I'm a little bit confused why there are **no values retrieved** by my php file. Even so, the insert query works although it insert empty value into the database. So my question is how to retrieve it properly? I already change the method in php script to POST, both of it doesn't return any good signs.

Arduino Code:

```
void postData()
{
  sim900a.println("AT+HTTPINIT");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPPARA=\"URL\",\"test.my/demo/writedata.php\"");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPDATA=12,10000");
  delay(1000);
  printSerialData();

  sim900a.println("strBoton=999");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPACTION=1");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPREAD");
  delay(1000);
  printSerialData();

  sim900a.println("AT+HTTPTERM");
  delay(1000);
  printSerialData();
}

```

PHP Code:

```
<?php
$servername = "test.my";
$username = "****";
$password = "****";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$Boton = $_GET["strBoton"];

$sql = "INSERT INTO test VALUES ('$Boton')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

```

Output:

```
AT+HTTPINIT
OK

AT+HTTPPARA="CID",1
OK

AT+HTTPPARA="URL","test.my/demo/writedata.php"
OK

AT+HTTPDATA=12,10000
DOWNLOAD
OK

AT+HTTPACTION=1
OK

AT+HTTPREAD
OK

AT+HTTPTERM
+CME ERROR: operation not allowed

AT+SAPBR=0,1
OK

```

# Answer
I am not sure but, in this tutorial at page 8, it does almost the same code pattern like yours. You might want to check it. Sorry but I don't know PHP, I can't help you with it.

But I am confused with AT+HTTPACTION, since AT+HTTPACTION=0 is the read and AT+HTTPACTION=1 is the post. Check the tutorial and optimize your commands.

Also check this one. It writes WAIT=6 after AT+HTTPREAD before terminating it.
> 0 votes

---
Tags: gsm
---


# Question
Title: What does the term "9g" in servo's rating mean?
I frequently see 9g mentioned in servos. I searched the web but couldn't find any worthwhile answers. At first I thought it meant 9grams but the weight of the servo isn't 9 grams, so have to be something else.

# Answer
> 10 votes
According to Flite Test web site, the 9g reference is the weight without the wire lead. They measured one model at 8 grams rounded down. I suspect the weight also ignores the horn as well as the wire.

The article referenced on the web site calls the weight reference as a standard, which means that it more likely allows for heavier or lighter servos as long as the size of the servo matches.

If you purchase a servo for a model known to use a 9g servo, you know the hole you have to build for it to fit. If you purchase a 5g servo, it will be a different hole and you may have a 6 or 7 gram weight, but the servo fits as it should.

# Answer
> 1 votes
From a model airplane perspective...

The "9g" is supposed to mean 9 grams in weight. Each vendor has their own way to define their weight.

* with wires
* without wires
* with or without control horns
* "about the same as a competitor's 9 gram servo"

Most are not accurate.

It is not a standard for size, and has nothing to do with hole size or screw spacing

# Answer
> 0 votes
According to the link it is.

However, if you look at this more detailed datasheet, it shows 14.7 g.

Probably it's the weight of the motor part itself, not the plastic enclosure around it.

Btw, most websites (without actually using data sheets), mention a weight of 9 g.

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


# Question
Title: Arduino nano ATmega328p with CH341 won't upload
When I try to upload a sketch to an Arduino Nano, it stays stuck on uploading, and after a time it shows the following error code:

* stk500\_getsync() attempt 1 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 2 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 3 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 4 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 5 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 6 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 7 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 8 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 9 of 10: not in sync: resp=0xc2
stk500\_getsync() attempt 10 of 10: not in sync: resp=0xc2

Sometimes the `resp=0xc2` variable changes to another hex code.

The weird thing here is that before this happened everything worked fine. I could upload and the serial communication was fine. But after trying to upload the same sketch with a different variable, this started to happen.

Windows recognizes the COM port, in Arduino the COM port is selected. Sometimes, without doing anything, the Arduino works fine again, I can see the serial communication fine, but after some time the serial communication stops sending and again I can't upload the sketch.

I have 2 Arduino Nanos. Both of them start presenting the same problem. But the other one has the Power, RX, and TX led always on and this one never worked again, like the other one that sometimes can upload the sketch and see the serial communication that the last sketch was sending. I have an Arduino Mega, this one has the ATmega16U2 to communicate to USB and this one works fine. And I also have a NodeMCU Lua, with CH341. But this one works just fine.

# Answer
> 2 votes
If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --\> Processor:"ATmega329P" --\> ATmega328P(Old Bootloader)

# Answer
> 0 votes
Open your device manager in computer if ot would show your arduino nano as USB 2.0 then you need to install CH340G DRIVERS from Google install it and then again connect it to the computer your problem would be solved but remember to remove TX and RX pins before uploading code...

---
Tags: arduino-nano, uploading
---


# Question
Title: How to write Arduino API code in VL53L1X?
I'm trying write code for the VL53L1X on Arduino, but I didn't get the VL53L1X registers. How to access them and how to measure the data in VL53L1X? Can anyone help me?

# Answer
He's not asking about a VL53L1X Arduino. He's asking for code to support the VL53L1X (which is an ST distance sensor) that runs on an arduino.

ST have provided a library, but it's huge with many large buffers and doesn't run on an arduino as distributed. They've also forbidden anonymous distribution of a corrected version, presumably because they don't want to make it easy to run on 16-bit processors. It might run easily on a Teensy 3.

Sparkfun have just released a library. It's much smaller but, like the Polulu library for the VL53L0X, it's full of magic numbers where they've stripped the structure out and just write the end result into the registers - so it will be difficult to get the best from the sensors.

https://github.com/sparkfun/SparkFun\_VL53L1X\_Arduino\_Library/blob/master/src/SparkFun\_VL53L1X\_Arduino\_Library.cpp

There is a good case for writing something halfway : without the overcomplicated code typical of ST's Cube environment but with a bit more content than Sparkfun's version.

It's a boring job unless you have something you need from it. Worthwhile only if you have a good case to support it on AVR. If you try to build the ST sources, look carefully at the maximum write size on I2C (135 bytes) and compile with maximum warnings enable (it will pick up several 16/32 bit wordsize errors, mostly critical).
> 1 votes

---
Tags: c++, arduino-nano, c
---


title: Use ESP8266 GPIOs after Flash Startup

text:
# Question
Title: Use ESP8266 GPIOs after Flash Startup
I'm a bit confused about the ESP8266 launching and GPIO behaviour.

When I'm programming the ESP8266 I have to set GPIO2 high and GPIO0 low. But when I want to use the ESP8266 in my project I have to set GPIO2 and GPIO0 to HIGH, but if they are both high I can't use them as inputs or outputs. So my question is how can I use atleast of the GPIO as an output and starting the ESP8266 without reprogramming it.

# Answer
> 1 votes
ESP8266 was developed for 'Serial over WiFi' as system-on-chip based on the Tensilica processor. The GPIO pins of Tensilica where used for different purposes of the system, like antena, flash memory connection, boot setup etc.

The more general use of the ep8266 as micro-controller with WiFi has evolved, but needs to accept the legacy of the original concept. Smart people even found a way how to share SPI with the flash memory of the system.

If you want to use the IO pins of the esp8266 (they are not called GPIO in datasheet), you must accept the required boot state and use only circuit, sensor or actuator that doesn't disturb it and can handle it.

io0 LOW tels the esp8266 to boot into bootloader flashing mode. It is evaluated by ROM software in the boot process. Pull-up circuit is required to achieve normal boot. So if you want to attach something to this pin, it must accept this conditions. For button it is ideal.

If you want to use io 0 or io 2 as output, use logic that is normally HIGH and make sure it is not connected direct or indirect to ground at startup.

---
Tags: programming, esp8266, pins, bootloader
---


# Question
Title: Arduino BMP085 Barometric sensor blank serial monitor
I am a beginner as far as arduino and microcontrollers are concerned. I am using a BMP085 barometric pressure sensor.I have made all the necessary connections to my arduino uno board and double checked them. What I want to do is get readings from the sensor and display them on my arduino serial monitor. The code I am using compiles and uploads without any error but when I open my serial monitor, it is blank. I tried using a humidity/temperature sensor before this and that sensor returns values to the serial monitor. The barometric sensor is new and this was my first time usage.

Here is my sketch. I took it from here. https://www.sparkfun.com/tutorials/253

Any help would be greatly appreciated.

the code

```
#include <Wire.h>

#define BMP085_ADDRESS 0x77  // I2C address of BMP085

const unsigned char OSS = 0;  // Oversampling Setting

// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;

// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;

short temperature;
long pressure;

// Use these for altitude conversions
const float p0 = 101325;     // Pressure at sea level (Pa)
float altitude;

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

void loop()
{
  temperature = bmp085GetTemperature(bmp085ReadUT());
  pressure = bmp085GetPressure(bmp085ReadUP());
  altitude = (float)44330 * (1 - pow(((float) pressure/p0), 0.190295));

  Serial.print("Temperature: ");
  Serial.print(temperature, DEC);
  Serial.println(" *0.1 deg C");
  Serial.print("Pressure: ");
  Serial.print(pressure, DEC);
  Serial.println(" Pa");
  Serial.print("Altitude: ");
  Serial.print(altitude, 2);
  Serial.println(" m");
  Serial.println();

  delay(1000);
}

// Stores all of the bmp085's calibration values into global variables
// Calibration values are required to calculate temp and pressure
// This function should be called at the beginning of the program
void bmp085Calibration()
{
  ac1 = bmp085ReadInt(0xAA);
  ac2 = bmp085ReadInt(0xAC);
  ac3 = bmp085ReadInt(0xAE);
  ac4 = bmp085ReadInt(0xB0);
  ac5 = bmp085ReadInt(0xB2);
  ac6 = bmp085ReadInt(0xB4);
  b1 = bmp085ReadInt(0xB6);
  b2 = bmp085ReadInt(0xB8);
  mb = bmp085ReadInt(0xBA);
  mc = bmp085ReadInt(0xBC);
  md = bmp085ReadInt(0xBE);
}

// Calculate temperature given ut.
// Value returned will be in units of 0.1 deg C
short bmp085GetTemperature(unsigned int ut)
{
  long x1, x2;

  x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
  x2 = ((long)mc << 11)/(x1 + md);
  b5 = x1 + x2;

  return ((b5 + 8)>>4);
}

// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up)
{
  long x1, x2, x3, b3, b6, p;
  unsigned long b4, b7;

  b6 = b5 - 4000;
  // Calculate B3
  x1 = (b2 * (b6 * b6)>>12)>>11;
  x2 = (ac2 * b6)>>11;
  x3 = x1 + x2;
  b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;

  // Calculate B4
  x1 = (ac3 * b6)>>13;
  x2 = (b1 * ((b6 * b6)>>12))>>16;
  x3 = ((x1 + x2) + 2)>>2;
  b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;

  b7 = ((unsigned long)(up - b3) * (50000>>OSS));
  if (b7 < 0x80000000)
    p = (b7<<1)/b4;
  else
    p = (b7/b4)<<1;

  x1 = (p>>8) * (p>>8);
  x1 = (x1 * 3038)>>16;
  x2 = (-7357 * p)>>16;
  p += (x1 + x2 + 3791)>>4;

  return p;
}

// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
  unsigned char data;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 1);
  while(!Wire.available())
    ;

  return Wire.read();
}

// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
  unsigned char msb, lsb;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 2);
  while(Wire.available()<2)
    ;
  msb = Wire.read();
  lsb = Wire.read();

  return (int) msb<<8 | lsb;
}

// Read the uncompensated temperature value
unsigned int bmp085ReadUT()
{
  unsigned int ut;

  // Write 0x2E into Register 0xF4
  // This requests a temperature reading
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x2E);
  Wire.endTransmission();

  // Wait at least 4.5ms
  delay(5);

  // Read two bytes from registers 0xF6 and 0xF7
  ut = bmp085ReadInt(0xF6);
  return ut;
}

// Read the uncompensated pressure value
unsigned long bmp085ReadUP()
{
  unsigned char msb, lsb, xlsb;
  unsigned long up = 0;

  // Write 0x34+(OSS<<6) into register 0xF4
  // Request a pressure reading w/ oversampling setting
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x34 + (OSS<<6));
  Wire.endTransmission();

  // Wait for conversion, delay time dependent on OSS
  delay(2 + (3<<OSS));

  // Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF6);
  Wire.endTransmission();
  Wire.requestFrom(BMP085_ADDRESS, 3);

  // Wait for data to become available
  while(Wire.available() < 3)
    ;
  msb = Wire.read();
  lsb = Wire.read();
  xlsb = Wire.read();

  up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);

  return up;
}

```

wirings: https://i.stack.imgur.com/oRX0V.jpg

# Answer
> 1 votes
There are several versions of breakout boards for the BMP085. The device itself is 3v3. Some breakouts provide a regulator so you can supply 5V. Some also perform level-shifting so you can drive the I2C lines at 5V and work correctly with the sensor's 3v3 levels.

It isn't clear which type you have there, but you seem to be powering it from 3v3 on the arduino. A photo of the other side of the sensor board would help.

If the sensor has a regulator, sourcing it from 3v3 will drop it a little (the regulator needs some overhead). This might mean the sensor is running at too low a voltage.

If the board has no regulator, then it's correct to power it from 3v3. However, the I2C lines also need conversion. You will be driving 5V into a 3v3 input, which can damage it. You will also be receiving 3v3 levels from the sensor into the 5V arduino, which will probably work but might not.

Ideally, put level shifters in between. They need to be bidirectional, like these : https://www.adafruit.com/product/757

In some cases you can get away with resistors only, but not easily on the bidirectional I2C bus. SPI is easier as the pins are unidirectional.

---
Tags: arduino-uno
---


# Question
Title: Problem for control speed of a DC motor with a L298N
*(Not native english speaker here, feel free to edit my sentences)*

I try to control the speed of a DC motor with a L298N shield but it doesn't work very well. Here is my scheme :

The power comes from a transfo with an adjustable voltage of ~7v 1.0 Amp. I don't care about the sens of rotation, so I set `IN1` to 5v and `IN2` to the ground, is it right to do it like that ?

Now here is the code I'm using :

```
#define CONTROL_M   9  // To Enable input

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

void loop ()
{
    test_analog_motor();
}

void test_analog_motor()
{
    for (int i; i < 250; i=i+25)
    {
        Serial.println(i);
        analogWrite(CONTROL_M, i); // Any value between 0 and 255
        delay(500);
    }
}

```

With that code, the speed of my motor should progressively increase and then goes back to 0. I'm aware that, maybe if the value is too low, the motor will have trouble to start so I "help" it manually.

If I doesn't use the Enable output of my Arduino and just use the jumper instead, the motor turns with a good torque. This prooves at least that my shield isn't damaged.

Now here is the problem I have : With the scheme I've shown above, it simply doesn't work, nothing happens when I set the grounds in common, why ? Then if I remove the cable that goes to the arduino ground, it works but the motor has a very low torque, it seems also that there is a kind of latency in regards to what display the Serial monitor.

I feel a bit stupid with what I did with the grounds, it seems wrong t me but I don't know what to do instead :/ What can I do ? My goal is to have the best possible control of the speed of that DC motor in term of reactivity, does a L298N is suited for that ?

**EDIT** I did tested the PWM with an oscilloscope and a multimeter, the arduino PIN I was using worked correctly. I don't know why but now, the shield works too, I mean : Problem solved. One theory is that I adjusted the tension of my power supply under 5V. In that cas the shield doesn't nothing Arduino is magic sometimes...

# Answer
> 3 votes
You do need the ground wire. The reason it 'works' without it is that enable input effectively then has an aerial connected and is responding in the same was as if you touch the input jack on an amplifier and hear a buzzing sound.

There is a link behind the blue connectors that enables the onboard 5v regulator. I assume you have this fitted, or it wouldn't work with the jumper as you describe.

There is a tutorial here : http://www.instructables.com/id/How-to-use-the-L298-Motor-Driver-Module-Arduino-Tu/

I can't see anything different from what you're doing that would cause it to fail, but perhaps you have a problem with pin 9 from your board - you might have damaged it by misconnection, as certain ways of wiring that schematic could put 12V on the arduino pin. You could also try using pin 13 : the arduino LED should then be lit in sympathy with the PWM signal and you'll know it's working.

---
Tags: arduino-uno, motor, arduino-motor-shield
---


# Question
Title: Need library help for Arduino USB host shield
Recently Purchased a "TOOGOO(R) T45 USB Host Shield" from Amazon. I attempted to use the "USB Host Shield Library" from Github, but It seems like it might not support this particular shield.

I would really like to learn how to use this shield to interact with my joystick but the only tutorial information I have found to help me with this is from Circuits@home and they seem to be using a specific shield in their development of the code library.

Can anyone point me to a tutorial or Github library that can help me learn to work with this setup?

I'm using an Arduino Uno and a Thrustmaster USB joystick.

Thanks in advance.

UPDATE\*

I fixed the initial problem of accessing the HIDDESC report. I now have the report, but the formatting of the report is particularly hard to understand. Using the Circuits@home articles I'm a little lost on how to read the report data I was given. It does not seem to be formatted in the same way as the example. Can anyone help with interpreting my device report?

> Start
> 0000: 05 01 09 04 A1 01 09 01 A1 00 09 30 09 31 09 32
> 0010: 09 BB 15 80 25 7F 46 FF 00 66 00 00 66 00 00 75
> 0020: 08 95 04 81 02 C0 09 39 15 01 25 08 35 00 46 3B
> 0030: 01 65 14 75 04 95 01 81 02 05 09 19 01 29 04 15
> 0040: 00 25 01 75 01 95 04 81 02 95 08 81 01 05 08 09
> 0050: 43 15 00 26 FF 00 35 00 46 FF 00 75 08 95 04 91
> 0060: 82 55 00 65 00 55 00 65 00 55 00 C0
> Usage Page Gen Desktop Ctrls(01)
> Usage Game Pad
> Collection Application
> Usage Pointer
> Collection Physical
> Usage X
> Usage Y
> Usage Z
> Usage Undef
> Logical Min(80)
> Logical Max(7F)
> Physical Max(FF00)
> Unit(0000)
> Unit(0000)
> Report Size(08)
> Report Count(04)
> Input(00000010)
> End Collection
> Usage Hat Switch
> Logical Min(01)
> Logical Max(08)
> Physical Min(00)
> Physical Max(3B01)
> Unit(14)
> Report Size(04)
> Report Count(01)
> Input(00000010)
> Usage Page Button(09)
> Usage Min(01)
> Usage Max(04)
> Logical Min(00)
> Logical Max(01)
> Report Size(01)
> Report Count(04)
> Input(00000010)
> Report Count(08)
> Input(00000001)
> Usage Page LEDs(08)
> Usage Slow Blk On Time
> Logical Min(00)
> Logical Max(FF00)
> Physical Min(00)
> Physical Max(FF00)
> Report Size(08)
> Report Count(04)
> Output(10000010)
> Unit Exp(00)
> Unit(00)
> Unit Exp(00)
> Unit(00)
> Unit Exp(00)
> End Collection Game Pad Pointer X Y Z Undef(00)(00)(7F)(00)
> Hat Switch(00)
> Btn0001
> (00) Btn0002
> (00) Btn0003
> (00) Btn0004
> (00)
> (00)(00)(00)(00)(00)(00)(00)(00)
> Slow Blk On Time

# Answer
The photos on Amazon show a clone of the circuit@home board so the same library should work. You may be running into the problem mentioned in the following page.

https://esp8266-notes.blogspot.com/2017/08/defective-arduino-usb-host-shield-boards.html
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to re-solder the resistor in order to reprogram the Atmega8U2
As I see here I need to reprogram the ATMEGA8u2: https://www.arduino.cc/en/Hacking/DFUProgramming8U2 I need to solder a 10k resistor into a specific place.

In a previous attempt I did that and resulted the following marks:

So How I can resolder the resistor in order to reprogram the atmega8u2?

# Answer
Looks like you ripped a pad off. To prevent that in the future, try using more flux and dropping the temp (Max around 320\*C/610\*F). The iron shouldn't be in contact with the board for more than about 3 seconds. No force should be necessary to remove components.

Not to worry though. Common beginner's mistake and not too hard to fix.

To prep this for repair:

* Gently clean the area up with 91% isopropyl alcohol and cotton swabs.
* Carefully scrape away the solder mask (blue paint) on what's left of the copper trace all the way back to the via (little hole). Try to remove all the solder mask from the via. Straighten and flatten the pulled up trace.
* Clean, flux, and tin (apply as thin layer of solder) to the trace and remaining pad. Filling in the via is OK as it will give better surface area to attach the repair.
* Flux and solder the resistor to the remaining pad to keep it in place and properly aligned for the repair.

To repair the damage:

* We need to bridge the gap created by the damaged pad. A globby solder bridge may work, but wire is much better.
* Find a piece of thin gauge solid core wire (30-22AWG. Some 24AWG from an ethernet cable would do fine).
* Orient the wire so that it's directly over the remaining trace and also making contact with that end of the resistor.
* You can trim it to size now or after soldering. It may be easier to keep in place if you trim it after soldering as long as you have some fine flush cut pliers. Either way, leave enough that it covers the entire cleaned and tinned portion of the trace.
* Flux and solder the wire to both the resistor and trace. This will complete the circuit.
* Clean again with alcohol. Let dry. Test the board.

Give this Adafruit article a read. I've got extensive professional soldering training and endorse it fully as the best beginners soldering guide I've found.
> 2 votes

# Answer
That pad connects to the same place as the circuit used for resetting the ATMega328P chip - that is, pin D7 on the ATMega8U2.

It just pulls the pin PD7 down to ground with more "force" than the internal pullup of the pin itself.

You can attach that resistor to anywhere along that line, and probably the most convenient place would be to the ATMega16U2 side of capacitor C5.

That capacitor has one end linked to the RESET pin on the main Arduino header, so you can connect a DMM in continuity test to that pin and "buzz out" each capacitor until you find the one point where it beeps (I think it's one that's right next to "Reset EN").

*Carefully* solder your resistor to the *opposite* side of the capacitor to the side that beeps (the side nearest the ATMega8U2 chip, probably), and connect the other end of the resistor to GND on one of the main headers.

By the way - get yourself a flux pen and apply flux to where you are soldering *before* you start soldering. It should help you avoid these kind of problems in the future. Also get a proper temperature controlled soldering iron (I use 350C for mine most of the time) and some solder wick to help recover from solder messes. All part of the standard EE's toolkit.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Nano ATmega328P bootloader difference
There are two ATmega328P bootloaders, old and current. What is the difference between these bootloaders?

I'm aware that Nanos sold by Arduino use the new bootloaders but I haven't been able to find any release notes about the bootloader.

# Answer
The bootloader currently shipped on the official Arduino Nano boards and selected via the Arduino IDE's **Tools \> Processor \> ATmega328P** after choosing **Tools \> Board \> Arduino Nano** is the same version of optiboot used by the Arduino/Genuino Uno: https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L152

```
nano.menu.cpu.atmega328.bootloader.file=optiboot/optiboot_atmega328.hex

```

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L72

```
uno.bootloader.file=optiboot/optiboot_atmega328.hex

```

The bootloader selected via **Tools \> Processor \> ATmega328P (Old Bootloader)** is the "ATmegaBOOT" bootloader.

As used by the Nano hardware definition, there are two significant differences between the two bootloaders:

1. Optiboot will not go into an endless reset loop after a watchdog reset. ATmegaBOOT will.
2. Optiboot expects the upload communication at 115200 baud. ATmegaBOOT, 57600. This is the reason why the old boards don't work with the **Tools \> Processor \> ATmega328P** selection and vice versa.

There is another very significant difference between the two bootloaders that, sadly, you will not benefit from with the new Arduino Nano board/hardware definition: Optiboot will fit in a 0.5 kB boot section, while ATmegaBOOT requires a 2 kB boot section. Unfortunately Arduino forgot to change the BOOTSZ fuse accordingly and so the opportunity to free up 1.5 kB of precious flash memory for the users of the Nano was lost. The willingness of Arduino to knowingly release flawed hardware has historic precedent.

> I haven't been able to find any release notes about the bootloader.

Arduino's release notes have not yet adapted to the fact that hardware packages may be released independently of IDE releases ever since Arduino IDE 1.6.2. There is a note about the bootloader change in the IDE release notes for the next IDE release:

https://github.com/arduino/Arduino/commit/ec179e5af67b7f1eeb5e46d22034798f8b24b7cb

Other than that, you can consult the commit history:

https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f
> 18 votes

---
Tags: bootloader
---


# Question
Title: How to fix Arduino restarting when two servos are powered by an external power?
Can anyone help me fix this? It always restarts when I power the servos with an external battery. I connected one battery to Arduino and one battery to servos, each 5V, but my Arduino keeps restarting.

# Answer
> 1 votes
You will need to fix this on your own but I can suggest some things that you will likely need to investigate.

1. Evaluate what exactly causes the AVR to get reset. It is highly likely that long wires and current surges as loads are applied is causing either the GND or the VCC to the AVR to be compromised and initiating a brown out reset in the MCU.
2. Driving inductive loads without proper design may be putting high voltage spikes into your design that create havoc with proper software execution and/or risking serious damage to the silicon components. Make sure you take steps to eliminating such with clamp diodes, filter caps or zener diodes.
3. You will have to check your exact MCU data sheet but many parts have a reset reason register that your software can read to see what particular thing initiated the reset.
4. Lastly the most important thing is to make sure you have the proper tools for debugging problems like this. It is very common that you should have access to an oscilloscope so you can find the problems and learn how to fix them. The best way to learn how to design in a way that you avoid problems like this on the next project is to see first hand what went wrong and learn from it.

# Answer
> 0 votes
The reason here is, you are not able to provide enough current required for the servo. There are multiple ways to work around.

1. Change the code: Just try to rotate only one servo at a time. Rotate the second servo after servo1 finished rotation.
2. Use a 9V battery and connect it to the power socket of arduino \[this could solve the issue if you are using normal servos\]
3. Use separate power supplies for servo and Arduino. Use two different 5V supplies to power servo and arduino. Please don't forget to connect the grounds of both supplies together.

---
Tags: servo
---


# Question
Title: Cannot connect to mBot after using Arduino IDE
Today I bought an mBot (from Makeblock) the one that uses 2.4G serial connection. After assembling it, I connected to it using mBlock (software based of Scratch) and I could control it using keyboard triggers. Then I went in Arduino IDE and used it to run some scripts on the mBot.

Next I tried to switch back to mBlock software, but now it cannot connect to the mBot anymore. Whatever Scratch-like scrips I build, they don't run anymore in mBlock.

Did I miss anything? Is there anything I can do so I can start using mBlock again?

# Answer
I received some really good piece of advice on the official forum and it solved my problem, it now works:

> When you go back to using the mBlock (Scratch) environment you will need to reload the firmware (Upgrade firmware from the Connect menu item). At least that’s what I’ve had to do. Oh, and make sure that you have shut down the Arduino environment to release the serial port.
> 2 votes

---
Tags: arduino-ide, mbot
---


# Question
Title: How to test if PWM mode is working correcly?
I d'like to test if the PWM mode is working correctly on the pins of my Arduino Board. Do you know a simple schema to do this ?

# Answer
There are my options:

* The default way to do this is to use an oscilloscope. These can be quite expensive.
* Use a logic analyzer if the voltage is logic/binary (0 and 3.3 or 5V). These are very cheap.
* The easiest way to know if it works without the devices above, is to lower the speed drastically (using a divider in the software, like 1000 or more to get PWM widths of 100 ms to multiple seconds) and connect the PWM output with a resistor and a LED to GND. If the LED flashes faster, the PWM speed is high, otherwise low. By using a stopwatch you can roughly calculate the PWM speed (taking the divider into account) and after the test remove the divider.
* If the PWM is controlled completely from your Arduino (probably not), you can use a software counter and print it out afterwards to see the speed.
> 1 votes

# Answer
You could just do a simple analogWrite, varying the duty cycle, with an LED/resistor. Fade the value up & down, see if the LED gets brighter & dimmer.
> 0 votes

---
Tags: pwm, testing
---


title: Use external power - nodemcu 0.9

text:
# Question
Title: Use external power - nodemcu 0.9
I'd like to deploy my project so I'm looking for a way to power the nodemcu. I'd like to know if there's a way to power it with a 9V battery **without any other external circuit**.

Until now I've found information for the nodemcu 1.0 and it supports up to 20V on the VIN port. Here's the article I read: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

I'd like to use the two port: 5V and GND but I'm not sure, here there is no VIN port and I'd prefer to not burn my board. Are there any better way to power my project?

# Answer
> 1 votes
It looks like the 0.9 uses the SPX3819 regulator. That can run with up to 16V on the input, so 9V on the 5V pin (*as long as USB never gets connected*) should work fine.

**Except:** 9V PP3 batteries are useless. If it can even provide enough power to run the board (which is doubtful) it won't last more than a few hours. You would have to ensure that you use *very very* deep sleep mode to get any semblence of longevity out of it.

The 3.3V regulator will be throwing away half to two-thirds of the power as heat. So wasteful. You would be better off investing in a 3.3V switch-mode ("buck") regulator circuit (cheap on eBay) to directly power the 3.3V pin of the board instead of 9V into the on-board regulator.

---
Tags: nodemcu, battery
---


# Question
Title: USB Device not recognized (error 43, arduino uno)
I know that there's already post about this, but mine is different. Instead of not recognized, it gets recognized, and I can upload codes, but after a while, windows starts to not recognize it. And there is a temporary fix for this for my laptop, I need to restart. And even after restarting, it still becomes not recognized after a while

Edit : forgot to mention, even if it is not recognized, it still sends power to the arduino

# Answer
The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE\_1.8.10.0\_x86\__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND both pins can be found on ICSP2 of the UNO. This will surely solve the issue. But, if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.
> -1 votes

---
Tags: arduino-uno, usb
---


title: Adding music to loop

text:
# Question
Title: Adding music to loop
Im newbie. I just wanted to ask how can i put my tmrpcm.play into loop. Im trying to put it in a loop but the problem is it didn't play. I also try adding a method and call the method into the loop but it give me the same problem also. It will just only play in the void setup.

Here's my code.

```
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup(){
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

tmrpcm.setVolume(5);
tmrpcm.play("Yeah.wav");
}

void loop(){  }

```

# Answer
The library has a built in loop function:

```
audio.loop(1);             0 or 1. Can be changed during playback
                           for full control of looping.

```

See WIKI page of the library.

Btw, it is unclear if you mean by 'a loop' a while(true) loop or the void loop() function. Although it should not make a difference.
> 1 votes

# Answer
The TMRpcm library is *non-blocking*. That means, when you start playing it keeps playing in the background. If you put the play function in a loop it will just keep restarting what you are playing over and over again and you won't get to hear anything.

As Michel says, you can get it to loop automatically (`tmrpcm.loop(1);`), in which case you just leave it in `setup()` and leave `loop()` empty.

If you want to do it manually you should check to see if the sound has finished playing or not. The simplest way is:

```
loop() {
    if (!tmrpcm.isPlaying()) {
        tmrpcm.play("Yeah.wav");
    }
}

```

That is - if it's *not* playing then start it playing. When it finishes it'll not be playing any more, so it will start playing again.
> 1 votes

---
Tags: arduino-uno, sd
---


# Question
Title: I am new to arduino please help me in understanding this code
```
while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

```

Why we require **char c** and what is the use of using this command **Serial.write(c)**

# Answer
> 1 votes
`client.read()` returns exactly one byte from the serial input buffer for the port connected with object `client`. That is why you use a `char` variable. The name `c` is not relevant.

The next line, `Serial.write(c)` then writes that same character to the main serial port.

The code basically reads from one serial port and writes the same data immediately to the other serial port.

# Answer
> 0 votes
What you have there is simple "Serial pass-thru" code. Whatever a client receives gets printed on the serial terminal.

It can be written, line by line, in English like this:

```
- While the client is connected:
    - If there is some text available in the client:
        - Read one character from the client and store it in the
              variable "c" which is of "char" type.
        - Print that character out to the serial port.

```

The reason you use `Serial.write(c);` is so that you can see what has been received.

---
Tags: ethernet-shield
---


title: Burning a Uno bootloader into a Nano

text:
# Question
Title: Burning a Uno bootloader into a Nano
I bought some cheap Arduino Nanos from ebay, but the watchdog does not work in them.

So I removed their old bootloader and burnt a new Nano bootloader from the Arduino IDE. Same problem, the watchdog didn't work.

Then, I burned a Uno bootloader to the Arduino Nano and now the watchdog works properly. The only issue here is that in Arduino IDE I now have to tell it that I am programming an Arduino Uno instead of a Nano. So far everything seems to work just fine.

Are there other problems that may arise from using a Uno bootloader in a Nano? I notice that there are some extra analog pins in Arduino Nano, but I will still be able to use them with the Arduino Uno bootloader right?

# Answer
Assuming they're based on the more recent Arduino Nano 3.x series or later, the microcontroller in your Nanos is probably an ATmega328 running at 16 MHz. That's the same as the Uno, so there should be no major problems hopefully.

It might be worth checking that you've got the latest version of the Arduino IDE though. I seem to remember there was a problem in some older bootloaders which prevented the watchdog from working properly.
> 2 votes

# Answer
In boards.txt in the Uno section, you change one line for the pinout type from uno.standard to all\_pins or something like that to make the analog inputs A6 & A7 available. Compare the standard Nano line against the Uno line and you can see the difference. I can't access the Arduino files from here to say what they are specifically, sorry.

Ok, here we go:

Uno uno.build.variant=standard

Nano nano.build.variant=eightanaloginputs

So change the Uno line to uno.build.variant=eightanaloginputs

Then you can bootlood the Nano board with Uno bootloader and should have A6, A7 available without issue.
> -1 votes

---
Tags: arduino-uno, bootloader, arduino-nano, isp
---


# Question
Title: MQTT not working on ESP8266 (Nodemcu 0.9)
I'm trying to use NodeMCU on my **ESP8266** (NodeMCU 0.9) but the board **keep crashing** and I don't understand why.

I **tested** the **mqtt broker** using command line and it **works** perfectly, so I can suppose that the problem is not the server.

I was following this guide but it doesn't seem to work with me.

Here's the code I wrote:

Previously:

```
#include <PubSubClient.h>
#define MQTT_SERVER    "1.2.3.4"
#define MQTT_PORT      1883
#define MQTT_USER     "user"
#define MQTT_PSW      "psw"
...
WiFiClient client;

```

Then:

```
PubSubClient clientMqtt(MQTT_SERVER, MQTT_PORT, this->client);
//Try mqtt connection
while (!clientMqtt.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(clientMqtt.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
}

//Try send message
clientMqtt.publish("bin", "test", true);

```

The code works correcty until `clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW)` where at the first/second attempt crashes.

This is the output:

```
Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...

Soft WDT reset

ctx: cont
sp: 3ffefa90 end: 3ffefe30 offset: 01b0

>>>stack>>>
3ffefc40:  3ffe897d 40202c5d 3ffefcc4 40202dab
3ffefc50:  3ffe89b7 3ffefcc0 3ffefcc4 40203cdc
3ffefc60:  514d0400 00045454 3ffe89a7 40204cdc
3ffefc70:  3ffe89c0 3ffe89a9 00000000 3ffe88fa
3ffefc80:  3ffeeb70 3ffefdb0 3ffeedd8 3ffe88fa

```

# Answer
The `Soft WDT reset` means that the software watchdog timer reset. Depending on the version of Arduino core to the ESP8266 using `delay()` can cause this to happen, though current versions handle this better, and using `delay()` does not cause problems. Make sure you are up-to-date with the Board Manager definitions for ESP8266-based projects.

This page has lots of information on the watchdog timers and especially notes how to use a tool called ESP8266/ESP32 Exception Stack Trace Decoder to determine exactly what line in your code caused the reset to happen.

This page notes that the PubSubClient library can cause problems with the watchdog feeding and gives examples of some alternative `yield()` and `delay()` functions you can include and call instead of the built-in versions, which help alleviate resets when using PubSub on ESP8266.

The software watchdog timeout is on the order of 3 seconds, so you can also try reducing your `delay(5000)` to something shorter, like `delay(1000)` while debugging, to rule out the 3-second WDT reset due to the `delay()` call.

Your output also indicates status `-2` to the `state()` function. The documentation for PubSubClient notes that this means "the network connection failed". So one other thing to check is that your device actually connects to the WiFi network and that the MQTT server is listening on the IP address and port you specify.
> 4 votes

---
Tags: esp8266, arduino-ide, nodemcu, mqtt
---


# Question
Title: Send events to Azure IoT Hub combined with deep sleep mode
I use a Node MCU ESP8266. I have a working C app sending temperature and humidity sensor data to Azure IoT Hub continuously. I see events/messages coming in at Azure.

Now I'd like the app to only send data every minute or so. So I implemented a deep sleep scenario. The problem is my messages are queued but not sent.

My suspicion is that the IoTHubClient\_LL\_DoWork() does not send the data immediately before the device is going into deep sleep. But I don't know enough about C or the AzureIoT SDK. Here is my code:

```
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <WiFiUdp.h>

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>

#include <AzureIoTHub.h>
#include <AzureIoTProtocol_MQTT.h>

#include <ArduinoJson.h>

#define IOT_CONFIG_CONNECTION_STRING "CONNSTRING"

#define DEVICE_ID "NodeMcu"

#define WIFI_SSID "SSID"
#define WIFI_PW "PW"

#define MESSAGE_MAX_LEN 256

static bool messagePending = false;
static bool messageSending = true;

static int messageCount = 1;

static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle;

void setup()
{
    delay(1000);

    Serial.begin(115200);

    connect();
    initTime();

    iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(IOT_CONFIG_CONNECTION_STRING, MQTT_Protocol);
    if (iotHubClientHandle == NULL)
    {
        Serial.println("Failed on IoTHubClient_CreateFromConnectionString.");
        while (1);
    }

    //IoTHubClient_LL_SetOption(iotHubClientHandle, "product_info", "HappyPath_AdafruitFeatherHuzzah-C");
    //IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL);
    //IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, deviceMethodCallback, NULL);
    //IoTHubClient_LL_SetDeviceTwinCallback(iotHubClientHandle, twinCallback, NULL);
}

void loop()
{
    if (!messagePending && messageSending)
    {
        char messagePayload[MESSAGE_MAX_LEN];
        readMessage(messageCount, messagePayload);
        sendMessage(iotHubClientHandle, messagePayload);
        messageCount++;
        delay(5000);
    }

    IoTHubClient_LL_DoWork(iotHubClientHandle);
    delay(10);
}

void connect()
{
    delay(10);

    if (WiFi.status() == WL_CONNECTED)
    {
        Serial.println("Already connected...");
        return;
    }

    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(WIFI_SSID);

    WiFi.begin(WIFI_SSID, WIFI_PW);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
}

void initTime() {
    time_t epochTime;

    configTime(0, 0, "pool.ntp.org", "time.nist.gov");

    while (true) {
        epochTime = time(NULL);

        if (epochTime == 0) {
            Serial.println("Fetching NTP epoch time failed! Waiting 2 seconds to retry.");
            delay(2000);
        } else {
            Serial.print("Fetched NTP epoch time is: ");
            Serial.println(epochTime);
            break;
        }
    }
}

void readMessage(int messageId, char *payload)
{
    float temperature = readTemperature();
    float humidity = readHumidity();
    StaticJsonBuffer<MESSAGE_MAX_LEN> jsonBuffer;
    JsonObject &root = jsonBuffer.createObject();
    root["deviceId"] = DEVICE_ID;
    root["messageId"] = messageId;

    // NAN is not the valid json, change it to NULL
    if (std::isnan(temperature))
    {
        root["temperature"] = NULL;
    }
    else
    {
        root["temperature"] = temperature;
    }

    if (std::isnan(humidity))
    {
        root["humidity"] = NULL;
    }
    else
    {
        root["humidity"] = humidity;
    }

    root.printTo(payload, MESSAGE_MAX_LEN);
}

float readTemperature()
{
    return random(20, 30);
}

float readHumidity()
{
    return random(30, 40);
}

static void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char *buffer)
{
    IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char *)buffer, strlen(buffer));
    if (messageHandle == NULL)
    {
        Serial.println("Unable to create a new IoTHubMessage.");
    }
    else
    {
        //MAP_HANDLE properties = IoTHubMessage_Properties(messageHandle);
        //Map_Add(properties, "temperatureAlert", temperatureAlert ? "true" : "false");
        Serial.printf("Sending message: %s.\r\n", buffer);
        if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, NULL) != IOTHUB_CLIENT_OK)
        {
            Serial.println("Failed to hand over the message to IoTHubClient.");
        }
        else
        {
            messagePending = true;
            Serial.println("IoTHubClient accepted the message for delivery.");
        }

        IoTHubMessage_Destroy(messageHandle);
    }
}

static void sendCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback)
{
    if (IOTHUB_CLIENT_CONFIRMATION_OK == result)
    {
        Serial.println("Message sent to Azure IoT Hub");
    }
    else
    {
        Serial.println("Failed to send message to Azure IoT Hub");
    }
    messagePending = false;
}

```

# Answer
You need to call IoTHubClient\_LL\_DoWork until all messages are processed and only after that you can go to sleep.

Check the following code:

```
void IoTHubFullSendReceive()
{
  IOTHUB_CLIENT_STATUS Status;

  while ((IoTHubClient_LL_GetSendStatus(IoTHubClientHandle, &Status) == IOTHUB_CLIENT_OK) && (Status == IOTHUB_CLIENT_SEND_STATUS_BUSY))
  {
      IoTHubClient_LL_DoWork(IoTHubClientHandle);
      ThreadAPI_Sleep(50);
  }
}

```
> 2 votes

---
Tags: esp8266, c, sleep
---


# Question
Title: Controlling multiple 24V solenoids with Arduino
I'm building a pump for which I need 4 medium strength solenoids (20-50N). 24V is probably the minimum I will need to put through them, but this is something I need to test, once I've got them working. At 24V they draw 400mA.

I've found various posts with very useful info, especially https://playground.arduino.cc/Learning/SolenoidTutorial and https://forum.arduino.cc/index.php?topic=417030.0

Will the attached sketch below work for one? If so what resistance should R1 be? And if so can you see any problems with hooking up 4 working at different intervals?

The power supply is an LRS-350-24RS, and the Mosfet has a max gate source voltage of 35V. The 5v-24v optocoupler is off ebay - https://www.ebay.co.uk/itm/152904980799

Many thanks for your help!!

# Answer
> 2 votes
No, it won't:

* The diode D1 is backwards.
* The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch. However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab

R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much. R2 is a resistor just like you use for any LED with an Arduino. D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)

To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage *VGS* is below 4V):

simulate this circuit

# Answer
> -1 votes
The MOSFET, to be driven from Arduino directly, needs to have a Logic Level gate. I've been using AOD514. Logic level gate, Low Rds, rated for 30V. https://www.digikey.com/product-detail/en/alpha-omega-semiconductor-inc/AOD514/785-1357-1-ND/3060919 SMD only, they seem to have cancelled their thru-hole line of parts that I used to use. I have up to 32 of them on a board with the gates driven by 74HC595 shift registers for driving 1A loads (only limited by trace widths, not the transistors), with diodes added at the coil if needed. http://www.crossroadsfencing.com/BobuinoRev17/

---
Tags: arduino-uno, mosfet, inductive
---