body: 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?

title: Running Arduino mega on 5V power supply

Answers: 4

body:
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.

body:
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.

body:
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.

body:
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).
[![Ardiono Mega pinout][1]][1]

  [1]: https://i.stack.imgur.com/maoqX.png


body:
I bought this "knockoff" Arduino UNO with an integrated ESP 2866 wifi module. But I can't make it work. I've followed [this][1] 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][2]. 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.

  [1]: https://www.youtube.com/watch?v=tj2fwh989D8
  [2]: https://s.click.aliexpress.com/e/_AEhGBH

title: Arduino UNO with integrated ESP2866 wifi not working correctly

Answers: 2

body:
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.

body:
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](https://youtu.be/VfwvVi0rnLQ?t=358) 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](https://www.youtube.com/watch?v=VfwvVi0rnLQ) - I am just curious! :)


body:
I have a *digispark* ATtiny85 development board and I am using the Arduino IDE to program it along with the Arduino UNO as my hardware programmer.

I have successfully burned the fuses for both the internal 1 and 8 MHz RC oscillators using the *original* Arduino as ISP sketch (you'll understand why I said *original* in a moment), but as my application needs precise timing, I would like to use an external oscillator, however, every time I tried to burn/program the bootloader/fuses using the Arduino IDE and using the *original* Arduino as ISP, the avrdude spits the infamous (Yikes).
I searched online and found an *updated* version of the Arduino as ISP sketch, which is supposed to an updated version, it has only one downside, which is, it can't do anything other than burn/program the bootloader/fuses, meaning that it can't be used to program the ATtiny85 like the *original* Arduino as ISP could do.

So without hesitating, I tested it to burn/program the bootloader/fuses for the internal 1 and 8 MHz RC oscillators, and it worked perfectly, and as expected, it fails to upload the code.
But the *original* Arduino as ISP successfully uploaded the code.
When I tried to burn/program the bootloader/fuses for the *external* 8MHz crystal oscillator using the *updated* Arduino as ISP, it worked flawlessly... until I noticed that the ordinary Arduino as ISP can not upload the code anymore and I am presented with the infamous (Yikes!) error.

Let me elaborate the difference in the *connections* between the two sketches.
The updated Arduino as ISP generates a clock signal on pin #9, which connects to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), while the *original* Arduino as ISP does not utilize this pin at all.

I found the updated Arduino as ISP on the *electronics stack exchange* forum, but unfortunately I lost the link to the question which contained why is this updated Arduino as ISP is better.
I can provide both codes though if someone needs them.

I have my crystal connected in both cases, burning/programming the bootloader/fuses and while trying to upload my code.

This is the infamous (Yikes!) error which I was talking about.
[![enter image description here][1]][1]

This is my current wiring.
[![enter image description here][2]][2]
Please note that I connect pin #9 to the CLKI of the ATtiny85 (AKA Pin #2 "PB3"), only when I am using the *updated* Arduino as ISP.

This is the *actual* wiring.
[![enter image description here][3]][3]

[![enter image description here][4]][4]

[![enter image description here][5]][5]

[![enter image description here][6]][6]

[![enter image description here][7]][7]

My two questions are:
1) How could I burn/program the bootloader/fuses of the ATtiny85 to use an external oscillator of 8MHz or 16 MHz?
2) How could I upload my application code after burning/programming the bootloader/fuses?

I hope the answers elaborate how the connections would differ, if it would.

Thank a lot in advance.

  [1]: https://i.stack.imgur.com/ebRAN.png
  [2]: https://i.stack.imgur.com/CPhVg.png
  [3]: https://i.stack.imgur.com/KbLK5.jpg
  [4]: https://i.stack.imgur.com/TPncu.jpg
  [5]: https://i.stack.imgur.com/Goypa.jpg
  [6]: https://i.stack.imgur.com/mJa0b.jpg
  [7]: https://i.stack.imgur.com/uOGMB.jpg

title: Programming ATtiny85 with Arduino-IDE and an 8MHz external oscillator

Answers: 1

body:
If you look at the [Digispark Schematic][1] you'll see resistors and Zener diodes attached to XTAL1 and XTAL2:
[![Digispark Schematic with circuitry connected to XTAL1 and XTAL2 pins highlighted.][2]][2]

These are for the USB D+ and D- signals that the Digispark bit-bangs.  I deeply suspect that the crystal is just not going to resonate with these parts connected.

To get back to a working Digispark you'll probably have to inject signal onto XTAL1 again and reprogram the fuses to internal OSC.

  [1]: https://s3.amazonaws.com/digispark/DigisparkSchematicFinal.pdf
  [2]: https://i.stack.imgur.com/VHd1L.png


body:
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?

title: I need a good battery reccomendation

Answers: 2

body:
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.

body:
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).


body:
I am new to Arduino, and it's confusing to me how you can just write code in the IDE and use functions or macros such as `#define ISR()` in the avr-libc library without having to include the header file in the Arduino sketch.

I was trying to find where `digitalPinToInterrupt()` is defined, but had no luck. Any idea?

title: Where is the digitalPinToInterrupt macro defined

Answers: 2

body:
Generally, if you want to find identifiers in your Arduino board support, you can run the [ctags program][1] on the libc and Arduino core files.  ctags is used as part of the [build process][2] in its effort to generate C++ declarations for you.  So it is generally available to you as an Arduino user.  You should find `ctags` or `ctags.exe` in:

> */path/to/arduino15*`/builtin/tools/ctags/`*version-number*`/`

This can be run against your board support in:

> */path/to/arduino15*`/packages/`*vendor*`/hardware/`*architecture*`/`*version-number*`/`

And your standard libraries found under directories in the form of:

> */path/to/arduino15*`/packages/`*vendor*`/tools/`*compiler-tool*`/`*version-number*`/`

If you're wondering what */path/to/arduino15/* would be on your system, it's [documented here][3] in terms of where the preferences file is stored.  The relevant paths containing and version numbers and architecture names should show in the verify/compile output when verbose mode is turned on in preferences.

Specific example
----------------

On my linux system with reasonably current versions of UNO-related things, my command-line would look like:

```none
~/.arduino15/packages/builtin/tools/ctags/5.8-arduino11/ctags \
    -f /tmp/output-file \
    -R \
     ~/.arduino15/packages/arduino/hardware/avr/1.8.3/ \
    ~/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/avr/include/
```

The resulting tag file can then `grep`ed or just opened and the following entries can be found, showing the filenames and line numbers to investigate:

```none
DigitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/circuitplay32u4/pins_arduino.h 138;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/ethernet/pins_arduino.h 79;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/gemma/pins_arduino.h 64;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/leonardo/pins_arduino.h 160;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/mega/pins_arduino.h 110;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_control/pins_arduino.h 120;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_motor/pins_arduino.h 115;" d
digitalPinToInterrupt /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/standard/pins_arduino.h 79;" d
```

In the [case of an UNO][4] the `standard` [variant][5] is [the significant declaration][6].

---

There are different implementations of ctags.  The one used by the Arduino support files is [Exuberant CTAGS][7] and you may want to read [its documentation][8], to learn how to control the program to display differently to only search for specific identifiers, etc.  It is also typically used with editors that have some special support for the resulting tags file, to jump to definitions, like an IDE would.

  [1]: https://en.wikipedia.org/wiki/Ctags
  [2]: https://arduino.github.io/arduino-cli/latest/sketch-build-process/
  [3]: https://docs.arduino.cc/hacking/software/Preferences
  [4]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/boards.txt#L78
  [5]: https://arduino.github.io/arduino-cli/latest/platform-specification/#boardstxt
  [6]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/variants/standard/pins_arduino.h#L79
  [7]: http://ctags.sourceforge.net/
  [8]: http://ctags.sourceforge.net/ctags.html

body:
If you like to tinker with the files. Than platformio is great option to go with. It provides auto completion and much more advance functionality.

You can easy see where some function/mecro is defined, by just right click on the function than click on the "Go to definition" option.
[![Here is the picture][1]][1]

The file that contains the definition will be opened in the new tab. As for your current Macro check the image below
[![digitalPinToInterrupt macro definition][2]][2]

  [1]: https://i.stack.imgur.com/Ar9hq.png
  [2]: https://i.stack.imgur.com/9tPRn.png


body:
I'm trying to make a project with this conection diagram [![enter image description here][1]][1] but I don't think it's correct , and my adxl sensor died . Can you help me with a modified one ?

  [1]: https://i.stack.imgur.com/NORNF.png

title: Interfacing Arduino nano ,adxl335 ,nrf24l01

Answers: 0


body:
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.

title: Digital pins are no longer outputting enough to click a relay

Answers: 1

body:
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:

[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/grdIq.png


body:
I'm trying to build an Arduino project where it involves a TFT and an ethernet W5500 component.

Here's the [project][1] I want to build to learn Arduino. However I wanted to change the board that already has an ethernet PoE [here][2]. The TFT I plan to use is a [shield][3]. It seems that pin D10 are being used by both components.
Is it possible through software to use a different Digital pin through software for either the board or the TFT display?  I have read where users are cutting traces and using jumper wires - would that be required in my case? I am planning on using SPI pins if possible. Thanks!

  [1]: https://www.instructables.com/Arduino-and-ENC28J60-Ethernet-Controller-320x480-T/
  [2]: https://robotdyn.com/leonardo-eth-v2-with-atmega32u4-ethernet-w5500-arduino-compatible-board.html
  [3]: https://www.adafruit.com/product/1947

title: How to avoid two arduino components using the same digital PIN

Answers: 0


body:
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?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/IomMR.png

title: NodeMCU and relay with VIN power

Answers: 1

body: Looks fine to me, I don't see any issues, assuming the PSU has sufficient 'grunt' to power both, and most will have.


body:
I have started learning about `arduino` and just bought a `bluetooth` module, HC-05. From where i bought, it says it has range of approx.10 meters. I made hc-05 connection with `arduino` in below described ways

I am using it as a slave with default configurations, 9600 baud rate and HC-05 name with pin 1234

    GND of HC05 -> GND of `arduino`
    VCC of HC05 -> 5V of `arduino`
    TX of HC05 -> RX of `arduino`
    RX of HC05 -> TX of `arduino` via voltage divider network 2k---|---1k

Below is my `arduino` code

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(2, 3); // RX | TX
    // Connect the HC-05 TX to Arduino pin 2 RX.
    // Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.

    int pin = 13;
    char c = ' ';

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Arduino is ready");
     pinMode(pin,OUTPUT);

     // HC-05 default serial speed for communication mode is 9600
     BTserial.begin(9600);
     Serial.println("BTserial started at 9600");
    }

    void loop()
    {
      if (BTserial.available()>0){
        c = BTserial.read();
        Serial.println(c);
        switch (c){
          case '1' :
            digitalWrite(pin,HIGH);
            break;
          case '2' :
            digitalWrite(pin,LOW);
            break;
          default: break;

        }
      }
    }

Following things happening to me:

1. When I power the module I am able to discover it with my phone but only when I hold my phone very near to the module. If I move away from the HC05 module, for example 3-4 feet, I am not able to discover it.

2.After connecting with it (while holding phone near to the module), I am able to send data to it but again, if I move away , only a few steps, I am unable to send data and I disconnect from it automatically. Also if I change direction of the antenna even then no communication happens.

My purpose is to control my home's lights and TV with the help of this module and Relays. But HC05 is useless so far. I was hoping that I would code it and wire it and hang it on a wall and interact it with and `andoird` app.

Is it suppose to happen like this? or there's something wrong with my module's antenna

thank you.

title: HC-05 bluetooth module short range

Answers: 0


body:
I'm learning about GPS technology and I bought the Maduino Zero SIM808 board V3.5 to design a vehicle tracker. I have found source code for the project online.  After I upload the code to Maduino board, the code executes fine.

I'm sending "Location" to the device and i'm expecting reply with google map on my phone to be able to check device location, but i'm not getting reply from the device. i have changed the AT commands to test if i will get reply from the device, here is the source where i got the project: https://how2electronics.com/gps-gsm-based-vehicle-tracking-system-using-arduino/

Here is my output from the code:

```none
Text Mode: ON
GPS Intializing…
GPS Initialized
Location:
Send sms to get the location
```

```c++
#include<string.h>

#define DEBUG true

int PWR_KEY = 9;
int RST_KEY = 6;
int LOW_PWR_KEY = 5;

String msg = String("");
int SmsContentFlag = 0;
String mob;
String loct;
void setup()
{
  pinMode(PWR_KEY, OUTPUT);
  pinMode(RST_KEY, OUTPUT);
  pinMode(LOW_PWR_KEY, OUTPUT);
  digitalWrite(RST_KEY, LOW);
  digitalWrite(LOW_PWR_KEY, HIGH);
  digitalWrite(PWR_KEY, HIGH);

  //      String msg = String("");
  //    int SmsContentFlag = 0;

  SerialUSB.begin(115200);
  Serial1.begin(115200);
  //modulePowerOn();
  delay(2000);
  SerialUSB.println("Checking Module...");
  int i = 1;
  String res;
  while (i) {
    Serial1.println("AT");
    while (Serial1.available() > 0) {
      if (Serial1.find("OK"))
        i = 0;
    }
    delay(500);
  }
  SerialUSB.println("Module Connected");
  //GprsTextModeSMS();
  SerialUSB.print("Text Mode: ");
  i = 1;
  while (i) {
    Serial1.println("AT+CSMP=17,167,0,0");
    delay(100);
    Serial1.println("AT+CMGF=1\r");
    while (Serial1.available() > 0) {
      if (Serial1.find("OK"))
        i = 0;
    }
    delay(500);
  }
  SerialUSB.println("ON");
  Serial1.println("AT+CGNSPWR=1");
  delay(100);
  Serial1.println("AT+CGNSSEQ=RMC");
  SerialUSB.println("GPS Intializing...");
  delay(5000);
  SerialUSB.println("GPS Initialized");
  SerialUSB.flush();
  i = 1;
  String str;
  while (i) {
    Serial1.println("AT+CGPSINF=0");
    delay(100);
    while (Serial1.available() <= 0);
    if (Serial1.find("AT+CGPSINF=0")) {
      str = Serial1.readString();
      //SerialUSB.println(str);
      i = 0;
    }
    delay(500);
  }
  loct = str.substring(4, 23);
  SerialUSB.print("Location: ");
  SerialUSB.println(loct);
  //while(1);
  SerialUSB.println("Send sms to get the location");
}

void loop()
{
  char SerialInByte;

  if (Serial1.available())
  {
    //char SerialInByte;
    SerialInByte = (unsigned char)Serial1.read();
    if ( SerialInByte == 13 ) //0x0D
    {
      ProcessGprsMsg();
    }
    if ( SerialInByte == 10 )
    {
    }
    else
    {
      //EN: store the current character in the message string buffer
      msg += String(SerialInByte);
    }
  }
  if (SmsContentFlag == 1) {
    int i;
    SerialUSB.println("Flag Cleared");
    SerialUSB.print("Message: ");
    SerialUSB.println(msg);
    if (msg.indexOf("Location")) {
      SerialUSB.println("Message Received");
      i = msg.indexOf("+27");
      //SerialUSB.print("index: ");
      //SerialUSB.println(i);
      //SerialUSB.println(msg[i+1]);
      i = i + 3;
      for (int j = 0; j < 10; j++, i++) {
        mob += msg[i];
      }
      SerialUSB.print("Mobile: ");
      SerialUSB.println(mob);
      String cmd = "AT+CMGS=\"";
      cmd += mob;
      cmd += "\"";
      cmd += "\r";
      Serial1.println(cmd);
      delay(100);

      Serial1.print("Your Vehicle Current Location ");
      Serial1.print(loct);
      Serial1.print("\n");
      Serial1.print("Check Map: \n");
      Serial1.print(" https://www.google.com/maps/@");
      Serial1.println(loct);
      Serial1.println((char)26);
      delay(1000);
    }
    ClearGprsMsg();
    SmsContentFlag = 0;
    msg.remove(0);
    mob.remove(0);
  }
  delay(100);
}

// EN: Request Text Mode for SMS messaging
void GprsTextModeSMS()
{
  Serial1.println( "AT+CMGF=1" );
}

void GprsReadSmsStore( String SmsStorePos )
{
  // Serial.print( "GprsReadSmsStore for storePos " );
  // Serial.println( SmsStorePos );
  Serial1.print( "AT+CMGR=" );
  Serial1.println( SmsStorePos );
}

// EN: Clear the GPRS shield message buffer
void ClearGprsMsg()
{
  msg = "";
}

// EN: interpret the GPRS shield message and act appropiately
void ProcessGprsMsg()
{
  SerialUSB.println("");
  //  Serial.print( "GPRS Message: [" );
  SerialUSB.print( msg );
  //    Serial.println( "]" );
  if ( msg.indexOf( "Call Ready" ) >= 0 )
  {
    SerialUSB.println( "*** GPRS Shield registered on Mobile Network ***" );
    GprsTextModeSMS();
  }

  //EN: unsolicited message received when getting a SMS message
  if ( msg.indexOf( "+CIEV" ) >= 0 )
  {
    SerialUSB.println( "*** SMS Received ***" );
  }

  //EN: SMS store readed through UART (result of GprsReadSmsStore request)
  if ( msg.indexOf( "+CMT:" ) >= 0 )
  {
    // EN: Next message will contains the BODY of SMS
    SmsContentFlag = 1;
    // EN: Following lines are essentiel to not clear the flag!
    //ClearGprsMsg();
    return;
  }

  // EN: +CMGR message just before indicate that the following GRPS Shield message
  //     (this message) will contains the SMS body
  if ( SmsContentFlag == 1 )
  {
    SerialUSB.println( "*** SMS MESSAGE CONTENT ***" );
    SerialUSB.println( msg );
    SerialUSB.println( "*** END OF SMS MESSAGE ***" );
    //ProcessSms( msg );
  }

  /*ClearGprsMsg();
    //EN: Always clear the flag
    SmsContentFlag = 0; */
}
```

title: SIM808 GPS+GSM Vehicle Tracking using Maduino Zero SIM808 GPS Tracker V3.5

Answers: 0


body:
I'm using "mega 2650 pro" Arduino with SIM808 BK-808 V-3.1 and I connect the vcc for the sim808 to 5volt pin in the arduino, and the arduino connected with laptop usb. and I add a sim to the sim808 module.

I upload the following code:
```
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX 14
#define PIN_RX 15
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

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

//******** Initialize sim808 module *************
while(!sim808.init()) {
delay(1000);
Serial.print("Sim808 init error\r\n");
}

//************* Turn on the GPS power************
if( sim808.attachGPS())
Serial.println("Open the GPS power success");
else
Serial.println("Open the GPS power failure");

}

void loop() {
//************** Send the coordinates(latitude&lonitude)in the Serial Monitor *******************
if (sim808.getGPS()) {

Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon);

}

}
```

but the output is

Sim808 init error

and I tried several codes to test AT commands, nothing work!

so what is the problem?

title: sim808 init error when trying to use DFRobot to get gps

Answers: 0


body:
I'm building a device that uses two ultrasonic sensors to detect objects and provide audio feedback in the form of beeps that get faster the closer an object is. I have two speakers, one for each sensor, but the tone command will only do one set of beeps at a time. I tried to get around this with the Polytone Library and polytone command, but when I go to compile, I get an "exit status 1. Error compiling for board Arduino Uno" message. What am I doing wrong? Is there another way to get both sensors beeping  at the same time? Please help!

I'm very new at coding. I tried to put the polytone code in a couple different ways, which I can show if that helps. There's also gyroscope code in there, but I have that working pretty well, so I guess just ignore that.

        #include <digitalWriteFast.h>
    #include <Polytone.h>

    #include <Wire.h> //library allows communication with I2C / TWI devices
    #include <math.h> //library includes mathematical functions

    const int MPU=0x68; //I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; //16-bit integers
    int AcXcal,AcYcal,AcZcal,GyXcal,GyYcal,GyZcal,tcal; //calibration variables
    double t,tx,tf,pitch,roll;

    const int anPin1 = 0;
    const int anPin2 = 1;
    int triggerPin1 = 13;

    long distance1, distance2;

    //Code Part 2: Level LEDS
    // Level LEDs
    int levelLED_level = 11;
    int levelLED_rollpos = 9;
    int levelLED_rollneg = 8;
    int levelLED_pitchpos = 12;
    int levelLED_pitchneg = 10;
    int LED_temp = 7;
    Polytone poly;
    void setup(){
        Serial.begin(9600);  // sets the serial port to 9600
        pinMode(triggerPin1, OUTPUT);

        Wire.begin(); //initiate wire library and I2C
        Wire.beginTransmission(MPU); //begin transmission to I2C slave device
        Wire.write(0x6B); // PWR_MGMT_1 register
        Wire.write(0); // set to zero (wakes up the MPU-6050)
        Wire.endTransmission(true); //ends transmission to I2C slave device
        Serial.begin(9600); //serial communication at 9600 bauds

        pinMode(levelLED_rollneg, OUTPUT);
        pinMode(levelLED_rollpos, OUTPUT);
        pinMode(levelLED_pitchpos, OUTPUT);
        pinMode(levelLED_pitchneg, OUTPUT);
        pinMode(levelLED_level, OUTPUT);
    }

    void start_sensor(){
      digitalWrite(triggerPin1,HIGH);
      delay(1);
      digitalWrite(triggerPin1,LOW);
    }

    void read_sensors(){
      /*
      Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
      Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
      */
      distance1 = analogRead(anPin1)*1.35;
      distance2 = analogRead(anPin2)*2.092;
    }

    void print_all(){
      Serial.print("MB1000");
      Serial.print(" ");
      Serial.print(distance1);
      Serial.print("mm");
      Serial.print(" ");
      Serial.print(" ");
      Serial.print("MB1260");
      Serial.print(" ");
      Serial.print(distance2);
      Serial.print("mm");
      Serial.println();
    }

    //Front sensor ranges
    void midiSlowFront() {
      poly.begin(); // Set up polling timer interrupt
      poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo

      poly.tone(262);
      delay(2000.0);
      poly.end();
    }
    void midiFront() {
       poly.begin(); // Set up polling timer interrupt
       poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
       poly.tone(262);
       delay(500.0);
       poly.end();
    }
    void midiFastFront() {
       poly.begin(); // Set up polling timer interrupt
       poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
       poly.tone(262);
       delay(150.0);
       poly.end();
    }

    //Side sensor ranges
    void midiSlowSide() {
       poly.begin(); // Set up polling timer interrupt
       poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
       poly.tone(440);
       delay(2000.0);
       poly.end();
    }
    void midiSide() {
       poly.begin(); // Set up polling timer interrupt
       poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
       poly.tone(440);
       delay(500.0);
       poly.end();
    }
    void midiFastSide() {
       poly.begin(); // Set up polling timer interrupt
       poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
       poly.tone(440);
       delay(150.0);
       poly.end();
    }

    void loop(){
        Wire.beginTransmission(MPU); //begin transmission to I2C slave device
        Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
        Wire.endTransmission(false); //restarts transmission to I2C slave device
        Wire.requestFrom(MPU,14,true); //request 14 registers in total

        start_sensor();
        read_sensors();
        print_all();

        //Acceleration data correction
        AcXcal = -950;
        AcYcal = -300;
        AcZcal = 0;

        //Temperature correction
        tcal = -1600;

        //Gyro correction
        GyXcal = 480;
        GyYcal = 170;
        GyZcal = 210;

        //read accelerometer data
        AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) 0x3C (ACCEL_XOUT_L)
        AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) 0x3E (ACCEL_YOUT_L)
        AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) 0x40 (ACCEL_ZOUT_L)

        //read temperature data
        Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) 0x42 (TEMP_OUT_L)

        //read gyroscope data
        GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) 0x44 (GYRO_XOUT_L)
        GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) 0x46 (GYRO_YOUT_L)
        GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) 0x48 (GYRO_ZOUT_L)

        //temperature calculation
        tx = Tmp + tcal;
        t = tx/340 + 36.53; //equation for temperature in degrees C from datasheet
        tf = (t * 9/5) + 32; //fahrenheit

        //get pitch/roll
        getAngle(AcX,AcY,AcZ);

        //printing values to serial port
        Serial.print("Angle: ");
        Serial.print("Pitch = "); Serial.print(pitch);
        Serial.print(" Roll = "); Serial.println(roll);

        Serial.print("Temperature in celsius = "); Serial.print(t);
        Serial.print(" fahrenheit = "); Serial.println(tf);

        if ((roll < 7.00) && (roll > -7.00) && (pitch > -7.00) && (pitch < 7.00)){
        digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, HIGH);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if (roll > 7.01) {
        // Turn on Pos Roll LED
        digitalWrite(levelLED_rollpos, HIGH);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if (roll < -7.01) {
        //Turn on Neg Roll LED
        digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, HIGH);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if (pitch < -7.01) {
        //Turn on Neg Pitch
        digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, HIGH);
        }

        if (pitch > 7.01) {
        //Turn on Pos Pitch
        digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, HIGH);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if ((pitch > 7.01) && (roll > 7.01)){
        digitalWrite(levelLED_rollpos, HIGH);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, HIGH);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if ((roll > 7.01) && (pitch < -7.01)){
         digitalWrite(levelLED_rollpos, HIGH);
        digitalWrite(levelLED_rollneg, LOW);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, HIGH);
        }

        if ((roll < -7.01) && (pitch < -7.01)){
         digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, HIGH);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, LOW);
        digitalWrite(levelLED_pitchneg, HIGH);
        }

        if ((roll < -7.01) && (pitch > 7.01)){
         digitalWrite(levelLED_rollpos, LOW);
        digitalWrite(levelLED_rollneg, HIGH);
        digitalWrite(levelLED_level, LOW);
        digitalWrite(levelLED_pitchpos, HIGH);
        digitalWrite(levelLED_pitchneg, LOW);
        }

        if (tf > 72.00){
          digitalWrite(LED_temp, HIGH);
        }

        if (tf < 72.00){
          digitalWrite(LED_temp, LOW);
        }

        if((distance1 > 24)){
        midiSlowFront();
        }
        if((distance1 < 24) && (distance1 > 12)){
        midiFront();
        }
        if(distance1 < 12){
        midiFastFront();
        }
        if(distance2 > 24){
        midiSlowSide();
        }
        if((distance2 < 24) && (distance2 > 12)){
        midiSide();
        }
        if(distance2 < 12){
        midiFastSide();
        }
      delay(150);
    }

    //function to convert accelerometer values into pitch and roll
    void getAngle(int Ax,int Ay,int Az) {
        double x = Ax;
        double y = Ay;
        double z = Az;

        pitch = atan(x/sqrt((y*y) + (z*z))); //pitch calculation
        roll = atan(y/sqrt((x*x) + (z*z))); //roll calculation

        //converting radians into degrees
        pitch = pitch * (180.0/3.14);
        roll = roll * (180.0/3.14) ;
    }

EDIT: Here's the stuff before the error message, my bad!
```

In file included from C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:1:0:

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src/digitalWriteFast.h:25:0: warning: "digitalPinToTimer" redefined

 #define digitalPinToTimer(P) \

In file included from sketch\polytonetest.ino.cpp:1:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:180:0: note: this is the location of the previous definition

 #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )

In file included from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.h:11:0,

                 from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:7:

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\digitalWriteFast.h:25:0: warning: "digitalPinToTimer" redefined

 #define digitalPinToTimer(P) \

In file included from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.h:10:0,

                 from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:7:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:180:0: note: this is the location of the previous definition

 #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )

libraries\arduino-polytone-master\Polytone.cpp.o (symbol from plugin): In function `Polytone::begin()':

(.text+0x0): multiple definition of `t'

sketch\polytonetest.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:18:15: warning: type of 't' does not match original declaration [-Wlto-type-mismatch]

 unsigned long t = 0;

               ^

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: type 'double' should match type 'long unsigned int'

 double t,tx,tf,pitch,roll;

        ^

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: 't' was previously declared here

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: code may be misoptimized unless -fno-strict-aliasing is used

collect2.exe: error: ld returned 1 exit status
```

title: Issues with Polytone Library?

Answers: 0


body:
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.

```c++
#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
}
```

title: Create a dead zone for joystick

Answers: 3

body:
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:

```c++
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.
```

body:
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.

```c++
#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);
  }
}
```

body:
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:

```c++
/*
 * 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;
```


body:
I am using a L298N motor driver to connect a motor with NodeMCU. But i did a few tests since a few tests while learning how to control it now when i connect it the motor doesn't even work. Then i removed the nodemcu and just used the motor driver to control the motor, then also it did not work. I don't know why.
I am new to controlling motors and this is my first time.

Also I am using 9v battery to power the motor driver.

l298n- https://www.amazon.in/gp/product/B08SK2ZPYD/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1

nodemcu - https://www.amazon.in/Lolin-NodeMCU-ESP8266-CP2102-Wireless/dp/B010O1G1ES/ref=sr_1_2?dchild=1&keywords=nodemcu&qid=1617973657&s=industrial&sr=1-2

title: L298N Motor Driver not working

Answers: 0


body:
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?

title: How to webClient.write() an image stored on a String?

Answers: 2

body:
You should not use `String` to store binary data.

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

```c++
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](https://stackoverflow.com/questions/8659808/how-does-http-file-upload-work)

body:
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();


body:
So i wanted to build a music visualizer using a MSGEQ7. As I just got started with electronics, I did some soldering beforehand and I think I am doing okish. While it might not be perfect, the contact should be fine.

I hooked my arduion MEGA 2560 Board up with the Spectrum Shield and ran the code according to this webpage
https://learn.sparkfun.com/tutorials/spectrum-shield-hookup-guide/all

My solders are fine, however, the serial output for the 7 freuquency bands never changes and stays at 150 once I plug in an aux cable. I checked if the audio is processed at all by connecting a speaker to the output and the music does play. However, there are no changes of the frequency bands when playing music.

Is my board broken? If needed, i can provide pictures of my soldering/circuit. I got pretty frustrated cause I am just getting started and I don't even know how to tell what's wrong.

I really appreciate any help.
Thanks!

title: Sparkfun Spectrum Shield no change in frequency

Answers: 0


body:
I'm having trouble getting my NodeMCU connected to 4 x 4 Digit 7 Segment Displays.

So far I've been able to connect 2 & get them to display things from the demo repository.

However, after trying all possible combinations of different pins & looking up the pinout reference I have no idea why I can't get them to work.

Any help would be greatly appreciated.

I'm working with:

- ESP8266 NodeMCU ESP-12E (CP2102)

- 4 Digit 7 Segment Display (TM1637)

As suggested @romkey:

    #include <Arduino.h>
    #include <TM1637Display.h>

    // Module connection pins (Digital Pins)

    #define CLK_1 D2
    #define DIO_1 D3

    #define CLK_2 D5
    #define DIO_2 D6

    #define CLK_3 13
    #define DIO_3 15

    // The amount of time (in milliseconds) between tests
    #define TEST_DELAY   500

    TM1637Display display1(CLK_1, DIO_1);
    TM1637Display display2(CLK_2, DIO_2);
    TM1637Display display3(CLK_3, DIO_3);

    void setup()
    {
    }

    void loop()
    {
      int k;
      uint8_t data[] = { 0xff, 0xff, 0xff, 0xff };
      uint8_t blank[] = { 0x00, 0x00, 0x00, 0x00 };
      display1.setBrightness(0x0f);
      display2.setBrightness(0x0f);
      display3.setBrightness(0x0f);

      // Brightness Test
      for(k = 0; k < 4; k++)
     data[k] = 0xff;
      for(k = 0; k < 7; k++) {
        display1.setBrightness(k);
        display1.setSegments(data);
        display2.setBrightness(k);
        display2.setSegments(data);
        display3.setBrightness(k);
        display3.setSegments(data);
        delay(TEST_DELAY);
      }
      while(1);
    }

I've tried addressing the CLK_3 & DIO_3 pins as "Dx" but that didn't work as well.

Repos used:
 - https://github.com/avishorp/TM1637

title: ESP8266 + 4x TM1637 == possible?

Answers: 0


body:
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:
https://arduino.stackexchange.com/questions/19961/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:

[![Picture of the screen of an oscilloscope showing that the frequency at which the digital pin toggles is close to 410kHz][1]][1]

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 ?

  [1]: https://i.stack.imgur.com/aeUoa.jpg

title: Arduino Uno's Timer maximum frequency using Timer Compare Interrupt, not Timer Output Pins (e.g. OC0A)

Answers: 1

body:
> 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.


body:
I'm trying to find a code that would take the PPG signals from the MIKROE-2036 Heart Rate 3 Clicker and process the information through the Arduino Nano to find a person's Oxygen Saturation. Basically, by using this code how do I measure Oxygen Saturation from the given analog inputs from the LEDs?

This is the test code that the Arduino Nano could use, but it's more of a template:

    /*
     * AFE4404 Basic Read library example.
     * https://github.com/rakshithbk/AFE4404-Library
     *
     * On Arduino Uno -  | AFE4404 | Uno Pin
     *                   | I2C_Dat | A4
     *                   | I2C_Clk | A5
     * get_led_val() will return uint32_t values.
     *
     * Advanced - you can modify the sample period and other
     * parameters in the library files (refer AFE4404 datasheet)
     */

    #include <Wire.h>
    #include <AFE_connect.h>

    AFE A;

    void setup() {
      Serial.begin(115200);
      Serial.println("AFE4404 basic readings -\n");
      A.init();
    }

    void loop() {
      Serial.print("LED 1 Val = ");
      Serial.print(A.get_led1_val());
      Serial.print("\t LED 2 Val = ");
      Serial.print(A.get_led2_val());
      Serial.print("\t LED 3 Val = ");
      Serial.print(A.get_led3_val());
      Serial.println();
    }

This is the library I found that uses the Heart Rate 3 Clickers LEDs: https://github.com/rakshithbk/AFE4404-Library

title: How do I measure the analog PPG signals from my Arduino Nano that's wired up to the Heart Rate 3 Clicker

Answers: 0


body:
I am working on a project where I am trying to determine respiration rate through an Arduino Nano and a MikroE Heart Rate 3 Click device.  I have been working on this for a few months, reading different research papers attempting to find an algorithm that would give me respiration rate values, but am having trouble finding an algorithm that both does what I need and encode it into the Arduino.  Does anyone know of a code that would work?
I have so far have only the basic code that reads the PPG values, but it does not provide me with the Respiration rate values.  This is the code I have so far:

    /*
     * AFE4404 Basic Read library example.
     * https://github.com/rakshithbk/AFE4404-Library
     *
     * On Arduino Uno -  | AFE4404 | Uno Pin
     *                   | I2C_Dat | A4
     *                   | I2C_Clk | A5
     * get_led_val() will return uint32_t values.
     *
     * Advanced - you can modify the sample period and other
     * parameters in the library files (refer AFE4404 datasheet)
     */

    #include <Wire.h>
    #include <AFE_connect.h>

    AFE A;

    void setup() {
      Serial.begin(115200);
      Serial.println("AFE4404 basic readings -\n");
      A.init();
    }

    void loop() {
      Serial.print("LED 1 Val = ");
      Serial.print(A.get_led1_val());
      Serial.print("\t LED 2 Val = ");
      Serial.print(A.get_led2_val());
      Serial.print("\t LED 3 Val = ");
      Serial.print(A.get_led3_val());
      Serial.println();
    }

title: How to use an Arduino along with a PPG sensor to find respiration rate

Answers: 0


body:
I am using the "MIKROE Heart Rate 3 click" PPG sensor (https://www.mikroe.com/heart-rate-3-click) and an Arduino Nano (https://store.arduino.cc/usa/arduino-nano) to find heart rate estimation. Does someone know what code to use?

The library associated to the MIKROE is unavailable, therefore, I tried using the AFE4404 library through the code shown below and running a separate algorithm for finding heart rate, however, once I ran it, the monitor and plotter do not provide any peaks that must be used to run the algorithms.

PPG TEST CODE (used previously but do not know how to find heart rate)

```c++
/*
 * AFE4404 Basic Read library example.
 * https://github.com/rakshithbk/AFE4404-Library
 *
 * On Arduino Uno -  | AFE4404 | Uno Pin
 *                   | I2C_Dat | A4
 *                   | I2C_Clk | A5
 * get_led_val() will return uint32_t values.
 *
 * Advanced - you can modify the sample period and other
 * parameters in the library files (refer AFE4404 datasheet)
 */

#include <Wire.h>
#include <AFE_connect.h>

AFE A;

void setup() {
  Serial.begin(115200);
  Serial.println("AFE4404 basic readings -\n");
  A.init();
}

void loop() {
  Serial.print("LED 1 Val = ");
  Serial.print(A.get_led1_val());
  Serial.print("\t LED 2 Val = ");
  Serial.print(A.get_led2_val());
  Serial.print("\t LED 3 Val = ");
  Serial.print(A.get_led3_val());
  Serial.println();
}
```

GitHub
rakshithbk/AFE4404-Library
Basic Library of AFE4404 for Arduino Uno. Contribute to rakshithbk/AFE4404-Library development by creating an account on GitHub.

title: Code for Heart Rate Detection using PPG Sensor

Answers: 0


body:
I have a problem with transmiter (Arduino uno) and receiver (Arduino nao). When I am trsmiting that I receive that: [![][1]][1]

  [1]: https://i.stack.imgur.com/8t6IG.png

An this is my code for receiver

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN  7
    #define CSN_PIN 8

    const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

    RF24 radio(CE_PIN, CSN_PIN);

    char dataReceived[10]; // this must match dataToSend in the TX
    bool newData = false;

    //===========

        void setup() {

            Serial.begin(9600);

            Serial.println("SimpleRx Starting");
            radio.begin();
            radio.setDataRate( RF24_250KBPS );
            radio.openReadingPipe(1, thisSlaveAddress);
            radio.startListening();
        }

        //=============

        void loop() {
            getData();
            showData();
        }

        //==============

        void getData() {
            if ( radio.available() ) {
                radio.read( &dataReceived, sizeof(dataReceived) );
                newData = true;
            }
        }

        void showData() {
            if (newData == true) {
                Serial.print("Data received ");
                Serial.println(dataReceived);
                newData = false;
            }
        }

and transmitter

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN  7
    #define CSN_PIN 8

    const byte slaveAddress[5] = {'R','x','A','A','A'};

    RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

    char dataToSend[10] = "Message 0";
    char txNum = '0';

    unsigned long currentMillis;
    unsigned long prevMillis;
    unsigned long txIntervalMillis = 1000; // send once per second

    void setup() {

        Serial.begin(9600);

        Serial.println("SimpleTx Starting");

        radio.begin();
        radio.setDataRate( RF24_250KBPS );
        radio.setRetries(3,5); // delay, count
        radio.openWritingPipe(slaveAddress);
    }

    //====================

    void loop() {
        currentMillis = millis();
        if (currentMillis - prevMillis >= txIntervalMillis) {
            send();
            prevMillis = millis();
        }
    }

    //====================

    void send() {

        bool rslt;
        rslt = radio.write( &dataToSend, sizeof(dataToSend) );
            // Always use sizeof() as it gives the size as the number of bytes.
            // For example if dataToSend was an int sizeof() would correctly return 2

        Serial.print("Data Sent ");
        Serial.print(dataToSend);
        if (rslt) {
            Serial.println("  Acknowledge received");
            updateMessage();
        }
        else {
            Serial.println("  Tx failed");
        }
    }

    //================

    void updateMessage() {
            // so you can see that new data is being sent
        txNum += 1;
        if (txNum > '9') {
            txNum = '0';
        }
        dataToSend[8] = txNum;
    }

Do you see an error?

title: Arduino NRF24LO1

Answers: 0


body:
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.

title: Converting an int to an unsigned char for display on a Nokia 5110

Answers: 1

body:
> 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.


body:
I found a simple code online that meets my goal to almost 100%, however when I place my hand in front of it, the number continues to count. I am trying to only count "1" when the solid object has moved from initial view of the sensor, to ending view.

    #define trigPin 13
    #define echoPin 12
    int counter = 0;
    int currentState = 0;
    int previousState = 0;

    void setup() {
     Serial.begin (9600);
     pinMode(trigPin, OUTPUT);
     pinMode(echoPin, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
     long duration, distance;
     digitalWrite(trigPin, LOW);
     delayMicroseconds(2);
     digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);
     digitalWrite(trigPin, LOW);
     duration = pulseIn(echoPin, HIGH);
     distance = (duration/2) / 29.1;
     if (distance <= 10){
     currentState = 1;
     }
     else {

title: How do you count objects (using ultrasonic sensor HCSR04) as 1, after they leave the trigger/echo path?

Answers: 0


body:
I'm looking to make a DIY version of [Dan Conrad's Spectrabloom][1]. 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][2].

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?

  [1]: http://www.chromaccord.net/spectrabloom/
  [2]: https://learn.sparkfun.com/tutorials/picobuck-hookup-guide-v12

title: Spectrabloom LED light box

Answers: 2

body: 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.

body:
> 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.


body: 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

title: Electronics Laboratory

Answers: 2

body:
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!

body:
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][1]), 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.

  [1]: https://arduino.stackexchange.com/questions/73393/making-cases-for-projects/73395#73395


body:
Heeya Guys!
Today I created a project with the help of instructables site. I followed the on screen steps and everything. Uploaded the sketch and it works like a charm, but there's one problem.

Everything works correctly but not the "Day", i.e as of today its Friday, 9 April 2021, the clock shows the correct time and date but it tells that today is "Tuesday" in place of Friday. I don't know why this is happening.
Any help would be appreciated :)
Here's the code that I'm using:

```c++
/*Arduino Clock by AnthoTRONICS
* Last edit: March 22,2019
*/
// Libraries you'll need (Same as the ones in the guide:
// TAKE NOTE OF THE VERSIONS!!!

// MD Parola 3.0.1: https://github.com/MajicDesigns/MD_Parola // click the link to download the library
// MD_MAX72XX 3.0.2: https://github.com/MajicDesigns/MD_MAX72XX //click the link to download the library
// DS3231 1.0.2: https://github.com/NorthernWidget/DS3231 // click the link to download

/*CODE:*/
// Header file includes
// These are for the matrix
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#include "Font_Data.h"

//These are for the clock
#include <DS3231.h>
#include <Wire.h>
DS3231 Clock;

bool Century=false;
bool h12;
bool PM;
byte  dd,mm,yyy;
uint16_t  h, m, s;

#define MAX_DEVICES 4 // Set the number of devices
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
// NOTE: These pin numbers will probably not work with your hardware and may
// need to be adapted
#define CLK_PIN   13
#define DATA_PIN  11
#define CS_PIN    10

// Hardware SPI connection
MD_Parola P = MD_Parola(HARDWARE_TYPE,CS_PIN, MAX_DEVICES);

#define SPEED_TIME 75 // speed of the transition
#define PAUSE_TIME  0

#define MAX_MESG  20

// Global variables
char szTime[9];    // mm:ss\0
char szMesg[MAX_MESG+1] = "";

uint8_t degC[] = { 6, 3, 3, 56, 68, 68, 68 }; // Deg C
uint8_t degF[] = { 6, 3, 3, 124, 20, 20, 4 }; // Deg F

char *mon2str(uint8_t mon, char *psz, uint8_t len)

// Get a label from PROGMEM into a char array
{
  static const __FlashStringHelper* str[] =
  {
    F("Jan"), F("Feb"), F("Mar"), F("Apr"),
    F("May"), F("Jun"), F("Jul"), F("Aug"),
    F("Sep"), F("Oct"), F("Nov"), F("Dec")
  };

  strncpy_P(psz, (const char PROGMEM *)str[mon-1], len);
  psz[len] = '\0';

  return(psz);
}

char *dow2str(uint8_t code, char *psz, uint8_t len)
{
  static const __FlashStringHelper*  str[] =
  {
  F("Sunday"), F("Monday"), F("Tuesday"),
  F("Wednesday"), F("Thursday"), F("Friday"),
  F("Saturday"), F("Sunday")
  };

  strncpy_P(psz, (const char PROGMEM *)str[code-1], len);
  psz[len] = '\0';

  return(psz);
}
// Time Setup: Code for reading clock time
void getTime(char *psz, bool f = true)
{
  s = Clock.getSecond();
  m = Clock.getMinute();
  h =Clock.getHour(h12,PM); //24hr Format
  sprintf(psz, "d%cd", h, (f ? ':' : ' '), m);
  //12hr Format
  //uncomment if you want the clock to be in 12hr Format
  /*if (Clock.getHour(h12,PM)>=13 || Clock.getHour(h12,PM)==0)
  {
    h = Clock.getHour(h12,PM) - 12;
  }
  else
  {
    h = Clock.getHour(h12,PM);
  }*/

}

void getDate(char *psz)
// Date Setup: Code for reading clock date
{
   char  szBuf[10];

   dd=Clock.getDate();
   mm=Clock.getMonth(Century); //12
   yyy=Clock.getYear();
   sprintf(psz, "%d %s d",dd , mon2str(mm, szBuf, sizeof(szBuf)-1),(yyy + 2000));
 //strcpy(szMesg, "29 Feb 2016");
}

void setup(void)
{
  P.begin(2);
  P.setInvert(false); //we don't want to invert anything so it is set to false
  Wire.begin();

  P.setZone(0,  MAX_DEVICES-4, MAX_DEVICES-1);

  P.setZone(1, MAX_DEVICES-4, MAX_DEVICES-1);
  P.displayZoneText(1, szTime, PA_CENTER, SPEED_TIME, PAUSE_TIME, PA_PRINT, PA_NO_EFFECT);

  P.displayZoneText(0, szMesg, PA_CENTER, SPEED_TIME, 0,PA_PRINT , PA_NO_EFFECT);

  P.addChar('$', degC);
  P.addChar('&', degF);

}

void loop(void)
{
  static uint32_t lastTime = 0; // millis() memory
  static uint8_t  display = 0;  // current display mode
  static bool flasher = false;  // seconds passing flasher

  P.displayAnimate();

   if (P.getZoneStatus(0))
  {
    switch (display)
    {
      case 0:    // Temperature deg C
      P.setPause(0,1000);
      //P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_UP);
      P.setTextEffect(0, PA_MESH, PA_BLINDS);
      display++;
      dtostrf(Clock.getTemperature(), 3, 1, szMesg);
      strcat(szMesg, "$");
      //strcat(szMesg, "26.5$");

        break;

      case 1: // Temperature deg F
        //P.setTextEffect(0, PA_SCROLL_UP, PA_SCROLL_LEFT);
        P.setTextEffect(0, PA_OPENING, PA_GROW_DOWN);
        display++;
        dtostrf((1.8 *Clock.getTemperature() )+32, 3, 1, szMesg);
        strcat(szMesg, "&");

   // strcpy(szMesg, "71.6&");

        break;

      case 2: // Clock

     P.setFont(0, numeric7Seg);
     P.setTextEffect(0, PA_PRINT, PA_NO_EFFECT);
     //Sleep Mode
     //Uncomment to enable Sleep Mode and adjust the hours to your needs
     /*if (h==12 || h<8)//Time intervals (in this case, from 12AM to 8AM)
     {
      P.setIntensity(0); //Set display brightness to lowest setting
     }
     else
     {
      P.setIntensity(6); //Set display brightness to 6 (15 is the brighest)
     }*/
     P.setPause(0,0);

     if (millis() - lastTime >= 1000)
    {
    lastTime = millis();
    getTime(szMesg, flasher);
    flasher = !flasher;
    }
    if(s==00&& s<=30){
    display++;
    P.setTextEffect(0, PA_PRINT, PA_SCROLL_UP);
    }

    //  strcpy(szMesg, "36 % RH");

        break;

      case 3: // day of week

        P.setFont(0,nullptr);
        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        display++;
        dow2str(Clock.getDoW()+1, szMesg, MAX_MESG); // Added +1 to get correct DoW

       //dow2str(5, szMesg, MAX_MESG);
        break;
      default:  // Calendar

        P.setTextEffect(0, PA_SCROLL_LEFT, PA_SCROLL_LEFT);
        display = 0;
        getDate(szMesg);
        break;
    }

    P.displayReset(0);
  }

}
```

title: DS3231 Clock project shows right date but wrong day

Answers: 2

body:
The library seems to be [addressing device register 3][1].
According to the [DS3231 datasheet][2] this register has valid values 1-7, with 1 being Sunday.

You have:

```c++
dow2str(Clock.getDoW()+1, szMesg, MAX_MESG);
```

1-7 becomes 2-8.  And then, how `dow2str`:

```c++
strncpy_P(psz, (const char PROGMEM *)str[code-1], len);
```

2-8, become array indices 1-7.

Your array is:
```c++
  static const __FlashStringHelper*  str[] =
  {
  F("Sunday"), F("Monday"), F("Tuesday"),
  F("Wednesday"), F("Thursday"), F("Friday"),
  F("Saturday"), F("Sunday")
  };
```

The indices here start at 0, so everything is off-by-one.  But, I don't know how you get Tuesday out of Friday.  If you cut your code down to something smaller that is testable without the display code, just using `Serial`, you'll probably get better answers.

  [1]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.cpp#L226
  [2]: https://datasheets.maximintegrated.com/en/ds/DS3231.pdf

body:
I did this project and my weekday was off by 1, always a day earlier I fixed this by removing the Sunday at the beginning of the list and moving it to the end why you had two Sunday entries I do not know. That fixed my issue. I do not know why yours is showing Tuesday for Friday though.

char *dow2str(uint8_t code, char *psz, uint8_t len)
{
  static const __FlashStringHelper* str[] =
  {
    F("Monday"), F("Tuesday"),
    F("Wednesday"), F("Thursday"), F("Friday"),
    F("Saturday"),F("Sunday")
  }


body:
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.

title: Communication between two Arduinos using ENC28J60?

Answers: 1

body:
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();
   }
```


body:
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.[![enter image description here][1]][1]

R1 = 1k

  [1]: https://i.stack.imgur.com/PaQyn.png

title: Is it possible to use the same power source for the arduino and a high current

Answers: 1

body: 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.


body:
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
    }

title: What is the difference between serial begin() and wire.setClock() for I2C communication?

Answers: 2

body:
`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.

body:
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.


body:
<!-- language-all: cpp -->
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.

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?

Answers: 1

body:
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(){
       ;
    }


body:
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.

[![ESP32S v1.1 NODEMCU][1]][1]

[![ESP32 DEVKITV1][2]][2]

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][3])?  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?

  [1]: https://i.stack.imgur.com/rCx7E.png
  [2]: https://i.stack.imgur.com/5yhC9.png
  [3]: https://en.wikipedia.org/wiki/NodeMCU

title: ESP32S v1.1 NodeMcu vs ESP32 DevKitV1

Answers: 1

body:
The [DevKit][1] is a development board by ESP32 manufacturer [Espressif][2] to demonstrate ESP32 usage and to support prototyping.

The NodeMcu is a board by [NodeMcu][3] 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".

  [1]: https://www.espressif.com/en/products/devkits/esp32-devkitc
  [2]: https://www.espressif.com/
  [3]: https://www.nodemcu.com/index_en.html


body:
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();
    }

title: Init a calss inside a class

Answers: 2

body:
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.

body:
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:

```c++
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][].

[rule of three]: https://en.wikipedia.org/wiki/Rule_of_three_(C++_programming)