title: Running Arduino mega on 5V power supply

text:
# Question
Title: Running Arduino mega on 5V power supply
I'm wondering if I can run Arduino mega on 5V power supply, even though it's recommended for 6-12V. USB has only 5V right, will it be a problem? I expect to draw quite a lot of power from the 5V pin too so could it be a problem?

# Answer
> 2 votes
Here's what I did for my project:

I used a high current regulated 5V supply. I took a USB cable with the square connector that goes into the Arduino and cut it in half. I attached the red and black wires to +5V and ground on my regulated power supply. I then drove the high current components in my project directly from the 5V supply.

If you use this approach you should probably also add filter capacitors between 5V and ground at both the Arduino and the high current load. Those will help smooth out the voltage variations as the high current load switched on and off.

# Answer
> 11 votes
The 6-12V range applies only to the onboard voltage regulator(if you provide power via Vin or the barrel jack). The Arduino itself runs on 5V and the regulator needs a bit headroom above that to do the regulation.

You can run the Arduino via USB, since it has 5V, just as needed by the Arduino

And you can provide power directly to the 5V pin (with a voltage of 5V or course).

If some of your components draw a lot of power, you should never draw that current through the Arduino. You need to connect the power supply in parallel to your components and the Arduino, so that the high currents can flow past the Arduino, not through it.

# Answer
> 3 votes
If you connect it from the USB port on your computer to the USB plug on the Mega, you'll do fine. What you can't do is connect a 5v source to the barrel jack; that goes to the board's voltage regulator which needs ~ 7v minimum to provide 5v out.

"Quite a bit of power" is a rather vague specification. A USB port can supply 500mA unless the device in question negotiates for more current and the port in question is capable of supplying it. What is probably more concerning is if you're trying to pull a lot of current *through the Mega*, you risky overloading its pin-drivers or its PCB tracks. The Mega's pins are spec'd for 20mA; 40mA Absolute Max, briefly, to not damage it. The total current budget is 200mA max. If you're planning to approach either of those levels, you should consider powering some of your devices separately. That might include powering from the same or another USB port, as long as you don't pass it through the board, and you observe the USB ports' maximum currents as well.

# Answer
> 2 votes
Yes, you can run the Arduino Mega off of a 5V supply. Instead of connecting the voltage to the DC jack, instead feed your 5V into the +5V pin on the Arduino header. (it is one of the red pins in the image below).

---
Tags: arduino-mega, power
---


title: NodeMCU and relay with VIN power

text:
# Question
Title: NodeMCU and relay with VIN power
Have read a lot of different things online, and I just ain't sure yet.
I'm trying to hook up a NodeMCU to control some relays. And want to power the NodeMCU by the VIN pin.
Anyone know if this setup is possible?
Or should I do it in another way?

# Answer
Looks fine to me, I don't see any issues, assuming the PSU has sufficient 'grunt' to power both, and most will have.
> 1 votes

---
Tags: nodemcu, relay, wires
---


title: I need a good battery reccomendation

text:
# Question
Title: I need a good battery reccomendation
I have simple project composed of an Arduino Nano, a HC-05 module, and a small toy DC motor controlled using a L293D driver, I want to be able to power this circuit entirely using a battery, here is what I tried:

-The motor/L293D combo works when the Arduino Nano is powered through it's USB jack, except the L293D is drawing power from the Nano, which I know is very bad practice, but I only did it for testing purposes.

-The HC-05 module also works fine when the Nano is powered through it's USB jack, as expected.

-However, the power received through the USB jack is not enough power for both the HC-05 and the L293D & motor simultaneously, if I want to change the PWM through the HC-05, I have to disconnect the motor, send the instruction, then disconnect the HC-05 and re-connect the motor.

-I have tried 3, pretty much new 9V batteries, none of them were enough to power anything, not the Nano board through the Vin pin, not an Uno board through barrel plug, not the motor, nothing, except a LED diode, I've read somewhere that most brands of these kinds of batteries don't actually provide nearly as much power as they claim, so that might explain it. (In case it's relevant, the brands I tried are VARTA, Uniross and Goldmen.)

-Someone gave me the idea of using an old mouse cable to power the Arduino, by taking the VCC and GND wires from the mouse cable and using those to power the Nano board through it's Vin and GND ports, it works, but not any components connected to it, not even the HC-05 module, which I even tried powering directly from the mouse cable, which lit up it's LED, but did not get it to work.

Honestly this isn't that relevant, I just wanted to make sure the Vin pin worked.

-Also, few side notes:

My multimeter mysteriously stopped working when I actually needed it, which is why I couldn't take any measurements.

The L293D datasheet and other pinouts suggest no less than 12V supply voltage, so maybe a 9V battery wasn't the right answer to begin with.

The power coming from the mouse cable is enough to power the DC motor independently, but not through the L293D, it says online the average output for these cables is around 5V, but without measurements I can't be sure.

The battery holder for the toy train that has DC motor inside accepts 1.5V batteries wired in series, and considering there's not much else there aside from the motor itself, it's safe to say that 3V is the minimum required voltage for the motor.

So, what battery do you think would be most suitable for my project?

And if it's not against the rules, what brand would you recommend?

# Answer
> 2 votes
The L293D has about a 2.6V drop on the output pins. That means for a 3V motor you need to provide about 5.6v for it to run at full speed. 5V will work, but it will run slightly slow and underpowered.

9V batteries are useless. Only any good for very low power applications like smoke alarms. They just can't provide the current you need.

Instead you need to be looking at model aircraft / drone suppliers for a "2S" battery (7.4V Li Poly / Li Ion) and a suitable 5V (or 5.6V if you can get it) UBEC (switching regulator).

# Answer
> 1 votes
You could also use a 4 channel relay for making the motors work and they can be independent of using power from arduino and is really effective, I sometimes use it for high voltage optocoupling and can be used for small ones too all you need to do is build logic and everything would work fine I assume you know how to reverse polarity on a dc motor. Relays are not power hungry and can be powered from arduino but if you could give it an external 5 volts that would be better. Which in case of L293d driver is not the case you would require at least 12 volt to power the driver itself.

---
Tags: arduino-nano, motor, battery, hc-05, l293d
---


# Question
Title: Send values from Arduino Uno to Wemos D1 R1
I have a weather project in which I have to measure the temperature and humidity (DHT22 sensor), the pressure, and other things, and then show them on a local web page (using a Wemos D1 R1) in either my phone or PC (I have both an Arduino Uno and a Wemos D1 R1 for this project)

I wanted to use only the Wemos D1 R1 since it works the same as an Arduino Uno except it has an ESP8266 WiFi built-in while the Arduino Uno doesn't, but as you may know it only has 1 analog pin while I need at least 3 or 4 analog pins, so in my case I should connect the sensors with the Arduino Uno and measure the temperature, humidity, etc. and then send those values to the Wemos D1 R1 which will show the results itself on a web page as I said earlier.

It seems that there is a way to do that using an I2C connection, but I have read many articles talking about connecting an Arduino to another Arduino using an I2C connection, but I don't know how to do that in my case (Arduino Uno and Wemos D1 R1); if there is another way to send values please tell me.

# Answer
As I see it, the most straight-forward way to connect 2 Arduinos is using their built-in UART (aka Serial port, TX/RX pins) communication.

There are many tutorials on this on Google, and a similar explanation can be found in this question: Serial communication arduino mega and D1 Wemos Mini

However, there is a slight difference. Arduino Mega has built in more than 1 hardware serial ports (I can't recall now if it's full 3 ports, or just 2), what leave one port for debug purposes, and the other - for your communication. In your case (Arduino Uno) - you have only one serial port, that if will be used for the inter-Arduinos communication - will not be available for debug/console messages. The solution for this is adding a Software Serial port, also highly available in tutorials over the net, here is one example: softwareserial between arduino uno and esp8266

Enjoy your project!
> 2 votes

# Answer
I agree with @Offer that using UART is the simplest solution to connect the devices. I just want to suggest two alternatives:

1. Use an external analog to digital converter IC. Using the Arduino only for analog conversion is a bit over powered. E.g. the ADS1115 has a resolution of 16 bits and there's already a library, so usage should be easy.
2. The ESP8266's bigger brother - the ESP32 - has several ADC pins.

The biggest advantage (beside the higher resolution) is, that you only need to write code for one device, which makes your project less complex.
> 2 votes

# Answer
Have a look at my blog 'Paynters Palace' and search for posts with the 'I2C' tag - you'll find quite a bit of useful code, I think.

This project shows how to connect two Arduinos using SPI

This project shows how to connect two Arduinos using I2C and how to pass arbitrary data types between the two units
> 0 votes

---
Tags: arduino-uno, esp8266, i2c, arduino-uno-wifi
---


title: Ethernet Shield: Maximum speed

text:
# Question
Title: Ethernet Shield: Maximum speed
Looking at this shield here: https://store.arduino.cc/arduino-ethernet-shield-2

It states that "Connection speed: 10/100Mb". However from looking at various forums it appears that no one can get much more than 300Kb/sec with this device?

Can anyone explain what causes this limitation and how to overcome it? If its SPI that is the bottleneck is there some alternative? I am looking to get speeds of 6 mega bytes per second or more using a TCP connection.

I am extremely new to all this so apologies if I've missed something extremely obvious here. I also had a look at bluetooth/wifi shields but it appears they seem to also have some similar throughput issues. USB looked like it could work but is extremely complex for a newbie.

# Answer
It's not just the SPI what limits overall speed. You also need some proccessing power, and AVR based Arduinos lacks of it. It all depens what do you want to do with data.

If you need some serious processing power, it might be better to use something much more powerfull, like raspberry PI with real operating system. You can even run some web server at the speeds you can't even imagine with Arduino with the ethernet shield
> 2 votes

# Answer
A guy on this forum reports achieving 100 Kbyte/sec with a W5100 ethernet shield, which would be 800 kbit/sec:

https://forum.arduino.cc/index.php?topic=555957.0
> 2 votes

---
Tags: ethernet-shield, speed
---


# Question
Title: Digital pins are no longer outputting enough to click a relay
I've been working on a project for awhile now, and I ran into a problem a week ago I couldn't solve. I'm using an Arduino uno R3.

My project involves the use of 4 relays triggered by the digital pins. Write a HIGH value, relay clicks. Write a LOW value, relay unclicks. Rather simple.

One day, I come back to it to discover it can no longer click the relays. No changes were made to my code that worked previously. The relay light came on, but no click. Could it be that I sent HIGH to 4 at the same time? My theory is that I could've drawn too much power at the same time, weakening it in a way that causes it to not output as much as it did previously.

I tested a relay on a different board and it works perfectly fine.

# Answer
Not knowing the reference of your relay, my answer is generic but should suit your needs.

Relays need 2 things in order to work properly: a sufficient voltage source, and one that can provide enough current.
The Arduino output pins provide 5V on 5V boards or 3.3V on 3.3V boards. BUT, most Arduino GPIO can provide only 20 mA of current. That might not be enough for your relay. The solution here is to use a transistor to drive the relay.
Also, relay coils are inductive loads that generate voltage spikes when current is turned off. That voltage can rise much higher than 5V and damage your Arduino pins and weaken or destroy them. The solution to this problem is to add a flyback diode.

This is what a typical circuit with relay driven by an Arduino looks like:

When the Arduino pin is LOW, the transistor is turned off and no current goes through the relay.
When the Arduino pin turned ON, the transistor turns on fully saturated and the relay coil is energized.
When the Arduino pin is turned LOW, the coil generates a negative voltage and current is allowed to go through the diode, dissipating energy in the relay coil. More information on flyback diodes: https://en.wikipedia.org/wiki/Flyback\_diode
> 3 votes

---
Tags: arduino-uno, relay
---


# Question
Title: How to webClient.write() an image stored on a String?
My application runs on an ESP32-CAM. It takes pictures and stores to SPIFFS. Periodically SPIFFS is checked and if images are found: 1- The image is saved to a FTP server 2- The image is summited to a Web Service that returns some informations about the image 3- Values are saved to mySQL 4- The image is deleted from SPIFFS

To read the image from SPIFFS I use the following fragment of code:

```
String imageName   = file.name();
imageBuffer = "";
while (file.available()){
   imageBuffer += char(file.read());
}

```

The FTP transfer works perfectly with the following command:

```
ftp.WriteData((uint8_t*)imageBuffer.c_str(),imageBuffer.length());

```

The service the image is submited for analizes works OK if I use the command:

```
webClient.write(fb->buf,fb->len);

```

But as it is not usable in the current implementation of my project I am trying to work with:

```
webClient.write((uint8_t*) imageBuffer.c_str(), imageBuffer.length());

```

I get no errors in return but it just does not work and the web service at the destination returns nothing.

What Am I doing wrong?

# Answer
You should not use `String` to store binary data.

Instead allocate yourself an array of `uint8_t` of the right size.

```
uint8_t *imageData;
size_t len = file.size();

imageData = alloca(len);
file.readBytes(imageData, len);

webClient.write(imageData, len);

```

With that said, without knowing what the rest of your program is doing I can only surmise that you're just blasting raw data at the web server and hoping it sticks. That's not how web data transfers work. You have to craft the upload page properly as multi-part mime form data. Read this for more information
> 1 votes

# Answer
OK, I got it to work as follows:

Not passing the binary anymore, passing the file name so the FTPPost function will do its own reading of the file on SPIFFS and will post in 256 bytes chunks. The same strategy works with HTTP post to the WebService.

```
  File picFile = SPIFFS.open(fileName,FILE_READ);
  const size_t bufferSize = 256;
  uint8_t buffer[bufferSize];
  while (picFile.available()) {
    size_t n = picFile.readBytes((char*) buffer, bufferSize);
    if (n != 0) {
      ftp.WriteData(buffer, n);
    } else {
      Serial.println(F("Buffer was empty"));
      break;
    }
  }
  picFile.close();

```
> 1 votes

---
Tags: esp32, web
---


# Question
Title: Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A)
I want to achieve the generation of a custom binary signal over a digital pin at the highest possible frequency on Arduino Uno.

Using Timer's output pins (e.g. OC0A), one can get a pin to toggle at a maximum frequency of 16MHz (which corresponds to a sqaure wave of frequency 8MHz), as described here: Maximum frequency of digital signal in Arduino Uno?

However as far as I understand, Timer's output pins are only useful if one needs to generate a repetitive waveform such as a PWM or square wave, so it cannot serve my purpose which requires the generation of a custom binary signal.

Using the following code, I was expecting digital pin 9 to toggle at a frequency close to 16MHz too, since I use no prescaler and set the Compare Match Register value to 0:

```
void setup()
{
    DDRB = 1 << 1;  // Set D9 as OUTPUT

    cli();
    TCNT0 = 0; TCCR0A = 0; TCCR0B = 0;
    TCCR0A |= (1 << WGM01);  // CTC mode
    TCCR0B |= (1 << CS00);  // no prescaling
    OCR0A = 0;  // Highest timer overflow frequency possible
    TIMSK0 |= (1 << OCIE0A);
    sei();
}

ISR(TIMER0_COMPA_vect)
{
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
}

void loop(){}

```

However in fact it appears to toggle at a frequency of only approximately 410kHz (which corresponds to a square wave of frequency 205kHz), as the below image shows:

I used Timer0 but I get the same frequency with Timer1 and Timer2.

* How can one explain that using this code I get this toggle frequency on the digital pin ?
* How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

# Answer
> 3 votes
> How can one explain that using this code I get this toggle frequency on the digital pin ?

Code takes time to execute. Your ISR, when compiled, looks like:

```
ISR(TIMER0_COMPA_vect)
{
 124:   1f 92           push    r1
 126:   0f 92           push    r0
 128:   0f b6           in  r0, 0x3f    ; 63
 12a:   0f 92           push    r0
 12c:   11 24           eor r1, r1
 12e:   8f 93           push    r24
 130:   9f 93           push    r25
    PORTB ^= 1 << 1;  // Toggle D9; this allows to measure the toggle frequency, however this could be replaced by some code to generate a custom binary signal
 132:   85 b1           in  r24, 0x05   ; 5
 134:   92 e0           ldi r25, 0x02   ; 2
 136:   89 27           eor r24, r25
 138:   85 b9           out 0x05, r24   ; 5
}
 13a:   9f 91           pop r25
 13c:   8f 91           pop r24
 13e:   0f 90           pop r0
 140:   0f be           out 0x3f, r0    ; 63
 142:   0f 90           pop r0
 144:   1f 90           pop r1
 146:   18 95           reti

```

That's 18 assembly instructions, each needing between 1 and 4 clock cycles to execute. Referencing the datasheet you can count the exact cycles needed and sum them up, yielding 31 clock cycles.

Toggling at maximum speed that would be 16MHz / 31 = 516kHz.

And then you have the rest of the code running between each call to the interrupt, so it's slower than that.

> How can I generate a custom binary signal over a digital pin at the highest possible frequency ?

By not using interrupts, and writing a tight loop in assembly language.

---
Tags: interrupt, timers
---


# Question
Title: Converting an int to an unsigned char for display on a Nokia 5110
I've been working on a small project getting some images displayed in a Nokia 5110 screen via an Arduino. I've been getting it working, but one of the issues I have is that I would like to have a list on integers and convert that an unsigned char array that the display requires. Generally I have something like this which works out of the box.

```
unsigned char src [] PROGMEM = {0x00, 0x00}

```

Surprisingly, I found that this also works

```
unsigned char src [] PROGMEM = {255, 255}

```

But when I have a list like this

```
int src [] = {255,255}

```

and try to convert it to an unsigned char array, things don't display correctly

```
unsigned char new_src[2];

for (int i=0; i<2; i++){
    new_src[i] = (unsigned char) src[i];
}

```

When I try to display this, it's clearly broken. I thought simply casting the `int` to an `unsigned char` would be enough (it doesn't work even if I don't cast it).

Here's how I display the array (for 84x48, the above arrays were just an example) :

```
Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);
display.drawBitmap(0, 0,  src, 2, 48, BLACK);
display.display();

```

On more note:

The end game is to have a file with a list of ints. I would then read that list of ints into an array and convert it into an unsigned char array and then display that.

# Answer
> The idea is that I would read a list of ints from a file ( I have several files that I would iterate through) and convert that list to the unsigned char array on each loop iteration.

The file could be a stream of bytes just as well as a stream of ints (or uints). If it were, no conversion would need to be done - just read a byte & store it, read a byte & store it, .... If instead, it is a character representation of values, "37, 150, 8, ...", again, read the characters of one value, convert them to `int8_t` or `uint8_t` and store them in your byte array. Look up the atoi() or sscanf() functions to do the conversion.
> 0 votes

---
Tags: arduino-uno, data-type
---


title: Spectrabloom LED light box

text:
# Question
Title: Spectrabloom LED light box
I'm looking to make a DIY version of Dan Conrad's Spectrabloom. I've got an Arduinio Uno, a piece of code that uses PWM to randomly fade three 1w LEDs (one red, one blue and one green) and a PicoBuck LED driver.

Question is - do I have to have two power supplies? One to power the PicoBuck and one to power the Arduino or can I have them all running off one supply? If the latter - can anyone give me pointers on the way to hook everything up?

# Answer
> 1 votes
> Question is - do I have to have two power supplies?

No, you can use one power supply for both. But you need to make sure, that the LED current is not flowing through the Arduino, since that can kill the Arduino. To do that, you need to connect the power supply to the LED driver and the Arduino in parallel. For example, lets assume you have bought a 5V wallwart/power supply, which is can provide enough current for your whole circuit (and some headroom for further development). Then you can connect the positive lead to the 5V pin of the Arduino and the Vin+ (positive supply voltage) pin of the LED driver. Also connect the negative lead of the power supply to ground on Arduino and Vin- (negative supply voltage) of the LED driver. That way the current for the LEDs comes directly from the power supply and doesn't need to flow through the Arduino, but past it.

# Answer
> 0 votes
Three 1 Watt LED could potentially draw 600 mA total, exceeding the maximum draw for the Arduino. Each LED could draw 200 mA, exceeding (by 10x) the draw of a pin driver. So, yes, you need to supply the LEDs separately from the Arduino. Also, that driver is a constant-current driver, at 330 mA per channel. Your LEDs would prefer a constant voltage, chopped by PWM.

---
Tags: arduino-uno, led
---


# Question
Title: Arduino UNO with integrated ESP2866 wifi not working correctly
I bought this "knockoff" Arduino UNO with an integrated ESP 2866 wifi module. But I can't make it work. I've followed this tutorial because it's the same product as I have, but I can't make it work anyway - even blinking with LED doesn't work. Does anyone have experience with this exact (or similar) board with integrated ESP2866? I would be really glad for any help. link to the product. If you need to know anything else, I'll try my best to answer it.

My problem:

The board normally loads into IDE and i can send code to it. But after I do that, I get this:

```
Executable segment sizes:
IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)
DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 257316 bytes (24%) of program storage space. Maximum is 1044464 bytes.
Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM6
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 2c:f4:32:44:1f:0b
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Erasing flash (this may take a while)...
Chip erase completed successfully in 8.7s
Compressed 261472 bytes to 193136...
Wrote 261472 bytes (193136 compressed) at 0x00000000 in 17.0 seconds (effective 122.9 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

```

But the LED doesn't blink.

# Answer
I don't know why the answer below is accepted, as it clearly doesn't solve the question but also gives **false** information. In this answer @chrisl assumed that blinking green LED is what was programmed with sketch, but if you will open sketch used in this video and read comments in the source code, then this misconception will become obvious: actually red **RX** LED is what was programmed.

This board has two independent chips: ATmega328P and ESP8266, and ESP8266 built-in LED is **combined** with RX LED. So when you are blinking with ESP8266 LED, you are blinking with RX led. And this is what tricked most people answering here, as they were looking on green blinking LED, which is controlled by ATmega328P. Having said that, I also have to admit that I don't have solution for original question and I don't know why it doesn't work for @krystof18, but in video it clearly works.

**EDIT:**

**TL/DR:**

Don't use `LED_BUILTIN`, but attach an external LED and a resistor to ESP GPIO pins. Modify the sketch to use correct pin and upload while switches 5,6 and 7 are ON. Then disconnect the board and turn switch 7 OFF. Then you have to power board again and it should work.

**Long explanation:**

I have a board visually similar to what is on the video tutorial you have posted, but for me the blink example doesn't work, probably because LED is wired to some other PIN, rather than `#defined` for `LED_BUILTIN`. But I managed to get it working using this tutorial! Watch from 5:58. (Please note this video is in language I don't understand and have no idea what language it is, but the video itself is so obvious, that you basically don't need to understand what does that guy say).

Basically in this tutorial it is just blink example, but using external LED, instead of built-in. If you look at your board, then you can find 4x3 bar of pins located near 0, 1 and 2 Arduino digital pins. This bar is labelled "ESP pins" and it is what is says: ESP8266 pins. Pin labels are on the back of the board.

So this guy in video just connects GPIO16 and GND pins to a LED with resistor, and then modifies original blink example to use 16 instead of `LED_BUILTIN`. Then he uploads it to his board with switches 5,6 and 7 ON. **Then he plugs-off the board and turns switch 7 OFF**, so only switches 5 and 6 are on. Then he plugs board back in and it works!

I tried it and it works for me, hooray!

Also, if anyone can tell me what language this guy speaks in the video tutorial I posted \- I am just curious! :)
> 1 votes

# Answer
You are obviously currently programming the ESP8266, not the Atmega328p. The board seems to have DIP switches on it. With those you can control, which chip is connected to which. The product description has the following table

```
Connection  DIP
1   2   3   4   5   6   7
ATmega328<->ESP8266     ON  ON  OFF     OFF     OFF     OFF     OFF
USB <->ATmega328    OFF     OFF     ON  ON  OFF     OFF     OFF
USB<->ESP8266 (Update firmware or sketch)   OFF     OFF     OFF     OFF     ON  ON  ON
USB<->ESP8266 (communication)   OFF     OFF     OFF     OFF     ON  ON  OFF
All independent     OFF     OFF     OFF     OFF

```

If you want to program the Atmega328p on it, you need set the DIP switches to the combination "USB \<-\> Atmega328". Currently you most likely have the combination "USB\<-\>ESP8266 (Update firmware or sketch)", which means, that the ESP is connected to the USB chip (and thus to the PC) for programming. For blinking the Arduinos buildin LED you need to program the Atmega328p.

---

**About the blink sketch:** In the tutorial video he programs the ESP. But in the blink example he changes the delay time to 5000, which would mean on and off times of 5s. The LED, that he is pointing to, is blinking much faster, though he doesn't address this. I think he actually has the standard blink sketch on the Atmega and only pretends (or just didn't notice) that this happened due tp his programming. As you don't see a blink with the ESP, but with the Atmega, I would guess, that the LED marked with L is connected only to the Atmega (like on a normal Uno) and the ESP doesn't have any LED to blink connected. So everything is actually working as expected, the tutorial was just bad at that point.
> 3 votes

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


# Question
Title: tinkercad arduino simulator integers being outputted as larger numbers than they are?
I am using an Arduino simulator on www.tinkercad.com (a seemingly nice free product from Autodesk). Working on conversion of an integer to a 16 bit binary string for output to a DAC, but unfortunately even at the first step I am getting unexpected behavior.

```
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  Serial.print("Sanity Check\n");
  uint16_t num = 12000;
  Serial.print("\nNumber: " + String(num) + "\n");
  delay(3000);
}

```

Surprisingly the above code gave the following output:

```
Sanity Check

Number: 12222

```

Is there something I am doing wrong, or something wrong with the simulator? The error seems to crop up with any value over 10000. 10001, 10002, 10003 all print as 10000. 11000, 11001, 11002, 11003 all print as 11111. etc, etc. What could be going on?

# Answer
> 5 votes
Bug. No other explanation. Real hardware (Arduino Uno) prints 12000.

Even the debugger tells me that the value of that variable is 12000.

Outputs:

```
Number: 12222
12000
12222 something

```

Most interestingly if you `Serial.println()` the number, it is outputted correctly. The bug must be in the constructor of the `String` object, as demonstrated by the "test" `String`. This bug also occurs on other data types, e.g. `int`.

If you only use direct `Serial.print[ln]` calls you should be able to workaround that bug.

# Answer
> 1 votes
Tinkercad is (was) a very good simulator but it has stopped updates. Here is the output from the free Arduino simulator from here

This project is used for the below screenshot

Here is an article pointing some more features of the simulator

---
Tags: simulator
---


# Question
Title: OTA update - sodaq board (arduino M0 compatible)
I am trying to perform a firmware update from an SD card, on a Sodaq Sara AFF board. If i use the SDU.h library in my sketch, it fails the board check. See this link please.

I have edited the SDU.cpp myself to force the selection of `ARDUINO_SAM_ZERO`. It is now :

```
__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x6000] = {
  #include "boot/mzero.h"
};

```

I have increased the size to 6000 otherwise it was complaining `too many initializers`.

I also have changed the SD\_SS\_PIN to match my pin on the `SDUboot.ino`, under `extras`. Afterwards, i recompiled it with `build.sh` in the same folder.

But I am unable to perform the firmware update. After power cycling the board (original code: the blink example, target update: blink with a faster rate) - the original firmware remains.

I exported the firmware using arduino IDE -\> export compiled bynary, and tested both versions with and without bootloader.

Any help would be appreciated.

# Answer
> 1 votes
**SOLVED!**

I have compiled my own SDUBoot.ino with fixed `SDU_START 0x2000` and for SODAQ Sara (`boot/sodaq_sara.h`). My sketch with `#include "SDU.h"` compiles successfully. The board package is also installed in Arduino (http://downloads.sodaq.net/package\_sodaq\_samd\_index.json). Here my code with changes (base is SodaqCore-samd-1.8.6-sodaq from Github):

File `libraries/SDU/extras/SDUBoot/SDUBoot.ino`:

```
#include <SD.h>
#include <FlashStorage.h>

#define SDU_START    0x2000
#define SDU_SIZE     0x4000

#define SKETCH_START (uint32_t*)(SDU_START + SDU_SIZE)

#ifndef SDCARD_SS_PIN
#define SDCARD_SS_PIN 10
#endif

#define UPDATE_FILE "UPDATE.BIN"

FlashClass flash;

// Initialize C library
extern "C" void __libc_init_array(void);

int main() {
  init();

  __libc_init_array();

  delay(1);

  if (SD.begin(SDCARD_SS_PIN) && SD.exists(UPDATE_FILE)) {
    File updateFile = SD.open(UPDATE_FILE);
    uint32_t updateSize = updateFile.size();
    bool updateFlashed = false;

    if (updateSize > SDU_SIZE) {
      // skip the SDU section
      updateFile.seek(SDU_SIZE);
      updateSize -= SDU_SIZE;

      uint32_t flashAddress = (uint32_t)SKETCH_START;

      // erase the pages
      flash.erase((void*)flashAddress, updateSize);

      uint8_t buffer[512];

      // write the pages
      for (uint32_t i = 0; i < updateSize; i += sizeof(buffer)) {
        updateFile.read(buffer, sizeof(buffer));

        flash.write((void*)flashAddress, buffer, sizeof(buffer));

        flashAddress += sizeof(buffer);
      }

      updateFlashed = true;
    }

    updateFile.close();

    if (updateFlashed) {
      SD.remove(UPDATE_FILE);
    }
  }

  // jump to the sketch
  __set_MSP(*SKETCH_START);

  //Reset vector table address
  SCB->VTOR = ((uint32_t)(SKETCH_START) & SCB_VTOR_TBLOFF_Msk);

  // address of Reset_Handler is written by the linker at the beginning of the .text section (see linker script)
  uint32_t resetHandlerAddress = (uint32_t) * (SKETCH_START + 1);
  // jump to reset handler
  asm("bx %0"::"r"(resetHandlerAddress));
}

```

File `libraries/SDU/extras/SDUBoot/build.sh`:

```
#!/bin/sh -x

ARDUINO=arduino
SKETCH_NAME="SDUBoot.ino"
SKETCH="$PWD/$SKETCH_NAME"
BUILD_PATH="$PWD/build"
OUTPUT_PATH="../../src/boot"

if [[ "$OSTYPE" == "darwin"* ]]; then
    ARDUINO="/Applications/Arduino.app/Contents/MacOS/Arduino"
fi

buildSDUBootSketch() {
    BOARD=$1
    DESTINATION=$2

    $ARDUINO --verify --board $BOARD --preserve-temp-files --pref build.path="$BUILD_PATH" $SKETCH
    cat "$BUILD_PATH/$SKETCH_NAME.bin" | xxd -i > $DESTINATION
    rm -rf "$BUILD_PATH"
}

mkdir -p "$OUTPUT_PATH"

buildSDUBootSketch "SODAQ:samd:sodaq_sara" "$OUTPUT_PATH/sodaq_sara.h"

```

File `libraries/SDU/src/SDU.cpp`:

```
#include <Arduino.h>

#include "SDU.h"

__attribute__ ((section(".sketch_boot")))
unsigned char sduBoot[0x4000] = {
  #include "boot/sodaq_sara.h"
};

```

Sketch file `sdu_test.ino`:

```
#include <Arduino.h>
#include "SDU.h"

#if defined(ARDUINO_SODAQ_SARA)
#define DEBUG_STREAM SerialUSB
#else
#error "Please select the SODAQ SARA as your board"
#endif

#define DEBUG_STREAM_BAUD 115200

String message;

void setup() {
  // Start communication.
  DEBUG_STREAM.begin(DEBUG_STREAM_BAUD);

  while (!DEBUG_STREAM) {
    // Wait for Serial Monitor to be opened.
  }

  message += "Sketch compile date and time: ";
  message += __DATE__;
  message += " ";
  message += __TIME__;

  // print out the sketch compile date and time on the serial port
  DEBUG_STREAM.println(message);
}

void loop() {
  // add you own code here
}

```

File `arduino/50/.arduino15/packages/SODAQ/hardware/samd/1.8.6/variants/sodaq_sara/linker_scripts/gcc/flash_with_bootloader.ld` add these lines:

```
KEEP(*(.sketch_boot))

. = ALIGN(0x2000);

```

here:

```
...
SECTIONS
{
    PROVIDE(__sodaq_firmware_state = ORIGIN(FLASH) - 0x100);

    .text :
    {
        __text_start__ = .;

        KEEP(*(.sketch_boot))

        . = ALIGN(0x2000);
        KEEP(*(.isr_vector))
        ...

```

On SD card (formatted as FAT32) I have stored the renamed file `UPDATE.bin` **without** bootloader of the compiled sketch file. Pin **D10** is connected and used as chip select CS.

Build boot hex files:

```
$ cd libraries/SDU/extras/SDUBoot
$ ./build.sh

```

Version **1.8.6-sodaq** has these missing lines on arduino\_zero variant but not on sodaq\_sara variant.

---
Tags: ota
---


title: Electronics Laboratory

text:
# Question
Title: Electronics Laboratory
I would like to know if someone could explain to me how to create an arduino electronics laboratory with soldering iron etc. with a low budget \<3

# Answer
There won't be a really complete list, since there are many many tools, that one could use for an electronics/Arduino laboratory. Also low budget is relative, so you might wanna choose out of the below list based on your real budget and the actual price of the parts at your place. Also consider, that many tools can be bought very cheap, but these tools are often bad, which means, that you most likely will buy a better replacement product later (buying cheap means buying twice). Still a low budget can absolutely justify buying cheap at first (some bad tools is better than no tool).

Note: I will use Euro as currency here (as I'm from Germany), which can about be used interchangeably for US Dollar. Your mileage may vary.

* **Breadboards:** For working with Arduinos you wanna first build your circuits on a breadboard for testing. You should at least get one. I've seen 3-Packs of breadboards on platforms like amazon for about 12€.
* **Jumper-Wires (male-male/male-female):** These wires with attached dupont jacks will make it easier to prototype on breadboards.
* **Colored Wire spools:** I have a few spools with 4 different colors of 0.2mm² wire. You can use these for your PCBs and for breadboards. The different colors help to color code your wires for better overview. They cost a few € each.
* **Multimeter:** A simple multimeter, that can measure voltage, current and resistance and in best case has a continuity check mode. This is a very important base tool for all electronics. I think most multimeters from 15€ up would be ok.
* **Pliers and Wire cutter:** These are good for pressing and for cutting things. If you train a bit, you can even use the wire cutter for removing the isolation at the end of your wires. Technically a proper wire stripper is better, but I think using a wire cutter for the low budget start is totally ok. A wire cutter can go as cheap as 10-15€ for a decent one.
* **Soldering iron:** Don't buy one of these soldering irons, that go directly into the mains. Buy a little soldering station with basic temperature control and integrated holder and a sponge for cleaning the tip. It should also have the possibility to change the tip (when you need a smaller/bigger tip or when your tip is no good anymore). A few years ago I got one of these for about 15€. Going a bit higher will benefit you with a better solder station.
* **Solder wire:** You need to buy the actual solder. You should buy a spool of solder wire with integrated flux. Though most little spools have that. Depending on the exact solder wire it can be useful to also buy some flux (I'm currently using a flux pen), if the solder isn't flowing good enough.
* **Third hand with magnifying glass:** When soldering it is sometimes helpful, when you can put a part into a clamp (like the third hand) and then use your hands for soldering iron and solder wire. The magnifying glass (which is also hold by the third hand) can help with small parts and inspection of your soldering work. It often costs only a few €, but getting up a bit can give you better durability and stability.
* **Perfboard:** To build PCBs yourself you can most easily use perfboards. That are simple boards with solder pads for through-hole components. You can solder the components to the and then connect the pads via solder/wires. These are available with each pad not connected to anything else, or already connected like on a breadboard (I use these ones, like in this answer), or in stripes,... Building better PCBs would involve a more complicated process with chemicals or sending the PCB files to a manufacturer.
* **Heat shrink tubing/sleeves for wires and cables:** To isolate wires, you might want to get correspondingly sizes heat shrink tube. They slide onto the to-isolate place and then get heated with a heat gun or a lighter. They shrink down and so enclose the part for isolation.
* **Oscilloscope:** This is normally one of the most expensive tools. A decent oscilloscope can cost 250€ and up (into infinity). But you can sometimes get the big old oscilloscopes second hand (for example from ebay) as others upgrade to a digital oscilloscope. Or you can buy an USB oscilloscope, which works with your PC. I got one of these for about 50€. Or there are simple kits for standalone oscilloscopes (with limited capabilities) for 35€ and up. An oscilloscope is important for analyzing analog signals.
* **Logic Analyser:** This is used to analyze digital signals. Standalone logic analyzers are expensive, but you can get a USB version for about 10€. The opensource software sigrok can then be used to interface the logic analyser. This tools is really really useful in relation to its low price. For example: You can use it as debug tools by setting pins inside your code at special places. That gives a better view on the temporal code flow than the typical Serial output.
* **Hot glue gun:** Seems pretty basic, but I really often use my hot glue gun. You can fix things, protect them, build a supporting structure,... They only cost a few € plus a few for the glue sticks.
* **Scalpel and box cutter:** Cutting things is also important and these two are good at it. They only cost a few € and have interchangeable blades. Especially a fresh scalpel blade can make the cutting of light materials really smooth.

That's about, what I can think of currently.
> 2 votes

# Answer
I can't help with the whole laboratory, but I can suggest the free ArduinOscope mini-app to turn an Arduino UNO into an oscilloscope that uses your computer as the display. Here's the link to the Help topic that describes controls, features, and performance: https://www.daqarta.com/dw\_rroo.htm. This is a large macro script that comes with my Daqarta software https://www.daqarta.com. Please note that you don't have to purchase anything to use the DaquinOscope; a license is needed (after the trial period) only to use your sound card inputs, not the Arduino. (You also don't need a license to use the sound card *outputs*, so you can use the free Daqarta Generator to create test signals.)

Enjoy!
> 0 votes

---
Tags: arduino-uno, electronics
---


# Question
Title: Communication between two Arduinos using ENC28J60?
How can I connect and send data between two Arduinos using ENC28J60 ethernet adapters on both of them? Is there any guide or example code for me to take a look from or any library I can use to achieve this communication?

I have one Arduino connected to an ultrasound sensor and the other to a relay module so that one Arduino measures the distance between certain objects and send the distance to the other Arduino, which then processes it to check if it is within a certain limit. If not then it turns on the relay. I could have used two ESP32 with one in AP mode but the range is not enough and serial communication is not possible, as the cables are fragile and the distance is too large. Also I couldn't find another way of sending the data.

I'm open to any suggestion, even changing the method of communication. Or using of any other ethernet module.

# Answer
> 0 votes
You can use my EthernetENC library. See the examples of Arduino Ethernet library on how to use Ethernet libraries for Arduino.

EthernetClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. EthernetServer listens on a port. If server is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a EthernetClient object wrapping the socket. Everything you write or print to a EthernetClient is send to that one remote socket.

If the client board creates a EthernetClient and connects it to IP address and port of the EthernetServer on your 'server' board, then you get there a EthernetClient from server.available() and this two EthernetClient objects are connected. What you write/print on one side you read only from the EthernetClient object on the other side.

client socket

```
   if (client.connect(serverIP, PORT)) {
     client.print("request\n");
     String response = client.readStringUntil('\n');
     Serial.println(response);
     client.stop();
   }

```

server side

```
   EthernetClient client = server.available();
   if (client && client.connected()) {
     String request = client.readStringUntil('\n');
     Serial.println(request);
     client.print("response\n");
     client.stop();
   }

```

---
Tags: arduino-uno, communication, ethernet, signal-processing, ethernet-shield
---


# Question
Title: Is it possible to use the same power source for the arduino and a high current
I've need to control some leds which draw 300mA with an arduino (actually an atmega) and after some searching I think the following is the circuit I need, but I'm not really sure if the power source for the LEDs can be the same as for the arduino.

R1 = 1k

# Answer
> 2 votes
If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.

---
Tags: power, current, transistor, atmega
---


title: ESP32S v1.1 NodeMcu vs ESP32 DevKitV1

text:
# Question
Title: ESP32S v1.1 NodeMcu vs ESP32 DevKitV1
I have two different ESP32 development boards labelled "ESP32S v1.1 NODEMCU" (A) and "ESP32 DEVKITV1" (B). From what I can tell they have the same major components, but their pins and general layout are quite different. I assume they are both knock-offs.

When uploading from the Arduino IDE, both read the same revision number and features:

```
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz

```

From what I can tell NodeMcu has something to do with the firmware for the ESP8266 (wiki)? Also, it seems my ESP32S NodeMcu board doesn't have the standard pin layout for ESP32 boards.

What exactly is this NodeMcu board and what are the differences between the two?

# Answer
> 2 votes
The DevKit is a development board by ESP32 manufacturer Espressif to demonstrate ESP32 usage and to support prototyping.

The NodeMcu is a board by NodeMcu intended for the NodeMcu Lua language firmware.

There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.

You can use both development boards with the ESP32 "Arduino boards support package".

---
Tags: esp8266, nodemcu, esp32, espressif
---


# Question
Title: What is the difference between serial begin() and wire.setClock() for I2C communication?
I am a new Arduino IDE user and have a simple question below

For I2C transmission speed setting, there are serial begin() and wire.setClock(). Some sample codes just use Serial.begin() without Wire.seClock(), some use both as shown below. What is the real differences between them? When to use just serial and when to use both of them? Thanks.

```
void setup() {
  Serial.begin(9600);          // start serial communication at 9600bps

  Wire.begin();                // join i2c bus (address optional for master)

  Wire.setClock(400000); //Increase  I2C clock rate to 400 kHz
}

```

# Answer
> 3 votes
`Serial` has nothing to do with `Wire`/I2C communication. The examples only have this, because mostly they use `Serial` out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).

If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to `Serial` out.

# Answer
> 1 votes
Serial.begin starts the communication on USB or RX/TX pins. It has nothing to do with Wire library and I2C communication.

I2C clock speed determines the speed of communication on the I2C bus. Wire.begin() among other settings, sets the I2C clock speed to some default value.

Wire.setClock() allows to set a different clock speed. This should be supported by all devices on the I2C bus or clock speed can be changed before communicating with a specific device on the bus.

Wire.setClock should be called after Wire.begin because Wire.begin sets the clock speed to some default.

---
Tags: i2c
---


# Question
Title: LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board
As I am learning the Arduino coding, I want to see if my program can turn on the LED light. I have tried all the things, but the code does not start the LED light I have installed on the board.

The code compiles successfully and upload on the board, but nothings happens after that. See the output logs as below:

**See all the configuration of board as below:**

**The board I have:** UNO+WiFi R3 ATmega328P+ESP8266 CH340G Board compatible with Arduino

https://robocraze.com/uno-wifi-r3-atmega328p-esp8266-ch340g-board-compatible-with-arduino

**Board switch settings:**

5,6,7 =\> ON (to upload the code from Arduino IDE)

**Yellow LED installed:**

13 =\> Positive, GND =\> Negative

**Board setup:**

**Arduino IDE Setup:**

**Program:**

```
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delay(2000);
  digitalWrite(13, LOW);
  delay(2000);
}

```

**Output logs after uploading the code:**

```
esptool.py v2.8
Serial port COM8
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: ec:fa:bc:3e:2e:6f
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0340
Compressed 261472 bytes to 193134...
Wrote 261472 bytes (193134 compressed) at 0x00000000 in 17.1 seconds (effective 122.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

```

As you can see, the last message is **Hard resetting via RTS pin....**

Would anyone please tell me what is happening here? Why the program does not start the LED light even after everything looks fine?

Any help would be greatly appreciated.

Thanks.

# Answer
The Uno+WiFi board is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.

The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).

To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.
> 0 votes

---
Tags: arduino-uno, arduino-ide, interrupt, atmega328, arduino-pro-mini
---


title: Init a calss inside a class

text:
# Question
Title: Init a calss inside a class
I'm building a monitoring IP class, `IPmonitoring`, that using an SPIFFS class that I wrote, `flashLOG`. Inside `IPmonitoring` I have 2 instances of `flashLOG` (code below).

My sketch have several instances of `IPmonitoring` for several servicesI wish to monitor. I Wish that `connectionLOG` and `disconnectionLOG` have unique and automated names.

For example if I'm monitoring a service called `MQTT` its connect and disconnect log will be `MQTT_discolog.txt` and `MQTT_conlog.txt`. In my code below, `filename1` and  `filename2` are consts.

```
class IPmonitoring
{
private:
        char *_IP;
        char *_nick;

        flashLOG connectionLOG;
        flashLOG disconnectionLOG;

public:
        IPmonitoring(char *IP, char *nick, char *filename1 = "/conlog.txt", char *filename2 = "/disconlog.txt")
            : connectionLOG(filename1), disconnectionLOG(filename2)
        {
                _IP = IP;
                _nick = nick;
        }

```

**EDIT1 - example how to use class**

my goal is that `filename1` for example will be `MQTTbroker_connlog.txt` meaning a combination of `_nick` and a suffix,

```
IPmonitoring MQTT_service("192.168.3.200","MQTTbroker");

void setup()
{
MQTT_service.start();
}

void loop()
{
MQTT_service.loop();
}

```

# Answer
Judging from your example usage, you want the filenames to be built by the `IPmonitoring` constructor. However, since that class cannot know in advance how much space is needed for the file names, you are left with two choices:

1. Let those file names be data members: arrays of `char` of some fixed size. This will impose a limit on the maximum file name length.
2. Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:

```
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};

```

Note the destructor, which is needed to avoid memory leaks, unless all the instances of the class are statically allocated (which would be good to avoid memory fragmentation). You may want to implement a copy constructor and a copy assignment operator, as per the rule of three.
> 1 votes

# Answer
You have three options for the file names and generally.

1. constant string a.k.a. string literal
2. string buffer global or on stack with scope valid while the string is used
3. dynamically allocated string on heap

with 2) and 3) you can then build a string with C str or sprintf functions

option 3) is alright on MCU if you create these file names only at startup, not if you create them repeatedly as the sketch is running

If you choose option 3) you can build the strings in the constructor of IPmonitoring class, but you can't build the string in the member initialization part of the constructor. You have to add setters to `flashLOG` class and after building the strings for file names set them to the `flashLOG` instance with the setters.
> 1 votes

---
Tags: library
---


# Question
Title: FTDI Breakout with additional ISP connector
### TL;DR - Can the six yellow ISP pins be used as a normal ISP?

---

The usual USB-TTL FTDI breakout board looks like this:

Recently, I came across a variant of the board shown below. However, what are the additional yellow header pins on this board for? They are labelled ISP.

Here is a view of the rear:

So can they really be used as a standard ISP/ICSP?

However, according to the diagram below, which labels the 6 pins in question, I am not sure that there is a valid correlation of signal lines.

That is to say, would CTS to MISO, RI to RST, DSR to SCK and DCD to MOSI work? Or is that why a special version of avrdude is required, as alluded to in FT232RL: USB to Serial 232 TTL Adapter –?and ISP? - post #6:

> As a new feature there is a 6-pin ISP header available. With it, avrdude and avrftdi you can program Atmels and Arduino bootloaders. A special version of avrdude with compiled FTDI driver is neccessary.

However the provided link to that version of avrdude, with the compiled FTDI driver, is dead.

It is also said, in post #7, that these pins are actually equivalent to an X3 connector, as found on the older Arduino Dicimila/NG/Duemilanove boards.

and those can (evidently) be used like so, as a bit banged SPI,

It should be noted that the RI, CTS, DCD and DSR (labelled RSD) pins are available, along the sides of the original FTDI breakout board. So, does the breakout board with the ISP header just provide access to these same signals using a different header?

I am a little confused - have I just over thought this, and this breakout board is simply an ISP/ICSP header *and* an FTDI connector rolled into one board (when used with the appropriate version of avrdude)? Or is it not a usual ISP header? I can not find any *specific* documentation relating to this type of breakout board, as stated in post #4.

Can anyone say, definitively, what these six pins are for? If they are not a normal ISP header, could you provide a detailed way of using it? A schematic would be helpful.

# Answer
There's a thread about that on the Arduino Forum \- someone had a similar question.

---

I found a schematic (below) which is *not* for that board, however the header pins are labelled the same as you found, so it is plausibly similar.

It appears that header is used for "Synchronous Bit Bang mode" as documented here: Bit Bang Modes For The FT232R and FT245R (Application Note AN\_232R-01, Document Reference No.: FT\_000339)

---

You can in fact configure that header to be an SPI programmer, as described for example, in FT232R Bitbang Programmer.

---

I made up a test as I had a similar board in my parts drawer:

It had provision for a 6-pin header similar to yours. Turning the board over we can see that they were labelled exactly the same as yours:

I soldered on a header (in yellow, to be consistent) giving me this:

I added a white dot to indicate pin 1 (visible on the edge) so I plug the cable in the right way around.

---

When I attempted to use the board I got this message from avrdude:

> avrdude: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again

So, it had to be compiled from scratch! I am using Ubuntu 14.04 if you are trying to follow along. :)

---

## Download avrdude

Go to the site http://www.nongnu.org/avrdude/

I downloaded version 6.3 source: http://download.savannah.gnu.org/releases/avrdude/avrdude-6.3.tar.gz

## Install libusb and libftdi

Before compiling I had to grab libusb and libftdi:

```
sudo apt-get install libusb-1.0-0-dev
sudo apt-get install libftdi-dev

```

## Compile avrdude

Now we make avrdude after extracting the archive and navigating to its folder:

```
./configure --enable-libusb --enable-libftdi
make

```

## Find correct configuration

Inside the `avrdude.conf` file which comes with avrdude I found (after some pondering) this seems to be the correct entry:

```
# see http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
# Note: pins are numbered from 1!
programmer
  id    = "arduino-ft232r";
  desc  = "Arduino: FT232R connected to ISP";
  type  = "ftdi_syncbb";
  connection_type = usb;
  miso  = 3;  # CTS X3(1)
  sck   = 5;  # DSR X3(2)
  mosi  = 6;  # DCD X3(3)
  reset = 7;  # RI  X3(4)
;

```

The mapping of pins to numbers works like this... From the PDF about bit bang mode mentioned above we have this table, with annotations in blue by me:

The numbers refer to the bit number (i.e. in the range 0 to 7) in the "bit banged" data byte. We can see from the earlier schematic that, for example, MISO on the ICSP header is wired to CTS on the FT232RL. Thus MISO is data bit 3, which we tell avrdude in the above configuration. Similarly SCK is data bit 5, and so on.

I attempted to test like this:

```
./avrdude -C avrdude.conf -carduino-ft232r -pm328p  -v

```

## Fix permissions

I got a permissions error which was fixed by creating a file in the folder `/etc/udev/rules.d/` called `71-FTDI.rules`. Inside this is:

```
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE:="0666"

```

The numbers may vary for your board. You need to find the vendor and product ID. In Ubuntu you can do `lsusb` and see (amongst other things):

```
Bus 003 Device 061: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
                       ^^^^ ^^^^

```

Note the two hex numbers, which get copied into the rules file.

After doing that, tell the system to reload the rules:

```
sudo udevadm control --reload-rules

```

Then unplug and replug the FTDI board to get it to notice the new permissions.

## Test board detection

Finally, the avrdude line above works and reads the chip:

```
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD

avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:DE, L:FF)

avrdude done.  Thank you.

```

I had mine plugged into an ATmega328P.

---

## Example connected to a Diavolino

Once we have got this far you just connect the FTDI board to your target board with a straight-through cable.

---

## Summary

The FTDI board you have (and the one I have) can be used as a ICSP programmer for the AVR chips, as described above. Thus a simple board can be both a USB to serial converter, and also an ICSP programmer.

I see similar boards selling on eBay for around $5 so that is probably quite a cheap programming option.
> 15 votes

# Answer
## Arduino IDE:

Additional programmers.txt entries to use "FT232R as ISP"

```
ftdi232rasisp.name=FT232R as ISP
ftdi232rasisp.communication=usb
ftdi232rasisp.protocol=arduino-ft232r
ftdi232rasisp.program.tool=avrdude
ftdi232rasisp.program.extra_params=

```

avrdude.exe with FTDI bitbang support https://github.com/mariusgreuel/avrdude
> 1 votes

---
Tags: ftdi, isp, icsp
---


# Question
Title: Is there a way to go to the start of the void loop() function kind of like a "continue" keyword in c in loops?
I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the `void loop()` function with an `exit(0)` to terminate the program analogous to `break` keyword in C language. Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the `void loop()` function.

# Answer
> 1 votes
In the loop() function, `return` will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling `loop()` again.

Another way to accomplish the same thing is to write everything in your `setup()` function, including whatever kind of loop construct you want, and use `break;` and `continue;` statements as you're used to:

```
void setup(){
   // pinMode() & digitalWrite() calls
   // Initialize the Serial port if you need to
   // Any other one-time setup
   //
   // Everything happens here:
   for( .... ){
      // loop contents here
      if( whatever ){
         continue;
      }
      else if( something_else ){
         break;
      }
   }
}

// This just stalls forever when setup() ends:
void loop(){
   ;
}

```

---
Tags: programming
---


# Question
Title: Using esp-wroom-32 without a development board
There are lots of examples on the internet on how to build Arduino from scratch such as IN THIS LINK. I will like to do the same but with the esp32.

I have this development board:

And I am able to program it with the Arduino framework/IDE thanks to THIS VIDEO.

---

## Now the question

**How can I flash my code and run it on a standalone ESP-WROOM-32 chip like this one:**

I do not want to use voltage regulator etc as I am planning to run it from a 3.3V battery.

Before asking this question this was my research:

1. In this video (https://www.youtube.com/watch?v=n43rHugPbTg) Hugatry does exactly what I am looking for but he does not explain what pins he is using. Moreover what happens if I connect my 5v serial to the chip? will it burn?
2. I went directly to espressif website and looked for the schematics (https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32d\_esp32-wroom-32u\_datasheet\_en.pdf). It is hard to understand I just want to do something simple.
3. This blog (http://blogs.oregonstate.edu/copaps/resources/programming-esp32-on-custom-pcb/) explains how but the pins are different than my esp-wroom-32 chip.

Looking more on the internet/youtube everyone explains how to solder it. But I haven't found a diagram that will enable me to flash it and run my code. Also will I have to burn a bootloader like with arduino?

What I am about to try is to buy a 5V to 3.3V serial converter connecting TX with RX and RX with TX. Providing 3.3V power to the 3.3V pin and connect the last cable to ground. If I try that will it work?

# Answer
This is what I was looking for. The development board is not the minimum as @Majenko and @StarCat stated on their comments. This is exactly what I need as I plan to run my project from a battery. Moreover, the development board consumes a lot more energy when in sleep mode. I will even remove the LED that shows on this diagram:

So basically use a programming board like @KenVanHoelandt stated to program the board and then wire the esp32 like in the diagram above.

I got that diagram from this link:

https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/
> 7 votes

# Answer
There are programming boards available to which you can plug one of these SOCs into them. There are different boards for different types of ESP SOCs. You can find them at popular Chinese vendors, and probably elsewhere too.

They look like this:
> 2 votes

# Answer
You could use wireless. First, use OTA programming (eg Elegant OTA) to burn a basic OTA uploader. Then, in principle, you can then upload any sketch you want so long as it ALWAYS has the basic OTA sketch included within your program.
> 1 votes

---
Tags: esp32, esp
---


title: Issue with HC-SR505 sensor

text:
# Question
Title: Issue with HC-SR505 sensor
I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.

Because of cost constraints, I decided to go with HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505?

Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Help?

Code:

```
const int buttonPin = 4;

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

   pinMode(buttonPin, INPUT);
 }
 void loop()
 {
    if (digitalRead(buttonPin) == HIGH)
    {

      Serial.println("Presence Detected");
    }
    else {

      Serial.println("No Presence Detected");
    }

 delay(2000);

 }

```

# Answer
> 2 votes
You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.

The 505 holds the HIGH output for a certain amount of time. None of the documentation I can find on it specifies the amount of time. So it is very possible that you are operating right near that limit. If their quality control is not perfect, some might work correctly and some might not.

In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.

That is the main difference between the 501 and the 505. On the 501 it is adjustable in both sensitivity and time delay. With the 505 those values are preset.

As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.

The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501. They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.

# Answer
> 2 votes
By shining with a bright light through the PCB, I came up with this reverse-engineered circuit diagram. From my understanding, the IC is some sort of special OP amp. I suppose one can change the timing by adjusting the 154 (150k) resistor and the sensitivity by adjusting the 335 (3.3Meg) and/or the 103 (10k) resistor.

# Answer
> 1 votes
According to this wiki: https://www.elecrow.com/wiki/index.php?title=HC-SR505\_Mini\_PIR\_Motion\_Sensor, there is an 8 second +/-30% delay.

The sensor is very sensitive to motion. Waving your hand in front of it "as fast as you can" (at close range) will trigger the sensor. While testing the two I had purchased, they had to be pointed away from me or there were "false alarms".

# Answer
> 1 votes
I had the same problem of the sensor giving random 1/0 values. I then looked at the circuit closer.

The PINs are badly marked which doesn't tell great detail, PIN-1 is marked with "+", however the word "OUT" is sitting between PINs 2 and 3.

If you connect + to the +5V, and then the middle PIN into the GND and then OUT into your Arduino (say PIN-10 of your Arduino), then you will notice ups and downs that does not correspond to any movements, (i.e. telling you "Bad Sensor")... however:

> Part-1 of the solution:

Swapping PINs 2 and 3 of the sensor (i.e. + goes into +5V of Arduino, Ground is PIN-3 of the sensor, and Middle is what you should be reading (i.e. PIN-10 of Arduino)) then this should start to work, but we're not finished yet, you would still get bad results...

> Part-2 of the solution:

If you are reading from PIN-10 of Arduino, then on your setup() function would usually be like this:

```
setup()
{
 pinMode(10, INPUT);
}

```

This is NOT enough for that sensor!... I know,... should be right?!...

Anyway, you MUST tell that PIN to be ZERO at the start, otherwise, it's hell brake loose... Therefore, please write the PIN with 0 and then it should all work fine after that:

```
setup()
{
    pinMode(10, INPUT);
    digitalWrite (10, LOW);
}

```

Following the above does resolve the issue, the sensor worked absolutely fine.

One annoying issue however which I am currently trying to work on is to reduce the sensor delay timer from 8 seconds into just 1-2 seconds, i.e. once someone is in-front of the sensor I don't want it to tell me that the person was there still when he left the area almost 7 seconds ago... I might post another article on how to do this later.

In the mean time, I hope this helps to resolve this problem

Regards Heider

---
Tags: sensors
---


title: Can't include files

text:
# Question
Title: Can't include files
For some reason, the Arduino IDE can't find the file I have made for the project:

```
#include <foo1.h>
#include <foo2.h>
#include "foo3.h"

```

Where foo1 and foo2 are normal libraries thus included with \<..\> but foo3 is another file I wrote which resides in the same directory as the .ino file from where this code is taken. If I essentially convert foo3 into a library and include it as a library in my project it works but makes the project harder to move.

Error I get:

```
Project.ino:6:23: fatal error: foo3.h: No such file or directory
:#include "foo3.h"
:compilation terminated
Error compiling project sources

```

Note: Error is persistent in both the Arduino IDE and VMicro

# Answer
> 2 votes
The question is a bit unclear, however as far as I know, for the included libraries use:

```
#include <SPI.h>

```

So the `<` and `>` are used for common libraries which are in the C:\Program files...\Arduino folder

And for specific (own made or sketch-depending) include files

```
#include "MyFile.h"

```

should be used, which should be located in the same folder as the sketch file.

# Answer
> 2 votes
It seems that my mistake was that I just created new files with another program and simply put them in the project directory. This probably confused the IDE as the files were not included in the build of the project.

Managed to fix this issue by creating new files within the project itself and simply copying my code into them. For VMicro/Visual Studio:

> VMicro\Add Code\Add Empty Arduino .h and .cpp files

# Answer
> 2 votes
Changing to double quotes with header files in the same folder worked for me.

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


# Question
Title: How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?
I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.

This is my MATLAB code:

```
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.

```

Output is

```
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>

```

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even 121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

# Answer
> 1 votes
I've configured the timer differently making use of its `UserData` property. The timer will update the data every fixed period for a specified number of samples.

```
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end

```

# Answer
> 0 votes
Each communication with Arduino takes 20ms, you have two in the loop so in the ideal conditions you could get 25 readings/second. See here the source

This also depends on the size of the data you request.

I think this is what you are looking for but I cant give you any advice since I don't have Matlab and Octave is not having this feature.

---
Tags: sensors, timers, matlab, data
---


title: How to convert string to long?

text:
# Question
Title: How to convert string to long?
There is `String.toInt()`, but no `String.toLong()` or the many other variations. Do I have to resort to `atol(String.c_str())` or is there a better way to convert a `String` to a long?

# Answer
Using `atol(String.c_str())` looks OK to me. If there was a `String.toLong()` it would be written that way anyway.

In fact, looking at the code for `String.toInt()` that's exactly what it does:

```
long String::toInt(void) const
{
    if (buffer) return atol(buffer);
    return 0;
}

```

So the answer is: use `String.toInt()`.
> 8 votes

# Answer
So the answer is: use String.toInt().

Probably not, as this is the definition of a String method:

long String::toInt(void) const

The real work is:

atol(buffer);

ASCII to long.
> 1 votes

---
Tags: convert
---


# Question
Title: Bad Data : Arduino Mega & NodeMCU Serial Communication
Currently I am working on an Arduino project. The project required to establish communication between Arduino Mega and NodeMCU ESP8266. Here are some details about the project:

* NodeMCU Rx Pin is connected to Arduino Mega Pin 14 (Tx3), while NodeMCU Tx Pin is connected to Arduino Mega Pin 15 (Rx3), Jumper Wires is used to connect NodeMCU and Arduino Mega
* Both Arduino Mega and NodeMCU are using baud rate 115200

Code for NodeMCU ESP8266 (Send The Data to Arduino Mega):

```
void loop(){
       esp.println("0000");

       esp.flush();
}

```

Code for Arduino Mega (Receive Data) :

```
 if(Serial3.available()){

  data = Serial3.readStringUntil('\n');

  Serial3.flush();

  Serial.println(data);

}

```

The result :

The intented and expected result is "0000", however, the result shown in serial monitor is not accurate. Anyone could advise?

# Answer
> 1 votes
Sir mane ardunio mega 2560 my programing k hy jo k different sensor k value lake display karty hy aur sir ab my us value ko server jo k thingspeak hy aus p bajna chahta ho sir aus k leye mane esp8266 node-mcu use kar raha ho to sir ab my chahta ho k arduino value lake node-mcu ko send kary aur node mcu phr server p sir in k leye serial communication chahyae between two arduino sir is k leye koi refrence or any help

---
Tags: serial, arduino-mega, esp8266, arduino-ide, communication
---


# Question
Title: How to change Windows 10 Device Manager so Arduino NANO COM3 can operate on COM4
The Arduino ATmega328 NANO uses COM3 on my WINDOWS 10 computer, but COM3 is NOT available.

QUESTION: Please explain in detail how I can change this Arduino NANO to operate on COM4

# Answer
> 1 votes
In device manager, right click on the device and select "Properties". Then go to the tab "Connection properties" and click on "Advanced". There you can change the COM port number assignment for a particular device.

# Answer
> 0 votes
In general, Windows assigns COM ports to USB devices when they are plugged in the first time. If you have multiple USB sockets, the same physical device will be assigned a different COM port when plugged into different sockets. Is it possible that you have changed your setup and are now using a different USB socket? Try the others to see if that works.

---
Tags: arduino-nano
---


# Question
Title: Why my arduino board does not blink properly?
I have two files

blink1.cpp

```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

blink2.cpp

```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

---

The difference between these two files are the definition of only a few unused ports in blink2.

I compile and upload them to the board by

```
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex

```

The first one does not blink properly but the second one does. What is the problem of the first code?

# Answer
There are a couple of issues here.

One of them has already been raised in a comment:

```

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {

```

The more serious issue is in the command line you used to compile the program. When compiling for an Uno, you should add the option `-mmcu=atmega328p`. This way the compiler knows which version of the C runtime it should add to your program. Otherwise the compiler will include no runtime at all.

The C runtime does some important initializations. For example, it clears the register `r1`, which is *required* by the ABI, and *assumed* to be the case by the compiler. For example, when you write `*portB = (int8_t) 0x00;`, the compiler copies `r1` to the port, without first clearing it. Another important role of the C runtime is to call `main()`. Without it, the program will start by executing whichever function happens to be at the start of the flash. Unless you program in assembly, you have no control over that. If the first function happens to be `main()`, the program may work as expected. If it is another function, that function may then return to the bootloader. Any seemingly innocuous change in the program can then change the behavior.

Then a few minor issues, that should not prevent the program from working:

* `int8_t` is meant to be a signed type. If you want the unsigned version, use `uint8_t` instead. Sure, these are your own type definitions, but creating a type that conflicts with a standard type can only create confusion. Best option is to drop the definition and include `<stdint.h>` instead.
* Whereas `port_type` should certainly be a “pointer to volatile” data, there is no point in making the pointer itself volatile. That can only hinder valid optimizations.
* `portB` and `ddrB` should be `const`, and that may allow the compiler to better optimize them. But why not use `PORTB` and `DDRB` from `<avr/io.h>`?
> 2 votes

---
Tags: arduino-uno, c++, port-mapping, avr-gcc
---


title: ESP32 CAM failed to get frame in time

text:
# Question
Title: ESP32 CAM failed to get frame in time
So I think the title says it all. I recently purchased an ESP32 CAM in India for a pretty cheap price.

It looks like an AI Thinker but doesn’t have the tag on the chip itself. Nonetheless, to get it setup before my use case I decided to test the camera. I loaded up the CameraWebServer example and set my camera type to AI thinker.

The code uploads successfully and runs successfully. I can open up the IP address and it shows the page. However whenever I try to get a still or start a stream, it gives this error:

```
[E][camera.c:1344] esp_camera_fb_get(): Failed to get the frame on time!
Camera capture failed

```

It’s pretty annoying and this happens in both 5V power and 3V power. The camera does physically get a bit hot after loading the website. Oh yeah, I have an OV 2460 Camera attached to the ESP.

Any advice is appreciated. Thanks!

# Answer
Solution for if this occurs on a known working ESP-32-cam with PSRAM (i.e. example sketch with face recognition works ok).
If you're using anything other than `PIX_FORMAT_JPEG`, try reducing `xclk_freq_hz`.
In my case, it suddenly worked fine with `PIX_FORMAT_RGB888`, `FRAMESIZE_VGA` and `xclk_freq_hz = 5000000` (4x lower).

( @Vraj P, this might not apply directly to what you found your problem was, but this post gets seen by many searching for this problem. Thanks!).
> 5 votes

# Answer
I had tried and tried to get the camera working. However, I decided to concede to the part of me that thought it was a hardware error. I purchased a new OV2640 module and instantly it worked.

I think I learned my lesson in purchasing cheap components. I inspected the old one further. Turns out there was a faulty ribbon cable. Anyways, I hope you aren’t in this situation. Seems like the only solution is to purchase new hardware, and the current issue is faulty hardware.
> 2 votes

# Answer
One possible cause is given here (scroll down to find this specific issue) https://randomnerdtutorials.com/esp32-cam-troubleshooting-guide/

There appear to be two sets of ESP-32-CAMs, one with and one without the PSRAM.
> 1 votes

# Answer
Look I've just had that problem for a month and if you're using esp32- ov2640 look the camera reference because the one I've had was TY 0V2640-V2.0 and what I've saw it's like a cheap copy of the normal camera, so be careful. I had to buy a new one because everything looked like a broken image, although all the config worked fine. Even changing the `PIX_FORMAT` and `xclk_freq_hz` didn't work. The camera was the problem.
> 1 votes

# Answer
This stung me too. I found increasing the frame buffer count helped.

```
camera_config_t config;
config.fb_count = 10;  // Or some other number

```
> 1 votes

---
Tags: esp32, camera
---


# Question
Title: Is it safe to connect VCC to a data pin on Attiny chips?
I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

# Answer
As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.

It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).
> 3 votes

---
Tags: attiny
---


title: Get production count for current minute

text:
# Question
Title: Get production count for current minute
I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds. I have a system for detect real-time product output and get it to the Arduino using digital input pin.

I wrote below codes and for that. what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.

**My question is, Is there any easy and efficient way for do this without using few variables ?**

```
    #define countSensor 8  //count sensor input

    uint8_t records[60];
    uint8_t countSensorState = 0;
    uint8_t totalCount = 0;
    uint8_t countOfLastSec = 0;
    uint8_t lastCount = 0;
    uint8_t lastMinCount;
    uint32_t preMills = 0;

    void setup() {
      Serial.begin(9600);
      //init sensor input pin
      pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

      //clear random value of memory locations
      for (int i = 0; i < 60; i++) {
        records[i] = 0;
      }

    }

    void loop() {
      //get count at falling edge
      if (digitalRead(countSensor)^ countSensorState) {
        if (!digitalRead(countSensor)) {
          totalCount++;

        }
        countSensorState = digitalRead(countSensor);
      }
      //get count of last second
      if (millis() - preMills > 1000) {
        preMills = millis();
        countOfLastSec = totalCount - lastCount;
        lastCount = totalCount;
        //record last 60s counts
        //--shift back a second in the array
        for (int i = 0; i < 59; i++) {
          records[i] = records[i + 1];
        }
        //--record current second in array at 59th index
        records[59] = countOfLastSec;
        //get last 60s count
        for (int i = 0; i < 60; i++) {
          lastMinCount += records[i];
        }
        Serial.println(lastMinCount);
      }

    }

```

# Answer
As I said in a comment, if you really need to compute that moving sum, you absolutely need to store the last 60 one-second counts in memory. That being said, there are a few small issues with this code for which I would have some suggestions:

* There is no point in storing `totalCount`. You do not really use it, and it will eventually overflow.
* You do not need to explicitly initialize all globals to zero, as that is implicitly done by the runtime: it is a requirement of the language.
* Your are calling `digitalRead(countSensor)` three times in a row. The logic for counting edges is sound as long as the three calls yield the same result, but that is not guaranteed. It is safer to only read the pin once per loop iteration.
* Similarly, the two calls to `millis()` can yield different results, and that will make your timings slightly off.
* The condition `millis() - preMills > 1000` will only fire when 1001 milliseconds have elapsed. Because of the way `millis()` works, sometimes you will miss the 1001th millisecond, and process on the 1002nd millisecond. In order to avoid accumulating these small timing errors, it is best to update `preMills` by always adding exactly 1000.
* As pointed out by jsotola, you do not need to shift the array: you can instead reuse the array cell that holds the data you do not need anymore.
* You do not need to perform the whole sum every time. You can instead update the previously computed sum by removing the count of the second that falls off the current one-minute window, and adding the count of the current second.

Here is my attempt at applying all the above suggestions. Warning: it has not been tested.

```
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

void setup() {
    Serial.begin(9600);
    pinMode(countSensor, INPUT_PULLUP);
}

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}

```
> 1 votes

---
Tags: arduino-uno, arduino-mega, time, millis
---


title: Create a dead zone for joystick

text:
# Question
Title: Create a dead zone for joystick
I'm trying to create a dead zone so the joystick will turn the motor off completely when in the center position. It's much too sensitive and will start the motor if barely touched. How could I fix the code so the off position of the joystick is bigger? This is the original code.

```
#include <Servo.h> //Using servo library to control ESC

Servo esc; //Creating a servo class with name as esc

void setup()
{
  esc.attach(9); //Specify the esc signal pin,Here as D9
  esc.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}

void loop()
{
  int val; //Creating a variable val
  val = analogRead(A0); //Read input from analog pin a0 and store in val
  val = map(val, 0, 1023, 1000, 2000); //mapping val to minimum and maximum(Change if needed)
  esc.writeMicroseconds(val); //using val as the signal to esc
}

```

# Answer
Here's how to create the new mapped range with a dead zone. I used `Servo.write()` which specifies the position in degrees because I couldn't understand what microsecond timings you need, but it should be easy to change it back. I've also added some debug statements to print `val` as the joystick is moved.

```
#include <Servo.h>

// Constants for servo angles in degrees.
const int SERVO_MIN = 0;
const int SERVO_MID = 90;
const int SERVO_MAX = 180;

// Constants for raw ADC values of joystick positions.
const int ANALOGUE_MIN = 0;
const int ANALOGUE_MID = 512;
const int ANALOGUE_MAX = 1023;
const int ANALOGUE_THRESHOLD = 100;

Servo esc;

void setup()
{
  esc.attach(9);         // Specify the esc signal pin as D9.
  esc.write(SERVO_MID);  // Move servo to mid position in degrees.
  Serial.begin(115200);
  Serial.println();
  Serial.println("Servo Test");
}

void loop()
{
  static int old_val = -1;   // Initialise to invalid value.
  int val = analogRead(A0);  // Read input from analogue pin A0.

  // Process val if it has changed.
  if (val != old_val)
  {
    old_val = val;
    Serial.print(val);
    Serial.print(", ");

    // Create the dead zone as per Majenko's algorithm.
    val -= ANALOGUE_MID;
    int direction = val < 0 ? -1 : +1;
    val = abs(val);
    val -= ANALOGUE_THRESHOLD;
    if (val < 0) val = 0;

    // Create a new mapped range with a dead zone.
    val *= direction;
    val += ANALOGUE_MID;
    Serial.print(val);
    Serial.print(", ");
    val = map(val, ANALOGUE_MIN + ANALOGUE_THRESHOLD, ANALOGUE_MAX - ANALOGUE_THRESHOLD, SERVO_MIN, SERVO_MAX);
    Serial.println(val);

    // Move servo to new angle in degrees.
    esc.write(val);
  }
}

```
> 1 votes

# Answer
My method is to separate the direction from the magnitude:

* Subtract the "center" value to create a ± range
* Use the sign to indicate the direction
* Take the `abs` to give the magnitude
* Subtract the "threshold" value
* If negative set to zero

So, with example values:

```
int val = analogRead(0);          // Raw value
val -= 512;                       // Subtract center value (512)
int direction = val < 0 ? -1 : 1; // Direction is either -1 or +1
val = abs(val);                   // Remove the sign
val -= 10;                        // Subtract the threshold (10)
if (val < 0) val = 0;             // Anything below zero is now zero
// val is now 0-501 with a dead zone, and direction is -1 or +1.

```
> 0 votes

# Answer
Note that in your case, the width of the input range (1023) is only very slightly larger than the width of the output range (1000). You could take this width difference (23) as the dead zone, and this would simplify the arithmetics: now the linear parts of your map have a slope of exactly 1, and you do not need multiplications or divisions.

The map is then:

* \[0, 500\] → \[1000, 1500\] (slope =1)
* \[500, 523\] → 1500 (slope = 0)
* \[523, 1023\] → \[1500, 2000\] (slope = 1)

In code:

```
/*
 * Map:
 *   [  0,  500] -> [1000, 1500]
 *   [500,  523] ->  1500
 *   [523, 1023] -> [1500, 2000]
 */
if (val < 500)
    val = 1000 + val;
else if (val < 523)
    val = 1500;
else
    val = (1500 - 523) + val;

```
> 0 votes

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