# Question
Title: Infrared sending not working slight misconfiguration?
Edit: Took some advice from below but it still doesn't work. I think it probably blocking code but please tell me how I could fix it to send a the valid infrared signal, NOTE: I wouldn't actually code it like this I am just trying to learn and understand how to do it and then make it better after:

```
uint8_t Status;
uint8_t Counter;
const uint32_t Code[] = {4507,4507,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,1694,573,1694,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,573,573,573,573,573,573,573,573,573,573,1694,573,573,573,1694,573,1694,573,1694,573,1694,573,1694,573,1694,573,46560};

void setup() {
  pinMode(4, OUTPUT);
}

void loop() {
  while(Counter<70) {
    if (Status=1) {
        digitalWrite(4, HIGH);
        Status=3;
        while(Status=3) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=2;
        Counter++;
    } else {
      if (Status=2) {
        digitalWrite(4, LOW);
        Status=0;
        while(Status=0) {
          delayMicroseconds(26);
          digitalWrite(4, HIGH);
          delayMicroseconds(26);
          digitalWrite(4, LOW);
        }
        delayMicroseconds(Code[Counter]);
        Status=1;
        Counter++;
      }
    }
  }
}

```

# Answer
> 0 votes
There are two basic things wrong here - one with your understanding of the timings, and the other with your understanding of how IR communication works.

First the timings - those are both ON *and* OFF timings. You don't just turn on for a defined length of time - you turn on for a defined length of time *and then turn off for another defined length of time*.

So for the timings in your code `4507,4507,573,1694,573,...etc...` you would:

* Turn on
* Wait 4507us
* Turn off
* Wait 4507us
* Turn on
* Wait 573us
* Turn off
* Wait 1694us
* Turn on
* Wait 573us
* ... etc ...

You have no "off" time in your code, only ever on times.

Secondly is your understanding of IR communications. It does not involve turning an LED on or off for defined times. It's not as simple as that. Instead you are controlling the *modulation* of an LED. When the LED of an IR remote control is "on" it's not just turned on - it's rapidly turning on and off. The receiver looks for the presence or absence of this rapid turning on and off light. This is the "carrier frequency" of the signal and must match what the receiver is looking for.

Typically this is between 30kHz and 50kHz depending on the receiver.

So you need some way of generating that rapid on-off signal. Normally this is done using PWM by the IR libraries and switching between 0% and 50% duty cycle for the off and on periods of the signal you want to send.

So it's far simpler to just use a library that does all this underlying work for you.

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Using LM70 temperature sensor with Arduino
I am trying to sense the temperature using the LM70 temperature sensor with an Arduino Mega. As you can see in the Datasheet, it uses the SPI protocol. I have made the following connections (VSSOP-8 Package):

* SI/O pin --\> Pin 50 Arduino Mega.
* SC pin --\> Pin 52 Arduino Mega.
* CS pin --\> Pin 53 Arduino Mega.
* V+ pin --\> 3.3V Arduino Mega.
* GND pin --\> GND Arduino Mega.

My code does not work (it does not print the right temperature), and I think it can be for two reasons:

1. I am not reading correctly the information from the sensor. It sends 16 bits, from which the 11 first bits store the data for the temperature.
2. I am not calculating the temperature in the right way.

This is my code:

```
// the sensor communicates using SPI, so include the library:
#include <SPI.h>

void setup() {
  pinMode(51,OUTPUT); //MOSI
  pinMode(50,INPUT); //MISO
  pinMode(52,OUTPUT); //CLOCK PIN
  digitalWrite(53,HIGH); //slave select stays high. When we set this to low, the sensor will start to send data.
  SPI.begin();
  Serial.begin(9600);

  //time to set up
  delay(500);
}

void loop() {
    //enable Slave
    digitalWrite(A0,LOW); //Enable communication with slave
    delay(500); //wait for conversion

    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;
    Serial.println(temperature); //display temperature on serial monitor

    //disable Slave
    digitalWrite(53,HIGH); //set to High again
}

```

Please, if you see something wrong in my code, let me know. Thank you in advance.

# Answer
There are several things that are not doing correctly. This is not a complete answer but to provide you some directions on how to get it right.

1. `A0` is pin 54, it is not `SS` which is pin 53;
2. On how to use the SPI library properly, I would suggest that you read my blog on SPI, it will also help you to get the data out of data sheet that you need for SPI programming. Based on the timing diagram on the data sheet, you will need to configure the SPI as `SPI_MODE2`;
3. LM70 SI/O pin is used as both MOSI and MISO, you will need to connect MOSI to SI/O via a 10k resistor, and connect SI/O direct to MISO, this information is available in the data sheet;
4. LM70's temperature data is in Two's complement format, To convert it, it needs a little bit work. It is then need to shift down/right using bitshift operator by 5 bits to get ride of the first 5-bits, before finally multiply by 0.25C as per data sheet.

```
int value = 0x4b1f;  //value from SPI, temp = 125 degree C
int mask = 0x8000;   // mask for MSB
int temp = (-(value & mask) + (value & ~mask)) >> 5;
Serial.print("Temp");
Serial.println(temp*.25);

```

Read all links that I provided to understand the subjects and give it a try. Good luck!
> 2 votes

# Answer
Your problem lies here:

```
    int val = SPI.transfer(0x00); // read from sensor
    Serial.println(val); //display reading on serial monitor
    int temperature = val * 0.25;

```

And it's a twofold problem.

First:

```
int val = SPI.transfer(0x00);

```

That only reads the first 8 bits of the data. To get all 16 bits you have to do two transfers and then combine them together with bitshifting:

```
int bh = SPI.transfer(0x00);
int bl = SPI.transfer(0x00);
int val = (bh << 8) | bl;

```

That then gives you a value that is right-aligned. you then need to shift it to the left the right number of bits and "sign extend" it to keep it negative if needed. If you're not interested in the fractional part then it's as simple as:

```
val >>= 7;
if (val & 0x0100) {
    val |= 0xFE00;
}

```

Now... what does that all mean? Well, assume it's currently 25°C. From the datasheet we can see that would give us a reading of `0000 1100 1001 1111` (note there is a typo in the datasheet saying that is 0b9f in hex when in fact it's 0c9f).

Let's do those operations - first the bit shift:

```
Dec   Hex   Bin
3231  0C9F  0000110010011111 >> 7
25    0019  0000000000011001

```

Then we look to see if bit 8 is set or not (bit 8 was the most significant bit). If it is then we OR it with bits 9-15 also set. This "sign extends" it.

Let's take a look at -25°C from the datasheet:

```
Dec   Hex  Bin
-3169 f39f 1111001110011111 >> 7      Shift right 7 bits
487   01e7 0000000111100111 & 0x0100  And with 8th bit
256   0100 0000000100000000           Result is not 0 so is true

"Or" the shifted value with 0xFE00:

487   01e7 0000000111100111 or
65024 fe00 1111111000000000 =
-25   ffe7 1111111111100111

```
> 1 votes

---
Tags: arduino-mega, spi, temperature
---


# Question
Title: What wireless protocols can be used with arduino?
Before you close this saying it's not related to programming. It is related to programming since i'm using it and asking about libraries.

What are the common types of communication protocols and their libraries? Theres WiFi which uses esp8266 etc. Zigbee which can be used with XBee, Bluetooth which can be used with esp32 and others. What are a list of wireless protocols and chips and libraries for those wireless communications? (This list will be compiled by multiple people hopefully so its okay if you don't know the library or chip but protocol is good) thank you and hopefully no take down \<3

# Answer
Arduino allows you to connect external peripherals (via I2C, SPI, UART, I/O) and shields.

It'll be impossible to list them all, as you can even make your own; but here an overview of the most common I can think off:

* WiFi
* Bluetooth
* LoRa
* Zigbee
* Z-wave
* RF (433mhz)
* InfraRed
* GSM/LTE

It'll be a trade-off between signal range, power usage, delay and bandwidth.

Do note that your question in this way is quite broad. If you want to use this to start your own wireless proejct, you can follow these steps (, but do note that we expect one to do some research/tests himself before posting a question):

1. Find a tranmission layer applicable for your project based on requirements.
2. Find Arduino compatible hardware (if none found; make your own or find another transmission layer / adjust requirements)
3. Find libraries/examples of this hardware being used with Arduino.
4. Buy the hardware (this is not step 1!)
5. Use the found sources and make your project reality.
> 3 votes

---
Tags: arduino-uno, arduino-ide, library, wireless
---


# Question
Title: Why Can't I Program my Atmega168 Pro Mini?
I'm trying to program a Atmega168 Pro Mini 3.3V/8mhz I bought online. I followed a tutorial that walks through the steps of how to program a Pro Mini with an Arduino Uno. However, in their example they are uploading code to a Atmega328 Pro Mini though I don't think it matters.

Anyway, I followed the same steps as they did (namely hooking up Uno's ground -\> ground, 3v -\> Vcc, Reset -\> DTR, tx-\>tx, rx-\>rx). When I attempted to upload via Arduino IDE I got the message that the programmer was not responding. I also noticed that the transfer led on the Uno was not lighting up. Did I screw up something? Also, are my hookups correct? I would think tx pin should connect to rx pin, but I just followed the instructions. Would appreciate any thoughts

# Answer
> 1 votes
Your hookup seems to be correct. However check if there is a capacitor on the pro-mini board between DTR and reset pin, some arduino clones don't come with one. If there isn't any you can simply connect a capacitor like this: Reset pin (Arduino Uno) -\> Capacitor (0.01uF for example) -\> DTR (pro mini). The reason for this hookup is exmplined well here

---
Tags: arduino-uno, arduino-pro-mini
---


title: Arduino binary LED 10 bit display

text:
# Question
Title: Arduino binary LED 10 bit display
I'm working on a simple ADC project, the goal is to adjust the on/off of the LEDs according to the binary reading (1-on,0-off). I've tried this with 8 bit, and it works as intended. But on 10 bit, two of the LEDs with representation of 2^8 and 2^9 won't turn on even though the reading on the serial monitor is 1023 (should be 1111111111 -all LEDs on). I wonder if there's anything wrong with my code or circuit? (I'm totally new to arduino, sorry for the noobness) -I'm using Arduino UNO R3, the details are shown in the image

```
void setup(){
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin(9600);
}

void loop(){
  int sensorValue = analogRead(A0);
  Serial.print("Decimal=");
  Serial.print(sensorValue);
  Serial.print("\tBinary=");
  Serial.println(sensorValue,BIN);

  if(sensorValue>=0&&sensorValue<=1023){
    digitalWrite(4,(sensorValue&1));
    digitalWrite(5,(sensorValue&2));
    digitalWrite(6,(sensorValue&4));
    digitalWrite(7,(sensorValue&8));
    digitalWrite(8,(sensorValue&16));
    digitalWrite(9,(sensorValue&32));
    digitalWrite(10,(sensorValue&64));
    digitalWrite(11,(sensorValue&128));
    digitalWrite(12,(sensorValue&256));
    digitalWrite(13,(sensorValue&512));
  }
  delay(20);
}

```

# Answer
> 3 votes
According to the official documentation, the second parameter of `digitalWrite()` should be either `HIGH` or `LOW`. Thus, in order to be compliant with the published API, you are supposed to write:

```
digitalWrite(12, sensorValue&256 ? HIGH : LOW);

```

In practice, `digitalWrite()` interprets any non-zero value as `HIGH`. However, its prototype is:

```
void digitalWrite(uint8_t pin, uint8_t val);

```

Both parameters have the type `uint8_t`, which means “8-bit unsigned integer”. If you provide a value that doesn't fit in 8 bits, the implicit cast to `uint8_t` will reduce it modulo 28. Thus, both 256 and 512 become zero through the implicit cast.

# Answer
> 1 votes
Seems, digitalWrite does not take any `int` != 0 as HIGH

Rather consider supplying a boolean (one byte value)

```
   digitalWrite(12,(sensorValue&256)==256);
   digitalWrite(12,(sensorValue>>8)&1);

```

or similar

---
Tags: arduino-uno, adc
---


# Question
Title: Sequencing air pistons proble - Help please?
I am a beginner trying to activate 2 sets of 3 air pistons sequentially by going through the YouTube Tutorials... Help, please, pretty please?? :-)

There are 3 sets of 2 pistons, each set working in opposition. So I have P1/P2, P3/P4, and P5/P6, each set working in opposition to squeeze at the center sequentially - Initial state at turn-on/Reset must be:

```
// Step 1 Run Once:
P1 Down/P2 Up  // Move simultaneously (joining at the center) and HOLD in position -
P2 Up/P3 Down  // Move simultaneously and HOLD -
P5 Up/P6 Down  // Move simultaneously and HOLD -
// Wait for Start button -

```

I need to start/stop the sequencing with a toggle push-button - I have reed-switch sensors that will give me a set of two TRANSIENT contact closure for each piston moving to the Up and Down positions -

Once started, the sequence needs to be as follows:

```
// Loop until Reset button is pushed -
// STEP 2: -
P1 Down/P2 Up (HOLD) // Old Initial State, unchanged -
P3 Down/P4 Up (MOVE) // Piston 3 moves Down/Piston 4 moves Up and HOLDS -
P5 Up/P6 Down (HOLD) // Still Old Initial State, unchanged -

```

// PROBLEM: P3 Down AND P4 Sensors only give me a TRANSIENT closure: These two transients MUST occur to initiate Step 3, but they are not always exactly synched together, so my initial try by putting them in series fails... - // I need to use that set of contact closures to trigger the next command: -

```
// Step 3: -
// The transient closures of P3 Down/P4 Up Sensors is the trigger needed for -
P5 Down/P6 Up (MOVE) // P5 moves Down/P6 moves Up and HOLD -
P1 Up/P2 Down (MOVE) // P1 moves Up/P2 moves Down and HOLD -
P3 Down/P4 Up (HOLD)  // P3/P4 HOLD -

// Back to Step 2 until the Reset button is pushed -

```

I can send you my attempt at coding for this, but it does not work unless the two sensors close simultaneously, which only happens in simulation... ARGH.. :-(

Can someone send me a piece of code that will work for this, please? I would really, really appreciate that... Very frustrated right now! You can email me at XXXXXXX.XXXX@XXXXX.XXX or text/call at (XXX)XXX-XXXX Thanks either way. Sincerely, Michael

PS: I tried to wire for a separate toggle switching for each sensor, but I run out of pins on my Arduino UNO R3... Looking into it via YouTube https://www.youtube.com/watch?v=cAT07gy4DII "Increase the digital outputs on an Arduino (PART 1 & 2)" but that is way more complex... Trying to wade my way through that now...

# Answer
> it does not work unless the two sensors close simultaneously

If I understand correctly, the problem is that when your Arduino detects the second transient signal, the first one is not active anymore, and your program doesn't remember it has already seen that first signal.

Your Arduino has memory. Thousands of bits of memory! So it can remember quite a few things. The solution to your problem is to simply make use of that memory. When you detect a signal that should be useful for a future decision, take note, store it in a variable. In order for the variable to be remembered across calls of the function where you set it, it has to be global. Or, better yet, `static` local.

Here is how that could look like in code:

```
// A `static' variable is a variable that remembers its state across
// calls of the function. A global variable would do the same, but
// code is usually clearer when variables are defined close to where
// they are used. A `bool' (for "boolean") is a variable that can only
// be either `true' or `false'.
static bool P5_is_up, P6_is_down;

// If the sensor tells us that the P5 piston went all the way up, take
// note of the fact and remember it.
if (digitalRead(P5_up_sensor) == LOW)
    P5_is_up = true;

// Same for P6 going down.
if (digitalRead(P6_down_sensor) == LOW)
    P6_is_down = true;

// If both pistons finished their travel, we can move to the next
// step. `&&' means "and".
if (P5_is_up && P6_is_down)
    goto_step_3();

```

You will need to reset those variables to `false` at the appropriate time. The example code above doesn't show that as it only deals with the logic for deciding when it is time to start step 3.

You will probably end up with many of these variables, and lots of repetitive code. So you will need to structure your program in order to avoid excessive repetition. But that is not your immediate problem. For now, try to make the logic work for a single step transition. Once you get the logic right, you can worry about generalizing the logic to any transition.
> 1 votes

---
Tags: arduino-uno, programming, sensors, relay, timing
---


title: Dealing with a Signal Source

text:
# Question
Title: Dealing with a Signal Source
The following circuit is a simplified version of a more complex system. For testing purposes, the 555 Timer was added to serve as a test signal source with frequencies set by the resistors in series. Each arbitrary signal is indicated by a push button and the Arduino needs to be able to distinguish what button has been pushed. Unfortunately, there can only be 3 buttons and more cannot be added. This is where the problem occurs. How can you reliably indicate which push button has been pressed without interfering with the arbitrary waveform?

At first, my original thought was to have the Arduino sample the signal based on that sample the Arduino would be able to tell which button is pressed.

When button 1 in the pink is pushed the Arduino receives a takes the following sample of the signal.

```
843
848
849
849
849
849
   // Time 0 when button is pushed
532
414
500
373
463
346
425
370
386
476
346
442
642
788

```

Moving the input

```
    // At t = 0 the Serial Monitor reads zero
    998
    998
    998
    998
    998
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    0
    0
    0
    0
    0
    998
    0
    0
    0
    0
    998
    0
    0
    0
    998
    998
    998
    0
    998
    0
    0
    0
    998
    0
    0
    0
    0

```

Moving the analog input does not make it any easier to distinguish which button was being pushed. Which is why I decided to ask the community on how to deal with this. I have tried using a relay and simply hard coding all of the cases but the result is a system is not very robust and is vulnerable to easily break over time.

# Answer
> 1 votes
After a day or two of working on this problem, I have found that it is best to avoid using the analog pins and stay away from directly interfacing with the 555 Timer. This is a simplified version of a more complex circuit and the 555 Timer represents some arbitrary signal source. For example, on mobile radio, you push a button to send out a certain frequency. That is the concept here only the frequencies cannot be adjusted yet. Now that it has been clarified that the 555 Timer has been placed in the circuit for debugging purposes here is the best solution I have found to this problem. First, I have found that it is doable to read in from the analog pin on the Arduino but not easy. This leaves a lot of room for error being that the waveform is arbitrary with some random frequency. Therefore, I have opted to use the digital pins on the Arduino.  by using the digital pins I have now only have to worry about whether the button is high or low. Then NPN transistors were used to act as switches once the button is pushed. The diodes then were added to maintain a steady voltage across the base of the transistor. For testing purposes, the LCD was removed and replaced by an LED. As far as the code is concerned it is nothing extraordinary or complex as shown below. Therefore, I believe this may be the best way to go about solving this problem.

```
const int D_pin10 = 10;
const int D_pin9 = 9;
const int D_pin8 = 8;
int led = 13;
void setup()
{
  pinMode(D_pin10 , INPUT); // pin 10 is an input
  pinMode(D_pin9 , INPUT); // pin 10 is an input
  pinMode(D_pin8, INPUT); // pin 10 is an input
  pinMode(led, OUTPUT);
}

void loop()
{
  int High_Low10 =0;
  int High_Low9 =0;
  int High_Low8 =0;

  High_Low10 = digitalRead(D_pin10);
  High_Low9 = digitalRead(D_pin9);
  High_Low8 = digitalRead(D_pin8);

  if(High_Low10 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else if(High_Low9 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else if(High_Low8 == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else
  {
    digitalWrite(led, LOW);
  }
  delay(1000);
}

```

# Answer
> 3 votes
There's an easy way to achieve reading multiple pushbuttons using single analog input.

All you need to do is create some voltage dividers at different voltages which can be read using analogRead. The last resistor,R6, in the diagram below ensures that the pin reads 0 when no push-button is pressed (i.e pull-down resistor). In the diagram below, connect Vcc to 5V on the Arduino.

Try it out, you should be able to get well spaced out values for different push buttons!

---
Tags: analog-sampling, digital-analog-conversion
---


# Question
Title: Arduino Vin pin does not work, but Arduino 5v pin power works
I have a very weird problem, at least it seems to me that way. I have connected L298N motor driver, Arduino and a hobby servo with a 6v power supply (tested with both 4xAA and 9v alkaline batteries). And wrote a simple program to rotate the servo every 10ms. There are no other motors connected as of yet.

1. Power supply is connected to the L298N 12v and GND.
2. Arduino is connected to the 5v and GND of L298N driver with the Vin and GND of Arduino respectively.
3. Servo's power (red wire) is connected to L298N 5v, GND is connected to the L298N's GND, and, servo's control (orange wire) is connected to pin 9 of Arduino.

The problem is that the servo hardly moves when Arduino gets power supply gets from the Vin input. However, if I connect it to the 5v of the Arduino power it works as expected. But I was under the impression that 5v pin of Arduino was to for the output and not for the input power supply. Could you guys please tell me what am I doing wrong here?

# Answer
The Vin pin on the Arduino Uno board is connected to the **input** of the 5V onboard voltage regulator of the Arduino board.

This voltage regulator needs an input voltage that’s about 1.5V above its (regulated) 5V output that will feed the Arduino.

Arduino - note the recommended values of the Input Voltage (7-12V)

If you feed 5V into Vin, the voltage drop on the internal regulator will cause the Arduino board to be supplied with only about 3.5V, which is probably enough to make it function, but not enough to control the servos.

The solution, as you already found out, is to feed the 5V from the L298N board directly into the 5V pin of the Arduino. Please take care to measure the actual voltage from the L298N before you do this (it should be 5 Volts). Alternatively you could connect 12V to the Vin pin of the Arduino, but again, make sure you know what you’re doing.
> 2 votes

# Answer
You are using Arduino to drive one servo motor and that's simple with only using arduino board with this setting:

1. 5V supply pin
2. GND pin
3. any pwm pin

Now using the LM298N here isn't optimal. If you googled LM298N, you would get the main application of this driver which is to drive DC and stepper motors.

For driving multiple servo motors, you can use this module board to drive upto 16 servo motors.

Here is a link for it on Banggood.

PCA9685 16-Channel 12-bit PWM Servo Motor Driver I2C
> 0 votes

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


# Question
Title: Help in personal alarm clock project, cant write time on seven segment display
I'm trying to make a type of Arduino alarm clock, which when the time I inputed is equals to the current time, a servo will turn on my lights. It basically consists of a Keypad, an RTC DS1307 and a TM1637 seven segment display. The basic idea is that the RTC module would print time to the display until I decide to write something on the keypad, which would clear the time on the display to let me write the alarm. My problem is that the display manages to both show time on the display and write to the display but this only works on separate code, not together.

The keypad has a '\*' and '#' character, when i decide to write the time i want the lights to turn on, after writing it i press the '\*' character to save that time and then the idea would be to compare the time written and the present time, if i press '#', then all would be canceled and the RTC module would continue to show the time on the display. (i have not manage to advance that much due to my error on not being able to clear the display when i want to write on the keypad)

```
#include "Arduino.h"

// KEYPAD
#include "Keypad.h"

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

char customKey;

byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// DISPLAY
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"

const byte PIN_CLK = 4;   // define CLK pin (any digital pin)
const byte PIN_DIO = 5;   // define DIO pin (any digital pin)
SevenSegmentExtended      display(PIN_CLK, PIN_DIO);

// RTC

#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

void setup(){
    Serial.begin(9600);         // initializes the Serial connection @ 9600 baud
    display.init();
    display.setBacklight(100);  // set the brightness to 10 %
    display.print("ON");      // display INIT on the display
    delay(1000);                // wait 1000 ms
    display.clear();
}

// OTROS

#define digit 4

byte data_count = 0;
char Data[digit];

void loop(){

    tmElements_t tm; // CLOCK

    display.setColonOn(true);
    customKey = customKeypad.getKey();

    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }

    if (customKey) { // ACTIVATE KEYPAD

        display.clear();

        if (customKey == '*') { // IF *
            display.blink();

            if (Data[data_count] < 3) {
                error();
            }

        } else if (customKey == '#') { // IF #
            display.blink();
            display.setColonOn(false);
            display.clear();
            clearData();
        } else { // WRITE ON DISPLAY

            Data[data_count] = customKey;
            display.setCursor(0,data_count);
            display.print(Data[data_count]);

            if (data_count < 4) {
                data_count++;
            } else {
                error();
            }
        } // END DISPLAY WRITE

    } // END KEYPAD IF

} // END LOOP

void error() { // DISPLAY ERROR AND DELETE DATA
    display.clear();
    display.setColonOn(false);
    display.print("ERR");
    delay(1000);
    display.clear();
    clearData();
}

void clearData() { // CLEAR DATA
    while (data_count != 0) {
        Data[data_count--] = 0;
    }
}

```

This are the libraries i'm using if it helps: https://github.com/bremme/arduino-tm1637, https://github.com/PaulStoffregen/DS1307RTC and the Keypad library from Arduino library manager

Hope I made myself clear with my problem, english is not my first language, if you want more clarification then let me know!

That is basically what i've got, i'm sorry if the post is too long, i have been struggling with this problem for two days and i don't know how to proceed. Hope you all can help. Thanks!

# Answer
> 2 votes
I think your problem is here:

> ```
> if (RTC.read(tm)) {
>     display.printTime(tm.Hour, tm.Minute, true);
> }
>
> ```

This code displays the current time, and it runs on every single loop iteration. This is visibly not what you want. Your project should have at least two distinct operational modes: “display the current time” and “allow the user to input data”. You need a variable to remember which is the current mode, e.g.

```
enum { MODE_DISPLAY_TIME, MODE_DATA_INPUT } mode;

```

You need to precisely define the events that make your program switch modes, and code specific behaviors for each mode. For example:

```
if (mode == MODE_DISPLAY_TIME) {
    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }
} else if (mode == MODE_DATA_INPUT) {
    // Handle user input.
}

```

This general approach is called a “finite state machine”. You can read more about it in this blog article by Majenko.

---
Tags: arduino-nano, display, code-review, rtc, keypad
---


title: Photoresistor help

text:
# Question
Title: Photoresistor help
I'm a newcomer to Arduino, trying to read analog values from a circuit with a photoresistor. I believe I am using a 1-ohm resistor

The problem I am having is that my photoresistor does not seem to be working, or my circuit is wrong. When I run the below code on my Nano, my Serial monitor constantly prints 1023. When I cover the photoresistor completely with my finger, the value dips down to 900-950, but then jumps back up to 1023. It dips down to 900-950 again, and jumps back to 1023. This happens continuously.

Here is my code:

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

void loop()
{
  int value = analogRead(A0);
  Serial.println(value);
  delay(20);
}

```

Here is an image of the circuit I am using. In my case, I am using a Nano instead of Uno.

I ran the above code on the virtual circuit above, and it works as expected. However, on my physical device, the phenomenon I explained above occurs.

Is there something wrong with my circuit? Could it be an issue with my photoresistor?

# Answer
> 3 votes
If you pealed the backing off the bread board you will find that you have plugged in your green, red and photo resistor wires into one piece of metal. This means they are shorted together and as such do not work as you might expect.

Also, be aware that photo resistor or cadmium sulfide cells are slow to react to changes in light. Sometimes taking about a second to fully change to a new resistance. If you need a faster response consider using a photo diode or photo transistor.

---
Tags: arduino-nano, photoresistor
---


# Question
Title: TPIC6B595 Output Unable to Allow Supplied Power to 7-segment Display
We have an Arduino Nano connected to 4 small (0.5") common-anode 7-segment displays and 2 large (3") common-anode 7-segment displays. We are trying to multiplex the displays. The larger one requires more power than the smaller one (9V) which the shift register cannot supply.

Therefore, we have supplied 9V to the open drain outputs of the shift register that are connected to the larger displays with a pull-up resistor (390ohm). However, more power (7.5V) goes to the resistor than the display (1.5V).

They are connected like in the ShiftDisplay library's schematic, with a pull-up resistor added according to this link on open drain.

How do we use the open drain outputs logic to supply power to the display?

The data sheet of the big 7-segment display can be found here. Each display requires 160mA of continuous current.

# Answer
> 1 votes
You are getting confused. The pullup resistor is only needed on open drain when you are using it to generate logic levels. It turns the OD output into an RTL output.

You don't want that.

Instead you want your open drain outputs to act like a low-side switch transistor - which is infact what they are.

You can do that by simply placing your LEDs in *series* with your "pullup" resistor, thus:

simulate this circuit – Schematic created using CircuitLab

I have only shown two elements there (everything inside the dashed box is inside the shift register), but you can see now how when an output is "on" the transistor conducts, and the current flows through the LED, through the resistor, through the transistor, and down to ground.

Your resistor value is then calculated as simply

```
    9 - Vfled
R = ---------
      Iled

```

For 20mA and a 2V forward voltage that comes out as 350Ω - so your 390Ω resistors are perfectly fine.

# Answer
> 0 votes
Can you use different resistors for each display group? If so that will solve your problem along with what Majenko said.

---
Tags: arduino-nano, power, shift-register, multiplexer, 7-segment
---


# Question
Title: My code is not uploading to Arduino Uno, Please help!
I am very new to arduino, so new that it is my first board. I keep running into this error
`avrdude: stk500_recv(): programmer is not responding`
`avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00`
I have searched the internet for hours, tried solutions from almost every StackExchange question related to this topic, and even Reddit posts but none of those have been able to help me. All my settings are as they are supposed to be. Both the correct board and serial port are selected but it still keeps giving me this error:
`System wide configuration file is "/home/rahat/Desktop/Arduino/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"`
`User configuration file is "/home/rahat/.avrduderc"`
`User configuration file does not exist or is not a regular file, skipping`

```
   ` Using Port                    : /dev/ttyS4
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200`

```

`avrdude: stk500_recv(): programmer is not responding`
`avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00`
Also my operating system is **Ubuntu 20.04 LTS**

# Answer
> 2 votes
First of all find out on which port the Arduino is connected by running the command : `dmesg | grep tty`. You should get `[82893.921017] usb 1-1: cp210x converter now attached to ttyXXX` with the `ttyXXX` COM port. Then check if the port is visible `Tools->Port`. If the port is not visible then you have a permission issue.

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: Terminal read-only serial monitor without blocking serial port for sketch upload
I would like to have all serial output from Arduino (nano) dumped to the terminal in Linux, without blocking the serial port for uploading new sketch version (for quick debugging loop), when using Arduino-Makefile:

```
[Errno 16] could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

```

Is there something made for that already? I did read about 10 related questions here and elsewhere (using `screen`, `socat` and others) but none of them deals with the question how to not block the port.

I might eventually code something in Python, which will disconnect when signalled and reconnect again after a few seconds (I use custom Makefile for the upload) and I imagine Arduino's IDE serial monitor does something similar.

Other pointers on how to solve the issue are appreciated!

# Answer
> 2 votes
> (using screen, socat and others) but none of them deals with the question how to not block the port.

> Other pointers on how to solve the issue are appreciated!

I say:

> Virtually all hardware problems can be solved with software. But, sometimes, the $50000 software problem can be solved with the $2 hardware solution.

This is one of those cases. Buy a CP2102 6-pin serial UART USB adapter for \< $2 on Ebay, or for \< $10 on Amazon, to provide a second serial interface to the same Arduino (both connected to the same hardware UART built in to the Arduino's ATmega328 mcu). Let the main USB serial interface handle code uploads to the Arduino. Let this 2nd, external UART handle READ-ONLY from the Arduino!

Plug it in:

```
Arduino     CP2102 USB 6-pin UART
-------     ---------------------
Tx          Rx
GND         GND

```

Done. Do NOT plug in the CP2102 `Tx` to anything.

Now, use `picocom` (one of my favorites), `screen`, or my crude datalogging Python serial terminal I wrote here (eRCaGuy\_PyTerm), or a 2nd instance of the Arduino IDE with the Serial Monitor, or any other serial terminal for that matter, to read from the CP2102 while the Arduino's built-in USB adapter does code uploading.

Two serial interfaces to the same pins on the Arduino: one does Tx/Rx to/from the Arduino, while the other does only Rx to read from the Arduino.

I use a 2nd UART like this all the time as a trick to allow me to read the data from the Arduino into one **Serial Monitor** in one instance of the Arduino IDE so I can *see the numbers,* and I use the external CP2101 USB adapter to *read the same exact data from the Arduino* into the **Serial Plotter** of another instance of the Arduino IDE so I can see the *live, plotted graphs!*

It's amazing how well this works. Quick hack. Easy solution.

---

Note: to you use my eRCaGuy\_PyTerm Python serial terminal, first set all your serial parameters inside the `user_config.py` file, then run `python3 serial_terminal.py` to run the program. It is a 2-way serial terminal, *with datalogging*. It works quite well. I really should improve its readme and post some examples someday.

# Answer
> 1 votes
You can write your own python script that prints received serial output. By using try/except in a loop you can "pause" your serial monitor while uploading is in progress.

I did the same a while ago using `pyserial` on linux. I'd like to share it, but at the moment I have no access to my other machine. I can post it later if you want.

---
Tags: serial
---


title: Smallest microcontroller?

text:
# Question
Title: Smallest microcontroller?
I am looking for a microcontroller that is small (like a attiny10) which is the smallest one I could find. Requirements I need: analogRead on 1 pin, 7 pins for analogWrite to micro leds so in total 10 pins (ground, power, analogRead, analogWrite). It's circuitry has to be basic no adding extra things like a crystal oscillator etc.. This will allow me to send a certain code to the recieving pin and then the microcontroller decide which led to turn on.

# Answer
I don't know whether it's really the smallest you can find but... The ATtiny84 has an ADC, more digital pins than you need, and is available in 3 mm packages (UFBGA and VQFN). There is also an Arduino-compatible core available for it.
> 1 votes

# Answer
I made a Arduino develop board with ATtiny3217, it has a 24-pin VQFN form factor, but as powerful as ATmega328p, with no external crystal and capable running at 20MHz.

If this is not suitable for you, look into the new tinyAVR family, they are the new generation of ATtiny with more functionalities than the older ATtiny family with the smaller footprint.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: ESP8266 not working with MPU 6050 over wire library and I2C
I'm trying to use this version of ESP8266 to access MPU 6050. However, it's not working.

https://www.amazon.com/gp/product/B07HF44GBT/ref=ppx\_yo\_dt\_b\_asin\_title\_o07\_s00?ie=UTF8&psc=1 i.e. NodeMCU CP2102 ESP-12E

The code worked with nano very fine. However, when I tried to scan the I2C device, it's said I2C device not found.

I have tried

```
  Wire.begin(D2, D1);

```

and

```
  Wire.begin(4, 5);

```

i.e. to change the pin to GIOP 4 5 in case if the default was not working. I have also tried to put a large capacitor between the power lines, still not working.

Why ESP8266 does not work with MPU 6050?(Serial and wire together)

**Updates:** Sometimes it does say device found, but after two updates, it turned to be not found again.

**Updates 2:** I watched the video and did what G6EJD suggested, i.e. restarted the IDE and everything. Now it's reading data. However, the data reading was somehow incorrect by a large factor. For example, at flat the device is reading

```
42.63/-38.37/7.82

```

for angle x,angle y,and angular speed z with complementary filter applied and steady at flat surface. It worked for nano but not for ESP 8266.

Also, I tried to adjust the circuit like the spectrum dandavis suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted. The pull up resistor did not seem to be response to what the device was reading.

**Update 3:** The power consumption has been ruled out and a pair of 100k resistor was also attempted. Not working.

# Answer
> 2 votes
I've been struggling with getting anything with the MPU6050's to work with either a D1 Mini or an older NodeMCU v1. I'm using D1/D2. I've used the i2cdevlib MPU6050 library as well as the Electronic Cats' version. I've used an assortment of sketches and even tried code which uses just Wire (no MPU6050 specific libs).

* The best I've been able to get is the Electronic Cats MPU6050 library, without DMP, where at least it thinks the MPU6050 has been connected to, but it just puts out 0's as raw values.
* The second "best", maybe, was some code that just used plain Wire, but except for Wire.endTransmission() returning success (and I had to slow loop() down for that), its numbers are gibberish (either 0's, or Z will just increment. Nothing is affected by the movement of the board itself).

The DMP versions always fail to initialize the DMP. I've tried 8.2k and 4.1k pullups on D1 and D2.

It works fine on an atmega32u4-based Pro Micro 16.

# Answer
> 1 votes
try to use

```
Wire.begin(0x68);

```

instead of

```
  Wire.begin(D2, D1);

```

---
Tags: esp8266, i2c, mpu6050, wire-library
---


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

---- EDIT -----

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

.ino code

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

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

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

// Variable to store the HTTP request
String header;

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

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

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

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

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

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

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

```

ESP8266 Stack debug

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

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

```

Thanks for any advice

# Answer
I don't know how, but finally I have found working solution... I have add `HTTPClient http;` at top of function and it works...

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

```

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

---
Tags: esp8266, arduino-ide, reset
---


# Question
Title: 9 volt battery unable to power 2 plastic yellow motors
I am trying to build a robot using a kit I got from amazon: https://www.amazon.co.uk/DFRobot-Tank-Mobile-Platform/dp/B014L1CF1K?th=1 (it uses plastic motors).

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

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

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

The motors I am using look like this:

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

---
Tags: motor, battery
---


title: Storing value in EEPROM in Arduino Uno

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

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

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

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

```

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

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

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

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

```

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

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

```

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

```
EEPROM.put(addr, val);

```

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

You recall it with:

```
EEPROM.get(addr, val);

```
> 2 votes

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

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

I use the AVR EEPROM "library" directly.

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

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

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

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

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

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: SRF04 Ultrasonic sensor - inaccurate readings
I have an Arduino Uno linked up to an SRF04 ultrasonic sensor. I'm using the library from here: https://code.google.com/p/srf04-library/

I'm then using the basic script "Centimeter" that comes in the examples. This gives me a reading, but it seems to be ~20-25% inaccurate. When it reads 100cm, the distance is actually nearer 80cm.

I've replaced the SRF04 with another, and the same issue occurs. Additionally, it seems when it reads out of range (or even on surfaces that give an uneven "bounce"), I get very random figures (e.g. -5cm).

Has anyone experienced something similar?

# Answer
> 9 votes
Just don't use that library, it seems poorly designed.

Here is how the distance for roundtrip is calculated (code excerpts):

```
long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

```

If we remove the averaging stuff (as `_average` is `1` by default), this boils down to:

```
digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

```

`pulseIn` normally returns an `unsigned long` which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.

If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then `pulseIn()` should return:

```
3 x 2 / 340 x 1000000 = 17646 us

```

So far we don't see any particular problem, that's fine.

Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of **36ms** will be sent by the sensor; in this situation, `pulseIn()` will return **36000us**.

The problem here is that `36000` does not fit into an `int` (max value = `32767`), the conversion to an `int` will change it into a **negative value**! That explains your strange negative outputs.

Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:

```
int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

```

The problem here is the `int` calculation, it should rather be performed as `float`. For a speed of sound of 340 m/s, one should divide the time of the echo in us by `29.4` (ie `1000000 / 340 / 100`), not 29, that can make a difference in the final calculated distance!

If you want to go on using this library, then just forget about the `getDistanceCentimeter()`method and replace it with the following code:

```
distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

```

All calculation is then performed as `float` and converted to `int` distance only at the end.

Your code should also explicitly detect negative values as meaning "no object detected".

# Answer
> 3 votes
While BrettM discussed some excellent points that can occur with ultrasonic/sonar/'Ping' sensors I've noticed a few others when I have used these sensors.

The first and most common issue with sensors of this type is accurately identifying what is triggering the distance value. Consider at an abstract level how these work. You've got the bit that transmits a 'ping'. It transmits the 'ping' and stops. At this point the bit that listens for the 'pong' activates and starts listening. These sensors work by sending out that 'ping' and starting a timer, the first 'pong' the sensor hears triggers a stop response to the timer and distance is, roughly, figured out from here. Notice that there is no way for the sensor to distinguish where the 'pong' is coming from. If you yodel on a mountain you don't know which surface echoed back and this is the same issue you are potentially facing with your sensor.

Typically when I work with people who are getting inaccurate readings from their sensors of the sort you are describing some variation of this issue is occurring. Often readings that are 'short' are so because there is an obstacle in the cone of the 'ping' that causes the sound to reflect back more quickly than expected for the surface you are measuring. Recall that sound is not a accurate,directed laser. Rather it spreads out in waves from the source. In my experience any objects within a roughly 160 degree arc(in my experience) in front of your sensor can cause these readings to be unusual. That can include the floor, your shoes, measuring devices. In theory the sensor is created to avoid these readings, in practice not so much.

To test if this is the case with your sensor setup I would recommend a few experiments. First setup the arduino and sensor in a fixed position and in such a way that the sensor is at the edge of a support surface with nothing but the surface you desire to measure in front of it. So, for example, set up the sensor on the very edge of a table facing a wall. Measure the distance from the wall to the support surface edge(table's edge). Some variation is normal, as described by BrettM, but 20% on 100 cm is a bit much in my experience. Once you get a solid, repeatable reading start changing the environment. Put something in the front arc of the sensor and see how that effects it. Move the sensor/support surface towards and away from the object. Typically when I see values like -5 that means something was too close to the sensor or, potentially, another sensor is interfering.

It is worth checking to confirm that there are no other range sensing devices in the area you are working within. Other devices sending out similar 'ping's can cause unusual readings(since they don't distinguish who's ping/pong is whose).

# Answer
> 2 votes
This is pretty standard. Altitude and air temperature will change the speed of sound enough to cause these errors, and minor variations in sensors could compound the problem. I would try calculating your own scale to convert ping time to distance using actual measurements from where you live; The library probably uses the speed of sound at sea level.

Similarly, any shape that poorly reflects or absorbs ultrasound will cause erroneous readings. There is really not much to do about this, sorry. If you have multiple sensors aimed a few degrees apart you are more likely to get one that will read the right distance.

# Answer
> 2 votes
This saved my project:

https://create.arduino.cc/projecthub/panagorko/next-level-ultrasonic-sensor-a67478?f

Please spread the word, I almost gave up. This gem seems widely unknown, I spent two full days in vain trying to improve my ultrasonic sensor's accuracy.

# Answer
> 0 votes
Have you got a satisfying answer to this question?

I'm having a same issue with my HC-SR04 sensor. It's supposed to be mm-accurate, instead I'm getting ~30%+ off values. E.g.) @ 30cm, the readout is ~40cm. @ 15cm, the readout is ~20cm.

This isn't exactly a "solution" but here's what I did. For calculating distance, I divided by additional 1.25.

> > distance = (duration/2.0)/29.4/1.25

Now my readings look a lot more accurate(+/-0.5cm) within ranges of 0~30cm. And although it wasn't perfect, at 2m it read 202cm.

Not sure if this is sensor issue or Arduino issue... Maybe it's lacking power such that a portion of echo pulse is not being registered at Ardu as High. I'm running my board on USB 5V, which is in turn taken off raspberry Pi2. Still, 25% is a huge discrepancy...

WOWOWOW OK I FOUND SOMETHING!

After writing that last paragraph, I connected Arduino to my PC (instead of RPi), uploaded the s/w without 1.25 factor, and the readings are correct! (more or less. NOT like +30% before)

So yeah, it's because of lack of power.

Hope this is the case with you as well, in which case we can finally put this issue down for good.

---
Tags: arduino-uno, sensors
---


# Question
Title: SSD1306 recognized in I2C scaner, can't get it to display
The gist of my issue is in the title. I have a cheap ebay SSD1306 128x64 display which I hooked up to my arduino, and checked the wiring at least 50 times and the address is correct, the display has the jumper set to 0x78 and the arduino (Nano with ATmega168) sees it on an i2c scanner as 0x3C which is expected.

Now I installed Adafruit's SSD1306 and GFX libraries and an OLED i2c library I found somewhere (can't find it, sorry. In the IDE it's called OLED\_I2C) and ran both example codes (shortened Adafruit's to fit on a 168) and I can't get it to show anything. I've tried many things including trying the 128x32 code with no luck, not even missing every other line. I think the display works since it shows up in the scanner, does anyone have any idea what could be wrong? Thanks in advance

My shortened Adafruit code:

```
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Draw a single pixel in white
  display.drawPixel(10, 10, SSD1306_WHITE);

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);
  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  testdrawline();      // Draw many lines

  testdrawrect();      // Draw rectangles (outlines)
}

void loop() {
}

void testdrawline() {
  int16_t i;

  display.clearDisplay(); // Clear display buffer

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn line
    delay(1);
  }
  for(i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000); // Pause for 2 seconds
}

void testdrawrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

```

# Answer
I tried researching a while after asking this question. Turns out changing OLED\_RESET to -1 fixed it.
> 2 votes

# Answer
I have some experience with the the screen you are using and I hope these tips can solve your problem.

* Changing the Address in the code

The OLED display you are using uses what is called I2c or IIC protocol which is the abbreviation of "Inter Intergrated Circuit", here is it's Wikipedia page to read about it.

The IIC communication has 7 bit address space, that means there is 127 distinctive address for example 0x3C,0x3D,0x38 etc....

Your display might have either the address 0x3C or 0x3D so you might try changing theses values until anything would show up.

* Unhooking any other IIC device

Although you can hook many IIC devices but as was said in the comments it's better to unhook everything except it, to troubleshoot.

* Correct voltage ?

You might know that some displays uses 3.3v or some uses 5v, but as it showed in the IIC scanner, I don't think that is the problem in your case but you should consider it.

* Try using other sketches

Well, I think that 99% of the problem lays in your code (sometimes happens to me), so I suggest using other library examples or completely other libraries, or if you would like to take the challenge open the datasheet for the ssd1306 and make your own library and codes.

I hope these tips will help you or any other viewer.

As a side note I am a student, so I completely will appreciate anybody editing the answer to make better or more clear.
> 2 votes

# Answer
The confusion about I2C address really comes from whether it's treated as a byte or 7-bit (MSB).

For example, on the OLED PCB, it's stated address I2C = 0x78, which is 0b\_0111\_1000 (I2C address write).

In the Adafruit Arduino SSD1306 library, it uses 7-bit I2C address, that 0x78 becomes 011\_1100 (taking the 7-bit MSB) = 0x3C
> 2 votes

# Answer
I copied your code and load to my display. It doesn't show anything. Here is the code that I had run successfully.

```
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire);

void setup() {

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // Address 0x3C for 128x32

  display.display();
  delay(2000);

  display.clearDisplay();      //this line to clear previous logo
  display.setTextColor(WHITE); //without this no display
  display.print("Hello World!");//your TEXT here
  display.display();            //to shows or update your TEXT
}

void loop() {

 }

```

Good Luck, Aung Myo Oo
> 1 votes

---
Tags: arduino-nano, i2c, display
---


title: The L LED Keeps Itself On

text:
# Question
Title: The L LED Keeps Itself On
I am using a Arduino Uno 3 for line follower robot. However when I power the Arduino Uno, the L led is turned on and is never turned off. After a bit of searching I found out that the L LED is connected to pin 13. So I set the pin 13 to low but still the led is on. Is there a problem with the arduino? Or there's something that I am unaware about? (Amongst a lot of other things that I don't know.)

# Answer
This is a “feature” introduced in the revision 3 of the Uno board. Up to Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ resistor. On Rev 3, the same LED+resistor combination is driven by pin 13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e. `INPUT` mode, the default mode when the program starts), the input of the op-amp is floating. The voltage at this input (and thus at the output) is not controlled and depends only on the parasitic conductances and on leakage currents.

If you want to turn the LED off, you not only need to write `LOW` to it, you also (and most importantly) should set the pin to `OUTPUT`.
> 7 votes

# Answer
Its possible its the Power LED you are looking at - that will always be on.

Simplest test is to load up the Blink Example that's included in the Arduino IDE - and the LED should blink once a second. That will show you if your Pin13 LED is working ok.
> 2 votes

# Answer
Now first check IC on your arduino UNO. if it is atmega328p, set the board to arduino nano in the software and set the processor th atmega328p. that makes it work. :)
> 2 votes

# Answer
I guess the arduino is burnt cus it happens with me in the same way. The usb port of my PC is writing device not recognize, and the atmega328p on the arduino temperature is getting high. To save my time I bought another new one I think that should help.
> 1 votes

# Answer
An LED lights up when in forward bias. That is, when the voltage on the anode is greater then that on the cathode. If the anode is connected to an Arduino GPIO pin (and the cathode is connected to ground and an appropriate limiting resistor is used), the LED will light up when the pin has positive voltage. This is when it is set to 1 in the code. If the cathode is connected to an Arduino GPIO pin (and the anode is connected to positive voltage and an appropriate limiting resistor is used), the LED will light up when the pin has zero voltage. This is when it is set to 0 in the code.
> 0 votes

---
Tags: led
---


# Question
Title: How do I connect an MPU6050 sensor to an Arduino MKR WIFI 1010?
I've been trying to connect an MPU6050 to my MKR WIFI 1010 following these general instructions and using the I2CDev library, but I keep running into problems.

For a while the Arduino just didn't show up as connected in the IDE when all the pins were connected, which I think I've gathered was due to a lack of pull-up resistors for the SCL/SDA pins. Adding 10 kOhm pull-up resistors helped a little (in making the Arduino visible) but it would hang when trying to upload the example sketch. 2.2 kOhm resistors seemed to do the trick, where now the example sketches (MPU6050\_DMP6 or MPU6050\_raw) can be uploaded. They still fail to read any actual values, however. The raw sketch gives 0 for everything, and the DMP6 sketch prints

```
Initializing I2C devices...
Testing device connections...
MPU6050 connection failed

Send any character to begin DMP programming and demo:
Initializing DMP...
DMP Initialization failed (code 1)

```

Does anyone know why the sensor still fails to give any measurements? I connect VCC and GND from the sensor to VCC (3.3V) and GND from my Arduino. SCL and SDA from the sensor are connected to VCC via 2.2 kOhm resistors and to the SCL and SDA pins of the Arduino (12 and 11). And INT from the sensor is connected to digital pin 2. (I tried this on a couple other pins like 0 and 1 since it seems from the tech specs that 2 is not an External Interrupt pin, but that didn't change anything.)

The sensor and examples worked without any extra effort on my Arduino Uno, but unfortunately I fried that with a 12V power supply by accident. I'll probably just get another Uno, but I'm curious why this didn't work, if I'm missing something about I2C or the MKR WIFI.

I'll also note that I had to add

```
define #BUFFER_LENGTH 64

```

to wire.h in order to get sketches including I2Cdev to compile (following these instructions).

# Answer
> 1 votes
The sensor was indeed broken, and I had no problems after ordering a new one.

---
Tags: sensors, i2c, mpu6050, mkr1010
---


# Question
Title: How to use correctly a microstepping driver with a lower voltage stepper motor
I want to use a microstepping driver like Haitronic's HS2215 with a NEMA 17 stepper motor with rated voltage of 4.2V and rated current 1.5A.

The input voltage range of the microstepping driver is 9-40VDC.

From what I understand, I can use the switches to set the maximum current. In this particular case I would use SW4=On, SW5=On, SW6=Off.

TB6600 current settings You can adjust the current that goes to the motor when it is running by setting the dip switches S4, S5, and S6 on or off.

I've found this Maker's Guide which describes the settings for use with an arduino. However, I am not certain what voltage (VCC) should I supply to the mircrostepping driver? Should I provide, the minimum of 9VDC, should I provide less? Is this irrelevant?

# Answer
That doesn't matter at all.

The voltage stepper motors are rated for is the voltage that, if applied to the motor coils, would create its rated current.

Stepper motor drivers monitor the *current*, and always use the full voltage available to them (9 - 40V in your case) to drive the stepper motor - using PWM. The stepper motors coils inductance slows down the change in current, allowing the driver to reach its set current.

Higher drive voltages simply mean that it's easier to overcome that inductance, allowing for faster stepper motor movements.

You'll want to set your driver at 1.0 or 1.5 A, and supply it with as much voltage (up to the rated 40 V) as you can.
> 1 votes

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


# Question
Title: Why do we use bitwise operators to assign PORTx, DDRx and Pinx?
I have come accross a lot of examples using ways similar to the ones shown below to assign values to the pins.

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

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

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

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

# Answer
> 7 votes
> My question is why do we need to use bitwise operations to make assignements?

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

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

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

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

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

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

```
Turn on:

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

Turn off:

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

```

# Answer
> 1 votes
### If you want to change all pins on a port at once, you don't have to.

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

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

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

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

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

# Answer
> 0 votes
The registers are 8 bits in size. And in the above two cases you want to set/clear 1 bit, while leaving the others the same.

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

# Answer
> 0 votes
**It makes code easier to write and re-use.**

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

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

---
Tags: pins, port-mapping
---


title: Wiring up an ESP 01 to Nano

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

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

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

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

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

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

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

* After taking some readings with my multimeter - I see the output of my regulated 3.3 rail drops to 2.55 with the ESP plugged in... Do I want to bring this up even more so it's 3.3 WITH the ESP plugged in?
* I don't think the above edits suggestion will work since I've also wired the chip to a 3.3 breadboard power supply powered by a barrel jack - still no avail
* I understand I can write firmware directly to the ESP-01, this is not my goal here. I require it as an add-on to the Nano, since I need its analog pins, amongst other things'

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

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

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

```

should be

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

```

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

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

```

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

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

Good luck to all!
> 3 votes

---
Tags: esp8266, arduino-nano
---


title: Arduino Nano stucks on uploading

text:
# Question
Title: Arduino Nano stucks on uploading
I'm trying to upload an simple blink sketch to my Arduino Nano, which not used for a while.

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

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

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

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

# Answer
I have solved the issue by selecting,

Tools \> Processor \> ATMega (Old bootloader)

@Juraj, Thank you for suggestion.
> 1 votes

---
Tags: serial, arduino-nano, usb, uploading
---


# Question
Title: Leds become dimmer after they reach a certain brightness, why?
**Even if I don't use buttons and I do an automated thing that makes the led brighter(Even the non-rgb one)after sometime it resets itself to a dimmer light, why?***

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

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

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

}

void loop()
{

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

}

```

# Answer
> 3 votes
The described behavior stems from 2 important facts:

1. The `loop()` function will run very fast (microsecond range), while the button presses of a normal human will be rather slow (in the tens or even hundreds of milliseconds). That means, that with only one button press you will enter the corresponding if statement many times, everytime adding 10 to the value. You don't have control how many times exactly the if statement will be entered, so the value, that comes out after your button press is somewhat randomly growing.
2. While the `analogWrite()` function takes an `int` as the value parameter (16 bits on AVR), internally it assigns that value to the corresponding Timer register, which is only 8 bits big. So it can only hold values between 0 and 255 anyway. If you provide a bigger number as a parameter, the higher part will just be cut off. For example: Providing 257 will result in a value of 1 (= 257 % 256 = 257 % 2^8 --\> 257 modulo 256). The higher values get wrapped around back into the range of 0 to 255.

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

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

* One button click (press + release) should increase the value of the corresponding LED by 10:

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

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

---
Tags: sketch
---