# Question
Title: Solar powered ESP8266. WiFi module usage optimizations
Above all, I am quite new to the ESP8266 and micro controllers development as a whole. I am now working on a project which is quite simple for now. It basically looks like this:

As you can see, I have an **ESP8266** and some input peripheral. Everything works perfectly fine for the moment, I can read the inputs from the **motion sensor** and **4x3 keypad**. And, respectively I can output on the **relay** and the **5mm LED**. In order to make it a real IOT, I have connected it to the internet via Thinger.IO. So, I have my **ESP8266** constantly connected to this platform and I can track it anytime, from anywhere.

This is great. But, my optimal goal is to **power my configuration from a solar panel** and make it independent of the electricity distribution network.

The average working current of the whole system is about **313mA** (10000 mAh battery gets completely drained for 32 hours. Its output is 5V, 2.1A).

So, I am now in a search of the best solar panel to fit my needs. An ultimate one would have the following maximal dimensions: **30x35** cm. *I am not sure there's a single panel that I can use but I am interested to hear your opinion in this.*

Another aspect, that **I'd like to optimize is the constant internet connectivity**. Basically, I need to have my configuration connected to the internet only when keypad input was made or motion sensor detected something. During the rest of the time, I don't need to be connected to the internet and I assume WiFi module could be suspended somehow. Currently, my code uses SmartConfig and is looks like this:

```
#include <ESP8266WIFI.h>

void connectToWifi() {
  WiFi.mode(WIFI_STA);
  WiFi.beginSmartConfig();

  while(!WiFi.smartConfigDone()){
    delay(500);
  }
}

void setup() {
  connectToWifi();

}

void loop() {

}

```

Everything works well. But, as I said, I'd like to be able to start/stop the WiFi module. I tried using the following API:

```
void toggleWifi(bool isWakeUpCall) {
  if(isWakeUpCall)
    WiFi.forceSleepWake();
  else
    WiFi.forceSleepBegin(30000000);

  delay(500);
}

```

but without much of a success. Once it gets into this portion of code, it gets completely disconnected and doesn't get connected anymore. I am now struggling with it.

I've read about the **sleep modes** offered by the ESP8266 but I don't think they are suitable for my case because I can not simulate external interrupt (*or maybe I can?*).

*I am really curious to hear your opinion on this.* :)

# Answer
> 1 votes
As described here the ESP8266 can be waken up using Timer Wake Up or external interrupt. The idea is simple: almost everything inside the ESP is powered down (including Wi-Fi and/or System clock or even the CPU) with only a timer running which was told when to activate before the ESP went to sleep. After the desired amount of time has passed the timer triggers GPIO 16 or D0 and if that is connected to the reset pin of the ESP is resets and starts executing code again until it goes to sleep again. For your case you can configure your motion sensor to output a LOW when motion is detected and connect is to a GPIO pin and the reset pin, so it will trigger a restart when motion is detected and in the startup sequence you look at the pin where the sensor is connected and do what you have to do. For the keyboard to work you can have the timer set to reset every 5 seconds, so you would have to hold a button for 5 seconds waiting for the ESP to wake up and accept your input or you could make a dedicated button for waking up the ESP if you want to enter the code. In that case the you don't need a timer, since as you described the ESP only has to do anything if the keyboard is activated or if the motion sensor is triggered and since they can be connected as external interrupts they will wake up the ESP if needed. I would recommend to check out this link for further details about the code and hardware.

---
Tags: esp8266, wifi, sleep, solar
---


title: Esp32: upload eeprom file

text:
# Question
Title: Esp32: upload eeprom file
I'd like to flash the eeprom sector with content so that the eeprom already holds data when it boots the first time. How do I upload such an eeprom file like I would do with avrdude on an atmega? Is there a tool that can be installed in the arduino IDE like the data uploader?

# Answer
> 1 votes
The ESP8266 has no EEPROM.

Instead the flash memory is *partitioned* into different areas for different purposes. One of those areas is set aside for "EEPROM Emulation" data.

To upload to that area you first need to know where that area is in the flash memory, and that is dependent on what partitioning scheme you are using at the moment.

Once you have worked that out (look in the partition scheme files in the core for more information) you can then use `esptool` to upload data to the right area of flash.

---
Tags: esp32, eeprom, flash
---


# Question
Title: BH1750 Light sensor always giving output as 54612lx
urgently need some inputs,

Connection:

```
VCC-5v
GND-GND
SCL-SCL(analog pin 5)
SDA-SDA(analog pin 4)
ADD-NC or GND

```

Code pasted below used library from GIT : https://github.com/claws/BH1750

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

BH1750 lightMeter;

void setup(){
    Serial.begin(9600);
    lightMeter.begin();
    Serial.println("Running...");
}

void loop() {
    uint16_t lux = lightMeter.readLightLevel();
    Serial.print("Light: ");
    Serial.print(lux);
    Serial.println(" lx");
    delay(1000);
}

```

# Answer
There may be a regulator and logic shifter on the board you are using but according to the data sheet the device is a 3V device with 1.8V logic and I2C levels. So this is the first thing you need to check.

Have you got 4.7K resistors pulling the SDA and SCL lines to Vcc?

Can you change your code to turn the device off and then take a reading?

There is nothing wrong with your code, your wiring looks OK, so that implies that there is something wrong with the device or the Arduino. Change the device (and code) for another I2C device and see if that works fine. If it does then it looks like there might be a problem with the BH1750.

Hope that helps.
> 1 votes

# Answer
Looking at the `BH1750.cpp` and `BH1750.h` and I think i've noticed some errors:

1. Change `#include "Wire.h"` to `#include <Wire.h>` in the header file, trivial perhaps but still...
2. In the method `BH1750::readLightLevel` in the .cpp, comment out `Wire.beginTransmission(BH1750_I2CADDR);` and `Wire.endTransmission();`; they aren't needed for a Read and may be responsible for the wrong value you're getting.
3. You can also try replacing `_delay_ms(10);` with `delay(10)`, just in case
4. You may also try commenting out `level = level/1.2;` just to see if this division has any adverse effects.

Save the files after making the changes.
> 0 votes

# Answer
I had to connect my `SCL` and `SDA` pins to dedicated **20th and 21st** pins on `Arduino MEGA 2560`.
> 0 votes

# Answer
I bought some "GY-302" modules on ebay, it's a breakout board with the BH1750 sensor on it. I tried one of them and it didn't respond at all, like you I saw 54612 (which is just 65535/1.2). I tried another of these modules and it worked. So, on the one that didn't work, the sensor chip was not well aligned and centered, and the soldering looked ugly on one side, so I used my soldering iron to attempt to reflow and re-align/center it. If you attempt to do that too, clean your soldering tip and do not add any solder! Now the soldering looks even uglier (under microscope..), but the sensor is working well! I don't have any pro equipment, not even a small tip for my crappy soldering iron, so I guess I am lucky that it worked.
> 0 votes

# Answer
i didnt solder my light sensor and it had the same error, as it was just resting on the pins, try pushing it up so the sensor makes contacts with the male headers or just solder them :D
> 0 votes

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


title: Serial.write without a receiver

text:
# Question
Title: Serial.write without a receiver
I'd like to send a monitoring information (temperature) to a serial receiver periodically. The problem is I don't know if there is any monitoring service (serial receiver) and how fast it is reading. I only need the latest value. The problem is that serial.write will block if the buffer is full. If I skip writing if the buffer is full, a receiver will only get old data on the first connect. How can I replace data in the buffer or make sure there is only one dataset in the buffer?

# Answer
> 2 votes
> The problem is that serial.write will block if the buffer is full.

Only until the bytes get sent out through the TX pin.

> If I skip writing if the buffer is full, a receiver will only get old data on the first connect.

No it won't. There is no "old" data.

> How can I replace data in the buffer or make sure there is only one dataset in the buffer?

You don't need to.

You are showing a fundamental misunderstanding of how serial works. When you send data it just twiddles the TX pin in the right way with the right timing. If there is something connected to it that understands that twiddling at the speed it's being twiddled then it interprets it as serial data. If there's nothing to see that twiddling it still twiddles. The "blocking" is only if you try and send more data than the serial port can physically send out in the time you're sending it.

If a serial port transmits in a forest and there is no one there to hear it, yes, it still makes a noise.

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


title: ATtiny167 Device not recognized

text:
# Question
Title: ATtiny167 Device not recognized
I'm frustrated I feel like I am 90% there but my computer will not recognize the ATtiny167. Here i9s the list of things I have completed/tried using Windows 10 and Arduino 1.8.6;

```
                  1) Installed Driver USB Bootloader is complete
                  2) Device Management I see the device
                  3) Arduino Sketch select 16.5 MHz board in parameters
                  4) Led on the board flashes sound beeps and stops flashing
                  5) "Device not recognized"
                  6) I have rebooted many times. I deleted everything and started over again with same
                      results
                  7) Used a 3rd party software to look at my USB ports it see the device
                   I have tried more than one device as well

         I'm stuck at this point. I've tried running example programs however the device is not recognized.

```

Any suggestions?

# Answer
If Digispark Pro clone is not recognized, you can try to use/upload .ino programs via ArduinoISP.

note use in File -\> Preferences -\> Additional Boards Manager URLs: http://drazzy.com/package\_drazzy.com\_index.json instead: http://digistump.com/package\_digistump\_index.json

(The first is AttinyCore by Spence Konde, the second is the normal Digistump AVR Boards)

Then selected Tools -\> Boards Manager, and Find AttinyCore -\> (Wait and Install).

Now you can upload File -\> Example -\> ArduinoISP on your Arduino connected in ISP mode with your ATtiny167.

Now select ATtiny167 Board, 16Mhz (External) and write bootloader with your Arduino connected in same manner ISP mode with your ATtiny167.

And now upload any .ino file for ATtiny167 in the same manner with your Arduino connected in ISP mode with your ATtiny167.
> 1 votes

---
Tags: attiny85, digispark
---


title: Arduino long distance cable tester

text:
# Question
Title: Arduino long distance cable tester
We have a 50 pair cable running about 1.5-2 KM with some services running on different pairs. One pair has recently become intermittent and is losing connection for 1-2 seconds at random. It might happen a few times an hour, so I jumped the service onto another pair. There is a modem connected to the pair for communication between two sites.

When resistance tested with a multi meter with a loop in one end it was reading 330 Ohms. When using an oscar meter it was reading -2.4db which is the same readings for other pairs.

I would like to use an Arduino to monitor the line resistance for a few days and see if there are any spikes or breaks in the line. I was going to use an analog input as a multimeter by using a known resistor and the looped pair as the other resistor.

Does anybody think this will not work?

How else could I go about this?

# Answer
> 1 votes
Sure, no reason that wouldn't work. For best results you want a known resistor of about the same resistance as, or a little below, the one you are measuring.

However, if what you are seeing is an actual open circuit then there's little benefit to measuring the resistance - you may as well just treat it as a switch or button, give it a large pullup, and use a digital input (or even an interrupt) to give a simple "OK / ERROR" signal.

# Answer
> 0 votes
For data communications the problem is often more complicated than DC resistance. Data signals are AC, and subject to impedance, (not simple resistance) inductance, and capacitance, as well as RF interference. A pair that's fine for slow on/off switching of DC signals may not be fine for higher frequency data signals.

You can also get intermittent shorts between wires in one pair and other pairs, even if the connection between the wires in the test pair are fine.

Back in the day I worked for a company that sold and serviced mini-computers to the US House of Representatives. The house offices would run serial cables up through walls and ceilings, and also under carpets. We had some flaky cables, and finally figured out that the offices would run the cables under the carpet, but over carpet tack strips. As people walked over the carpet, it would sometimes cause the tack strips to poke through the insulation, causing shorts and RF noise in the cables, which would mysteriously go away later.

Checking DC resistance will let you find breaks in your wires, but you can't assume that if the DC resistance looks good, the pair is good.

I would suggest using a simple voltage divider and one of the input lines on the Arduino for simple resistance testing, but that will only get you so far.

What you really want is a signal generator and an oscilloscope. You should send test signals (With voltages and signal patterns that resemble your data signals) down one pair at a time, and look at the signals on the far end, checking all the pairs. You should see your test signal come through, with the wave pattern still recognizable on the target pair, and no significant leaking of the signal to other pairs.

---
Tags: arduino-uno
---


# Question
Title: Arduino - manually ceate objects (e.g. WiFi library)
By default, if i include the WiFi library, the object WiFi will be registered globally. How can i disable this behavior without changing the library file itself? (removing the definition "extern ...") Or is there a way to delete the objects right after the inclusion? I just want to create the object manually when needed to save memory.

# Answer
I am not sure, if it would save enought memory to be worth the problems (it is just few bytes, buffers are created anyway), but lets say so. Then you need modify the library to not creating the object, as it is allocated statically and cannot be removed later (and reclaim its memory). To protect all other projects it would be probably best to use special `#define` to disable it only in memory critical projects - so the Wire.h should contain something like

```
#ifndef EXCLUDE_WIRE
extern TwoWire Wire;
#endif

```

and your program (`critical.ino`) should start with

```
#define EXCLUDE_WIRE
#include <Wire.h>

```

and then somewhere in `loop` / other function use

```
TwoWire Wire;

```

as local variable. If you need to call other functions with it, then you have to send its address as a parameter.

Anyway you will not save nearly any memory, as nearly all variables in TwoWire ((and namely buffers) are `static` and so class variables and so are common for all instacies of TwoWire and allocated automatically if there is (possibly used) any instance of TwoWire anywhere in your program.

So it would be better to create your own library to use the same functionality, but make sure, that all such variables are instance variables and properly created and released at the right time. This would also allowe for changing the buffer sizes, if needed.

As it is under LGPL 2.0+ you are legally allowed to do that (provided you fullfill all licence conditions).
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: How do software interfaces compare to hardware interfaces in therms of speed and reliability?
The Arduino core includes numerous software interfaces mimicking the hardware interfaces provided by the chip and even extending beyond. My question is, if in a project I can either use software or hardware protocol, what would be the difference in stability, speed and versatility? Is there a reason why hardware interfaces are preferred? Because anyways the protocol is handled by the CPU or am I mistaking something?

# Answer
> 1 votes
In your question you ask about all communication interfaces in general, so the answer will be as general as your question.

Hardware interfaces should always be preferred to software interfaces, though there are situations, where it is a better or needed to use a software interface due to limited resources.

> Because anyways the protocol is handled by the CPU

That is mostly wrong. The communication protocol is done by the hardware in most cases, if you use hardware interfaces. Serial (UART) for example automatically sends out the byte, that is placed in the hardware buffer, with the set configuration. It does not rely on any software for that. The same goes for SPI or I2C. The protocol of the interface is handled via hardware.

Though at least for Arduino Core/library users there is more to it, that get's handled automatically. Since the interface hardware is limited, the software have to take care of the resulting or needed data. For example: All the interfaces mentioned above use a 1 byte buffer for the data. The software must read or write this data, so that the hardware can work. If you don't read the byte of data, that was received by the Serial interface, it might get overwritten by the next byte. The hardware cannot provide a buffer, that is generally big enough, since the manufacturer cannot know, how long the transmissions will be. So the interfaces get a 1 byte buffer and the software has to do the rest. For this reason all the libraries use a bigger buffer in their software, that gets filled, when the hardware sends a corresponding interrupt.

So: Hardware interfaces implement the basic interface protocol (how the bits get transmitted) in hardware, thus the software only has to provide and read the byte data. The stability, speed and versatility is only determined by how the manufacturer build the hardware of that interface. This limit is clearly specified in the datasheet and does not change with the code.

For software interfaces, everything is done in software. This also involves monitoring and setting the corresponding pins with the correct timing. In the best case the software can utilize general hardware functions like a pin interrupt, but if it cannot do this, it has to constantly monitor (poll) the pins to receive something. Software interfaces are often called "bit banged", because the software manually pushes out each individual bit with the exact needed timing. That is a tedious task, which often blocks the execution of other code, since the timing often is critical. Especially the timing introduces limits, since doing things in software often involves many clock cycles more, than it could be done by dedicated hardware (consider all the code to poll a pin and the multiple if statements to react to specific situations). For example: When you write data with `SoftwareSerial` the call to the write function will block, because is manually pushes out bit after bit. Or with SPI: With hardware SPI you can go to incredible clock speeds in the MHz range. You won't every get near that with software, because the software simply cannot run this fast.

Note, that depending on the actual hardware of the used chip, a library may need to implement parts of the protocol in software. For example this is the case for using I2C on an ATtiny85, which does not have full I2C hardware support. Instead the USI (Universal Serial Interface) can be used to implement some functions of the protocol in hardware and the rest in software.

**TL;DR**

* Hardware interfaces lift the heavy duty of handling the low level protocol (transmitting the bits by the needed standard) (which can be rather complex) from the software
* The Software then only handles the byte data, not it's transmission
* Translating complex protocols from dedicated hardware to software (bit banging the data through simple pins) imposes great limits on speed and reliability.

# Answer
> 1 votes
Using a hardware interface takes a lot of load from the CPU. Let's take an asynchronous serial interface for example.

With the UART built-in hardware you'll get parallel-serial conversion and back done in hardware. The CPU "just" needs to store the data to be sent in a register. The receiving part is handled completely by the hardware and the CPU "just" needs to look at the "received" flag before reading the data. Or it sets up an interrupt as callback.

If you use a software interface the CPU needs to convert the parallel data to serial with several instructions and, really important, needs to maintain a certain timing. For receiving this might be even harder because of the asynchronous nature of the protocol. A timer might be usable to clock the communication, for example by an interrupt, but this puts a lot of load on the CPU. Certain conditions might make this usage impossible, too.

Now you might think about the issues you mentioned:

**Stability:** If done correctly both approaches are equally stable, meant as reliable function. If you have more tasks to be done you might not be able to meet the requirements. This comes "earlier" with software interfaces than with hardware interfaces due to the higher load.

**Speed:** Hardware interfaces can be faster than software interfaces because the hardware is commonly clocked faster than what is possible by software which needs multiple instructions for one step. But speed is always a relative issue. There are libraries implementing USB1.1 via software, and the USB1.1 protocol is both fast and really complex.

**Versatility:** Software interfaces are more versatile because hardware interfaces are limited in their capabilities. If a hardware interface can't do what you need there is no way to make it do this. Software can do "anything" as long as the CPU has enough time and resources for this.

Hardware interfaces are preferred because they are simpler to use and commonly don't put hard requirements on your software architecture.

---
Tags: softwareserial, software, core-libraries
---


title: Help with arduino code

text:
# Question
Title: Help with arduino code
Thank you for seeing my post.

I am trying to write a code that lets "A" displayed on row 1 and row 0 alternately on the LCD. starting from (0,1) then (1,0) then (2,1), then (3,0) etc.. when it reaches the last point is becomes "B" and bouncing back the other way until reaching the starting point when it becomes "A" again and repeat again..

I wrote this code but I got stuck at the end, I don't know how to bounce it back:

---

```
// include the library code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);   // initialize the library with the numbers of the interface pins

int x = 0;
int y = 1;

void setup()
{
    lcd.begin(16, 2);
    lcd.clear();
}

void loop()
{
    {
        {
            while (x < 15)
            {
                lcd.setCursor(x, y);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x = x + 1;
                lcd.setCursor(x, y - 1);
                lcd.print("A");
                delay(250);

                lcd.clear();
                x + x++;
            }
        }
        {
            while (x = 15)
                lcd.setCursor(15, 0);
            lcd.print("B");
            delay(2000);
            x--;
        }
    }
}

```

# Answer
> 2 votes
To me it seems, as if you have no knowledge about C/C++. ( I might be wrong. ;-) )

If you plan to do more programming projects, I advice you to learn the basics of this programming language before proceed with the projects. It would be hard thinking about an algorithm, if you don't know the tools to implement it.

In case you just need this once for a (let's say arts project \[or homework ;-)\] ), I add some example code. At the moment I have no chance to test the code. So it's blind written, and there might be typos. In about 8 hours I will have access to a test setup then I'll correct it if necessary.

```
#include <LiquidCrystal.h>

// Here you setup your LCD display
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// you initialize the position where the next character
// will be displayed (0,1) (x,y)
int x = 0;
int y = 1;
// setup is only done once
void setup()
{
    // initialize the lcd lib to be used with a 16x2 LCD
    lcd.begin(16, 2);
    // erase all character from the display
    lcd.clear();
}

// the loop is executed again and again and ...
void loop()
{
    // move forward
    // as long as the position is less than 15
    // you allow x = 0, 1, 2, ... ,15 because
    // you increase two times in each loop step
    while (x < 15)
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );

        lcd.clear();
        lcd.setCursor( x, y );
        lcd.print( "A" );
        delay( 250 );

        // step to the next position
        x = x + 1;
        // toggle y
        y = toggle( y );
    }

    // now move backward
    // x is still 15 and you want to go backwards until x == 0
    while ( x > 0 )
    {
        lcd.clear( );

        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y );

        lcd.clear( );
        lcd.setCursor( x, y );
        lcd.print( "B" );
        delay( 250 );

        // step to the next position
        x = x - 1;
        // toggle y
        y = toggle( y);
    }
}

// this is a subroutine that toggles y = 0 <-> 1
int toggle( int yval )
{
   // I use a ternary operator
   // in case y == 1, I return 0 and a 1 otherwise
   return ( yval == 1) ? 0 : 1;
}

```

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


# Question
Title: Does a pulldown resistor use less battery power than a pullup resistor?
I am designing a circuit connected to a simple open-close sensor, like a switch. For ease of construction, the circuit with the sensor switch closes to ground, and uses a 1 MΩ pullup resistor to Vcc to signal `HIGH` when the switch is open.

I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery. Would it be more efficient to use a pulldown resistor to ground, and have the switch open to Vcc?

Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Thank you!

# Answer
The input current does not depend on the pin level. Have a look at this discussion from avrfreaks. The input impedance of a digital pin is extremely high. The leakage current of the Atmega328P (here as example chip) is mentioned to be 1uA for both pin states. So this current is both unavoidable and neglectable from a normal view.

But the input impedance of a digital input pin is not only dependent on this leakage current. There is also a capacitance, which will lower the impedance for higher frequencies. So, if you drive the input with higher frequencies, the input will draw more current. But you only have a switch connected to it, which is very very low frequency.

So it doesn't matter, if you pullup or pulldown. The main current consumption will result from the moments, where the switch is activated, since then a current flows through the pullup/pulldown resistor to ground.

> Tangentially, should there be a resistor on the connection to Vcc as well?

No need for a resistor there. The input impedance of the pin is already high enough and you don't want to create a voltage divider with your pulldown resistor (which would change the voltage levels at the pin).
> 2 votes

# Answer
> I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery.

No, it doesn't. You get a small spike as the switch is opened or closed, as the gate capacitance is charged or discharged, but other than that there is negligible current draw by a pin, which remains static regardless of the direction of the biasing resistor.

> Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Absolutely not. The current draw of the MCU is not static. That means that the current through such a resistor would not be static, and so the voltage dropped across that resistor would fluctuate too - meaning if the current draw rises above a certain point the chip will be starved of power and will "brown out".

You only need a resistor to limit current when you have a device that cannot control the current by itself, such as an LED or other "non-linear" device.
> 2 votes

# Answer
If the sensor does provide two defined voltage levels, you do not need a pullup or pulldown resistor, but if it's only a switch: either (closed) connected to Vcc or GND, or (open) not connected, you need a pullup or pulldown resistor to get a defined voltage level in case there's "nothing else" (except the wire to the switch catching noise out of the air) connected to the digital input pin.

When the switch is open, the pullup/pulldown resistor is connected to the input pin and nothing but that neglectable leakage current is flowing.

When that switch is closed, some current will flow through that resistor, according to Ohm's law. You have to optimize between that current and the risk of catching some noise signal. Typically, µControllers like the Arduino atmel atmega328p have builtin pullup resistors of ~30k..50k, which should be fine for standard situations.

If you fear the battery drain, you can experiment with bigger resistors, but first make sure to build a scenario where the usual situation is "switch open". e.g. A fridge's door switch should be NC, but pressed while the door is closed. :)
> 2 votes

---
Tags: sensors, power, pull-up
---


title: 12V but what Ampere?

text:
# Question
Title: 12V but what Ampere?
So if my arduino will draw around 800mA @5V and the dc-dc buck converter around 266mA @5V plus solenoid 1.2A @12V, is it a good idea to get 12V 4A (48W) power supply? Since Filip Franik told me that it is a good practice to get 2 times the current I need just in case. Then what will happen to the current that are no in use?

# Answer
> 3 votes
So you want to use the 5V voltage regulator on the Arduino serve as the supply for your 5V components, and feed the 5V regulator from the 12V supply that powers your solenoid?

The problem with that plan is heat. The voltage regulator on the Arduino is a poorly heat-sinked (heat-sunk?) "linear" regulator. A linear voltage regulator is basically a solid state circuit that converts excess voltage to heat.

The higher the supply voltage you provide to the voltage regulator, the more heat it generates for a given current load.

If you feed 12V into the Arduino's voltage regulator, it needs to reduce the voltage from 12V to 5V. 12V - 5V is 7V. So it will convert 7V to heat. You're only drawing ≈220 mA. Total power that will be converted to heat is 7V\*0.22A, or around 1.54 watts of power. You should budget for at least 50% more current than you think you'll need, so lets use 330 mA. 7.0\*0.33 is about 2.3 watts.

From a little research I did, it sounds like a typical Arduino voltage regulator can dissipate around 1 watt of heat. You're well over that limit even at your low ≈220mA number, so you need a solution that won't overheat your Arduino's voltage regulator.

If you were to instead supply the Arduino's voltage regulator with 7.5V, it would have a lot less work to do. That's a voltage drop of 2.5V. So for a 0.33 max current draw, that would be 2.5\*0.33, or about 0.83 watts. That would be under the 1 watt ceiling. However, it sounds like your project is based on a 12V supply.

You could instead use an external switching voltage regulator to reduce 12V to 5V. (search for "boost voltage regulator".) Those are much more efficient, and don't generate nearly as much heat. You could then feed regulated 5V directly into the USB input on your Arduino, as well as supplying it to your other 5V components.

# Answer
> 0 votes
If my supply increase from 12V 1.5A to 4A. My arduino will draw around 800mA @5V (571mA @7V) plus solenoid 1.2A @12V, is it a good idea to get 12V 4A (48W) power supply? Since Filip Franik told me that it is a good practice to get 2 times the current I need just in case.

I know there is the efficiency of the converter is calculated by dividing the output power (Pout) by its input power (Pin) and then times the input current to get output current.

So for example 7V divide 12V is around 58.3% x 4A = 2.33A. Even if the solenoid takes 1.2A @12V, the current left is 2.8A, so the current is 1.63A, @ 7V. If arduino current draw what it needs and as long as it doesn't draw more than 2A, I think it is sufficient and safe.

---
Tags: arduino-uno, power, electricity
---


# Question
Title: How to increase the range to IR transistor receiver
I have a Arduino project which controls LED using IR Receiver and Transistor.The circuits works fine,But the problem is the LED is Blinking Brightly only for short range basically between 5-8 cm,but when i used my TV remote it works at for very long range(above 1 m).I have tried giving high voltage to IR Transistor,but no use. Please help to solve this problem!! Thanks in Advance!

# Answer
The reason your TV remote can work over a much longer distance is because it doesn't just turn an LED on and off.

Instead it turns the LED on and off *really fast*, and then turns that "turning on and off" on and off as well.

In technical terms: the light is modulated with a carrier frequency. Just the same as a radio signal is modulated with a carrier frequency, you can do the same with light.

The receiver then samples the light falling on it over time and passes it through a *band pass filter* to remove any frequencies in the changes of light intensity that aren't within the frequency of the carrier signal. What is left is then low-pass filtered to recover the overall "on-off" signal that is being transmitted.

Much of that is hard to do using an Arduino, so an IR *receiver* is used which integrates all the filtering and recovery of the signal. These are sold with different frequency sensitivities, and if you then turn an IR LED on and off at that stated frequency it will be able to "see" it far more efficiently than just having a light on or off.

There is a library for the Arduino that can handle the modulating of the LED at the right frequency for your chosen IR receiver.
> 0 votes

---
Tags: ir
---


# Question
Title: Temperature anomaly on BS18B20 + NodeMCU on Tingspeak
Temperature drops occasionally from 59+C to -13C or to other random values. Used sketch and info from this site: http://internetofthinking.blogspot.com/2016/02/upload-ds18b20-temperature-sensor-data.html

NodeMCU powered by phone charger 5v 1a via microUSB. Placing 4.7 kOm resistor between data wire and 3v3 didn't help me.

Does anyone know how to solve this issue? Like filtering results and pushing to server only values that do not differ by more than n\*C, or something like that?

Here is the sketch

```
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS 2  // DS18B20 on arduino pin2 corresponds to D4 on physical board

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="-";
const char* MY_SSID = "-";
const char* MY_PWD = "-";
int sent = 0;
void setup() {
  Serial.begin(115200);
  connectWifi();
}

void loop() {
  float temp;
  //char buffer[10];
  DS18B20.requestTemperatures();
  temp = DS18B20.getTempCByIndex(0)+5;
  //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
  Serial.print(String(sent)+" Temperature: ");
  Serial.println(temp);

  //if (temp != prevTemp)
  //{
  //sendTeperatureTS(temp);
  //prevTemp = temp;
  //}

  sendTeperatureTS(temp);
  int count = myPeriodic;
  while(count--)
  delay(1000);
}

void connectWifi()
{
  Serial.print("Connecting to "+*MY_SSID);
  WiFi.begin(MY_SSID, MY_PWD);
  while (WiFi.status() != WL_CONNECTED) {
  delay(1000);
  Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected");
  Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
   WiFiClient client;

   if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
   Serial.println("WiFi Client connected ");

   String postStr = apiKey;
   postStr += "&field1=";
   postStr += String(temp);
   postStr += "\r\n\r\n";

   client.print("POST /update HTTP/1.1\n");
   client.print("Host: api.thingspeak.com\n");
   client.print("Connection: close\n");
   client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
   client.print("Content-Type: application/x-www-form-urlencoded\n");
   client.print("Content-Length: ");
   client.print(postStr.length());
   client.print("\n\n");
   client.print(postStr);
   delay(1000);

   }//end if
   sent++;
 client.stop();
}//end send

```

# Answer
> 1 votes
> Have you checked the device's Scratchpad CRC

Idk how to.

> How is your device hooked up (diagram)

Device is hooked up in normal mode, right like in this pic

DS18b20 (waterproof) is located on top of the boiler in a special pit for measuring temperatures, there are definitely no any sort of microwaves here, and the temp is not higher than 80C. I'll try today to change the power supply, just in case, and later switch the sensor into parasite mode.

# Answer
> 0 votes
Discarding (potentially) bogus readings could help as a last resort, but something's going on to cause those bogus readings. You'd be better off finding and fixing that than finding a work-around.

These are pretty stable devices and you shouldn't see more than a couple of LSB (a few 1/4 degC). I'm inclined to suggest noise pickup on the one-wire bus but the bogus samples in your photo look identical. I have a \>15' parasitic one-wire bus, just a twisted pair with no shield, and a DS18b20 close to the MCU and another out at the end. I do smooth the input but no de-spiking.

Have you checked the device's Scratchpad CRC between converting and reading the temperature? How is your device hooked up (diagram)? Is it in parasitic mode?

---
Tags: nodemcu, thingspeak
---


title: buiReliable time in ISR

text:
# Question
Title: buiReliable time in ISR
I'm using a Nano. The code below is a simplified workup of my problem code.

The point of it is asynchronous debounced button press detection. The actual code sets a volatile bool to tell the main loop it saw a press, but this simplified version toggles the state of the built-in LED. Another LED follows the state of the pushbutton to make it possible to see whether the ISR is firing appropriately.

```
#define SHORT_PRESS_MS 50
#define PUSHBUTTON_PIN 2
#define BUILTIN_LED_PIN 13
#define OTHER_LED_PIN 12
volatile unsigned long fallTime = 0;
volatile int builtinLedState = LOW;
void isr_change()
{
    unsigned long now = millis();
    int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
    // show switch state with LED and 120 Ohms on D12
    digitalWrite(OTHER_LED_PIN, pushbuttonState);
    if ((pushbuttonState == LOW) || (fallTime == 0))
    { // change to low => falling edge
        fallTime = now;
    }
    if (pushbuttonState == HIGH)
    { // change to high => rising edge
        long pressMs = now - fallTime;
        if (pressMs > SHORT_PRESS_MS)
        {
            builtinLedState = !builtinLedState;
            digitalWrite(BUILTIN_LED_PIN, builtinLedState);
        }
    }
}
void setup()
{
    pinMode(PUSHBUTTON_PIN, INPUT_PULLUP);
    pinMode(BUILTIN_LED_PIN, OUTPUT);
    pinMode(OTHER_LED_PIN, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(PUSHBUTTON_PIN), isr_change, CHANGE);
}
void loop() {}

```

When this runs, OTHER\_LED slavishly follows the button. There is no perceptible lag and it never gets out of synch no matter how machine-gun my antics with the button.

However, toggling of the built-in LED is not reliable. That OTHER\_LED remains in sync with the button state implies that the event is always firing and the state is always what I expect, so it seems like there is a problem with my attempt to measure time.

What is the right way to measure time inside an ISR?

---

Applying suggested diagnostics confirmed the hypothesis of the accepted answer. Having determined the nature of the problem, I rewrote the ISR as follows.

```
void isr_change()
{
    static long fallTime = 0;
    static int lastPushbuttonState;
    int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
    if (lastPushbuttonState != pushbuttonState)
    {
        long now = millis();
        if (pushbuttonState == LOW)
        { // change to low => falling edge
            fallTime = now;
        }
        if (pushbuttonState == HIGH)
        { // change to high => rising edge
            long pressMs = now - fallTime;
            if (pressMs > SHORT_PRESS_MS)
            {
                digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
            }
        }
    }
}

```

Testing reveals that the problem is resolved and the intended behaviour is occurring (reliably detect presses of minimum duration).

Also of interest is the use of `static` to carry values between ISR invocations with local scope, rather than using global volatile variables.

# Answer
> 1 votes
I cannot make sense of this:

```
if ((pushbuttonState == LOW) || (fallTime == 0))

```

Why `|| (fallTime == 0)`? Other than this, your ISR looks fine to me. And your way of measuring the time is correct. The only scenario I can imagine that can make the toggling unreliable is the ISR missing transitions, which can happen if the input pin gives very short spikes.

Here is my scenario:

The button is pressed, `fallTime` holds the correct value, you release the button. At this point, the bouncing button generates a very short positive pulse: LOW → HIGH → LOW. The first transition triggers an interrupt request. However, there is some latency in handling the request. By the time the ISR starts running, the pin has already toggled back to LOW, and the ISR then incorrectly updates `fallTime`.

A little bit later, the pin toggles back to HIGH for good. However, `now` is very close to `fallTime`, and the rising edge gets ignored.

You can check whether you have missed transitions by toggling the LED every time you see the same state as in the previous ISR run:

```
void isr_change()
{
    static uint8_t previous_pin_state;
    uint8_t pin_state = digitalRead(PUSHBUTTON_PIN);
    if (pin_state == previous_pin_state)
        digitalWrite(LED_BUILTIN, !digiatlRead(LED_BUILTIN));
    previous_pin_state = pin_state;
}

```

# Answer
> 0 votes
you toggle the state of the main LED on CHANGE to HIGH. how should it be in sync with the other LED? and there could be more fast changes (bounce) which human eye can't see on LED

result of the sketch:

---
Tags: millis, isr
---


title: ESP32 + Fastled + WS2801

text:
# Question
Title: ESP32 + Fastled + WS2801
I'm using the ESP32 DevkitC board with Fastlib and a WS2801 LED strip. The LED strips works fine, i connected it properly (sometimes all LEDs are on, no flickering).

I Connected the light strip's Data cable (blue) to GPIO16 and Clock cable (red) to GPIO17. Compiling works but at first shows this error:

```
"No hardware SPI pins defined.  All SPI access will default to bitbanged output"

```

When the script starts, only the first 3 LEDs are glowing in light blue (instead of blinking) - here's my code:

```
#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 42

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 16
#define CLOCK_PIN 17

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
      // Uncomment/edit one of the following lines for your leds arrangement.
      // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);

      // FastLED.addLeds<WS2801, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<SM16716, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<LPD8806, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<P9813, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<APA102, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<DOTSTAR, RGB>(leds, NUM_LEDS);

       FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

```

Any ideas what's wrong?

# Answer
> 1 votes
This is hard to debug from afar...

Your sketch looks correct (hardly surprising, since it's just the Blink example). But I'd try to use IO18/SPI\_CLK for clock and IO23/SPI\_MOSI for data, as these are the hardware SPI pins of the ESP32. It might very well be that using these pins removes the warning about hardware SPI.

As I don't know all the variants of a WS2801 strip... is it maybe one of those strips that runs at 12V and can only be cut every three LEDs? This would explain why there are three LEDs lighting up instead of one (because then there would be one chip for three LEDs -- in other words, each "pixel" in your leds array corresponds to three physical LEDs)

Then there might be a problem with the voltage output of your ESP32 board. The ESP is running at Vcc=3.3V. The chips of the strip are running at Vcc=5V and expect 5V on their inputs. A logical 1 is assumed when the input in question is 0.7 * Vcc, i.e. the input signal may not be less than 3.3V. Now imagine that the power regulator on your ESP board drives the ESP at a teensy bit less (e.g. at 3.25V) and the power supply for the strip outputs a teensy bit more (e.g. 5.1V) -- suddenly, a logical 1 from the ESP is at 0.637 times the strips' Vcc and therefore in the undefined limbo between 0.3\*Vcc (highest definition for logical 0) and 0.7\*Vcc (lowest definition for logical 1). A level shifter module would help here to increase the ESP's output signal voltage (costs a few cents when ordered directly from China).

Then, at last, are you sure that the color order of the strip is RGB (as stated in your setup line)? I've seen more strips using GRB or BGR... which would explain why you see blue instead of red.

---
Tags: esp32, led-strip
---


title: Variable sets to 32767 - MATLAB Arduino

text:
# Question
Title: Variable sets to 32767 - MATLAB Arduino
I am running out of ideas of what may be causing this problem, and I would appreciate some help identifying anything I am overlooking.

## Quick Problem Summary

A variable gets set to 32767 quite often and I am unsure why. I tried checking if it was a types problem, if there was somewhere in my code it could overflow, any division by 0, initialising all variables in all sections of the code, and have now tried to cast all relevant variables to `int`. What else could I try?

This is how this variable gets set in a C++ function:

```
readValue = readAverage(A0);
targetValue = 2000; // Some constant number set beforehand
myVariable = targetValue - static_cast<int>(round(readValue));

// After some operations that only check if myVariable is within a range

// There are several states in which LOG_myVariable can get set in case there is an error where data wants to get logged
LOG_myVariable = myVariable

```

All of the variables above are public and get initialised to 0. See in the context section to see how the `readAverage` function works.

This code block above gets repeated thousands of times in a loop and exits when I send an interrupt. `LOG_myVariable` only gets set in the method above. Sometimes it gives me normal values that I would expect, but it is returning 32767 very often. Is this some C++ syntax or function I am overlooking?

### Some context:

An Arduino Due is using the MATLAB 2019 - Arduino Support Package Add-on. The variables described above are stored in memory and are dynamically overwritten during every logging function. I send them back to MATLAB via the C++ `commandHandler` as:

```
byte dataOut[2] = {
                  highByte(LOG_myVariable),
                  lowByte(LOG_myVariable)
                  };
sendResponseMsg(commandID, dataOut, 2);

```

In MATLAB, I convert it within a method after requesting the `dataOut` via `sendCommand`:

```
[dataOut] = sendCommand(arduinoObj, arduinoObj.LibraryName, commandID, dataIn);
            % Converts the two High and Low bytes from [dataOut] into a single integer.
            myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

```

`readAverage` works like this:

```
/*
Reads the raw ADC sampled value of a pin an averagePoints amount of times.
All the values get averaged and the function returns `outputAverage`.
Note
*/
int myClass::readAverage(const uint8_t pin) {
  int i = 1, outputAverage = 0;  // Iteration value, OutputAverage
  double sum = 0, runningAverage = 0;
  // Array Initialization
  int readings[70] = { 0 };

  for (i = 0; i <= 70; i++) {
    if ((runningAverage >= 0) && (runningAverage <= 4096)) {
      // First 10% readings to setup a runningAverage value
      if (i < 70 * 0.1) {
        readings[i] = static_cast<int>(analogRead(pin));
        sum += readings[i];
        runningAverage = static_cast<int>(sum/(i+1));

      } else if (i >= 70 * 0.1) {
        // Normal Operation
        readings[i] = static_cast<int>(analogRead(pin));

        // Filtering Outliers
        // If xReading is within [LOWER_PERCENTAGE, HIGHER_PERCENTAGE] * runningAverage range.
        if ((readings[i] >= LOWER_PERCENTAGE * runningAverage)
        && (readings[i] < HIGHER_PERCENTAGE * runningAverage)) {
          sum += readings[i];
          runningAverage = static_cast<int>(sum/(i+1));
        } else {
          // Enter Error/ Out of Bounds Log Mode, how?
          // Meant to filter out
        }
      }
    } else {
      /* Enter Unknown Error Mode
      Note it defaults to a single measurement, but no signal is sent to mention this.
      */
      runningAverage = static_cast<int>(analogRead(pin));
    }
  }
  outputAverage = static_cast<int>(round(runningAverage));
  return outputAverage;
}

```

Any tips on improving the code/logic are always appreciated too!

# Answer
Some findings:

* Your for loop iterates over 71 results, but your array has only the length 70. You may overwrite variables in the memory behind the array.
* You can use `else` instead of `else if (i >= 70 * 0.1)` because it is just the negation of the `if (i < 70 * 0.1)`. In the else case `(i >= 70 * 0.1)` is always true.

What is the type of `myVariable`? If you assign incompatible types (signage or length) an over- or underflow can happen. `32767 = 2^15 - 1 = 0b0011111111111111` (14 bits on) that looks pretty much like an underflow and a conversion of incompatible types.

**EDIT:**

By a second read of your question I saw another possibility of failure:

You copy the bytes of a two byte signed integer into 2 bytes and send it to matlab.

```
byte dataOut[2] = {
  highByte( LOG_myVariable ),
  lowByte( LOG_myVariable )
 };

```

Let's say you have a negative number in `LOG_myVariable`. In Memory this is represented with a one in the highest bit (MSBit) and the complementary bit string plus one (two's complement: See Wikipedia).

An Example:

16 bit signed int -1 is represented as `0b1111111111111111` you split it in two bytes `0b11111111` and `0b11111111`. The you send it to Matlab.

Now it depends on how Matlab interprets the bytes. Are that unsigned int8 or signed int8? you combine the bytes like so:

```
 myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

```

If Matlab interprets the bytes as unsigned you get `256*(-1) + (-1) == -257` but that's not -1. And if it interprets the bytes unsigned it gets `256*255+255 == 65535` which is also not -1. I bet there is a negative number that gives you 32767.
> 1 votes

---
Tags: c++, arduino-due, analogread, variables, matlab
---


# Question
Title: ESP-01 not waking correctly up after deep sleep
I have an ESP-01 that I want to measure pool temperature with. It will send the data over MQTT to the broker.

I have connected RST to GPIO16 so I can use the deep sleep functionality. Currently I am testing sending a "hello world" to the MQTT broker, and everything works fine when booting up the first time, but it seems like the ESP never wakes up correctly after the first deep sleep.

My script looks like this:

```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Set ADC mode
ADC_MODE(ADC_VCC);

// WiFi settings
const char* ssid = "Network";
const char* password = "Password";
IPAddress ip(192, 168, 0, 100);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

// MQTT settings
const char* mqtt_server = "192.168.0.110";
const int mqtt_port = 1883;
const char* mqtt_user = "User";
const char* mqtt_pass = "Password";
const char* mqtt_client_name = "poolsensor";
const char* mqtt_topic = "pool";

// Data wire plugged into D1 on the ESP8266 ESP-01 - GPIO 5
#define ONE_WIRE_BUS 5

// Setup OneWire instance to communicate with any device
OneWire oneWire(ONE_WIRE_BUS);

// Pass our OneWire reference to Dallas Temperature
DallasTemperature DS18B20(&oneWire);

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);

  // Annuonce connection
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  // Setup WiFi config and connect
  WiFi.mode(WIFI_STA);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're connected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");

    // Attempt to connect
    if (client.connect(mqtt_client_name, mqtt_user, mqtt_pass)) {
      // Success
      Serial.println("connected");
    } else {
      // Fail
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  // Start WiFi setup
  setup_wifi();

  // Set MQTT server
  client.setServer(mqtt_server, mqtt_port);

  // Set resolution to 0.25
  DS18B20.setResolution(10);

  // Start sensor
  DS18B20.begin();
}

void loop() {
  if (!client.connected()) {
    reconnect();
  } else {
    // Get temperature
    /*
    DS18B20.requestTemperatures();
    float temp = DS18B20.getTempCByIndex(0);

    if ((temp > -20) && (temp < 60)) {
      client.publish("pool/temperature", String(temp).c_str(), true);
    }
    */

    client.publish("pool/temperature", "hello world");
    Serial.println("published temperature");

    delay(1000);

    // Sleep
    ESP.deepSleep(60 * 1000000);

    delay(3000);
  }
}

```

Everything looks good in the serial monitor when compiling and uploading code, as the code runs the first time:

```
Connecting to Network
......
Connected, IP address: 192.168.0.100
Attempting MQTT connection...connected
published temperature

```

And I can see in my MQTT debugger that it receives `hello world`. After around 60 seconds, the following is shown in the serial monitor (lots of gibberish):

```
{l�l��|��d�|�d�b<����s�c$�#��ng�lgn���cxp��${$sd�s��'�c�ncp��

```

This is the last message I ever receive from the ESP, so I assume it never deep sleeps again and runs over the code again.

Anyone experienced the same, or see a bug in my code?

# Answer
Pretty sure you will need gpio 16 connected to reset in order for this to ever work, it’s tricky but not impossible. Have a read here:

https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/
> 2 votes

# Answer
You left io 0 floating. With io 0 not HIGH at boot, the esp8266 goes into flashing mode.

The wake-up from deep-sleep is boot startup. So your code doesn't start if io 0 is not pulled high. Add a pull-up for io 0.

If you set Serial Monitor to 74880 baud, you will see the boot-log readable. It will print 1 as first value in "boot mode". This value is set from state of io 15, 2 and 0. 15 should be LOW and io 2 and io 0 HIGH for normal boot. `1` indicates that only 2 is HIGH.
> 1 votes

# Answer
I had the same problem and i found out, my CH\_PD pin and RST pin were shorted together, when i was connecting wire from RST to GPIO\_16. On the chip, the CH\_PD pin is next to GPIO\_16, so when you short them, the RST pin is always high, so esp cannot reboot anymore without external grounding. I fixed it and now deep sleep is working again!
> 1 votes

---
Tags: esp8266, ds18b20, mqtt
---


title: Can't get OC1B (pin 10) to output

text:
# Question
Title: Can't get OC1B (pin 10) to output
I'm trying to get this program to use channel B for the output waveform using the phase correct PWM mode and using OCR1A as the top. With a 50% duty ratio I'm attempting to get a 10 Hz freq. I'm able to adjust the OC1A (Pin 9) if I set TCCR1A to 0x43; but nothing comes from pin 10. Code:

```
include "avr/io.h"

void setup()
{
 DDRB = 0x6; //set pins 9 and 10 as output

 /*set operation Toggle mode; WGM13:0 = 1011 phase correct PWM
CS12:0 = 101 prescaler = 1024*/
 TCCR1A = 0x23;
 TCCR1B = 0x15;

 OCR1A = 0x187; //391 for 50% duty cycle
 TCNT1 = 0; //clear counter and update OCR1A
}
void loop()
{ }

```

# Answer
You are using Timer/Counter 1 in Fast PWM Mode with TOP set to OCR1A:
`OCR1A`only describes the number to what it counts up so, 0…391 in your case.
You have to define the duty cycle with `OCR1B`. 50% would be 195.
> 1 votes

---
Tags: arduino-uno, led, atmega328, timers, port-mapping
---


title: Arduino IDE won't use selected port

text:
# Question
Title: Arduino IDE won't use selected port
I'm trying to program an ATtiny85, using an *AVRISP mkII* programmer (this one: https://www.amazon.de/dp/B00IYNAXUC/ref=cm\_sw\_r\_sms\_c\_api\_i\_VXOWDb3H3N5ND) with the Arduino IDE (version 1.8.10 on Ubuntu 18.10). For the ATtiny, I've installed https://github.com/damellis/attiny using the board manager, as recommended in countless tutorials.

Now, everything seems to be recognized fine, and I've selected the programmers port in the IDE: `/dev/ttyACM0`.
But when I try to upload a sketch, the IDE instead trys to pass `usb` as the port to `avrdude`. This is only visble when enabling verbose output: (paths abbreviated)

```
/home/[...]/avrdude -C/home/[...]/avr/etc/avrdude.conf -v -pattiny85 -cstk500v2 -Pusb -Uflash:w:/tmp/arduino_build_728460/sketch.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/[...]/avrdude.conf"
         User configuration file is "/home/[...]/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : stk500v2
avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)

avrdude done.  Thank you.

```

`usb` isn't even a selectable port in the IDE!

Simply pasting the avrdude command (first line in the output above) to a terminal and changing `usb` to `/dev/ttyACM0` makes it program the IC perfectly (but of course, that's a rather cumbersome workaround).

Also, selecting another programmer in the IDE (like AVR ISP, without the mkII) makes it use the correct port (but of course it won't work, since it's the wrong programmer).

Am I doing something wrong, or is this an actual bug in the Arduino IDE?

# Answer
I would say you have to select the Arduino as ISP Programmer. Not the mkII ISP. Perhaps the attiny board library can handle connection to attiny dev boards over usb if you use the standard programmer. But that's just a very very rough guess. But selecting the Arduino as ISP is a requirement.

**Edit:**

No you can not use the Arduino as ISP if you use an STK500 programmer.

D. A. Mellis' tool is designed for an Arduino as a programmer.

But if your work around does the programming, the mkII is the right tool. You have to find out, how the IDE builds the CLI string to start `avrdude`.

The tool you installed contains a text file called `platform.txt`:

```
name=ATtiny Microcontrollers

tools.avrdude.path={runtime.tools.avrdude.path}
tools.avrdude.erase.params.verbose=-v -v -v -v
tools.avrdude.erase.params.quiet=-q -q
tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

tools.avrdude.bootloader.params.verbose=-v -v -v -v
tools.avrdude.bootloader.params.quiet=-q -q
tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params}

```

I would say the entry `tools.avrdude.bootloader.pattern` does the trick. Especially the variable `{program.extra_params}`. You have to find out how the IDE is building this variable. One of it's options must be `-P<Port>`. But why does the IDE use the value `usb` for `<port>`?

I'll try to find out. But I have no access to an IDE at the moment. If you (or someone else) find a solution before me, please add an answer and mark it as accepted, so I need not investigate further.
> 1 votes

# Answer
You mean that the STK500 v2 programmer uses an emulated serial port rather than direct USB? Then I guess there is a bug in the Arduino IDE. The file `programmers.txt` contains the following lines describing the programmer:

```
avrispmkii.name=AVRISP mkII
avrispmkii.communication=usb
avrispmkii.protocol=stk500v2
avrispmkii.program.protocol=stk500v2
avrispmkii.program.tool=avrdude
avrispmkii.program.extra_params=-Pusb

```

You may locate this file in your Arduino installation and replace the last line from this snippet by

```
avrispmkii.program.extra_params=-P{serial.port}

```

If that works, it would be a good idea to submit a pull request with the fix to the Arduino team.

Alternatively, you may try selecting “Atmel STK500 development board” as a programmer. This is supposed to autodetect the version of the STK500 protocol, and uses the correct serial port.

**Edit**: you may also have to replace

```
avrispmkii.communication=usb

```

by

```
avrispmkii.communication=serial

```

C.f. this bug report, which seems to cover the exact issue you are facing.
> 1 votes

---
Tags: arduino-ide, attiny, avrdude, linux, programmer
---


title: C++ State Machine / Wpmf-convesion

text:
# Question
Title: C++ State Machine / Wpmf-convesion
I'm quite a newbie using C ++. I am trying to implement in C ++, the state machine described in this link for C language: https://barrgroup.com/Embedded-Systems/How-To/Coding-State-Machines.

I have created an Fsm class, which implements the behavior of the state machine, and a Machine class, whose methods will be the states.

The code works, but it generates a warning (-Wpmf-conversions) when I try to save the memory address of a Machine method, in `State state__`

```
class Fsm
{
public:
    typedef void (*State)();
private:
    State state__;
public:
    Fsm(State state);
    void dispatch();
};

Fsm::Fsm(State state)
{
    state__ = state ;
} //Fsm

void Fsm::dispatch()
{
    (*state__)() ;
}

class Machine : public Fsm
{
public:
    Machine() : Fsm((State)&Machine::initial) {}       // ctor
};

```

I'm using an Atmega2560, with AVR-GCC compiler.

# Answer
> 2 votes
A pointer to a member function is not allowed in C++. GCC *can* allow it, but moans at you because it's non-standard.

In C++ the normal way of dealing with the kind of thing you want is through class inheritance.

Typically you would create your base `Fsm` class that implements the basic functionality of your state machine control, then overlay over the top of that (create a new class that inherits the `Fsm` class) another class that implements your specific machine functionality. You can declare functions in your base `Fsm` class that are *pure virtual* \- that is, they exist, but have no body. It's then the job of the child class to actually implement that functionality. The parent `Fsm` class then knows about those functions and can call them.

So you would have something like:

```
class Fsm {
    public:
        void dispatch();
    protected:
        virtual void initial() = 0;
};

void Fsm::dispatch() {
    initial() ;
}

class Machine : public Fsm {
    protected:
        void initial() {
             Serial.println("Here");
        }
};

Machine mach;

mach.dispatch(); // --> "Here"

```

`Fsm` knows about `initial()`, but the function hasn't been further defined. `Machine` implements `initial()`. You then create an instance of `Machine` which contains everything needed. Calling `dispatch()` runs the function in the `Fsm` parent class which then calls `initial()` in the child `Machine` class.

---
Tags: c++, avr, atmega2560, avr-gcc, gcc
---


# Question
Title: ESP8266 Arduino MQTT callback with dynamic topics
I have a program that depending on user input, it creates one or several objects that will publish data to a MQTT broker, each one with a different topic. This is already done. The ESP8266 also has subscribe itself to the same topics it publishes. Now, the problem is that I have to create a dynamic callback in the ESP8266 to read the all the posible arriving topics to which the ESP8266 has subscribed and I am having trouble with that.

The callback function model is:

```
void MQTTcallback(char* topic, byte* payload, unsigned int length) {

// handle message arrived

}

```

The possible topics can be:

ObjectTL/TL\_1

ObjectTL/TL\_2

ObjectTL/TL\_3

...

ObjectTL/TL\_X

The number (TL\_X) depends of the user input I mention at the beginning. Thanks!

# Answer
I think using sscanf may help you

```
void MQTTcallback(char* topic, byte* payload, unsigned int length) {

  sscanf(data, "ObjectTL/TL_%d", dynamicTopicName);
  // handle message arrived
  your_dynamic_function(dynamicTopicName,byte* payload, unsigned int length)

}

```
> 1 votes

---
Tags: esp8266, mqtt
---


# Question
Title: Receive whole string in serial sending data?
I connect my NodeMCU to Arduino Uno. The goal is to receive the whole string for example "12", every 1 sec.

This is my code on Arduino Uno side ( the sender)

```
int mock = 0;

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

void loop() {
    //Write mock to NodeMCU
    s.print((int)mock,DEC);
    s.println();

    mock++;
    delay(1000);
}

```

On NodeMCU side ( the receiver)

```
 char data; //Initialized variable to store recieved data
 String line;
 void setup() {
   Serial.begin(115200);
   s.begin(115200);
   while (!Serial) {
    ;
  }
}

void loop() {

    if( s.available() >= 2) {
        for (int i = 0; i< 2; i++ ) {
            data = s.read();
            line += data;
        }
        delay(1000);
    }

    Serial.print(line);

}

```

But the result on the serial panel is not what I expected

How can I make it so that I can receive something like

```
12
(wait one sec)
13
(wait one sec)
....

```

Node MCU just prints the whole thing, I can't delay it.

# Answer
> 0 votes
in your nodemcu use

```
void loop() {
    if(s.readBytesUntil('\n',data ,2)>0)
      Serial.println(data);
    delay(1000);
}

```

> Serial.readBytesUntil(character, buffer, length)

**Serial.readBytesUntil()** reads characters from the serial buffer into an array. The function terminates (checks being done in this order) if the determined length has been read, if it times out , or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator). The terminator itself is not returned in the buffer.

**Serial.readBytesUntil()** returns the number of characters read into the buffer. 0 means that the length parameter \<= 0, a time out occurred before any other input, or a termination character was found before any other input.

# Answer
> 1 votes
If you send "12" you send 4 characters/bytes: '1', '2' and a new line which is two characters: ('\r', '\n').

On the receiver side you check for two characters (not the new line), so you should take it into account.

Actually, since you will eventually reach "100" you will receive 5 characters ('1', '0', '0', '\r', \\'n').

So it is better to change the receiver side to store the bytes in line UNTIL a new line is received (than you can support values of any length).

Also remove the delay on the receiver side, or at least decrease it a lot, because it doesn't matter to check (too) often. if there is no byte available, it will check again. Now it can happen at time 1001 ms a byte would be received, but at time 1000 ms it is checked and it will not be checked again until time 2000 ms.

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


# Question
Title: Is it possible to load both the arduino bootloader and a sketch onto an atmega328p via icsp?
i am familiar with uploading an arduino bootloader onto an atmega328p using another arduino via the arduino IDE. i have also installed software 'sketches' using that process which i believe leaves out the bootloader(meaning one wouldnt be able to upload new sketches in the future via usb). my question is: is it possible to load both the bootloader and a software program onto the chip via icsp? many thanks in advance.

# Answer
> 2 votes
The Arduino builder creates for AVR boards not only hex file for the sketch, but it creates a combined hex with bootloader and sketch too. It is for example for Blink.hex a Blink\_with\_bootloader.hex. If you use in IDE the "Export compiled binary" command in Tools menu, the builder puts the hex files next to ino file in your sketch folder.

If you want the command "Upload using programmer" to upload hex with the bootloader, modify in platform.txt the `tools.avrdude.bootloader.pattern` key to use `"-Uflash:w:{build.path}/{build.project_name}_with_bootloader.hex:i"`

---
Tags: atmega328, bootloader
---


# Question
Title: Do some arduino pins give signals when the controller starts?
For example, on the ESP32 board there are several contacts that can issue pulses when the controller starts, which is connected with the operation of the chip itself. It is not recommended to connect devices that respond to input signals from the ESP to these contacts.

Tell me, are there any contacts on the Arduino UNO (Atmega328P) that give out any impulses at startup?

In particular, it is important for me to know about the following contacts:

1. PB1 (9 pin)
2. PD4 (4 pin)
3. PD5 (5 pin)

Thank you!

# Answer
> 2 votes
Most Arduino boards come with a bootloader of some form. This bootloader may do things with IO pins. However apart from that, no, nothing else happens to any IO pins.

The bootloader may:

* Flash pin 13 (built in LED)
* Configure and communicate on pins 0/1 (UART)

With no bootloader then absolutely nothing happens on any IO pins.

---
Tags: arduino-uno, pins
---


# Question
Title: arduino & drivers to control 5 brushed CIM motors independently?
i am a complete newbie in electronics but i'm a bit familiar with C. i am building a machine that requires 5 little engines (12V 2.5in brushed CIM motors) & motor drivers (i need to adjust each motor's speed). i've got an arduino UNO which i think is too small to control that many motors. i would like to know if the setup i want was feasible to your opinion and which ardunio would i need to do that ? i guess an Arduino Mega ?

also, i came accross this tutorial : https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/ it explains how to configure an arduino with a driver & two motors.

in fact i want to prepare the same kind of thing but with 5 motors that i can control independently.

which hardware would you recommend to do such a thing please ?

many thanks ! regards

# Answer
> 1 votes
You should have just enough I/O with UNO, so long as you don't want to connect any other hardware/sensors. Since this is unlikely, it would be better to use another board like Mega, but I'll provide solutions anyway in case you want to try them out:

* **Option 1**: For 5 motors controlled with L298N boards you'll need 15 output pins, 5 of which should be PWM. Fortunately, there are 5 PWM outputs on the Arduino UNO on `PORTB` and `PORTD`. The remaining 10 outputs need only be digital (`PORTB` has 1 and `PORTD` has 5). You can use `DDRC` and `PORTC` commands to change function of the analog inputs labeled A0-A5, making them digital output, thereby gaining 6 more digital output pins for a total of 12 (more than the minimum 10 needed).
* **Option 2**: It is possible to use other PWM motor drivers that reduce number of pins required. Examples are DRV8838 (link to supplier) and DRV8833 (link to supplier) where 2 wires are needed per motor channel. As a bonus, these drivers are also significantly more compact than L298N.

---
Tags: arduino-mega, motor
---


# Question
Title: multiple invdividual servo controll arduino
I want to declare 11 servo motors in my code. Is there a better way to do that than just declare everyone under each other. The reason is that i have a code that will set the rotation for one at a time. The best would be a list so i could iterate over which server i want to move.

```
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
//etc
void moveServo(int n,int deg){
  servo[n].write(deg); //something like this
}

```

# Answer
> 0 votes
Consider using a specific processor / Arduino-board. In this thread there are references to using the Arduino 1280 board with the Arduino Servo Library to control up to 48 servos using a combination of hardware and software.

In C++ when you "instantiate" a class you are making good use of memory space as you do not really create duplicate code. All you create are copies of the variables necessary to support each instantiation. There should only be one copy of the code in memory. To iterate over each instantiation consider using a switch/case statement.

# Answer
> 0 votes
First: Your code would not work, since `servo` is not defined and thus not an array to iterate over. You would need to first define the array and then fill it with Servo elements.

```
Servo servo[11];

void setup(){
    for(int i=0;i<11;i++){
        servo[i] = new Servo();
    }
}

```

The different `Servo` objects are created dynamically. In most cases it is bad to use dynamic allocation on a microcontroller with litte RAM, but it is ok, when you only use it once at the start.

---
Tags: arduino-uno, servo, code-optimization
---


title: can i give a vcc to 14v?

text:
# Question
Title: can i give a vcc to 14v?
What is maximum voltage PWM pins can give? can i give a vcc to 14v?

# Answer
Since PWM pins are digital outputs, the maximum output voltage is VCC.
> 4 votes

# Answer
On a typical Arduino board, PWM pins will theoretically only ever operate at ground (+0v) or `Vcc` (typically +5v). PWM is a square wave, which means it alternates rapidly between those two values, aka `LOW` and `HIGH`.

With that said, if you run it with a 50% duty cycle, then the **average** voltage over several cycles will work out as 50% of `Vcc` (i.e. typically 2.5v). The same applies to other percentages. It's important to note that it's not equivalent to a 'true' analog signal though, and shouldn't be used as such.

As a side note, there are some modified Arduino clones which have a voltage selection switch. These typically let the pins operate at either 3.3v or 5v, and should affect PWM (as far as I know).
> 2 votes

# Answer
+5V

I understand for higher power people driving motors trigger a MOSFET transister which normally can go to 30 volts but this unit here appears to be able to switch 100 volts: https://www.banggood.com/100V-9\_4A-FR120N-Isolated-MOSFET-MOS-Tube-FET-Relay-Module-For-Arduino-p-1396252.html this unit is likely to be able handle up to 50 Khz switching frequency (based on the regular MOSFET switching speed). Anything higher you'd need GaN (Gallium Nitride) transisters as used in Class D audio amps. Anyhow 100 volts and 9.4 amps would be 940 watts of DC, or maybe 664 watts of RMS sine wave (ball park), probably I would not trust more than 300 watts through that thing mind.
> 1 votes

---
Tags: pwm
---


title: How to check if a LED is on?

text:
# Question
Title: How to check if a LED is on?
I have a circuit board / device that can be in different states. It indicates in which state it is by turning on one of three LED's. Now I want to use an ESP8266 to tell me (over the network) the current state. What kind of circuit would I need for this? (I have thought about using photodiodes, but I would much rather solder something directly to the board)

# Answer
If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266. If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate level shifter or the appropriate optical isolator:
> 1 votes

---
Tags: esp8266, led
---


# Question
Title: Taking data from main 120V 50/60Hz power
How can I take data from my house main power and reconstruct it signal? I used an transformer and an inverter amplifier to low voltage to 5 volts and read it with A0 analog pin, but I got a very strange datan and just a few numbers

`data = analogRead(A0);
 Serial.println(data);`

# Answer
The Serial output on an Arduino is quite slow. By printing your output, you will slow down the readings so much that it will appear to be nonsense.

You should collect a series of readings into a C array of floats in RAM, stop recording, and then log that array of values.

Note that you don't have a lot of RAM to work with on most Arduinos, so you will only be able to record a small number of values. A Mega 2560 has a lot more memory than others (8KB). It's still not a lot, but better than other boards. One of the ARM based Arduinos will have both a much faster processor and a lot more RAM.
> 1 votes

---
Tags: arduino-uno, arduino-ide, arduino-nano, electronics, matlab
---


# Question
Title: Program an ATMega328P and use it without Arduino board
I'd like to use an ATMega328P for my project, I hope to do it without the Arduino board.

I know with the Arduino IDE and an Arduino board I can program the microcontroller. However, would it be possible once I've programmed and debugged the program with Arduino IDE + Arduino board, to take away the microcontroller from the Arduino board and to use the ATMega328P separately, without the board?

If yes, what additional configurations I should do the ATMega328P to work correctly on the breadboard?

# Answer
Yes you can use **`ATMega328P`** without arduino board. I always use the IC without arduino. There are two ways of doing it.

1. You can use arduino board with the IC. Program the IC and then take it out and use it in your circuit. You will have to use **`16MHZ Oscillator`** with capacitors.
2. If you don't have arduino board, you can use other programmers like **`USBasp`** to program your **`Atmega328p`**. In this case, do not use the direct upload button instead use the upload using programmer options from file menu. Do not forget to select board as **`Arduino Pro or Pro Mini (5v, 16mhz) With ATmega328`** and programmer as **`USBasp`**.

**NOTE**: Refer to **Atmega328p Pin Mapping** and program your device accordingly. Enjoy!
> 9 votes

# Answer
You can remove an ATMEGA from an Arduino and use it in your own board, however when used on a typical Arduino board the chip will be fused for an external crystal as a clock source, rather than the (simpler but less accurate) internal clock.

You cannot change the clock source over ISP unless the clock source the chip is currently expecting is operational, so if you want to change the clock selection you will want to do that before removing the chip from the Arduino.

However, you can also provide a clock crystal and its two capacitors (or a substitute resonator which often has this built in) on your external board.

Typically chips (even those pre-flashed with a bootloader as a convenience) are cheaper than boards, so it's unclear why you would want to move the same chip off the Arduino as opposed to using another. You will want a USB-logical level serial adapter anyway, and once you have that you can do development on the bare chip on your board, even if you do initial testing on the Arduino. In a pinch if you don't have the USB converter you can either pull the chip out of an Arduino board and run wires from its D1 and D0, or hold the on-board chip in reset to allow you to borrow those serial lines without interference.
> 7 votes

# Answer
Search for "Build an Arduino" \- you'll find tons of how-to articles about doing just that. You'd need to be able to solder connections on a printed-circuit board (and not even that if you wanted to use a solderless breadboard), but it's really straightforward. You can even build it first and program the MCU on the PCB using an FTDI cable. I use an Arduino board and a solderless breadboard to experiment with unfamiliar parts, but I usually go immediately to a hand-built board once I'm familiar with all of the components I'll be using.

Prototyping with the Arduino board lets you throw together a bunch of parts and get something working quickly, and if the Arduino is more capable than your final target - f/ex, a Mega 2650 - you can temporarily ignore the memory and I/O constraints of the smaller device.
> 2 votes

# Answer
It's fairly easy to use a standalone Arduino chip. The one tricky thing about the chip used for the official boards is that they are fused to use the faster (and more accurate) external oscillator that's mounted on the board. This applies even when you purchase the loose chips, since most are resold with intention of being installed in an Arduino board to replace a burned-out one, with exception of perhaps the ones from Digikey.

Caveats: The Arduino is designed as a prototyping board, and few things do better than it does at this task. You may want to leave the chip on the Arduino board until you are done designing and testing your circuit. Only then do you connect it directly. It can be used in-place if you have a clock circuit in place, or you can change the fuses (see later) and reprogram the Arduino with an ISP adapter and a clock speed of 8mhz (PlatformIO lets you do this (*and* allows direct imports of an Arduino sketch) -- check their docs page for the Atmel AVR plugin, but you can also look up a number of guides on how to add a board file to Arduino to tell it to use the 8mhz option for a bare chip)

If you remove the chip for use in a different circuit, it either needs that clock circuit added back in, or to have its fuses changed (I'll get to that in a minute). It will also be hard to program, for a number of reasons, so you'll want to purchase a bit of fairly cheap hardware:

**Programming** a standalone chip: The Arduino's CPU is not natively designed to talk to a computer. You need an intermediary. On the Uno, this is done via a second Atmel chip that has USB capability, and a bootloader on the main chip. What that does, is that it uses the UART for upload of the program while the USB chip converts the PC's messages to UART signals. Since the bootloader is somewhat of a pain when the chip is on its own (since UART is picky and installing it sets the chip to use an external clock as a result), you'll want to buy an ISP programmer for the Arduino (or follow the Arduino-as-ISP sketch and instructions to make your own, which requires an Arduino with chip present, so you'd need a second to be programmed).

These can program the ATMega 328 directly over SPI, without a bootloader (there are many instructions on the Internet; search "program bare ATMega 328P with USBAsp", for instance). This makes it a lot easier to change and debug your program outside of popping the chip out and back into the original Arduino board. You also need one to change the clock settings if you don't want to use an external crystal.

If you want to **debug** the chip, it's useful to also purchase a FTDI adapter or other USB-to-UART converter. Note that without the reset circuit part of the board (or again, adding your own), this still won't let you program the ATMega even with the bootloader, though. For that, connect the ground, RX, and TX pins to the adapter. You may or may not want to connect the VCC line, but it's advised to not do so *if* there's a lot of things connected to the chip and/or it has its own power supply. Note that the RX and TX need to be swapped when you connect them; that is, RX to TX and TX to RX -- you want the chip to RX (receive) what the adapter is TX( transmit)ing, and vice versa.

The clock circuit is not hard to build, but it requires a few components you may not have. So, to **change the clock source**, go to http://www.engbedded.com/fusecalc/ and select the ATMega 328P. The defaults are good, but you may want to enable EEPROM keep-on-erase and disable the clock divide-by-8 or adjust the brownout settings. Don't touch anything else (disabling reset or SPI or enabling DebugWire result in "fun" that requires a HV programmer to fix). When done, paste the command it provides to the AVRDude command. You will need to change the -c options (-p is already set to the ATMega 328P, but will fail for non-P 328s -- don't buy those), and perhaps add the -P option (for Port). Do not omit the lowercase -u option, or it will refuse to update the fuses.

```
avrdude -p m328p -v -c usbasp -B 100 -u [add extras here: (-P <PORT>) <fuse set command here>]

```

*Note* that if you purchase a USBASP (make sure it has three sets of jumpers!), for all that they are my favorite programmer, they may not have the updated firmware that supports the -B option (which you'll probably need). That means that you need to attach it to an Arduino via the six-pin programming port, in the exact same way that you'd use it to program the Arduino's bootloader, but then use the Arduino-as-ISP sketch to program the new firmware to the programmer (search "update the usbasp firmware via arduino-as-isp")! For reference, that *usually* means that the cable faces away from the body of the board, and you'll probably have to program the sketch **before** connecting the cable. Also enable the power-from-programmer jumper on the USBASP (5V), and the "self-program" one. (see https://forum.arduino.cc/index.php?topic=560719.0 for the location of the power and program jumpers (JP2)).
> 2 votes

---
Tags: arduino-ide, atmega328
---


# Question
Title: How to use existing (non-arduino-specific) library with subfolders in Arduino IDE?
I have a generic c++ library that i'd like to use in an arduino project without making changes to the library code. The library contains subfolders and files in the library include other files of the same library with includes of the form

```
#include "libraryroot/subfoldername/header.h"

```

I tried putting 'libaryroot' into C:/Users/Username/Documents/Arduino/libraries but while I can include headers that lie directly inside 'libraryroot' using `#include <filename.h>` (not `#include <libraryroot/filename.h>`), Arduino fails to find the headers these files include

How can I make use of such a library in Arduino without having to change the library?

# Answer
To utilize subfolders with any name in an Arduino library, you must use the 1.5 library specification.

In libraries folder in your sketch folder, create a folder for the library. In this folder create a `src` subfolder and put the library source code into that subfolder. Then create a library.properties file in the root folder of the library with some dummy information. Fill the `includes` key with the main .h file of the library.

```
Documents/
  Arduino/
   libraries/
     FooLib/
      src/
       subfoldername/
        header.h
        some.h
        some.cpp
       foolib.h
       foolib.cpp
      library.properties

```

In code then use in `#include` the path with src folder as starting location.

`#include <subfoldername/header.h>`
> 1 votes

---
Tags: c++, library
---


# Question
Title: Arduino - Extracting Multiple Strings from Serial Read
I am trying to write an Arduino code that reads a long string, example \<11,22,33\>, through the Serial Monitor and then stores the 11,22, and 33 into separate bins of a matrix array.

So the user could input: \<11,22,33\> And the code would store the three entries into a matrix of strings:

```
matrix[0]=11;

matrix[1]=22;

matrix[2]=33;

```

Whenever I try to run the code the only result that's outputted is

```
matrix[0]=33;

matrix[1]=33;

matrix[2]=33;

```

But the strange part is when I put print commands after the Matrix\[i\]=data line in the code, the output shows the correct numbers! I'm not sure where the issue is and if somehow I made all entries the final entry. Any help is appreciated!

```
// Example 3 - Receive with start- and end-markers

const byte numChars = 32;
char data[numChars];    //data entry for appending Serial data
char *matrix[numChars]; //matrix of data entries
static byte i=0;  //matrix index

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithStartEndMarkers();
    showNewData();
    Serial.println(matrix[1]);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ind = 0;  //data index
    char startMarker = '<';
    char midMarker = ',';
    char endMarker = '>';
    char rc;    //Serial read character

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc == startMarker) {
            recvInProgress = true;  //if startMarker arrives then enter secondary if below
        }

        else if (recvInProgress) {  //begin appending characters if startMarker activated switch

            if (rc == midMarker) {  //if midMarker is reached...
                matrix[i]=data;     //append data to i-th entry in matrix
                i++;                //add to matrix index
                data[0] = '\0';     //clear data
                ind = 0;            //reset data index
            }
            else if (rc == endMarker) {     //if endMarker is reached...
                matrix[i]=data;             //append data to last entry in matrix (ensures last data is appended)
                data[ind] = '\0';           // terminate the string
                recvInProgress = false;
                ind = 0;                    //reset counters for data and matrix
                i = 0;
                newData = true;
            }
            else {
                data[ind] = rc;           //eppend Serial character into data
                ind++;                    //add to data index
                if (ind >= numChars) {
                    ind = numChars - 1;
                }
            }
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(matrix[0]);
        Serial.println(matrix[1]);
        Serial.println(matrix[2]);
        newData = false;
    }
}

```

# Answer
You define pointers for each value as :

```
char *matrix[numChars]; //matrix of data entries

```

However, in all cases you let it point to data:

```
matrix[i]=data;

```

Than you set the value starting from that address. So what happens is after you read the first value (11), and `matrix[0]` contains '11', than `matrix[1]` points to the same data which you write the value 22 to. And you do the same for 33. So you end up with 3 pointers to the same address (`data`) containing/overwriting the last value (33). So you get three times 33.

You should either continuing writing the string in `data` and refer to the correct part inside the string `data`. If you want to do a `Serial.println`, you have to end the strings with `\0`, so the string `data` and matrix references should be:

```
index:    0   1  2  3  4  5  6  7  8
data:     1   1 \0  2  2 \0  3  3 \0
matrix:  [0]       [1]      [2]
i:        0         1        2

```

It will help if you change

```
matrix[i]=data;

```

to

```
matrix[i]=&(data[ind]);

```
> 0 votes

---
Tags: arduino-uno, serial, programming, string
---


title: Distorted audio from mcp3002

text:
# Question
Title: Distorted audio from mcp3002
I have setup a MCP3002 to convert an analog signal to digital signal. When I read it directly through serial and convert it to a wav file, it sounds relative clear. Serial is limited for samples per second though, I can get about 7000 sps.

When I send the signal directly to a server I can reach around 17.500 sps. however when I convert this to a wav file, it also sounds relative clear, but with a slight distortion/'robot voice' through the audio.

Is there a simple way to prevent this, or why is this happening?

The code how I read the SPI is in this question: Reading data from MCP3002

# Answer
From the code you linked to, it appears the SPI port is completely controlled by the software:

```
void loop() {
    ...
    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);
    ...
}

```

This means that the timing of the SPI transaction (when exactly it starts) and, by extension, the timing of the ADC conversion, is dependent on the timing of your code execution. You have no good control on that timing. It depends on what other things may be in your loop, and on the other interrupt sources (timers, network...).

The least you can do is set up a timer interrupt, and run the SPI from the interrupt handler. Your timings should then be more consistent. You will still have some jitter due to the interrupt handler being delayed by some critical sections, including other interrupts. But it may be good enough for your application.

For best results, you would ideally want the timing to be completely controlled by hardware. Maybe there is a way to trigger the SPI port from a timer. This depends on the specific MCU you are using: you will have to dig into the datasheet.
> 1 votes

---
Tags: audio, digital-analog-conversion
---


# Question
Title: Including keypad library removes sound from my piezo element
I am using the keypad library to include keypad and input numbers. when a specific number is entered a sound must be made. However when I input using the serial monitor , sound is working. But when I include keypad , it only inputs numbers but not sound. Help please , how can I make both work? Thanks.

`#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
 {'1','2','3','A'},
 {'4','5','6','B'},
 {'7','8','9','C'},
 {'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,7,6,5}; //connect to the column pinouts`

Then I get the input from keypad and store as result

`char guess = 'n';
 char keypressed = keypad.getKey();
 if (keypressed != NO_KEY) {
 char guess = keypressed;`

in void loop, it get result(key from keypad) and must play it: Tried separate sketch it works. but with keypad only input is , not sound.

`Serial.print("You guessed:");
 Serial.println(guess);
 result = checkYourself(guess);
 Serial.println(result);
 playSound(result);`

check yourself takes in guess from keypad ,checks then returns as result. play sound function works when tried in another sketch( sorry not posting too much code its very long)

# Answer
> 1 votes
I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.

# Answer
> 0 votes
Please make sure that the pin connected to piezo does NOT used by keypad

---
Tags: library, piezo, keypad
---


# Question
Title: Arduino beginners kit example not working
I bought a beginners kit and can get all but one of the examples to work. I have tried different board layouts and varied the code with no success. When I first run the code the LED is off. When I ground pin 9 the LED comes on and stays on. Grounding pin 8 does not turn off the LED once it is lit.

```
int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;

byte leds = 0;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW)
  {
    digitalWrite(ledPin, HIGH);
  }
  if (digitalRead(buttonBpin) == LOW)
  {
    digitalWrite(ledPin, LOW);
  }
}

```

# Answer
> 0 votes
This kind of button has 4 pins. These pins are internally connected in pairs. It's easy to make a mistake when wiring. Please post the real picture of your wiring. Or you can refer to read more about button pin in this post

---
Tags: arduino-uno
---