title: Unable to upload code on Arduino Nano

text:
# Question
Title: Unable to upload code on Arduino Nano
My Arduino Nano v3.0 (made by Gravitech US) is behaving in an unexpected manner. Whenever I try to upload a simple Blink program on the board it always give error which is shown below.

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x01
...

```

I have another Nano (a Clone) and an Arduino UNO, both of which work perfectly using the same USB cable and PC.

History: When I used this Nano (original) for the first time, it was having some issue related to the FTDI chip. The FTDI USB was locking up on power up. I referred an answer from Arduino Nano 3.0: FTDI USB locks up on power up. I shorted the pin no. 26 (TEST) and 25 (AGND) on the FTDI chip, and then I was able to use it. I uploaded the Blink program and tested it, which was working fine.

Now, at present (three years later), when I try to upload even a simple Blink example sketch on it, it never succeeds, and gives me the above mentioned error.

I also tried holding the reset button and releasing it when it shows

> Uploading...

Another Issue: Sometimes when I just check the continuity on my Arduino Nano just to confirm whether the hardware is okay or not, it gives me unexpected results. On checking, the Pins RST and GND get shorted sometimes. And sometimes even VCC, RST and GND get shorted. I also checked the small reset switch on board, and it is working fine.

I contacted Gravitech, but they aren't responding.

What can be the issue with my arduino Nano? I haven't used it yet in any of my project. Just the Blink program that I uploaded 3 years ago on it, was the last time I saw it working.

Any help would be greatly appreciated.

# Answer
> 1 votes
Select Tools\>Processor\>ATmega328p(old bootloader)

I was having the same problem. The default uploaded sketch was causing the problem. The code was reading one of the analog pins and throwing the value via serial port and causing the problem. Changing to old bootloader fixed it for me

---
Tags: arduino-uno, arduino-ide, arduino-nano, ftdi
---


# Question
Title: Does the Arduino pro-micro 3.3v use an 8MHz crystal or a 16MHz crystal with a clock divisor of 2?
I am trying to convert some 5v Leonardo-compatible boards to run at a lower 3-3.7v voltage, so that I can power my project using LiPo batteries.

As far as I can tell, the default Leonardo settings (and pro-micro settings) will not run at this voltage. When I power the boards (which expect 5v) from a lithium battery, typically the system does not start at all. My two theories are that either the 16 Mhz xtal oscillator does not start resonating, or that the brown-out detection of the boards precludes booting at the lower voltage.

I would like to modify the boards to run on lower power. Since the pro-micro exists in a 3.3v variant, I presume there is some way to get the Atmega32u4 chip working at lower voltages. I have reviewed the Atmega32u4 datasheet and schematics from sparkfun, as well as examined the fuse bit differences between the 3.3v and 5v versions of the pro micro. As far as I can tell, the only difference in configuration is the brown-out detection. The clock source settings are configured for a crystal between 8Mhz and 16Mhz, so this could be the same for both boards.

I wasn't quite able to understand the build system for the Catarina bootloader, which might give hints as to how the clock is handled. It seems like both the 3.3v and 5v boards bootloaders are built from the same source, but with a different "CPU frequency" variable. However, there are quite substantial differences in the .hex file outputs and I wondering if there is something fancier going on.

As far as I can tell, it's possible to get an 8MHz clock on the Atmega32u4 either by using a 16MHz xtal with a clock divisor of 2, or using an 8MHz xtal with a clock divisor of 1.

Since the pro-micro 3.3v is the "mainstream" supported board using the Atmega32u4 at a lower voltage, I would like to configure my project to be compatible. Which means I need to build in a compatible clock source, if possible.

Does anyone know more details of the pro-micro 3.3v/8Mhz configuration that might help clarify how to set this up?

# Answer
> 2 votes
On the schematic of the Sparkfun Pro Micro 3.3V/8 Mhz (here) a resonator of 16 MHz is drawn. But also is stated there: "Board is marked with combination of resonator frequency and regulator voltage". From this you can deduct that the 3.3V/8MHz and the 5V/16MHz versions don't have the same resonator and that the 3.3V/8MHz version most probably has a 8MHz resonator.

---
Tags: arduino-pro-micro, atmega32u4
---


# Question
Title: Methodology for designing/prototyping LED patterns
Several of my projects go through this time-consuming and tedious phase:

1. design a LED pattern for a geometry of WS2812 LEDs
2. implement it with e.g. FastLED
3. write to Arduino and see results
4. goto step 1

The second step, implementing different ideas in C with FastLED (or similar) takes a lot longer than I'd like it to. How is this step usually solved? Are there higher-level software solutions? Specialised idea-testing hardware?

I'd like to easily try out ideas such as "what if these four LEDs blinked magenta every second, while a gradient was cycling around the gradient over here".

# Answer
> 3 votes
For designing patterns for visual evaluation, it would be better to just have the arduino/controller be a pass-through from something like a full computer. There is a project called FadeCandy, which allows one to send various patterns to a WS2812 chain using a protocol called Open Pixel Control.

Some options would be to build or buy a FadeCandy board, or to implement the OPC protocol on your own arduino so that you can play around with test patterns and designs in a rapid development environment like Python or just making the raw patterns in a file and dumping that to your device over the serial port or TPC, etc.

Once you have your patterns or design the way you want it, then you can translate it to C code and FastLED, knowing you have a fixed specification you are trying to implement, rather than reflashing an arduino for every iteration.

# Answer
> 0 votes
I'm not sure if there are already solutions for it (high chance there are, maybe in some DMX 'simulations'), however, it shouldn't be too difficult to make your own.

Use a programming language you like which can handle graphics, use the same data structure as you would with FastLed, and let the software program (you write) show the pixels on a screen. This means you don't need any Arduino code.

If you split the filling of the pixels and the showing of it on the screen, you can copy the resulting 'filling of the pixels' code on the Arduino.

**Update** Another solution, if you want to experiment with the actual WS2812, is to program all patterns you want to check with FastLed, and let inputs (via UART or fancy knobs/buttons/menu) decide what patterns (and properties) are executed. The key is to program the patterns in a flexible way (so use functions with parameters for each property, and states for which pattern(s) are executed or executed next if you want to check some sequence).

---
Tags: led, prototype, ws2812
---


# Question
Title: Testing Conditions on Port Bytes - ignoring certain bits?
Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).

For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "`X - Don't Care`".)

I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.

Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.

Thanks! -Mike

# Answer
You need to use boolean arithmetic. Use the `AND` operator (`&`) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:

```
byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111

if ((wanted & incoming) == wanted) {
    // whatever
}

```

The AND operator compares each bit of the bytes in turn. If they are BOTH 1 then the result is 1. Otherwise the result is 0. So the above gives:

```
wanted:    11001110
incoming:  11011111
AND:       11001110

```

And the result matches "wanted". If you had some other value for incoming it could look like this:

```
wanted:    11001110
incoming:  01011011
AND:       01001010

```

And you can see that the result doesn't match.
> 7 votes

# Answer
There are ways to mask off the don't care bits. Say your example, 0b11xx1111. Then

```
incomingByte = Serial.read();
incomingByte = incomingByte || 0b00110000;  // make 4, 5 high
if (incomingByte == 0b11111111){
// got all 1s, do something
}
else {
 // some 0s received, do something else
}

```
> 2 votes

---
Tags: arduino-mega, bit
---


# Question
Title: Why won't my code play a tone for my arduino
I have the following code that I use to try to play a melody on my Arduino, but there is no melody just a tapping noise.

I am using the built in `tone()` function to play on a speaker/buzzer.

I know my hardware setup is correct because running sample code online plays a nice melody.

```
void setup() { }
void loop() {

    noTone(6);
  // C7 in eighth
    tone(6, 2093, 250); delay(250);
    noTone(6);
    //B7 in eighth
    tone(6, 3951, 250); delay(250);
    noTone(6);
    //G7 in fourth
    tone(6, 3136, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //F7 in eighth
    tone(6, 2794, 250); delay(250);
    noTone(6);
    //E7 in eighth
    tone(6, 2637, 250); delay(250);
    noTone(6);
    //E7 in fourth
    tone(6, 2637, 500); delay(500);
    noTone(6);
    //G7 in eighth
    tone(6, 3136, 250); delay(250);
    noTone(6);
    //G7 in halves
    tone(6, 3136, 1000); delay(1000);
    noTone(6);
    //C6 in fourth
    tone(6, 1047, 500); delay(500);
    noTone(6);
    //B6 in eighth
    tone(6, 1976, 250); delay(250);
    noTone(6);
    //G6 in eighth
    tone(6, 1566, 250); delay(250);
    noTone(6);
    //C6 in eighth
    tone(6, 1047, 250); delay(250);
    noTone(6);

}

```

This is supposed to be the melody for poker face using the tone() function

# Answer
> 1 votes
I just downloaded it, and it works for me.

Hmmm. Try downloading the other examples again, just to make sure you haven't moved a jumper.

Another way to check this out is to cut down the program to one or two lines, and see if that does or doesn't work.

# Answer
> 0 votes
What is the speaker/buzzer you are connecting to? It may need more current then the pin can support (a few tens of mA, absolute max of 40mA to prevent damaging the pin).

---
Tags: arduino-uno, programming, audio
---


# Question
Title: What is more power efficient: GPRS or SMS for a GSM sim Arduino application?
I have a GSM shield for my arduino and am wondering the most efficient way to receive and send data to the cloud.

The specific project I am looking to accomplish is starting my car from a web browser (or custom built ionic mobile app) that will send data to my GSM shielded arduino and the arduino then "press the button" of an already installed remote car starter (which is all probably in the car's trunk).

What is more power efficient, sending and receiving a SMS (text message) or sending and receiving data via GPRS?

What is best when considering strategies like sleep, or deep sleep cycles?

# Answer
> 1 votes
Looking at it logically SMS is probably the most power efficient method.

The thinking is this:

**With SMS:**

* The shield sits there connected to the mobile network doing nothing much
* An SMS is sent by you which travels through the mobile network
* The SMS is sent from the mobile network to your GSM shield which then wakes up and does things with it
* The shield sits there connected to the mobile network doing nothing much

**With GPRS:**

* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service and sees a request is available
* The shield downloads the request
* The shield acts on the request
* The shield goes back to querying the on-line service
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* The shield queries an on-line service to see if a request is available
* ... etc ad nausium ...

As you can see with SMS the onus is on the mobile network to send the data to the shield, whereas with GPRS the onus is on the shield to keep querying an on-line service to see if there is any requests to handle. There is no way of you sending data to the shield directly (indeed, most GPRS services include at least one layer of NAT gatewaying). So your shield has to be active all the time and constantly looking at something online - not only power hungry, but potentially financially expensive too.

# Answer
> 1 votes
You could theoretically use a SIP Server in the middle to keep the session alive over GPRS or higher. And there are techniques you can use to make it as power efficient as can be, depending on your application (which is a rather simple one I assume with little data throughput).

However, as @Majenko stated above, it may not be as power efficient as SMS.

That said, there may be other considerations, such as cost of sending/receiving SMS messages that may matter as you weigh the totality of requirements for your application.

I haven't worked personally on a Particle board (particle.io) but they do have a MCU/3G board that provides a certain amount of free (as in no $) bandwidth per month that might be a reasonable solution to consider for your application.

Please keep us posted. I'm considering something similar myself.

---
Tags: gsm
---


# Question
Title: What should I use Arduino-Mega or Rasbeery pi?
I am doing a project on Vehicle tracking and security. In my project Micro controller will sense input from sensors and at the same time it has to sense signal from user for tracking purpose and continuously checking the speed limit and boundary. so, there will be 3-4 tasks that would be executing parallel. Can anyone suggest which one is perfect for this kind of project... Arduino-Mega or Rasberry Pi?

# Answer
A RaspberryPi is essentially a small, low-spec computer. It is mostly an overkill for many small projects. Imagine using a super high-spec computer to play Minecraft. It's just nonsensical.

I'm assuming you'll be connecting to the car battery? Take note of the power requirements of your project. The RaspberryPi has a power requirement of 2.1A at 5V (which is a lot!), whilst an Arduino has a minimum requirement of 250mA.

Also remember: the RaspberryPi is running an operating system in the background in order to run your code. It will be working on numerous other operations and programs, not just yours. The Arduino will only run your program.

I had a similar project to what it sounds like you're doing. I used an Arduino Mega and had Bluetooth, GPS, and SD card all connected to it. The project worked absolutely fine, and I had lots of spare program space left over should I wish to expand on it. For reference, feel free to explore.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Regarding running multiple functions using millis
I have been writing code for measuring when the digital signal comes and goes (ON and OFF respectively). I have done the part calculating a single system's downtime (difference in timings between ON and OFF from the system), but when I'm not able to scale up to multiple systems when I try to copy the same code which worked above. So it would be helpful if anyone could provide some insight into how it can be done plus explaining with the code would help.

My code:

```
unsigned long a=0, b=0, difference;
void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.print("start");
  Serial.print(",");
  Serial.print("stop");
  Serial.print(",");
  Serial.print("minutes");
  Serial.print(",");
  Serial.println("seconds");
}

void loop()
{
 //delay(1000);
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }
 if(A == HIGH)
  {
     a = millis();
     display_output();
   }
 delay(3000);
}
void display_output()
{
 int minutes, seconds, sec;
 difference = a - b;
 seconds = int(difference/1000);
 if(seconds >= 60)
 {
  //sec = seconds;
  seconds = seconds%60;
  minutes = minutes+1;
 }
 //minutes = int(seconds/60);
 Serial.print((a/1000)+1);
 Serial.print(",");
 Serial.print((b/1000)+1);
 Serial.print(",");
// Serial.print(difference);
 //Serial.print(",");
 Serial.print(minutes);
 Serial.print(",");
 Serial.println(seconds);
 //Serial.println(",");
}

```

# Answer
> 1 votes
First of all, you should notice there is a problem with your logic:

```
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }

```

Here you are testing the state of the pin. If it's `LOW` you take a record of the time. This is wrong. What you want to record is the time at which the inputs **falls**, not when it's `LOW`. This is called state change detection. In order to implement it, you have to compare the pin state that you just read with *the previous state*. The correct condition is “if the pin was `HIGH` last time I read it and is now `LOW`”:

```
// Global variable:
int pin_state = HIGH;

// Within loop():
int new_pin_state = digitalRead(2);
if (pin_state == HIGH && new_pin_state == LOW) {  // it just fell
    time_of_fall = millis();
    pin_state = new_pin_state;
}

```

Note that this assumes that the default state is `HIGH`. If the pin turns out to be `LOW` at power-up, then the code will assume it just fell when the program started.

Next, you have to remove any occurrence of `delay()` from your code. That will only make your timings wrong. At this point you have non-blocking code that can easily be adapted to handle multiple input channels.

Then you have to identify the variables that are channel-specific, and have a per-channel version of each variable (arrays are useful here). Then your code only needs to loop through the arrays.

Instead of having multiples arrays, you can make the code cleaner by grouping all the channel-specific data into a single data structure:

```
struct Channel {
    byte pin;
    byte state;
    unsigned long fell, rose;  // times of fall and rise
};

```

This way you can have a single array that holds all the data for all the channels:

```
const int CHANNEL_COUNT = 5;

Channel channels[CHANNEL_COUNT] = {
    { 2, HIGH, 0, 0 },
    { 3, HIGH, 0, 0 },
    { 4, HIGH, 0, 0 },
    { 5, HIGH, 0, 0 },
    { 6, HIGH, 0, 0 }
};

```

The code now becomes quite simple: you just loop through the array and handle one channel at a time:

```
void setup()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    Serial.println("pin,fell,rose,low time");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == HIGH && new_state == LOW) {  // input fell
            c.fell = millis();
        }
        else if (c.state == LOW && new_state == HIGH) {  // input rose
            c.rose = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

```

The function `display_channel()` is left as an exercise to the reader ;-) (hint: it's prototype should be `void display_channel(const Channel &c);` in order to avoid unnecessarily copying the data structure.

Next step in code modularity would be to turn the `Channel` structure into a class with a proper constructor, and make `display_channel()` a method of that class.

---
Tags: millis
---


title: Arduino ultrasonic sensor project

text:
# Question
Title: Arduino ultrasonic sensor project
I'm a newbie at Arduino, and I'm trying to make a project with ultrasonic sensor, I'm using the grove ultrasonic ranger, not the HC-SR04, and I already did test with distance and it worked very well, but now I need help with the code.

I need to create a vector that save the values of the distance to after calculate the speed using distance/time calculus, but the case of my project its to use in open places, so will be times that the distance will be "max" because there's nobody in the range, so I need a condition to exclude those values of the array (the maximum distance printed when the sensor can't feel nothing is 516 cm)
I'm not experienced with Arduino coding, so please help me, in anex is my code for basic scanning.

```
#include "Ultrasonic.h"

Ultrasonic ultrasonic(7);
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    long RangeInCentimeters;
    Serial.println("The distance to obstacles in front is: ");

    // two measurements should keep an interval
    RangeInCentimeters = ultrasonic.MeasureInCentimeters();
    if(RangeInCentimeters > 400)
    Serial.print ("distancia nula");
    else
    Serial.print(RangeInCentimeters);//0~400cm
    Serial.println(" cm");
    delay(1000);
}

```

# Answer
> 1 votes
If you don't know how many data points will be recorded, look into vectors or an external storage device. Alternatively you could use a circular array if you don't mind losing recorded data after a while.

If you know how many data points will be recorded, a basic array will suffice.

As for excluding invalid values:

```
// Keep trying to get a valid data point
While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
{
 delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
 RangeInCentimeters = ultrasonic.MeasureInCentimeters();
}

//... Store data to array/linked list/etc

```

I changed your max range to 512 because this is likely the max real value (2^9 = 512).

---
Tags: programming, sensors
---


title: Print uint8_t in arduino

text:
# Question
Title: Print uint8_t in arduino
I'm learning esp8266 using arduino IDE. I'm still a beginner in development board programming. What I've been trying to do is use a crypto library. I am trying out AES in arduino and I chose that library because it seemed complete, and was one of the only library that used ECB. My problem is whilst calling the encrypt function, I get confused with the output.

This is what I've done so far.

```
#include <Crypto.h>
#include <AES.h>
#include <string.h>

AESSmall128 aes128;

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

  uint8_t key = (uint8_t)1234567654321234;

    aes128.setKey(&key, 16);

    uint8_t output = 0;

    Serial.println("before");
    Serial.print(output);

      uint8_t input = (uint8_t)9164567654321234;

    aes128.encryptBlock(&output, &input);
    Serial.println("after");
    Serial.print(output);

}

void loop()
{
}

```

When I print `output` it returns `252`. What is 252? Why only 252? It seems really short looking at it. Why doesn't it output strings?

# Answer
> 4 votes
`uint8_t` is an Unsigned 8-bit Integer, and so the range of values it can represent are 0 to 255.

When you typecast your long/large values to `uint8_t`, you basically only show the least-significant 8-bits.

However, the `decryptBlock()` and `encryptBlock()` functions expect an array of bytes, not a single byte.

The library you link to notes, right in the linked position, that the output and input parameters must be at least `blockSize()` bytes in length. Referencing `blockSize()`, it notes that this function always returns `16`. So you need to pass an array of `uint8_t`s of at least 16 length.

When you define your variables for the key, plaintext, and ciphertext, you need to not define then as a single byte type, but as an array of bytes:

```
uint8_t[16] key =    {1,2,3,4,5,6,7,6,5,4,3,2,1,2,3,4};  // This is not a good key, btw
uint8_t[16] output = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
uint8_t[16] input =  {9,1,6,4,5,6,7,6,5,4,3,2,1,2,3,4};

```

(When passing an array, you don't need to dereference the variable, so call `aes128.setKey(key, 16);`, etc. Omit the `&`)

Each of the 16 bytes can have a value in the range 0 to 255. They do not have to be limited to single-digit numbers; I just copied/translated what you wrote to demonstrate the example. You could set your key in this way:

```
uint8_t[16] key =    {66,127,164,72,68,158,148,255,23,36,226,192,198,248,251,221};

```

You can also refer to bytes with a 2-digit hexadecimal representation:

```
uint8_t[16] key =    {0xa6,0x09,0x81,0xc5,0xb8,0xf6,0x9a,0x33,0x75,0x24,0xff,0x79,0xd3,0x48,0x4f,0x1d);

```

---

**UPDATE to address strings**

A C-style string is a sequence of bytes, with type `char` to indicate ASCII data, though any byte-wide type could work in theory. The sequence of bytes ends with a value of `0` (i.e., `0x00`, not the ASCII character `'0'`), so you must remember that the termination byte takes up a byte of memory.

To initialize your key with a string:

```
const unsigned char[17] key = "helloareyouarehi"; // 16 characters, and 1 byte termination means 17 total bytes reserved in memory.

```

I have not investigated how the crypto library you are using handles C-style strings, so let's assume it does not acknowledge them at all, and we will have to null-terminate our strings ourselves.

```
char[17] output = {0}; // Initialized to all zeros
char[17] input = "iwanttoencryptme";

aes128.encryptBlock(output, input);
output[16] = 0x00; // Just to be safe, put the null terminator in the last slot.

Serial.print(output);

```

If the `encryptBlock()` function only changes 16 bytes in the output array, then the 17th (zero) could remain from the initialization, but not knowing whether the function preserves strings, it is better to be safe than sorry.

# Answer
> 1 votes
The `uint8_t` is exactly 8bits wide, so it can hold values from 0 to 255. Your number however is about 54bits wide.

I think you should use the array.

Also numeric literals are usually int type, so even if you do have enough space for it, it gets wrong value. Something like `uint64_t value = UINT64_C(1234567654321234);` must be used

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


# Question
Title: convert 32 bit long to 4 bytes and back again - CAN Bus
So after 2 days attempting this I can't get my head round it.

So I am using CAN bus to transfer accelerometer data and time data (the micros() function if under 71 minutes will output data that can be an unsigned long), however I have to send the data as bytes. I have managed to bit shift a 16-bit int into 2 bytes but I am having trouble extrapolating that method (will add later) to using longs. I am having trouble understanding the union method as I am new to creating my own functions, so, how would you guys accomplish this? As simple as possible please :)

# Answer
> 1 votes
You can achieve what you want by using bitshifting and bit-wise and operators.

Here is an example that lets you extract the individual bytes of your `long` variable. I think it should be straigtforward to extend it to variables of different length:

```
void loop() {
  long a=0x12345678, c=0;
  byte b[4];
  Serial.println("Original:");
  Serial.println(a,HEX);
  delay(1000);
  Serial.println("Individual bytes:");
  for (int i=0; i<4; i++)
  {
    b[i]=((a>>(i*8)) & 0xff); //extract the right-most byte of the shifted variable
    Serial.println(b[i],HEX);
    delay(1000);
  }

  for (int i=0; i<4; i++)
  {
    c+=b[i]<<(i*8);
  }
  Serial.println("Reconstructed:");
  Serial.println(c,HEX);
  delay(1000);
}

```

Depending on what byte ordering (big or little endian) is expected, you might need to reorder the bytes before sending or after receiving.

# Answer
> 3 votes
The `union` type is similar to a `struct` except that each of the members of the element occupy the same memory. If you define a `struct` so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.

```
union packed_long {
  long l;
  byte b[4];
};

```

This is the type, so you have to declare the variable to be of that type:

```
packed_long mydata;

```

Now, you have two sub-elements of `mydata`: `l` and `b[]`.

To save your `long` value, write to the `l` part:

```
mydata.l = myaccel.getY();

```

To access each of the 4 bytes:

```
byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];

```

On the receiving end, you take each of the 4 bytes:

```
mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();

```

As long as you receive the bytes in the same order in which you sent them, you can now access your `long` value in `mydata.l`.

The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: `int32_t` (signed 32-bit integer) or `uint32_t` (unsigned 32-bit integer).

# Answer
> 1 votes
A way to send a long is to mask off and send the LSB byte (CAN standard), then shift the next one into LSB position, for 4 bytes:

```
uint32_t data;

// Send to CAN bus LSB-first
// This method is destructive; data should be a temp if the
// Arduino is to retain the data after sending it.
for( uint8_t b = 4; b > 0; --b ){
   sendByte(data & 0xFF);  // send curr byte
   data >>= 8;             // shift that byte away
}

// Read from CAN bus
for( uint8_t b = 4; b > 0; --b ){
   data >>= 8;                 // make room for byte
   data |= (readByte() << 8);  // read next higher byte
}
//

```

---
Tags: arduino-uno
---


# Question
Title: What is the easiest way to count how many global variables are in your sketch code?
I have a fairly complicated sketch with about 1k lines of code. I should also say that I'm not a programmer by trade...

As I go over my code and try to make it more efficient, it'd be good to know how many global variables are in my code and whether/if all of them are necessary as global. So:

1 - Is there an easy way to count how many global variables you've used (again, imagine complex code by a non-coder), and

2 - Is there an easy way in the Arduino IDE to jump to it?

# Answer
1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.

2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.

For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.

For a Arduino Uno and larger, the optimization is done more globally.

To optimize for ram, look for the hungriest memory eaters:

* For the Arduino Uno and other avr microcontrollers, the text with Serial.println can be put in PROGMEM with the F() macro.
* Many String objects might need a lot of heap memory.
* Arrays can get large quickly.
* Arrays of large elements (float, struct) can get large even more quickly.
* The SD library uses a lot of ram memory. There is a small version of the SD library.
* Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

* When an integer is changed into a byte, perhaps all the calculations are still done with integers and the compiler needs more memory to convert from byte to integer and back.
* Perhaps that integer was only used in registers and did not use a memory location.
* A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.
> 1 votes

---
Tags: sketch, variables, sketch-size
---


title: Accelerometer IoT

text:
# Question
Title: Accelerometer IoT
I am not sure if I am in the right place. I would like to build a device (as small as possible) that has an accelerometer and can talk to my phone via bluetooth. Im not asking anyone to build this for me. I would just like some starting help. Can you tell me the parts that I would need to accomplish this?

# Answer
> 0 votes
you will need:

1. **Arduino Mini** (can also use **Uno**/**Mega**/**Pro**....)
2. **Bluetooth Module** (mostly used: **HC-06**/**HC-05**)
3. **Accelerometer** (mostly **MPU-6050**)
4. Few **wires**.

If you want to carry this device around, you will need a **battery** to power this circuit.

# Answer
> 1 votes
Your smallest solution would not involve a conventional "Arduino" at all, but rather something like an nRF51822 Bluetooth Low Energy chip/module, which in addition to being a radio is a processor in its own right capable of running custom software built in a variety of ways, including one that extends the Arduino IDE to support it.

Basically, you need the nRF51822 or similar chip, an accelerometer, and whatever solution for powering the two you decide upon.

In terms of conventional bluetooth vs. BLE the choice depends not only on technical merits, but also on which phone you want to connect to. If you want to connect to an iphone, you are basically locked into BLE as the bluetooth stack there is restricted to approved devices. On the other hand older/cheaper Android devices may not support BLE, or support it poorly, while their conventional bluetooth does not have the approval restrictions of iOS.

# Answer
> 0 votes
If you want Arduino programming AND you have physical size limitations, you may want to checkout RFDuino.

http://www.rfduino.com/

They have a variety of breakout boards that make rapid prototyping easier.

I should say however that while I have purchased one of these, I have yet to get around to using one. Others with more experience may want to chime in.

---
Tags: arduino-uno, bluetooth, accelerometer
---


# Question
Title: What is the difference using library of SoftwareSerial.h and ESP8266WiFi.h?
What is the library I should use to upload the sensor data (ultrasonic and Infrared sensor) to the localhost server.

Because I saw some of the online resources using ESP8266WiFi.h library for the ESP01 and some of resources use the softwareserial.h library. So, what is the difference between these two libraries?

# Answer
The SoftwareSerial is used to communicate with the esp8266 from other MCU. The ESP8266WiFi library is for Arduino sketch running in esp8266.

The esp8266 can be used with firmware as 'network adapter' for your sketch running for example in Arduino Uno. MCU in Uno has only one hardware Serial which is used to communicate with the computer over USB (to upload and use Serial Monitor). To communicate with the esp8266 usually a second Serial interface is created with SoftwareSerial.

But esp8266 can be used as Arduino board with "esp8266 Arduino core". This 'core' contains Arduino libraries to access the WiFi functions of the esp8266 from a sketch running in esp8266.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Why does it skip the first index - shift register issue
So, I wrote this code myself and I'm a noob on the issue. I did get my code working, but cannot understand why it has to be the way it is.

```
int counter;
int ledValue[] = {
  1,0,1,1,1,1,1,1
};

void setup()
{
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop(){
  digitalWrite(5, HIGH);
  for (counter = 8; counter >= 0; --counter) {
  // turn the pin on:
    digitalWrite(2, ledValue[counter - 1]);
    digitalWrite(3, 1);
    digitalWrite(4, 1);
    digitalWrite(2, 0);
    digitalWrite(3, 0);
    digitalWrite(4, 0);
    delay(100);
  // turn the pin off:
  }
  delay(1000);
  digitalWrite(5, LOW);
}

```

Now, I am puzzled by both the `counter = 8` and the `[counter -1]`. To me it looks like I am loop-ing this 9 times, though I only got 8 items in the array

A. If I make it `counter = 7` and `[counter -1]` my output is 10111110. This loops 8 times (I think), but gives me 7 leds.

B. If I make it `counter = 7` and `[counter]` my output is 01111110. This loops 8 times (I think), gives me 7 leds but also an extra led burning up front, hence braking the prescribed pattern.

C. If I make it `counter = 7; counter >= -1` my output is 10111111.(as it should). But how can it be -1?

My guess is that I am doing something wrong at the beginnen, but I can't find what. Tried several tutorials and explanations, but it still puzzles me why the correct running code is that way.

Just to be sure, I am familiar with an array being 0-indexed.

Please helpt me understand my code ;-)

Edit: Small addition:

* pin 2 is connected to ShiftRegister pin 14
* pin 3 is connected to ShiftRegister pin 12
* pin 4 is connected to ShiftRegister pin 11
* pin 5 is connected to ShiftRegister pin 10

Thanks for the feedback. My lack of understanding does not concern the loop or array. What I can't get my head around is why the shift registers outputs the loop as it does. Would a picture of the setup help?

# Answer
The problem is in the directions the ShiftRegister gets.

This way, it works

```
...
digitalWrite(2, ledValue[counter - 1]);
digitalWrite(4, 1); //clock pin high
digitalWrite(4, 0);
digitalWrite(3, 1); //latch pin high
digitalWrite(3, 0);
digitalWrite(2, 0);
...

```

The clock and latch have to be low again before switching the signal back to 0.

In the upgraded version I put the clock and latch in a function.
> 1 votes

# Answer
The correct way to loop through an array of length 8 is:

```
for (int counter = 0; counter < 8; ++counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

```

If you want to loop through the array backwards, then:

```
for (int counter = 7; counter >= 0; --counter) {
    digitalWrite(2, ledValue[counter]);
    // ...
}

```

This loop will visit, in this order, the indices 7, 6, 5... 1 and 0.

For extra clarity, you could define a constant that holds the length of the array, then replace the numbers `8` and `7` above by `VALUES_COUNT` and `VALUES_COUNT-1` respectively.

You wrote:

> If I make it \[...\] my output is \[...\]

Not sure what you mean by that. This code should not have much visible output, as the LEDs are turned off only microseconds after being turned on. How do you determine what the program's "output" is? Maybe there is an issue with the way you are trying to diagnose the problem.
> 1 votes

# Answer
Make the problem as small as possible. For example:

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

  for( int i=8; i>=0; --i) {
    Serial.println(i);
  }
}

void loop() {
}

```

The output is:

```
8
7
6
5
4
3
2
1
0

```

Those are indeed nine numbers. An array in c++ starts at zero. Your array is from ledValue\[0\] up to (inclusive) ledValue\[7\]. See the answer by Edgar Bonet how the for-statements are used.
> 1 votes

---
Tags: shift-register
---


title: Equivalent of millis() in Atmel studio

text:
# Question
Title: Equivalent of millis() in Atmel studio
This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.

**Picture**: https://imageshack.com/a/img922/3060/umtNJp.jpg

**Update 2**

```
#define F_CPU 8000000UL
#include <avr/io.h>

#include <avr/interrupt.h>

#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)
volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

volatile uint8_t count;

ISR (TIMER0_OVF_vect)

{

    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

}

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

int main (void)

{
    DDRB |= (1<<0);
    TCNT0 = 0;
    count = 0;
    TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
    TIMSK0 = (1<<TOIE0);
    sei();

    while(1)
    {
        millis() to uart.

    }

}

```

# Answer
> 4 votes
The `millis()` function is defined in the Arduino Core for AVR architecture, specifically the `wiring.c` file.

You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called `timer0_millis` contains the number of milliseconds since the sketch started.

The `millis()` function basically returns that `timer0_millis` value.

If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.

---
Tags: arduino-uno, arduino-ide, atmel-studio
---


# Question
Title: Arduino Resetting in Automotive Application
I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.

The Setup:
Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment. Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin. I have also tried analog LM35 sensors. The system works outside the car just fine.

The Problem:
When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected. There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.

What I have learned:
-When I disconnect the temperature sensors from the PCB, problem goes away.
-It makes no difference if the wires to the sensors are shielded.
-It makes no difference if I use one wire digital or analog sensors.
-It makes no difference if I connect the PCB directly to the battery
-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)
-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.
-The chance of a reset changes when the sensors are moved or the length of wire is changed.
-It only resets when the key is turned off, never when turned on.

I tried to explain the best I can without writing a novel. I think I might need to isolate the ground to my PCB somehow. The problem is in the ground or the long wires to the sensors.

# Answer
> There is ***no power spike*** or loss to the PCB. The car is not actually running, I am just turning the key on and off.

And did you verify that with a digital scope? I doubt it.

I don't think you understand how ugly the electrical system in a car really is. If there is a coil or relay switched then there **will** be spikes. Do some research on electronics for use in an automobile.

Automotive relays can have a resistor in parallel with the coil to control the level of the back emf when the relay is turned off. You would think that a reversed diode should be used but a diode causes the coil current to discharge too slow and that causes the contact arcing to be extended. A resistor can be used to speed up the discharge but at the cost of a voltage spike on the electrical system.

An Arduino board is not appropriate. There needs to be a lot more protection.And one wire devices are basically an antenna looking for trouble.

https://www.st.com/content/ccc/resource/technical/document/application\_note/1f/d7/fc/6d/2e/27/48/98/CD00181783.pdf/files/CD00181783.pdf/jcr:content/translations/en.CD00181783.pdf

https://electronics.stackexchange.com/a/40425/195251

https://en.wikipedia.org/wiki/Load\_dump

https://electronics.stackexchange.com/a/163861/195251
> 4 votes

---
Tags: reset
---


# Question
Title: Connect two or more modules sharing the same pins?
I've found some separate instructions for connecting an SD reader/writer and also instructions for connecting a RFID reader and Piezo Buzzer. I would like to use both modules and the piezo buzzer together on the same Arduino. See below for the pin wiring details from each instruction I found:

**SD Reader/Writer**

* 3.3v goes to 3.3v on the Arduino UNO (for power)
* GND goes to Ground on Arduino UNO
* D0 goes to pin 12 on Arduino UNO
* D1 goes to pin 11 on Arduino UNO
* CLK goes to pin 13 on Arduino UNO
* D3 goes to pin 10 on Arduino UNO

**RFID Reader**

* SDA - Digital 10
* SCK - Digital 13
* MOSI - Digital 11
* MISO - Digital 12
* IRQ - unconnected
* GND - GND
* RST - Digital 9
* 3.3V - 3.3V

**Piezo Buzzer**

* Red - Pin 8
* Black - GND

Is using the same pin for more that one module ok?

# Answer
pins 11 MOSI, 12 MISO and 13 SCK are SPI bus. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.

I recommend to wire SD reader D3 to pin 4 and in sketch use `SD.begin(4)`.

Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino esp8266 interferes with analog sensors
UPDATE: I tried CNY70 sensor and the same error is valid for it too. Even outputs of CNY70 and LDR is the same while ESP8266 plugged in. I think ESP8266 interferes with all analog sensors

I connected my esp8266 and ldr sensor to my seeediuno (clon of arduino by seeedstudio) and ldr returns values like 70 110 105 120 etc. When I directly pointed light to ldr, return values don't change, value scatter randomly between 50-130. When I disconnect esp8266 and switch to arduino diecimila from ardunio ide, ldr sensor works fine. I think esp8266 somehow interferes with ldr sensor. How can I fix this problem?

```
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
[![#define SSID "myssşd"
#define PASS "mypass"
#define BID 000001

const char *host = "api.host.com";

void setup() {
  //start serial connection
  Serial.begin(115200);
  //configure pin 2 as an input and enable the internal pull-up resistor
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
  pinMode(A0, INPUT);

  WiFi.begin(SSID, PASS);

  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Connecting...");
  }
  //If connection successful show IP address in serial monitor
  Serial.print("Connected to ");
  Serial.println(SSID);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
}

void loop() {
  //read the pushbutton value into a variable
  int sensorValMeal = analogRead(A0);
  Serial.println(sensorValMeal);
  delay(1000);
}

```

This is how my serial prints looks like. You can see the anomally, I added my events as well.

```
Connecting...
Connecting...
Connecting...
Connecting...
Connected to Anaconda
IP address: 192.168.1.21
42 <- This is start
41
41
41
41
41
41
41
40
40
151 <- I turned my phones light to ldr
78
85
84
89
92
69
97
99
100
96
104 <- I switched of my phone's light
63
103
103
108
108
109
109
114
111
112
111
103
112
113
114
112
116
104
116
116
101
117
118
118
108
122
80
109
118
123
124
125
124
114
127
127
127
98
126
127
124
114
125
127
125
124
127
98
127
126
104
127
127
126
118
128
127
92
123
126
127
128
127
111
130

```

# Answer
You aren't using the Seeduino Arduino clone. You're using (as in writing software for, and programming) the ESP8266. Every instruction you write affects *only* the ESP8266. The Arduino is nothing more than a power supply (and maybe a USB to Serial adaptor if you use it as such).

To access the analog pins on the Arduino you will need to:

1. Design a communication protocol between the two boards
2. Implement that communication protocol for *both* boards
3. Program *both* boards with their own unique sketches that use the protocol to communicate between them.

The Arduino will gather the data using its sketch, then send the results to the ESP8266 for sending through the internet.

Alternatively put the standard AT firmware on the ESP8266 and use that as the protocol above - then you only have to implement it on the Arduino.
> 0 votes

# Answer
You read the analog pin of the esp8266, not the analog pin of the Seeeduino.
> 0 votes

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


# Question
Title: Why does Arduino Tone example with 8 ohm speaker make USB port fail?
I'm using an Arduino Nano and attempting to run the basic sample program at: https://www.arduino.cc/en/Tutorial/toneMelody

When I build the circuit they way they show (extremely simple) using an 8 Ohm speaker and connect the power to USB the Nano begins to power (never fully powers up) and then the USB port fails (I believe as a protection mechanism).

Is the schematic provided with that sample incorrect?
They say it can be used with an 8 Ohm speaker but they show it hooked up with e piezo.
Here are the comments from the Sketch:

Is it possibly overdrawing current with the 8 Ohm speaker?
Is the circuit incorrect in some way? **NOTE:** Without the speaker connected the Nano powers up with no problem. I am also building other circuits with the Nano and they work fine.

# Answer
> 1 votes
As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.

In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.

There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.

One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).

The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.

When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.

Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.

So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.

A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.

# Answer
> 0 votes
The USB +5v opens to protect your computers from the connected device trying to draw too much current. The pin driver may have burned out, or it may, in fact, have delivered an excessive current (even if not the full 625 mA) but have been saved from failure by the USB supply having opened soon enough.

---
Tags: arduino-nano, speaker
---


# Question
Title: Why does using ESP8266 in deep sleep mode still drain the battery quickly?
I've made a "weather station" using the ESP8622. To save battery I'm using sleep mode but still the battery is drained after a couple of days. According to this post it should last at least a year.

I haven't done any measurements yet, wanted to know if there's something obvious that I've missed that could explain why the battery is drained so quickly? Attaching code and an image showing the hardware setup.

```
#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define DHTPIN D2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

const char* ssid     = "xxxx";
const char* password = "xxxx";

const char* host = "xxxx";

void setup() {
  Serial.begin(115200);
  dht.begin();
  delay(10);

  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  readSensorsAndPost();
  ESP.deepSleep(18e8); //30 minutes
}

void readSensorsAndPost() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  char charVal[10];
  dtostrf(t, 5, 2, charVal);
  makeAnHttpRequest(charVal);
}

bool makeAnHttpRequest(String msg) {
  //send the value
}

void loop() {

}

```

# Answer
> 4 votes
The example shows a Sparkfun Thing, which the article notes doesn't have extra peripherals. What you show is something different, like a NodeMCU dev board, which typically has a linear regulator, possibly a power LED (which the article notes can be removed).

I see you're using a DHT11 or DHT22, which has a pull-up resistor. The pull-up resistor is constantly using power. Instead of connecting the pull-up to the power rail, you can connect it to a GPIO pin and pull that pin LOW before you go into sleep, which effectively disables the sensor and stops it from drawing power just to keep the data line high.

Safe to say that somewhere there is something drawing power -- have you measured the actual current draw in deep-sleep, or are you only noting that your batteries run low sooner than expected?

---
Tags: esp8266, battery, sleep
---


title: how can i split string data in arduino?

text:
# Question
Title: how can i split string data in arduino?
im sending string data via serial with following format ex. :45:60 or such as ":120:57".i got the data shown in Serial.println (secondValue) Serial.println (thirdValue); but i cant convert it to int

```
String myString;
char c;
int Index1,Index2,Index3, azi;
String secondValue, thirdValue;
void setup(){
Serial.begin(9600);}
void loop(){
while (Serial.available()>0)
{
delay(10);
c = Serial.read();
 myString += c;
}
 if (myString.length()>0)
{
Index1 = myString.indexOf(':');
Index2 = myString.indexOf(':', Index1+1);
Index3 = myString.indexOf(':', Index2+1);

secondValue = myString.substring(Index1+1, Index2);
thirdValue = myString.substring(Index2+1, Index3);

Serial.println(secondValue);
Serial.println(thirdValue);

myString="";
}
delay(1000);
}

```

# Answer
All numbers are integers? If yes, you can use `toInt()` function.

```
int secondValueInt, thirdValueInt;

secondValueInt = secondValueInt.toInt();
thirdValueInt = thirdValue.toInt();

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Taking String Input from NodeMCU Webpage and Printing it on Serial Monitor
I've started working with NodeMCU recently. I've very little knowledge about this device and how a website works. I'm trying to take a long string input from a website hosted by NodeMCU, store it on a variable and then print in on NodeMCU Serial Monitor.

I've got the following program. Here I only have created a text box for typing. But I don't know how to take that input inside a variable and use it later for serial printing.

```
#include <ESP8266WiFi.h>

const char* ssid = "****";
const char* password = "*************";

WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

WiFi.begin(ssid, password);

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

void loop() {
    WiFiClient client = server.available();
    if (!client) {
    return;
    }

    Serial.println("new client");
    while(!client.available()){
    delay(1);
    }

    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();

    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("");

    client.println("<!DOCTYPE HTML>");
    client.println("<html>");

    client.println("<label for='name'>Serial Printer (Put Text here: ): </label>");
    client.println("<br><br>");
    client.println("<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>");
    client.println("</html>");

    delay(1);
    Serial.println("Client disonnected");
    Serial.println("");

}

```

# Answer
> 1 votes
Try this. It uses the webserver library. I thought it was cleaner code. I also have a nicer way to include the pure html code.

For your original form go to yourIPaddress/single

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "MTS61752";
const char* password = "6900979039";

ESP8266WebServer webserver(80);

//------------------------------------------------
static const char PROGMEM singleLine[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>Single Line Input</title>
</head>
<body>
<form method="post" action="/save" >
<label for='name'>Serial Printer (Put Text here: ): </label>
<br><br>
<input type='text' id='name' name='name' required minlength='0' maxlength='800' size='100'>
<input type="submit" name="clk_action" value="accept">
</form>
</body>
</html>
)rawliteral";

//------------------------------------------------
static const char PROGMEM INDEX_HTML[] = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>Clock Settings</title>
</head>
<body>
<form method="post" action="/save" >
Turn on time:<br><input name="onTime" type="text" size="16" value="" ><br><br>
Turn off time:<br><input name="offTime" type="text" size="16" value="" ><br><br>
<input type="submit" name="clk_action" value="accept">
</form>
</body>
</html>
)rawliteral";

//------------------------------------------------
void handleRoot() {
  webserver.send(200, "text/html", INDEX_HTML);
}

//------------------------------------------------
void handleNotFound() {
  webserver.send(404, "text/plain", "Page not found ...");
}

//------------------------------------------------
void handleSave() {
  String str = "Settings Saved ...\r\n";

  Serial.print("number of arguments ");
  Serial.println(webserver.args());                    // number of arguments

  if (webserver.args() > 0 ) {
    for ( uint8_t i = 0; i < webserver.args(); i++ ) {
      str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

      Serial.println("Arg "+ String(i)+"="+ webserver.argName(i));
      Serial.println("Arg "+ String(i)+"="+ webserver.arg(i));
    }
  }
  webserver.send(200, "text/plain", str.c_str());
}

//------------------------------------------------
void handleSingleLine() {
  webserver.send(200, "text/html", singleLine);
}

//------------------------------------------------
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  webserver.on("/", handleRoot);
  webserver.on("/save", handleSave);
  webserver.onNotFound(handleNotFound);
  webserver.on("/single", handleSingleLine);

  webserver.begin();
  Serial.println("Web server has started");
}

//------------------------------------------------
void loop() {
  webserver.handleClient();

}

```

---
Tags: arduino-ide, nodemcu, web-server
---


# Question
Title: Routing Matrix with a large number of I/O
Lets say that i would like to make a 128x128 routing matrix with an arduino uno,

Since i am unexperienced i think of using two 4051’s for 8x8 patching and because i want to persist the patch, controlling them with two quad d type flip flops, then repeat the circuit to reach 128x128 patching capibility. Then my output count would be sufficent in arduino uno.

I think this would work but sounds unelegant to me. Do you have another advice for me to achieve this task?

Actually what I would like to achieve is a big digitally controlled patching matrix for my own analog synth circuits at home. So analog signals will be present and should have the avalibility to patch anything to anything.

# Answer
I would use a port expander that uses I2C for communications. One example is the PCA9555. You can add up to eight by setting the address bits (A0-A2). This will give you up to 64 outputs to control the selection bits of the 4051s.

While this is all intelectionally possible, from a logic perspective, I have concerns about how this can be practically implemented. I think you need to go into more detail on what you plan to do. What the purpose is.

Also, there are larger chip for do analog matrix switching. AD75019 is one example. https://www.analog.com/en/products/ad75019.html

They are more expensive but cost should not be the primary factor. Getting a design to work is more important.

Do a search for "Crosspoint Switch Array" for more chips like this.
> 1 votes

---
Tags: digital, multiplexer
---


# Question
Title: Is it possible to combine a HC-05 Bluetooth module and a shrinked arduino ATtiny45/85 to control a motor, LEDs, or other components?
I'm thinking of making a tiny RC toy project that is controlled through Bluetooth with most components at its tiniest size. I'm a complete beginner in this area so i'm not completely familiar with lots of components so please don't mind me if i sound dumb and uneducated. Anyway...

If it's possible: how many components can i use with the ATtiny45/85? or should i go with the atmega8.

I have a m20 mini motor, a micro servo and a few leds. This doesn't include other components that i havent purchase such as dc driver module and HC-05 Bluetooth module.

If not possible: what other options I can do to create my project.

# Answer
The ATTiny has 5 usable pins (6 if you decide to reuse the Reset pin). Since it doesn't have UART hardware, you need to use a SoftwareSerial library to communicate with the HC-05. This takes 2 pins. To drive a motor, you need at least 1 pin. If you need to control it's speed (instead of just on and off), you would need to generate a PWM signal. Either through hardware timer or by code. (The ATTiny has 2 timers. When you want to use PWM with hardware timer, you need to make sure, that the SoftwareSerial library doesn't want to use the same timer). For the servo it's similar. The servos position is encoded by pulse lengths. (Make sure, that the used library doesn't want to use an already used timer)

Unless you use techniques as multiplexing or matrixes (which are not that useful for a small number of LEDs), you need 1 pin per LED.

Depending on what exactly you want to achieve, you will pretty fast run out of pins. Since you are a beginner you should start with a chip with more pins. If you don't know, how exactly your project will be in the end, better by a chip with maybe double the pins, that you think you need. Develop, until you really know, what functionality your project should have, what not and what you need to achieve that. Based on this you can choose the correct chip, that is as small as possible. Also consider using SMD parts in the finished version. There are mostly much smaller, but also more difficult to solder.
> 1 votes

---
Tags: arduino-uno, motor, bluetooth, remote-control
---


title: Arduino self programming

text:
# Question
Title: Arduino self programming
I have noticed that some atmel chips can do "self programming" and I'm doing a hobbyist project where I need to change the "setting" of my arduino without code-reuploading through Arduino IDE.

Is it possible to do that ? If it's possible. Please give me some basic though about how to do it.

Thanks in advance !

# Answer
There are two areas of non-volatile storage in an Arduino: Flash and EEPROM.

Flash is where your program and constant values are stored. Variables with default values also have their default values stored in Flash.

EEPROM is a much smaller area with no real fixed purpose - you can store whatever values you want in there.

Flash can *only be written to by code that is in the bootloader area of flash*. This is important. A program *cannot* modify itself. Only the bootloader can modify a program - and then only in chunks ("pages"). It has to erase a whole page before it can write data to it.

The reason why you can't modify Flash from your main program is simple: Flash is the only place code can be executed from. If you erase the page of flash that contains the code that is programming the Flash then everything dies. Horribly. So it's stopped in its tracks by not allowing it to happen in the first place.

EEPROM, conversely, can be written to by anything - the bootloader *or* the main program. And on top of that individual values can be modified at will - no need to erase pages.1

So to answer the question behind your question ("How can I store and modify settings?"): it's quite simple - store them in EEPROM.

The IDE has examples of how to use the bundled EEPROM library, and there are more details in the Arduino reference manual.

---

1: Some systems don't have EEPROM, so they emulate it using Flash. These systems still have to erase the Flash in pages, but they try to do it transparently. Some (such as the ESP8266) use a `commit()` method to update a batch of values. Others, such as chipKIT boards, use wear levelling and separately indexed writing to reduce the need to erase pages.
> 6 votes

# Answer
You have multiple options to change *settings* without code-reuploading. By settings I mean values, not code.

First, you can add a physical UI to your project. It can be a push button and a LED, a key pad with a LCD display or a touch sensitive screen.

Second, your sketch can use `Serial` as way to receive comands and display information. You will need a tablet, smartphone or PC.

Third, you can also use Bluetooth instead of Serial.

Fourth, you can add WiFi to your project. With WiFi any solution is posible (web page, Android App ...).

You can also mix technologies: have a minimal physical UI for emergencies and a full interface via WiFi.

With NodeMCU you also have a file system where you can store you app data. It may be simpler to use than EEPROM.
> 3 votes

# Answer
Yes, you can self-program these. There are several different bootloaders you can use to do this - here's one: https://bitbucket.org/talk2/talk2boot
> 3 votes

# Answer
You can write to the non-volatile memory of the microcontroller and then read it again during setup.

Another (perhaps simpler) option is to have an external eeprom chip in a socket to hold the settings so you can program that separately from the module. That way you don't need to have a menu in your project.
> 2 votes

# Answer
Self programming is used by `Arduino` bootloader. If you want something special, you have to change bootloader, because you can't call `SPM` instruction outside of `BOOT` sector (the only exception are `AVRs` with a small program memory).

I'd recommend to use internal `EEPROM` storage instead.
> 2 votes

# Answer
You can do something simple - say have 2 pins to select 1 of 4 sets of values for the code to use. Read the pins in setup(), and change values to use in loop() accordingly.

```
void setup(){
change = PIND & 0b1100000; // say D7/D6 used on a Uno.
switch (change){
  case 0b00000000:
  // set values for D7/D6 = 00
  break;
  case 0b01000000:
  // set values 01
  break;
  case 0b10000000:
  // set values 10
  break;
  case 0b11000000:
  // set values 11
  break;
  }
}

```

Or wait in setup() for the choice to come in a Serial message. Maybe store the sets of values in EEPROM for selection via whatever source, and then let the code change the values if needed. Or think of other ways to select the values without having to change the existing bootloader.
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: Why to store a function parameter value in a class private variable?
I'm just curious, I'm going through a C++ library for the mcu2.4 TFT display.

And this method I notice when I run through C++ libraries.

Which is when a parameter is passed through a function, it's stored in a private variable; like this one:

```
HCTFT::HCTFT(byte DisplayType)
{
    _Display = DisplayType;

```

What's the benefit of this method? What's the similar method when I want to do it in C code?

# Answer
The reason is that \_Display will be used probably after its construction.

So you pass the byte during construction, and afterwards the value is available during the object's lifetime.

In C you probably will do this by:

* Passing the variable (byte DisplayType) in each function where the value is needed (you can use this way in C++ too but it's cumbersome in both C/C++ to pass the variable in all functions needed).
* Storing it in a global variable (static for that .c file); this is the typically C method.

*** Added explanation ***

Such a variable is called class variables and are mostly made private. The reason is that other objects cannot change the value directly. The only way to change a variable is:

1. By initializing it in the class constructor (like in your example).
2. Within the class itself (by any method).
3. By a typical Set method (like SetDisplayType). This method can check if the value passed is within a range, and there is only one entry point in this class to change it.

To retrieve the value, typically a GetDisplayType method should be created which is public. The variable itself is private.
> 4 votes

# Answer
Michel Keijzers explained pretty well the purpose of that idiom. Just to complement his answer, you can do exactly the same in C, only with a slightly different syntax:

```
typedef struct {
    byte _Display;
    // ...
} HCTFT;

HCTFT_construct(HCTFT *this, byte DisplayType)
{
    this->_Display = DisplayType;
    // ...
}

```

Now, every function that receives a pointer to an `HCTFT` (a HCTFT “method”) has access to that data as a member of the struct.
> 2 votes

# Answer
That is more *Object Oriented Programing* question than the Arduino related.

Encapsulation is one of the fundamentals of OOP and it's basically you'll provide some interface to the object and the outside world doesn't have to know anything about it's internals (so it's not possible to change it into inconsistent state).
> 2 votes

---
Tags: c++, c, class
---


# Question
Title: Rescuing an Arduino With a Broken Setup()
I may have bricked my Arduino Pro Micro by writing a broken code into the setup() function. When I plug my Pro Micro into my PC, I see it register a COM port for a brief moment before it disappears. Grounding and ungrounding the RST pin causes the device to appear in my control panel again for a brief moment. Attempting to upload the blink example from the Arduino IDE fails, since the COM port disappears before the process can complete.

Is there an alternate way of flashing code to the arduino which I could possibly use to fix this? I have a working Pro Nano I could use if needed.

# Answer
After Majenko's suggestion I tried looking into USB ASPs, and then did research about whether you can use an arduino as an ASP. Sort of. I'm not sure if an ASP is exactly the same thing as an ISP, but I used an Arduino Nano as an ISP to program the Arduino Pro Micro.

To do this, I opened the ArduinoISP example sketch and burned it to the Nano (over USB). Then I connected it to a breadboard, along with the Pro Micro. Connected the following pins:

```
nano pin          micro pin
13                15 (SCK)
12                14 (MISO)
11                16 (MOSI)
10                RST
5v                5v
GND               GND

```

It is important to connect a capacitor from Nano RST to GND. I was told to use a 10uF capacitor but I had a 1uF on hand that worked just fine. Then I opened up the Blink example sketch, set up the Arduino IDE for programming the Pro Micro, and set programmer to "Arduino as ISP". Hold shift, click upload, problem solved. Pro Micro is running Blink and I can now recognize it and program it over USB.

So I agree with Majenko; someone faced with this problem should buy a hardware programmer. But only if you don't have a spare Arduino ;)
> 2 votes

# Answer
You can try running the code upload command directly using a precompiled hex file.

Here is how.

Go to preferences in Arduino IDE

Set the `Show verbose output during: upload` option.

`Upload` the blink sketch. (arduino does not have to be connected)

After the compilation, check the log window at bottom of the IDE.

You will find a line like this:

```
E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

```

That is the actual code upload command.

Copy the command line and paste it into a windows CMD window.

Edit the COM port to match your Arduino.

Reset the Arduino and immediately press `Enter` to run the command line.

You may get lucky and the upload "squeaks" through.

You can also move the hex file to another folder so that it is always available for doing a quick recovery.

You could also create a BAT file so that double-click on the icon runs the upload.
> 2 votes

---
Tags: programming, hardware, programmer, arduino-setup
---


# Question
Title: Converting of 32 bit signed hex value to dec
Using Seed studio CAN shield to read and convert CAN data to dec value.

Example of expected result:

Full CAN message is 70 3B F1 FF 00 00 00 00 , using little endian first 4 bytes gives: FFF13B70 , which should be equal to converted dec value of -0.967824 (using factor of 0.000001).

Here is code to extract the text value I am using.

```
CAN.readMsgBuf(&len, buf);
unsigned char len = 0;
unsigned char buf[8];
    {
           String reg0 = String (buf[0], HEX);
           String reg1 = String (buf[1], HEX);
           String reg2 = String (buf[2], HEX);
           String reg3 = String (buf[3], HEX);
           Serial.print(reg3);
           Serial.print("\t");
           Serial.print(reg2);
           Serial.print("\t");
           Serial.print(reg1);
           Serial.print("\t");
           Serial.print(reg0);
           Serial.print("\t");
           String regsumm = (reg3 + reg2 + reg1 + reg0);

           Serial.println(regsumm);
        }

```

As result I got only text string which couldn't be converted into dec. Any other ways how do it?

# Answer
You have taken completely the wrong tack. You don't want to convert your data into text and then convert it back into data again - it's already data.

You can combine your first four buffer bytes into a single 32-bit signed integer with just:

```
int32_t val = ((int32_t)buf[3] << 24) | ((int32_t)buf[2] << 16) |
              ((int32_t)buf[1] << 8) | (int32_t)buf[0];

```

That gives you the value -967824, which is 0xFFF13B70 in hex notation, or `11111111 11110001 00111011 0111000` in binary. All of them are the same thing and are just a number.

You can then multiply that result by your "factor" into a float variable:

```
float dec = val * 0.000001;

```

Chances are it won't give you -0.967824 due to the nature of floating point values, so you may be better off keeping it as -967824 and working in "micro-units" instead of "units".
> 1 votes

# Answer
Since the bytes you received in the buffer are in little endian order, and your Uno is itself little endian, you don't even need to move bytes around: you can just reinterpret the bytes you already have as an `int32_t`:

```
union {
    uint8_t bytes[8];
    int32_t numbers[2];
} buffer;
unsigned char len = 0;

CAN.readMsgBuf(&len, buffer.bytes);
Serial.println(buffer.numbers[0] * 1e-6, 6);

```

This prints `-0.967824` to the serial port.

Note that this code will not work as expected on a big endian platform. If you want something portable, the usual solution is to build the result using bit shifts, as in Majenko's answer.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Regarding turning exact 180 degrees using an MPU6050
I want to turn robot exact 180 degrees by using an MPU6050. This is the code I tried. Can anyone help me?

```
#include <MPU6050_tockn.h>
#include <Wire.h>

#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

MPU6050 mpu6050(Wire);

void setup() {
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
  setupmotor();

}

void setupmotor(){
    pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

}

void loop() {
updatempu();

while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
       turn();
  }

}

void updatempu(){
    mpu6050.update();
  Serial.print("\tangleZ : ");
  Serial.println(mpu6050.getAngleZ());

}

void turn(){
  Serial.println("turn");
        digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
      digitalWrite(in4, LOW);
    digitalWrite(in3, HIGH);
      analogWrite(enA, 100); // Send PWM signal to motor A
  analogWrite(enB, 100);
}

void stp(){
    Serial.println("stop");
        digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    digitalWrite(in3, LOW);

}

```

# Answer
As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.

The first problem was pointed out in the comments and your own code correction seems ok to tackle that:

```
if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
    stp();
} else {
    turn();
}

```

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.

This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like this one). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

---

As Tom pointed out in his comment, you also get trouble with your first approach, if the method `getAngleZ()` returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library here. The line

```
float getAngleZ(){ return angleZ; };

```

tells us, that the return type of the method is `float`. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with `int`). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like `179,98`. But since `179,98` is not equal too `180` the statement

```
mpu6050.getAngleZ() == 180

```

would never become true. Of course the mentioned solutions above apply here too.
> 0 votes

---
Tags: arduino-uno, mpu6050
---


title: How to read a PWM OUTPUT PIN value?

text:
# Question
Title: How to read a PWM OUTPUT PIN value?
How to get a pwm pin value that is in pinMode OUTPUT?

How to get a digital OUTPUT PIN value:

```
#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    digitalWrite(pin, HIGH);
    Serial.println(bitRead(PORTD,pin));
    delay(1000);
    digitalWrite(pin, LOW);
    Serial.println(bitRead(PORTD,pin));
}

```

For testing reasons, I want to get PWM output pin value.

**Incorrect sketch:**

```
#define pin 3

void setup()
{
  pinMode(pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
    delay(1000);
    analogWrite(pin, 100);
    Serial.println(pulseIn(pin, HIGH)); // value of the PWM output pin
}

```

This sketch was created for example only. I don't know PWM value because PWM value will be generating dynamically. Could you explain how to get a PWM output pin value, please?

# Answer
> 1 votes
According to the source code implementation of `analogWrite` function (Arduino analogWrite source code explanation).

You can use `OCRnx` register for reading PWM value.

# Answer
> 1 votes
> I want to get PWM output pin value.

The pin will either be 0 or 1.

> analogWrite(pin, 100);

It will be 1 for 100/256 (39%) of the time, and 0 the rest of the time.

---

Why do you want to do this?

---
Tags: programming, arduino-nano, pwm
---


# Question
Title: Can a push button be used for TFT LCD screens?
I am trying to link my TFT LCD touch screen to a few push buttons. May I enquire why my code is not working? I'm trying to link the screen and the button so I'm trying to make the image display a flower if the button is not pushed and the tiger only if pushed.

At the moment this code ends up displaying both images at once and the button whether or not the button is pushed.

My components include a 2.8" TFT LCD screen and an Arduino Mega

```
#include <SD.h>
#include <SPI.h>
#include <LCD_GUI.h> //Core graphics library
#include <LCD_KBV.h> //Hardware-specific library

LCD_KBV mylcd(ILI9341,A3,A2,A1,A0,A4); //model,cs,cd,wr,rd,reset

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

#define PIXEL_NUMBER  (mylcd.Get_Display_Width()/4)
#define FILE_NUMBER 4
#define FILE_NAME_SIZE_MAX 20

const int buttonPin = 41;
int buttonState = 0;

uint32_t bmp_offset = 0;
uint16_t s_width = mylcd.Get_Display_Width();
uint16_t s_heigh = mylcd.Get_Display_Height();
//int16_t PIXEL_NUMBER;

char file_name[FILE_NUMBER][FILE_NAME_SIZE_MAX];

uint16_t read_16(File fp)
{
    uint8_t low;
    uint16_t high;
    low = fp.read();
    high = fp.read();
    return (high<<8)|low;
}

uint32_t read_32(File fp)
{
    uint16_t low;
    uint32_t high;
    low = read_16(fp);
    high = read_16(fp);
    return (high<<8)|low;
 }

bool analysis_bpm_header(File fp)
{
    if(read_16(fp) != 0x4D42)
    {
      return false;
    }
    //get bpm size
    read_32(fp);
    //get creator information
    read_32(fp);
    //get offset information
    bmp_offset = read_32(fp);
    //get DIB infomation
    read_32(fp);
    //get width and heigh information
    uint32_t bpm_width = read_32(fp);
    uint32_t bpm_heigh = read_32(fp);
    if((bpm_width != s_width) || (bpm_heigh != s_heigh))
    {
      return false;
    }
    if(read_16(fp) != 1)
    {
        return false;
    }
    read_16(fp);
    if(read_32(fp) != 0)
    {
      return false;
     }
     return true;
}

void draw_bmp_picture(File fp)
{
  uint16_t i,j,k,l,m=0;
  uint8_t bpm_data[PIXEL_NUMBER*3] = {0};
  uint16_t bpm_color[PIXEL_NUMBER];
  fp.seek(bmp_offset);
  for(i = 0;i < s_heigh;i++)
  {
    for(j = 0;j<s_width/PIXEL_NUMBER;j++)
    {
      m = 0;
      fp.read(bpm_data,PIXEL_NUMBER*3);
      for(k = 0;k<PIXEL_NUMBER;k++)
      {
        bpm_color[k]= mylcd.Color_To_565(bpm_data[m+2], bpm_data[m+1], bpm_data[m+0]);
        m +=3;
      }
      for(l = 0;l<PIXEL_NUMBER;l++)
      {
        mylcd.Set_Draw_color(bpm_color[l]);
        mylcd.Draw_Pixel(j*PIXEL_NUMBER+l,i);
      }
     }
   }
}

void setup()
{

    Serial.begin(9600);
    pinMode(buttonPin, INPUT);
   mylcd.Init_LCD();
   mylcd.Fill_Screen(BLUE);
   //s_width = mylcd.Get_Display_Width();
   //s_heigh = mylcd.Get_Display_Height();
   //PIXEL_NUMBER = mylcd.Get_Display_Width()/4;
   if(PIXEL_NUMBER == 60)
   {
       strcpy(file_name[0],"flower.bmp");
       strcpy(file_name[1],"tiger.bmp");
       strcpy(file_name[2],"tree.bmp");
       strcpy(file_name[3],"RedRose.bmp");
   }
   else
   {
       strcpy(file_name[0],"01.bmp");
       strcpy(file_name[1],"02.bmp");
       strcpy(file_name[2],"03.bmp");
       strcpy(file_name[3],"04.bmp");
   }
  //Init SD_Card
   pinMode(10, OUTPUT);

    if (!SD.begin(10))
    {
      mylcd.Set_Text_Back_colour(BLUE);
      mylcd.Set_Text_colour(WHITE);
      mylcd.Set_Text_Size(1);
      mylcd.Print_String("SD Card Init fail!",0,0);
    }
}

void loop()
{

 buttonState = digitalRead(buttonPin);

    File bmp_file;
    if (buttonState == HIGH)
    {bmp_file = SD.open(file_name[0]);
      } else {bmp_file = SD.open(file_name[1]);
      }

       if(!bmp_file)
       {
          mylcd.Set_Text_Back_colour(BLUE);
         mylcd.Set_Text_colour(WHITE);
         mylcd.Set_Text_Size(1);
         mylcd.Print_String("didnt find BMPimage!",0,10);
         while(1);
        }

          draw_bmp_picture(bmp_file);
         bmp_file.close();
         delay(2000);
     }

```

# Answer
First of all, I suggest you to keep your source code tidy, this makes a lot easier to *follow* the flow.

As I don't know the library you are using, I'm assuming you have tested loading one single image works as expected in which case you probably need to wipe the screen before drawing a new image: I can't tell for sure because you didn't mention which library you are using (a link would have helped).

If there's a function named `clear`, `emptyBuffer` or similar, then you should call it before drawing the image, otherwise, you probably have to draw a filled rectangle in the same area where you are going to put your image.
> 1 votes

---
Tags: arduino-mega, tft
---


# Question
Title: CH340G and CP2102 devices not recognized with Thinkpad L380
I have three different devices, none of them gets recognized on my new Thinkpad L380 running Windows 10:

* Arduino Nano Clone with CH340G chip (USB2Serial)
* NodeMCU (Lolin V3) with CH 340G chip (USB2Serial)
* NodeMCU (ESP-WROOM-32) with CP2102 chip (USB2UART)

All three of them are recognized properly both on my desktop computer running Windows 10 (on USB 2.0 ports) as well as on my other laptop (Acer Switch Alpha 12, Win10, USB 3.0 port).

But even after hours of trying I was not able to connect those devices to my Thinkpad. Things I've tried so far:

* Of course, simply installing the Arduino IDE and try plug'n'play
* Downloading and installing the CH340G driver from the official website
* Disabling Secure Boot, enabling testsigning mode and reinstalling the CH340G driver
* For the CP2102 device I only tried installing the driver under "normal" Windows (e.g. no testsigning enabled) since it also worked that way on my desktop computer

I have to admit that it's been a while since I set up the drivers on my other laptop and desktop computer, but I cannot remember that there was anything unusual I had to do back then.

Does anybody else know about problems regarding Thinkpad laptops? At first I thought USB 3.0 might be the problem, but the Acer laptop works just fine with the USB 3.0 port.

**Update**

Somehow the laptop now at least recognizes the Arduino Nano clone in the device manager and I can choose the COM port in the Arduino IDE. I can't tell what made the difference. All I did was to plug in a dongle for a wireless mouse in the USB ports to verify that they are working with "normal" devices and afterwards the Nano was recognized at least with a yellow "!" in the device manager. I then was able to uninstall the CH340 drivers and reinstall them. The device manager now displays the Nano as correctly installed.

But uploading a sketch fails. It outputs the errors:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x0a
avrdude: ser_send(): write error: sorry no info avail
avrdude: ser_recv(): read error: Access denied

```

The RX LED is faintly blinking in red at the beginning of the process, then the upload seems to get stuck until the error messages are displayed.

The NodeMCU Lolin V3 with the same CH340 chip is still not recognized, though.

Serial communication (with the Serial monitor of the Arduino IDE) is now possible. I uploaded the "ASCIITable" example using my Desktop PC, connected the Arduino to the ThinkPad and could successfully read the output over the serial interface.

# Answer
I recently bought a cheap USB 2.o hub. Turns out that the CH340G devices are recognised if I plug them in the hub rather than in the laptop directly. Maybe this helps somebody else who is searching for a solution, even though I can't explain why the hub is making a difference.
> 0 votes

---
Tags: serial, usb, windows, ch340
---


# Question
Title: Debug-logging without using Serial.print and without WiFi
In order to transmit text from the Arduino board to the HC-05 Bluetooth module, I have use `Serial.print`. However, I don't see a way to debug the code without using `Serial.print` to test the other features of the software. Is there another way to transmit text from the Arduino to the computer, and from the Arduino to the HC-05, simultaneously (and without WiFi)?

# Answer
> 1 votes
Yes, what version of Arduino are you using?

* For **Arduino Mega**, you can use `Serial.println` for writing debug data and `Serial1.println` for communication with HC-05. (See Example: MultiSerial Example)
* For **other Arduino boards**, you can use `Serial.println` for writing debug data and SoftwareSerial library for communication with HC-05. (See Example: SofwareSerial)

---
Tags: serial, hc-05, debugging
---


title: LCD lights up but shows no text

text:
# Question
Title: LCD lights up but shows no text
I've connected an LCD display to an Arduino Uno following the instructions from the Adafruit LCD lesson.

I've used the code sample described in the Adafruit lesson.

What happens after I connect the Uno to the USB cable is that the LCD lights up, but no text is displayed.

I've checked all connections and they look good. I am not 100%sure I have connected the potentiometer correctly, as this is the symptom I usually found online.

Could this also be a bad solder job? It's my first attempt and I guess it did not go that great.

Here are some more images, maybe someone with more experience can spot the error.

---

*Update*: here's what the board looks like once connected

and after removing the ethernet shield I get some weird flashes from time to time, only when I switch the potentiometer to maximum on one side, see video at https://i.imgur.com/ZclD2xz.mp4 .

*Update 2*: I realised that this is a 20-pin LCD screen and re-reading the datasheet and some online tutorials I switched digital wire connections to pins to the LCD 7-10 (DB0-DB3) - same result and then 11-14 (DB4-DB7) - garbled output, shown below. Still no idea what is wrong.

# Answer
From provided picture it is visible that your display is **not alphanumeric display** (with most popular HD44780 driver). **It is a graphical display** (most popular: KS0107 or KS0108 or ST7920). You can count horizontal pixels and vertical ones in the picture to confirm its resolution.
Without too many problems you can drive it with your Arduino. Try to use some of 128x64 Arduino libraries. Also, check the rear of the display for any part number to confirm the driver (search in google).
Good luck!
> 1 votes

---
Tags: lcd, breadboard
---