body:
I'm using a powerbank speced 5V at 2.4A to power my Teensy 3.6 via the USB port. However, Teensy recommends to not pull more than 250 mA from its 3.3V pin.

Is there any way I can pull more current, at either 3.3V or 5V, without splicing the USB cable? I will use it to control WS2812(b?) LEDs.

title: Pull more than 250 mA from powerbank-powered Teensy 3.6

Answers: 1

body:
The Teensy 3.6 breaks out the USB input power on the VUSB pin (labeled on on the back).

This is the raw 5V in from the USB connector before it feeds the 3.3V voltage regulator.

See the schematics at the bottom of [this page][1]

  [1]: https://www.pjrc.com/store/teensy36.html#tech


body:
I've come across an interesting yet old article within StackExchange which has great examples of sending structured variables over serial communications. The library StreamSend.h and it's source code no longer exist on this site and I'm finding it difficult to track down. The examples shown look good and I'd like to use them in my application. My application is communication of large amounts of data between an ESP8266 and a Arduino UNO (both are combined on the same PCBA) via UART serial.

This is the article I'm referring to:

https://arduino.stackexchange.com/questions/203/sending-large-amounts-of-serial-data

Can somebody send me the StreamSend.h library please or alternative methods for sending large amounts of data over serial (by large amounts of data I mean reading/writing say 10 to 20 variables of various data types so struct would suit well). Thank you.

Regards,

Brian

title: I'm looking for the StreamSend.h library for use in Arduino/ESP8266 serial communications using struct

Answers: 0


body: Can I use the Micromod nrf52840 processor module, Micromod ATP carrier, with Nano 33 type bootloader and modify the ArduinoBLE library or modify the MBED OS abstraction layer and make a promiscuous BLE sniffer that will output something, preferably a Wireshark compatible capture file to the main serial COM port and save the output from arduino IDE?

title: Micromod nrf52840 sniffer

Answers: 0


body:
I am trying to understand how to wire this Arduino Uno shield properly.

**My goal/main questions:** I have 6 servo motors and I am trying to wire them properly to this shield. Do I need an external battery pack? If yes, how do I wire that? I need all the wiring details because I cannot find information about this shield anywhere.

I've provided an actual photo of the shield and I even made a schema for you guys, if somebody wants to draw. I bought this arduino + servos + shield from aliexpress and there wasn't any documentation, explanation, schema or anything like that for that specific shield.
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/62KUA.png
  [2]: https://i.stack.imgur.com/ygc9S.jpg
  [3]: https://i.stack.imgur.com/FbrVU.jpg

Useful info:
- Servos are MG996.
- 4 motor && 16 servo board - name of the shield
- http://doit.am - website of the maker
- https://github.com/SmartArduino/SZDOITWiKi/wiki/Module-Preface - An incredibly cramped and unclear github that the maker provided for more info but it's yet again, unclear.

Conclusive question: Do I even need this shield at all? Can I just use a regular UNO to be able to freely operate with 6 servos?

------
CODE UPDATE:

    #include <Servo.h>

    Servo myservo;

    void setup() {
      myservo.attach(2);
    }

    void loop() {
      myservo.write(0);
      delay(1000);
      myservo.write(90);
      delay(1000);
    }

title: How to use this specific arduino shield

Answers: 1

body:
> Do I even need this shield at all? Can I just use a regular UNO to be able to freely operate with 6 servos?

You don't really need this shield for 6 servos. The standard servo library supports 12 servos on the Uno by using a hardware timer. In your case the shield would mainly help with

- Freeing up the hardware timer (in the case you need it)
- Providing a dedicated power line to the servos (since the current for the servos should not run through the Arduino)

If that is enough for you to still use the shield, you can absolutely do that.

>  I need all the wiring details because I cannot find information about this shield anywhere.

If you look at the wiki (whose link you provided) and navigate to the [page for this shield][1] you will see this diagram

[![enter image description here][2]][2]

- The servos are connected to the header names "16 road servo", each having the pins (from top to bottom in the image) PWM signal, positive power and ground.

- At the header marked "insert short circuit module" you can use jumpers to select the handling of the power supply, which you connect left to that to the terminals marked supply power. It is not described clearly there, but I would read the following meaning:
  - The VM terminal is used for the motor voltage. You might choose to provide your motors with a different voltage than 5V. If you set the jumper between VM and Vin you can connect that power input to the Vin input of the Arduino, thus powering it from the same power source as the motors (Vin goes to the Arduinos voltage regulator to get the voltage down to 5V). If your power supply is still just 5V, you should leave the jumper out and connect the power supply directly to the VM input (and of course also its ground).
  - Vs should be the power input for the logic circuit of the shield. If you put a jumper between the pins Vs and +5V, you will connect the power of the logic circuit on the shield to the 5V line of the Arduino. I would suggest doing that, because then you don't need to provide Vs from outside.

The other headers are for DC motors and for different modules, which can be connected.

> Do I need an external battery pack?

Here it is important to know, how you are powering the Arduino and how much current the servos need. [This datasheet of the MG996][3] states a stall current of 2.5A, way too much for the Arduino to handle and also way to much for any normal USB port (which will give you up to 500mA). As stated above, you should never run that much current through the Arduino. Provide the motors with power from a power source capable of providing the needed current (+ some headroom). If that is a battery pack or a power supply connect to mains is up to you.

  [1]: https://github.com/SmartArduino/SZDOITWiKi/wiki/2-4ch-DC-motor-&-16ch-servo-shield---motor-and-servo-shield
  [2]: https://i.stack.imgur.com/ftRrq.jpg
  [3]: http://www.electronicoscaldas.com/datasheet/MG996R_Tower-Pro.pdf


body:
I'm trying to use nrf2401 as transmitter on ESP32-cam module.
I'm programming with Arduino IDE, but I'm not sure how to set the pins.
I know that the board has 2 SPI interfaces. The first one is for the SD card built-in module.
The second one should be free.
Those are the pins for the second SPI:
**MOSI - 13,
MISO - 12,
CLK - 14,
CS 15**

Here is my code - https://pastebin.com/qEC3JA1d

Where should I define my pins for the SPI?

title: ESP32 cam module SPI and NRF

Answers: 0


body: I working on the system where ESP8266-01 should continuously on because I want to get the Wi-Fi function on. In that case ,I can't use the Sleep mode which is given in the Esp8266-01 . So, My Question is that "How much will current(mA) dropped if the esp8266-01 continuously on in 4.2 LiPo battery??

title: How Much mA dropped in ESP8266-01 Work in LiPo Battery if the WIFI function is continuously on

Answers: 2

body:
**The short answer** is - we don't know.

**Longer answer**:
It depends on such factors as:
1) The board circuit (the BBBL (known as The Big Bright Blue LED) on some boards could drain about 10-20ma only by itself)
2) The voltage regulator efficiency
3) The battery controller circuit / quality / keying efficiency.

**The reasonable value** is about 170-220 mA (taken [from the PDF][1], section 5.2) for continuous data transfer.

[![enter image description here][2]][2]

**The true solution is**:
Take the ammeter, connect it *in series with the battery* and measure.

  [1]: https://www.espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf
  [2]: https://i.stack.imgur.com/wlcVO.png

body:
If you really don't sleep at all you can count with about 70 mA, with some short spikes when transmitting.

Sleep mode disabled:

[![No sleep][1]][1]

(100 mA per division)

But you **don't need to disable sleep mode** completely to use Wifi, you can be in Auto Light Sleep, which I think is the default for Arduino, Non-OS and RTOS.

Auto Light Sleep:

[![Auto Light Sleep][2]][2]

(100 mA per division)

The Wifi will automatically wake up to transmit and it will also wake up according to the Access Points DTIM interval to receive (usually every 300 ms). You're looking at about 2 mA baseline consumption plus the Wifi send and receive spikes.

Unfortunately after bootup there is a 10 second interval with full 70 mA consumption before the Auto Light Sleep mode kicks in. That's a significant drain if you have frequent system resets, but it might have been a bug that has been fixed in the meantime. (I took those measurements in 2017 with the Arduino SDK.)

There are [other modes](https://blog.creations.de/?p=149), but these were the ones that matter in your case.

  [1]: https://i.stack.imgur.com/2W10Y.jpg
  [2]: https://i.stack.imgur.com/B1xtU.jpg


body:
Im trying to assign a static IP to my ESP32 and also set the host name.
I am able to get one or the other to work, but not get them to **work together**.

Tried moving around WiFi.hostname & WiFi.config in the code, tried WiFi.begin and then setting hostname & IP

    #include <WiFi.h>
    void setup() {

    IPAddress local_IP(192, 168, 1, 100);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress primaryDNS(208, 67, 222, 222);
    IPAddress secondaryDNS(208, 67, 220, 220);

    WiFi.mode(WIFI_STA);
    WiFi.hostname("ESP");
    WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
    WiFi.begin("xxxx", "yyyy");

    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    }
    }

**question in a question:**
The WiFi.config that that gives me a static IP is in the format local_IP, gateway, subnet, primaryDNS, secondaryDNS but the documentation for WiFi.config 2 (and also looking at the library WiFi.h code) is ip, dns, gateway, subnet.

and according to the documentation this should also work, but doesn't WiFi.config (ip)

title: Assign static IP and set host name

Answers: 1

body:
There is no such thing as a hostname associated with a specific device.

* When you request an IP from your router using DHCP the ESP32 has the option (which it uses) to tell the router what it'd like to be called. The router may, if it chooses, decide to inject that name into DNS lookups done through the router to resolve that allocated IP address.
* You can manually "advertise" a name through the mDNS protocol which requires the inclusion and use of another library and some more configuration in your sketch, along with mDNS support in the devices and applications doing the name lookup (it is getting more universally implemented but is by no means certain to be available).

Since you're not using either DHCP to obtain your IP, nor using mDNS to advertise your name, there is no mechanism that exists to magically make your device have a "name" on your network.

The simplest method to "get around" the issue is to just use DHCP and let your router do all the work. If you really want a static IP address then configure your router to provide a static IP address to your device.


body:
Like subject all ready telling you, I blew up my 3th Nano every.

I mounted them on a perf board, soldered with 99% tin 1.0mm and a Flux, cleaned with flux remover, etc... When I then power them up through USB I have a short on pin 29 and 30 (Vin Gnd). And the board is ready to go directly in the poubelle (the garbage thing).

Second and third time, after soldering I scratched the space between both pins to make sure there is no connection. But...
Yip again. Is this a common issue? Am I overseeing something?

Did my measurements with multimeter. No shorts.

[![pins][1]][1]

[![board][2]][2]

[![layout][3]][3]

[![pinout][4]][4]

  [1]: https://i.stack.imgur.com/Xnj0X.jpg
  [2]: https://i.stack.imgur.com/sqUIT.jpg
  [3]: https://i.stack.imgur.com/JU1su.jpg
  [4]: https://i.stack.imgur.com/OYGoN.png

title: 3th time blown à Nano every

Answers: 1

body:
If i am not wrong you have soldered nano directly to the  perf board, which i don't recommend at all. You could try soldering a female strip pin on to the pref board and insert the nano board in the strip pin. This way you could easily remove/install the board easily as you wish.
[![enter image description here][1]][1]

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


body:
I have the HM-10 Arduino BLE module. I am also building an app to send and read characteristics on the BLE module. On the Arduino BLE side of things though, how do I set up which characteristic listens for which kind of data?

So, if the BLE module has 1 service containing two characteristics the first one being read-only and the second one being write-only. On my android app, I can find the UUIDs of these two characteristics and perform read and write operations on the corresponding characteristics. But how would I go about initializing which characteristic on the BLE module should expect which kind of operation?

All I see other people do is they perform BLE.read and BLE.write functions to accomplish this. But if you have multiple characteristics and some that can do both kinds of operations, how do you distinguish between them in the code? Does the BLE module only think of the characteristics as one entity that can either be read to or written to, whereas the android app needs to know which is which? The HM-10 documentation talks about setting up the characteristic UUID but talks about pins on the chip to control things, which is weird because the arduino already has pins that you can use.

Worst case scenario, I guess I could just look at ArduinoBlue or Dabble's arduino source code.

title: configuring characteristics to communicate data on the Arduino bluetooth low enegy module

Answers: 0


body:
Or maybe you guys can point me towards another direction...

You may ask, why not connect the device directly to the PC?

Well, the device is designed to recognize only USB sticks, and dump the data into them, so I cannot just plug my PC into it and retrieve the data (as far as I know...), because the PC acts as a USB host (I think).

So I thought about using an arduino and make it act as a USB stick, and then pass the data from the arduino to the PC.

Is this possible? Or maybe what I need is a raspberry pi?

Every suggestion is welcomed. Thank you in advance!

title: Can I use an arduino as an interface to pass files between a device and a PC?

Answers: 1

body:
You have a device that saves information to a USB stick, is that right? Like a scanner or some sort of temperature logger?

To emulate a USB stick would be quite a task, because what you would have to do is pretend that you have a file system, as your device will be opening files, writing to them, and closing them.

It sounds like a lot of work - it might be easier to get another device that actually logs to something like a serial port.

Having said that, it seems on the face of it to be a reasonable request. Just as an example, I have a scanner that writes to a USB stick. It would be handy to have it send files directly to my PC without having to move the USB stick around all the time.

See [Make a computer act as a virtual USB device for other equipments](https://unix.stackexchange.com/questions/120368/make-a-computer-act-as-a-virtual-usb-device-for-other-equipments/401518#401518) as an example of a similar question, with answers suggesting that it might be possible, for example USB-USB cables.

Even if you got it to work, it might be tedious to use. For instance, if your gadget appends to some file on what it thinks is a USB stick you would have to emulate that file system, and then check on your PC if the file has got larger, and thus have new data on it.

Plus possibly the expense (and time) involved in getting this working might be more than just getting another gadget that actually logs via some sort of port, like serial or RS485.


body:
I just migrated to a new computer running on an M1 CPU (the new Apple Silicon, arm64 based). I've been searching for CH34x drivers for my TTGO-Lora32 board, but can't find any around, nor can I find mentions of them existing or not. The x86_64 driver installs, but obviously can't run due to it being an incompatible architecture.

Thus, is it currently possible to use a CH34x based board on an M1 Mac?

title: Is there an Apple Silicon (M1) driver for CH34x devices?

Answers: 4

body:
As it turns out, I found in the following post:

https://github.com/LilyGO/LILYGO-T-OI/issues/3#issuecomment-907645945

a link to a particular build of the CH340 drivers that is properly signed and can be installed on the M1 mac with no troubles.

body:
So they pushed a new version to GitHub late september:

https://github.com/WCHSoftGroup/ch34xser_macos

This should be the maintained version ahead of what they offer as a download on the official website.

Common other issues:

- When reinstalling, make sure to first remove all old files:
```
sudo rm –rf /var/db/receipts/*CH34xVCPDriver*.*
sudo rm -rf /Library/Extensions/CH34xVCPDriver.kext
```
also don't forget to check for any related files in `/dev/` and the .app file in your applications folder if these already exist.

- Restart the device before reinstalling.

- Restart the device after installation.

- Try a different USB-Cable / USB-Hub.

Note: steps listed here were reportedly solutions I came across during my research which worked for other people and my colleagues. <s>For me it still doesn't work; but I am using a lot of unstable builds for my OS and other software that might interfere.</s>

**Update February 2022:** Now with Monterey out of closed Beta this works like a charm for me. At least for the Web IDE.

body:
After hours of mindless reinstalling of the drivers on M1, reboots and other magic tricks, I almost decided to switch to windows to make my arduino ide work. My NodeMCU board with CH340G would either show up as a serial port or not.

So I leave this message here as clearly many people struggling with M1 end up on this page: buy good microUSB cable. And I mean a good one. All problems disappeared right away. I had three cables at home but none was working - clearly most are only good for charging the phone, but suck at data transfer.

body:
Worth the try. The .pkg file from here worked in my High Sierra. I've turned-on the "csrutil enable" before install, and it still worked...:

https://github.com/WCHSoftGroup/ch34xser_macos


body:
I'am looking for a way to obfuscate string at compile time on my personal board build with an SAMD21, i'am using Arduino IDE to compile and upload code. All solution I've found [like this one][1] for example doesn't work with Arduino IDE beceause it's for c++14 (using `constexpr` doesn't compile) is there a solution working for Arduino?

  [1]: https://github.com/adamyaxley/Obfuscate

title: Obfuscate string with on SAMD21

Answers: 0


body:
I'm trying to make my B103348 joystick control a DC motor but I'm getting very unstable values from it specifically when the y axis is at 0. This is what my Serial monitor shows...

> 0,
21,
21,
21,
0,
22,
23,
21,
21...

This is the wiring...

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

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

And here's the code...

```c++
int y_pin = A0;
int y_val;

int in_1 = 3;
int in_2 = 4;
int clock_wise_speed;
int counter_clock_wise_speed;

int en = 2;

int dt = 500;

void setup() {
pinMode(y_pin, INPUT);

pinMode(en, OUTPUT);
pinMode(in_1, OUTPUT);
pinMode(in_2, OUTPUT);

Serial.begin(2000000);
}

void loop() {
  //Clock wise = in_1 LOW and in_2 HIGH.
  //Counter clock wise = in_1 HIGH and in_2 LOW.
  y_val = analogRead(y_pin);
  clock_wise_speed = .21994 * y_val;
  counter_clock_wise_speed = 90;

  if(y_val >= 506){
    analogWrite(en, clock_wise_speed);
    digitalWrite(in_1, LOW);
    digitalWrite(in_2, HIGH);
  }

  if(y_val >= 501 and y_val <= 505){
    digitalWrite(en, LOW);
  }

  if(y_val <= 500){
    analogWrite(en, 225);
    digitalWrite(in_1, HIGH);
    digitalWrite(in_2, LOW);
  }

Serial.println(y_val);
delay(dt);
}
```
Thanks in advance.

title: I'm getting really unstable analog values with my B103348 joystick

Answers: 0


body:
I can't make function the NEO-6M-0-001 GPS module, this is the third one that already bought! I'm using an ATmega2560 as microcontroller for obtaining the data from the module and seems that the module never initializes.

I bought an USB-UART converter for checking if there is something that I did wrong (soldering, bad wiring, burned circuit, etc.). I connected the the module to the converter, opened the serial monitor to see what is happening and this is what I found:

```
$GPRMC,,V,,,,,,,,,,N*53
$GPVTG,,,,,,,,,N*30
$GPGGA,,,,,,0,00,99.99,,,,,,*48
$GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
$GPGSV,4,1,15,02,,,23,05,,,23,07,,,21,12,,,22*78
$GPGSV,4,2,15,13,,,22,16,,,22,17,,,23,18,,,22*70
$GPGSV,4,3,15,19,,,22,20,,,22,21,,,22,24,,,22*74
$GPGSV,4,4,15,26,,,22,27,,,22,50,,,27*7C
$GPGLL,,,,,,V,N*64
```

Seems that the data is missing, or I have to some how initialize the module. This is happening with the three modules. In the picture you can see the antenna that I'm using, I'm outdoors testing it. By the way, its true that without antenna the gps could be damaged?

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

I really appreciate if someone could help, thank you.

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

title: How to know if GPS module is dead?

Answers: 0


body:
Basically I have a keypad, that when a certain code is entered, it will write either "Wrong code" or "Good code" on the LCD.

At the same time a timer will count down until 0 is reached, in which case the whole LCD will display something (undecided/irrelevant).

I have tested the keypad module/part of the file, and it works exactly as expected. Each loop is entered correctly, and I have tested this part several times.

The problem, I believe, lies with the LCD. It will initialize, i.e It will display
"Time:
 Code:"

But then, what comes after feels like it is randomly decided.

Sometimes I can press 1 button, and it will be printed to the serial. Other times I can press more. Sometimes it will lag for every button press, sometimes it will only be the first button press that is slow.

Secondly, if I try to re-run the script nothing will happen. I have another script (see the 2nd code,) that will usually do the trick.

But all of this takes forever. My code is suppossed to run independently, such that I can play multiple code games, will this obstruct it? Any ways to fix it?

Main code:

    #include <Keypad.h>
    #include <LiquidCrystal_I2C.h>

    //LCD Setup
    LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    //Keypad Setting

      char resetTrigger = '*';

    //KeypadCodes

      String goodCode1 = "3569";
      String goodCode2 = "69696969";
      String enteredCode = "";
      //Len has to be declared before the "checker" loop
      int len = enteredCode.length();

    const byte ROWS = 4; /* four rows */
    const byte COLS = 4; /* four columns */
    /* define the symbols on the buttons of the keypads */
    char hexaKeys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };
    byte rowPins[ROWS] = {10, 9, 8, 7}; /* connect to the row pinouts of the keypad */
    byte colPins[COLS] = {6, 5, 4, 3}; /* connect to the column pinouts of the keypad */

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

    void setup(){
    Serial.begin(9600);
    lcd.init();
    lcd.backlight();
    lcd.clear();
    //Sets "Timer: " in the top and "Code: " in the bottom
    lcd.setCursor(0,0);
    lcd.print("Time:");
    lcd.setCursor(0,1);
    lcd.print("Code: ");
    }

    void loop(){
      char customKey = customKeypad.getKey();
      len = enteredCode.length();

      if (customKey){
        //Reset Trigger
      if (customKey == resetTrigger){
        //LCD clear code
        enteredCode = "";
        Serial.println(enteredCode);
        Serial.println("Reset trigger");
        len = enteredCode.length();
      }

      //Char added to code
      else{
        enteredCode.concat(customKey);
        Serial.println(enteredCode);
        Serial.println("Char added to code");
        lcd.setCursor(5,1);
        lcd.print(enteredCode);
        len = enteredCode.length();
      }
        //Correct code
      if ((enteredCode == goodCode1) or (enteredCode == goodCode2)){
        //LCD Correct Code
        //Good sound
        //Door open
        lcd.setCursor(2,0);
        lcd.print("Correct code");
        delay(1);
        Serial.println("Correct code");
      }
      //Wrong code
      if ((len==8) && (enteredCode != goodCode1) && (enteredCode != goodCode2)){
        //LCD clear code
        //Bad sound
        enteredCode = "";
        Serial.println(enteredCode);
        Serial.println("Wrong code");
        //Changes the LCD to wrong code, waits 2 secs and then back to code
        lcd.setCursor(2,0);
        lcd.print("Wrong code!");
        len = 0;
        delay(2);
        lcd.setCursor(2,0);
        lcd.print("Code:");
      }}

    }

2nd code (reset code):

    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    void setup()
    {
      lcd.init();                      // initialize the lcd
      // Print a message to the LCD.
      lcd.backlight();
      lcd.clear();
    }

    void loop()
    {
    }

EDIT:

So now it will work more regularly after changing it from (LiquidCrystal_I2C lcd(0x27,16,2)) -> LiquidCrystal_I2C lcd(0x27,20,4).

I am still having problems with it though.

I have noticed, that sometimes it won't update the screen unless I physically nudge the LCD-screen, which is weird.

Also if it runs for "too long," the screen will stop updating at all.

Maybe a hardware issue?

title: I2C 16x2 LCD - Will Initialize (sometimes) - Holds Up The Code

Answers: 0


body:
I am trying to implement a research paper for my project and there is a formula which I am failing to interpret:

[![Formula][1]][1]

According to the research paper, we extract the static acceleration component for each axis µ, (i=X, Y, Z) by using a running mean filter (the formula), where t is time index, win_size is the window size, and ,∗ is the acceleration data, respectively.

The research paper using MPU6050 to implement this formula. My question is how do I calculate these values using MPU6050. I am currently using [MPU6050_Light.h][2] library to calculate acceleration values and I have no idea where to move from here.

Help would be greatly appreciated.

  [1]: https://i.stack.imgur.com/CFp3Y.png
  [2]: https://github.com/rfetick/MPU6050_light/blob/master/documentation_MPU6050_light.pdf

title: Extract Static Acceleration from MPU6050 using Formula

Answers: 0


body:
So I'm trying to control 4 servo motors simultaneously using the Protothreads library by Ben Artin, but I am starting with 2 just to see if it works.

I have succeeded in getting two LEDs to blink at the same time but at different frequencies.

When I try to connect the 2 servo motors using exactly the same technique as the LEDs to get them to sweep simultaneously, they don't work together. Only one works.

Below is the code I am using:

```
#include <protothreads.h>
#include <Servo.h>

Servo myservo1;
Servo myservo2;

int pos1 = 0;
int pos2 = 0;

////////////////////////     T H R E A D    1     /////////////////////////

pt ptServo1;
int servoThread1(struct pt* pt) {
  PT_BEGIN(pt);
  for(;;) {
    for (pos1 = 0; pos1 <= 180; pos1 += 1) {
      // in steps of 1 degree
      myservo1.write(pos1);
      delay(2);
    }
    delay(500);
    for (pos1 = 180; pos1 >= 0; pos1 -= 1) {
      myservo1.write(pos1);
      delay(2);
    }
    delay(500);
  }
  PT_END(pt);
}

////////////////////////     T H R E A D    2     /////////////////////////
pt ptServo2;
int servoThread2(struct pt* pt) {
  PT_BEGIN(pt);
  for(;;) {
    for (pos2 = 0; pos2 <= 180; pos2 += 1) {
      // in steps of 1 degree
      myservo2.write(pos2);
      delay(2);
    }
    delay(500);
    for (pos2 = 180; pos2 >= 0; pos2 -= 1) {
      myservo2.write(pos2);
      delay(2);
    }
    delay(500);
  }
  PT_END(pt);
}

void setup() {
  myservo1.attach(9);
  myservo2.attach(6);
}

void loop() {
  PT_SCHEDULE(servoThread2(&ptServo2));
  PT_SCHEDULE(servoThread1(&ptServo1));
}

```

In the loop() function, whichever thread is called first, that's the servo that sweeps. The second servo does not do anything at all.

Any help would be greatly appreciated!

Thank you so much,

H

title: How to control multiple servo motors simultaneously using protothreading?

Answers: 0


body:
I'm trying to use protothreading to control two (and eventually four) servo motors over I2C using a PCA9685 PWM board.

To start, I am simply trying to sweep the two motors back and fourth at the same time.

Here is the code I am using:

```
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#include <protothreads.h>

#define SERVOMIN  150
#define SERVOMAX  600
#define USMIN  600
#define USMAX  2400
#define SERVO_FREQ 50

int servo1 = 0;
int servo2 = 4;

////////////////////////     T H R E A D    1     /////////////////////////

pt ptServo1;
int Servo1Thread(struct pt* pt){
  PT_BEGIN(pt);
  for(;;){
    for (uint16_t microsec = USMIN; microsec < USMAX; microsec++) {
      pwm.writeMicroseconds(servo1, microsec);
    }
    PT_SLEEP(pt, 500);
    for (uint16_t microsec = USMAX; microsec > USMIN; microsec--) {
      pwm.writeMicroseconds(servo1, microsec);
    }
    PT_SLEEP(pt, 500);
  }
  PT_END(pt);
}

////////////////////////     T H R E A D    2     /////////////////////////

pt ptServo2;
int Servo2Thread(struct pt* pt){
  PT_BEGIN(pt);
  for(;;){
    for (uint16_t microsec = USMIN; microsec < USMAX; microsec++) {
      pwm.writeMicroseconds(servo2, microsec);
    }
    PT_SLEEP(pt, 500);
    for (uint16_t microsec = USMAX; microsec > USMIN; microsec--) {
      pwm.writeMicroseconds(servo2, microsec);
    }
    PT_SLEEP(pt, 500);
  }
  PT_END(pt);
}

////////////////////////////////////////////////////////////////////////////

void setup() {
  Serial.begin(9600);
  PT_INIT(&ptServo1);
  PT_INIT(&ptServo2);
  pwm.begin();
  pwm.setOscillatorFrequency(27000000);
  pwm.setPWMFreq(SERVO_FREQ);  // Analog servos run at ~50 Hz updates
}

void loop() {
  PT_SCHEDULE(Servo1Thread(&ptServo1));
  PT_SCHEDULE(Servo2Thread(&ptServo2));
}

```

I am noticing that Servo 1 turns to -90 and stops. While it has stopped, Servo 2 turns to -90 and then stops....then Servo 1 turns to +90 and stops and so on. They are not doing the sweeping at the same time.

Any help would be greatly appreciated!

Thank you,

H

title: How to control multiple servo motors at the same time with protothreading using an I2C PCA9685 PWM board?

Answers: 1

body:
Without knowing Protothread in detail: It is most likely handling the threadchange during `PT_SLEEP()`, which you are only executing after one "sweep" (one of the inner for loops), not giving any opportunity to change to the other thread.

Additionally this way you don't have any delay in the inner for loops, thus they get executed very fast. Faster than the motor really can follow. This means, that the servo just moves to the end position as fast as it can and the for loop is essentially useless. You need a delay inside the inner for loops for slowing the signal down.

Please try something like this:

    pt ptServo1;
    int Servo1Thread(struct pt* pt){
      PT_BEGIN(pt);
      for(;;){
        for (uint16_t microsec = USMIN; microsec < USMAX; microsec++) {
          pwm.writeMicroseconds(servo1, microsec);
          PT_SLEEP(pt, 50);
        }
        PT_SLEEP(pt, 500);
        for (uint16_t microsec = USMAX; microsec > USMIN; microsec--) {
          pwm.writeMicroseconds(servo1, microsec);
          PT_SLEEP(pt, 50);
        }
        PT_SLEEP(pt, 500);
      }
      PT_END(pt);
    }

Change the sleep time in the inner loop according to your wanted sweep speed.


body:
[MINI ARDUCAM MODULE CAMERA SHIELD - 2MP OV2640](https://robu.in/product/arducam-mini-module-camera-shield-with-ov2640-2-mp-lens-for-arduino/)

[Arducam Multi-camera adapter board for Arduino SPI Mini Camera](https://robu.in/product/arducam-multi-camera-adapter-board-for-arduino-spi-mini-camera/)

I have the above two components with me along with ARDUINO UNO R3.
I want to stream video using these. ARDUCAM provides library for this.

[**ARDUCAM LIBRARY**](https://github.com/ArduCAM/Arduino)

[**ARDUCAM DATASHEET**](https://www.arducam.com/downloads/shields/ArduCAM_Camera_Shield_Software_Application_Note.pdf)

When I have chosen example program **ArduCAM_Shield_V2_Video_Streaming** and tried uploading it to Arduino it showed no ***ArduCAM.h: No such file or directory***.

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

I have downloaded the library and kept it in the libraries folder of ARDUINO.

Can someone help me out with this??

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

title: Mini Arducam module camera shield - 2MP ov2640 interface with Arduino Uno

Answers: 1

body:
The Uno which you mention has 2 KB of RAM. 2 MP of data would be 2,000,000 x 3 bytes (red, green, and blue), in other words 6 MB.

The screenshot you showed seems to show that the library is designed to take a still photo and buffer it. As you might imagine, buffering 6 MB would take a while, especially as you can only fit 2 KB at a time.

You simply won't be streaming video using the Uno, so the error message is more-or-less irrelevant.

It might be relevant if you actually wanted to take single photos and send them.

In that case, you probably haven't installed the library properly.


body:
1. I am using a SIM808 module. It's working fine with normal MQTT over TCP, but does not work when trying secured MQTT.

2. I sent `AT+SSLSETROOT="C:\USER\HENRY_SSL.CRT"` to set the root certificate (see this document: "SIM800 Series_MQTT_Application Note_V1.03"). The response I'm getting from the GSM is: `+CME ERROR: unknown`.

3. When I try `AT+SMSSL=1`, I get the same error. I checked with HTTP commands and it's working fine, but the `AT+HTTPSSL=1` command does not work. The SIM808 does not respond to SSL related commands.

But as per the Simcom website, the SIM808 does support SSL. Do I need to upgrade any firmware?

title: SIM808 does not support SSL related AT commands

Answers: 1

body: I updated the firmware version: 1418B05SIM808M32. Now all commands are working fine.


body:
My project is to use an Arduino to control two solenoid valves with pwm and receive an input signal from a sensor as feedback.

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

As can be seen from the picture, the valves direct the flow of water which cause a hydraulic actuator to move which is detected by an LVDT sensor.

What I want my program to do is to allow me to set a desired displacement as a goal which causes the Arduino to dynamically change the duty cycle of the pwm frequency based off of the feedback input the Arduino receives.

I am a total novice programmer and its my first time working with electronics. I'm just hoping someone can point me in the right direction.

Based off of youtube videos this is the code I've written.

    int myPin1=3;
    int myPin2=5;
    int readPin=A3;

    //V2 is input from sensor
    int V2=0;
    int delayTime=50;
    float D1=0.5;
    float D2=0.5;
    int readVal;

    int goal=;

    void setup() {
      // Set pin states:
      pinMode(myPin1,OUTPUT);
      pinMode(myPin2,OUTPUT);
      pinMode(readPin,INPUT);
      Serial.begin(9600);

      //set frequency of the PWM pins
      SetPinFrequencySafe(myPin1, 1000);
      SetPinFrequencySafe(myPin2, 1000);
    }

    void loop() {
      // Volatge reading from the VTLD:
      readVal=(5/1023)analogRead(readPin);
      V2 = (5./1023.)*readVal
      Serial.print("Voltage is ");
      Serial.println(V2);

      //PWM for the 2 output pins
      analogWrite(myPin1,D1);

      analogWrite(myPin1,D2);
      delay(delayTime);

      //Varying of dutcy cycle untill getting the desired actuator position
    while (V2!=goal) {
      if (V2>goal) {
        D1=D1+0.01;
        D2=D2-0.01;
      }
       if (V2<goal) {
        D1=D1-0.01;
        D2=D2+0.01;
      }
    }
      if (V2=goal) {
        D1=0.5
        D2=0.5
      }

    }

I have seen people using PID libraries but I'm not sure which one is suitable to use for my project.

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

title: I need help making an arduino control system

Answers: 0


body: I'm using the GP2Y0A21YK Sharp IR Sensor in a ball and beam system where I'm trying to balance the ball in the center of the beam using the IR Sensor as a distance locator and a servo motor to tilt the beam. I'm using a PID Controller for the system. However, something odd happens when I apply the code. When the servo motor is disconnected, I'm getting accurate readings of the location of the ball. However, as soon as I plug in the servo motor, the distance reading is completely off and inaccurate. I've read that powering the Arduino using both the USB port and Plug will make the readings more stable. However, I've tried that and it only improved the readings by a small bit. What can be causing this problem? Since the code and the schematic would take a bit of a space, kindly let me know if they are needed and I'm happy to provide.

title: Mixed SHARP IR Sensor Readings

Answers: 1

body:
It is likely your power source supplies insufficient current to power both the servo and the Arduino reliably.

It is also possible that the motor in the servo is creating noise on the power rails and inducing unexpected behavior in the Arduino.  But the former is more likely.

Consider using a power source which can supply more current.  For instance, [D size cell][1] batteries can supply much more current than a [small 9 volt battery][2].

Also consider using a separate power source for the Arduino and the motor.  Many resort to this option for such projects as you describe here.

  [1]: https://en.wikipedia.org/wiki/D_battery
  [2]: https://en.wikipedia.org/wiki/Nine-volt_battery


body:
I work With VS Code v:1.59.1.
With extension vscode-arduino v:0.4.4

befor update of vscode. in version 1.58. all was ok. I can build and upload code for all mucrocontrollers.

but after the update, I can build code for arduino uno.
but when i build the code for esp32, i get this error:

    [Starting] Analyzing sketch 'emptyProjct.ino'
    [Warning] Output path is not specified. Unable to reuse previously compiled files. Build will be slower. See README.
    Cargando configuración...
    Inicializando paquetes...
    Preparando tarjetas...
    Verficando...
    c:/users/hassan daoud/documents/arduino/hardware/espressif/esp32/tools/xtensa-esp32-elf/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: final link failed: bad value
    collect2.exe: error: ld returned 1 exit status
    exit status 1
    IntelliSense configuration already up to date. To manually rebuild your IntelliSense configuration run "Ctrl+Alt+I"
    [Error] Analyzing sketch 'emptyProjct.ino': Exit with code=1

other thing. in the right of status bar. in [Select Programmer], I can't show any programmer for ESP32, but when i change board to arduino uno, i can select from a lot of choises.

this screenshot is for adruino uno.
[![enter image description here][1]][1]

and this is for esp32 wroom
[![enter image description here][2]][2]

after the update of vscode I try to download another extension like [Espressif IDF]. because [vscode-arduino] dont fix the error of serial port.

I contact with [Espressif IDF] for an error in instalation and him tel me to download the sdk in a path with out spasing. and then its work. but the old library I download from Arduino IDE for ESP32 its work in the prev. ver.
with space in the path.

so I dont know if the problem is from the new library or what happen. but I cant build code for ESP32.

please help me
thank you a lot to all.

  [1]: https://i.stack.imgur.com/hwHMP.jpg
  [2]: https://i.stack.imgur.com/NKEab.jpg

title: Compiler error: final link failed: bad value collect2.exe

Answers: 1

body:
OK, I fix the error.

I remove all library for esp32 in my computer

    c:/users/hassan daoud/documents/arduino/hardware/
    c:/users/hassan daoud/appdata/local/arduino15/packages/

and install again from board manager.

all work ok


body:
The nano is inside of the house, and the pro mini is outside of the house. I want to send/receive text between them. The communication will be always nano sending text to mini, and then mini sending text to pro in response. There will be no case where mini sends text on its own first.

The line has three wires, but since I have to power the mini with that line, one is used for VCC and another is used for ground, leaving only one wire free. It this case, can I do UART communication between the two? If so, how should I connect the wire to them (including the ground)? And on the software side, how should I handle the communication? Could you give a simple code example in which nano sends "Hello" to pro mini, and then pro mini, after receiving "hello", sends "World" to nano?

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

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

title: Bi-directional UART communication on single data wire, possible?

Answers: 4

body:
This question likely suffers from the [X Y problem][1].  Where the question (about software) and possible answer (centered on hardware) do not approach the solution using the same methods.

The question is essentially asking how to design a [1-wire][2] interface over longer than normal distances. There are [1-wire Arduino libraries][3] and [1-wire Arduino tutorials][4]. But it is likely you will run into problems if your cable is very long.

Guessing at the distance you want to run your 3 wires (power, ground and data), this may be more an electrical engineering than a software problem.

**Power:**

All wires have resistance.  Using a voltage drop calculator from [here][5] we can calculate, assuming we are trying to send 5V over an 18 AWG copper wire 100 meters long to a 250mA load, an expected voltage drop of slightly over a volt.  That may cause unexpected results.

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

If this might be an issue, consider an alternate power source such as batteries, solar power or a second mains power adapter for the far Arduino.  It may even be considered to over drive the power lines several volts and regulate the voltage at the far end Arduino.

**Data:**

Reference to ground type data transmission is more susceptible to error the longer the cable run.  Several options to mitigating unexpected behavior can be made.  However switching over to a balanced pair is usually the best option.

**Options:**

If you are willing to power the far Arduino independently or add 1 additional data wire (either of these options will make available 2 wires for data) we can run the data portion of the cable for a good distance while mitigating noise problems associated with long communication cable runs.

**Try RS485:**

Consider using an [RS485][7] hardware interface at the near and far Arduino.  RS485 interfaces can be source easily for Arduino projects ([here][8] and [here][9] are two examples) and there are [Arduino RS485 software libraries][10] which handle the communications.

The intent of the project was not disclosed in the question.  However [here][11] is an example RS485 project where connected Arduinos communicate the position of a potentiometer such that the RS485 connected Arduino at the far end can mimic the potentiometer's movements on a motor driven servo.

The keen eye may note that the above project only uses 2 wires between the two Arduinos.  This is possible because in the above project the two Arduinos are independently powered (this is not seen in the diagram on the linked to web page).  Additionally, RS485 uses a balanced pair of signals (the 2 wires) and does not need to run an additional ground between the two Arduinos as a reference to detect the difference between 1s and 0s.

  [1]: https://en.wikipedia.org/wiki/XY_problem
  [2]: https://en.wikipedia.org/wiki/1-Wire
  [3]: https://www.arduino.cc/reference/en/libraries/onewire/
  [4]: https://www.hacktronics.com/Tutorials/arduino-1-wire-tutorial.html
  [5]: https://www.rapidtables.com/calc/wire/voltage-drop-calculator.html
  [6]: https://i.stack.imgur.com/SGoJu.png
  [7]: https://en.wikipedia.org/wiki/RS-485
  [8]: https://www.sparkfun.com/products/10124
  [9]: https://www.dfrobot.com/product-1024.html
  [10]: https://github.com/arduino-libraries/ArduinoRS485
  [11]: https://create.arduino.cc/projecthub/maurizfa-13216008-arthur-jogy-13216037-agha-maretha-13216095/modbus-rs-485-using-arduino-c055b5

body:
You can have bidirectional communication over a single wire by using
[open-collector][] outputs. For this, you could add a circuit like this
on each side of the link:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/93mZ7.png)

<!-- End schematic -->

Here, TX is the transmit pin of the Arduino, and DATA is the data wire.
The RX pin is connected directly to the data wire and, while writing
your sketches, you should account for the fact that anything you send
will be received back by the sender as an “echo”.

This scheme will slow down your signal transitions, limiting the maximum
achievable baud rate. Start with something conservative, like
9600 bps, and lower further if it doesn't work reliably.

[open-collector]: https://en.wikipedia.org/wiki/Open_collector

body:
An example of protocol using a single wire (besides ground, so a total of 2) for both bi-directional communication AND power: [Dallas 1-wire][1]

There are few other similar standard protocols and you are free to think about your own as long as you are willing to implement all the internals instead of using a well-written and widely used library.

  [1]: https://en.wikipedia.org/wiki/1-Wire

body: You could do it by using one wire for ground, one wire for nano->mini, and one wire for mini->nano.  The nano->mini wire carries both power and data.  You can keep it at some voltage above ground to provide the power and superimpose a data signal that is AC coupled off at the mini end.  Alternately, you can rectify the data to provide power if you make sure to send 01010101 whenever you don't have something else to say.


body:
I am testing communication between two nRF24L01 modules. The receiver is getting the transmitted message but is also continuously reading (null) data from a closed pipe? I am using the RF24 by TMRh20 version 1.3.12 library on an Arduino Pro Mini with some modified example code. Has anyone else experienced this phenomenon or have any fix for the issue?

Transmitter:
```
/*
* Arduino Wireless Communication Tutorial
*     Example 1 - Transmitter Code
*
* by Dejan Nedelkovski, www.HowToMechatronics.com
*
* Library: TMRh20/RF24, https://github.com/tmrh20/RF24/
*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  printf_begin();
  while (!Serial);
  Serial.println("[radioSend]");
  if (radio.begin()) {
    Serial.println("Radio Receiver starting");
  } else {
    Serial.println("Radio Receiver start failed");
    while (1);
  }
  radio.setChannel(120);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  radio.printPrettyDetails();
}
void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(10000);
}
```

Receiver:
```
/*
* Arduino Wireless Communication Tutorial
*       Example 1 - Receiver Code
*
* by Dejan Nedelkovski, www.HowToMechatronics.com
*
* Library: TMRh20/RF24, https://github.com/tmrh20/RF24/
*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
long counter = 0;
void setup() {
  Serial.begin(9600);
  printf_begin();
  while (!Serial);
  Serial.println("[radioReceive]");
  if (radio.begin()) {
    Serial.println("Radio Receiver starting");
  } else {
    Serial.println("Radio Receiver start failed");
    while (1);
  }
  radio.setChannel(120);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
  radio.printPrettyDetails();
}
int dpls3;
char text3[32] = "";
void loop() {
  uint8_t pipeNum;
  if (radio.available(&pipeNum)) {
    int dpls = radio.getDynamicPayloadSize();
    char text[32] = "";
    radio.read(&text, sizeof(text));
    if (pipeNum != 3) {
      Serial.print("[Pipe=");
      Serial.print(pipeNum);
      Serial.print("|Size=");
      Serial.print(dpls);
      Serial.print("|");
      Serial.print(text);
      Serial.print("] [Pipe=3|Size=");
      Serial.print(dpls3);
      Serial.print("|");
      Serial.print(text3);
      Serial.print("|Count=");
      Serial.print(counter);
      Serial.println("]");
    } else {
      memcpy(&text3, &text, 32);
      counter += 1;
      dpls3 = dpls;
    }
  }
}
```

Transmitter output:
```
[radioSend]
Radio Receiver starting
SPI Frequency  = 10 Mhz
Channel   = 120 (~ 2520 MHz)
RF Data Rate  = 1 MBPS
RF Power Amplifier = PA_MIN
RF Low Noise Amplifier = Enabled
CRC Length  = 16 bits
Address Length  = 5 bytes
Static Payload Length = 32 bytes
Auto Retry Delay = 1500 microseconds
Auto Retry Attempts = 15 maximum
Packets lost on
    current channel = 0
Retry attempts made for
    last transmission = 0
Multicast  = Disabled
Custom ACK Payload = Disabled
Dynamic Payloads = Disabled
Auto Acknowledgment = Enabled
Primary Mode  = TX
TX address  = 0x3130303030
pipe 0 ( open ) bound = 0x3130303030
pipe 1 ( open ) bound = 0xc2c2c2c2c2
pipe 2 (closed) bound = 0xc3
pipe 3 (closed) bound = 0xc4
pipe 4 (closed) bound = 0xc5
pipe 5 (closed) bound = 0xc6
```

Receiver output:
```
[radioReceive]
Radio Receiver starting
SPI Frequency  = 10 Mhz
Channel   = 120 (~ 2520 MHz)
RF Data Rate  = 1 MBPS
RF Power Amplifier = PA_MIN
RF Low Noise Amplifier = Disabled
CRC Length  = 16 bits
Address Length  = 3 bytes
Static Payload Length = 32 bytes
Auto Retry Delay = 250 microseconds
Auto Retry Attempts = 15 maximum
Packets lost on
    current channel = 0
Retry attempts made for
    last transmission = 0
Multicast  = Disabled
Custom ACK Payload = Disabled
Dynamic Payloads = Disabled
Auto Acknowledgment = 0b011111
Primary Mode  = RX
TX address  = 0x1010101010
pipe 0 ( open ) bound = 0x1010101010
pipe 1 (closed) bound = 0x2020270610
pipe 2 (closed) bound = 0xc1
pipe 3 (closed) bound = 0xc0
pipe 4 (closed) bound = 0xc0
pipe 5 (closed) bound = 0xc2
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=195500]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=216665]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=835055]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=882618]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=1168025]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=1310725]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=1405856]
[Pipe=0|Size=32|Hello World] [Pipe=3|Size=0||Count=1500987]
```

title: nRF24L01 continuously reading closed pipe

Answers: 0


body:
i'm trying to play a passive buzzer with an IR reciver

**My Code**

```

#include <IRremote.h>
IRrecv irrecv(10);
decode_results results;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(11, OUTPUT);//buzzer
  irrecv.enableIRIn();//Ir reciver at pin 10
}

int cmdex = 0;

void loop() {
  // put your main code here, to run repeatedly:

  if(irrecv.decode(&results)){
    cmdex = 1;
    Serial.println(results.value);
    unsigned long data = results.value;
    switch(data){
      case 0xFF30CF:
        noTone(11);
        tone(11, 1056);
        break;
      case 0xFF18E7:
        noTone(11);
        tone(11, 571);
        break;
      case 0xFF6897:
        noTone(11);
        break;
    }
    irrecv.resume();
  }
}
```

**Issue**

My problem is that if i use any button instead of 1 (FF30CF) 0 (FF6897) or 2 (FF18E7) the serilal port give me the right data, then when i pusch 1 the buzzer starts to play but when i push another button, the data keep changing at every push.

**Serial Output**
FF10EF *(here I push 4)*

FF38C7 *(here I push 5)*

FF5AA5 *(here I push 6)*

FF30CF *(here I finally push 1 and the buzzer starts to play)*

*(then I push 3 times 0, but the output is different from the expected FF6897 and the buzzer doesn't stop)*

D965AA42

EB670632

AB03A967

**Note**

- I'm using the IRremote.h library

title: Infrared Reciver doesn't work properly after the first signal

Answers: 0


body:
Why I can't use "timeA = delay" to make the lights turn on gradually.
The problem is that the delay don´t work, and the led light goes directly to the last color. What I need to do in my code to fix this?

Here is my code ↓

``` c++
// C++ code
//

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

void loop(){

  static unsigned long timeA = 10;
  const long interval = 10;

  static unsigned long timeB = 10;
  const long interval2 = 10;

  static unsigned long timeC = 10;
  const long interval3 = 10;

  unsigned long delay = millis();
  static unsigned long state = 0;
  int i = 0;

  if(delay - timeA >= interval && state == 0){
    state += 1;
    for(i=0;i<=255;i++){
        analogWrite(3, i);
        analogWrite(5, 0);
        analogWrite(6, 0);
        timeA = delay;
    }
  }
   if(delay - timeB >= interval2 && state == 1){
    state += 1;
    for(i=0;i<=255;i++){
        analogWrite(3, 0);
        analogWrite(5, i);
        analogWrite(6, 0);
        timeB = delay;
    }
  }
  if(delay - timeC >= interval3 && state == 2){
   state += 1;
   for(i=0;i<=255;i++){
        analogWrite(3, 0);
        analogWrite(5, 0);
        analogWrite(6, i);
        timeC = delay;
    }
  }

}
```

title: I want to turn on RGB led gradually

Answers: 2

body:
I think below is what you were going for. I removed the for-loop and used a static `i` variable to have each state take 256 intervals. Note that you don't need to have separate timeA/B/C variables. Using a single one would also make sure that the first "delay" actually occurs. It's not that critical for fading an led, but in other cases it might.

```lang-cpp
void setup()
{
  pinMode(3, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}

void loop(){

  static unsigned long timeA = 10;
  const long interval = 10;

  static unsigned long timeB = 10;
  const long interval2 = 10;

  static unsigned long timeC = 10;
  const long interval3 = 10;

  static unsigned long state = 0;
  static int i = 0;

  unsigned long delay = millis();

  if(delay - timeA >= interval && state == 0){
    analogWrite(3, i);
    analogWrite(5, 0);
    analogWrite(6, 0);
    timeA = delay;

    i++;
    if( i==256 )
    {
      i=0;
      state++;
    }
  }
   if(delay - timeB >= interval2 && state == 1){
    analogWrite(3, 0);
    analogWrite(5, i);
    analogWrite(6, 0);
    timeB = delay;

    i++;
    if( i==256 )
    {
      i=0;
      state++;
    }
  }
  if(delay - timeC >= interval3 && state == 2){
    analogWrite(3, 0);
    analogWrite(5, 0);
    analogWrite(6, i);
    timeC = delay;

    i++;
    if( i==256 )
    {
      i=0;
      state++; // you probably want to use `state=0;`, so it starts over again
    }
  }

}```

body:
You `millis()` code is not structured correctly. Lets look at what happens:

`timeA` and co are all initiated with the value 10. So as soon as the program has run 10ms, the first if statement (the one for state 0) will execute. First you increment `state`, so that the next state can be reached. Then you have a for loop without any timed code. It will execute very very fast, without giving the PWM hardware any chance to actually output the `analogWrite()` values. Then you update `timeA` (which normally wouldn't go into the for loop). We leave the if statement and reach the next one. Nearly no time has passed, since we entered the first if statement. And now we are executing the next if statement, since `state` is now 1 and the program had run for more than 10ms. Here it is the same as above.

So the program is rushing through the `analogWrite()` calls ending in the last one, since `state` is never reset, giving the last `analogWrite()` value the change to be output on the pin.

The whole structure of the code does not really make sense. I guess you wanted to do this non-blocking, thus using `millis()`. For loops are not really fitting to this and the `millis()` value has to be compared to the right values to get the order right.

**What to do now:** With the `state` variable you nearly have something that is called Finite State Machine (FSM). It is a powerful programming concept. Basically the state of the program decides, what block of code should be executed on each `loop()` iteration. This is best done via a switch statement. Then in each case we are using an if statement using the `millis()` value to decide, if it is time to execute the new `analogWrite()`:

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

    void loop(){

      static unsigned long timeA = 10;
      const long interval = 10;

      static unsigned long timeB = 10;
      const long interval2 = 10;

      static unsigned long timeC = 10;
      const long interval3 = 10;

      unsigned long delay = millis();
      static unsigned long state = 0;
      static int i = 0;

      switch(state){
        case 0:
          if(delay - timeA >= interval){
            analogWrite(3, i);
            analogWrite(5, 0);
            analogWrite(6, 0);
            i++;
            timeA = delay;
          }
          if(i > 255){
            state = 1;
            i = 0;
          }
          break;
        case 1:
          if(delay - timeB >= interval2){
            analogWrite(3, 0);
            analogWrite(5, i);
            analogWrite(6, 0);
            i++;
            timeB = delay;
          }
          if(i > 255){
            state = 2;
            i = 0;
          }
          break;
        case 2:
          if(delay - timeC >= interval3){
            analogWrite(3, 0);
            analogWrite(5, 0);
            analogWrite(6, i);
            i++;
            timeC = delay;
          }
          if(i > 255){
            state = 0;
            i = 0;
          }
          break;
      }
    }

By setting the variable `state` we can choose, what should be executed next. The variable `i` is handling the fading of each LED, while the `interval` variables set how fast the fading occurs. This coding principle can be used in many different situations, so learning it is really worth it.

Note:
- I have not tested the above code.
- The code can still be optimized/generalized.


body:
I was trying to get the data from MPU6050 using the Arduino library mentioned [here][1].

The following code is an edited version of the sample code given in the library folder which seems to be working fine.

```
#define printfloatx(Name,Variable,Spaces,Precision,EndTxt) { Serial.print(F(Name)); {char S[(Spaces + Precision + 3)];Serial.print(F(" ")); Serial.print(dtostrf((float)Variable,Spaces,Precision ,S));}Serial.print(F(EndTxt)); }//Name,Variable,Spaces,Precision,EndTxt

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps_V6_12.h"

#include "Wire.h"

MPU6050 accelgyro;
MPU6050 mpu;

I2Cdev a;

/*
    IMU Zero variables
*/

int16_t data_acc[3];
int16_t data_Gyro[3];

/*
   IMU initialization variables
*/
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
bool dmpReady = false;  // set true if DMP init was successful
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)

/*
   IMU angle finding variables
*/
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

Quaternion q;           // [w, x, y, z]         quaternion container
VectorFloat gravity;    // [x, y, z]            gravity vector
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

void Initialize()
{
  // initialize device
  Serial.println("Initializing I2C devices...");
  accelgyro.initialize();

  // verify connection
  Serial.println("Testing device connections...");
  Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
  Serial.println("tuning Each Dot = 100 readings");
  accelgyro.CalibrateAccel(10);
  accelgyro.CalibrateGyro(10);

  a.readWords(0x68, 0x06, 3, (uint16_t *)data_acc);
  a.readWords(0x68, 0x13, 3, (uint16_t *)data_Gyro);
} // Initialize

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Initialize();
  Wire.setClock(400000);
  while (!Serial);
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(data_Gyro[0]);
  mpu.setYGyroOffset(data_Gyro[1]);
  mpu.setZGyroOffset(data_Gyro[2]);
  mpu.setXAccelOffset(data_acc[0]);
  mpu.setYAccelOffset(data_acc[1]);
  mpu.setZAccelOffset(data_acc[2]);

  if (devStatus == 0) {
    // Calibration Time: generate offsets and calibrate our MPU6050
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    Serial.println();
    mpu.PrintActiveOffsets();
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
    mpuIntStatus = mpu.getIntStatus();
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  Serial.println("-------------- done --------------");
} // setup

void loop()
{
  if (!dmpReady) return;
  if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) {
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[2] * 180 / M_PI);
    Serial.println();
  }

}

```

Then I have activated the input capture pin to use with the interrupt and the code is as follows

```
#define printfloatx(Name,Variable,Spaces,Precision,EndTxt) { Serial.print(F(Name)); {char S[(Spaces + Precision + 3)];Serial.print(F(" ")); Serial.print(dtostrf((float)Variable,Spaces,Precision ,S));}Serial.print(F(EndTxt)); }//Name,Variable,Spaces,Precision,EndTxt

#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps_V6_12.h"

#include "Wire.h"

MPU6050 accelgyro;
volatile MPU6050 mpu;

I2Cdev a;

/*
    IMU Zero variables
*/

int16_t data_acc[3];
int16_t data_Gyro[3];

/*
   IMU initialization variables
*/
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
bool dmpReady = false;  // set true if DMP init was successful
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)

/*
   IMU angle finding variables
*/
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

Quaternion q;           // [w, x, y, z]         quaternion container
VectorFloat gravity;    // [x, y, z]            gravity vector
volatile float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

void Initialize()
{
  // initialize device
  Serial.println("Initializing I2C devices...");
  accelgyro.initialize();

  // verify connection
  Serial.println("Testing device connections...");
  Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
  Serial.println("tuning Each Dot = 100 readings");
  accelgyro.CalibrateAccel(10);
  accelgyro.CalibrateGyro(10);

  a.readWords(0x68, 0x06, 3, (uint16_t *)data_acc);
  a.readWords(0x68, 0x13, 3, (uint16_t *)data_Gyro);
} // Initialize

void timer4_initialization() {
  pinMode(49, INPUT);
  TCCR4A = 0; TCCR4B = 0; TCCR4C = 0;
  TCCR4B = B11000000;
  TIFR4 = _BV(ICF4);
  TIMSK4 = B00100000;
}

ISR(TIMER4_CAPT_vect) {
  if (!dmpReady) return;
  if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) {
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
  }
}

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Initialize();
  Wire.setClock(400000);
  while (!Serial);
  Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  Serial.println(F("Testing device connections..."));
  Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

  Serial.println(F("\nSend any character to begin DMP programming and demo: "));
  while (Serial.available() && Serial.read()); // empty buffer
  while (!Serial.available());                 // wait for data
  while (Serial.available() && Serial.read()); // empty buffer again

  // load and configure the DMP
  Serial.println(F("Initializing DMP..."));
  devStatus = mpu.dmpInitialize();

  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(data_Gyro[0]);
  mpu.setYGyroOffset(data_Gyro[1]);
  mpu.setZGyroOffset(data_Gyro[2]);
  mpu.setXAccelOffset(data_acc[0]);
  mpu.setYAccelOffset(data_acc[1]);
  mpu.setZAccelOffset(data_acc[2]);

  if (devStatus == 0) {
    // Calibration Time: generate offsets and calibrate our MPU6050
    mpu.CalibrateAccel(6);
    mpu.CalibrateGyro(6);
    Serial.println();
    mpu.PrintActiveOffsets();
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.print(F("Enabling interrupt detection (Arduino external interrupt "));
    mpuIntStatus = mpu.getIntStatus();
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
  }

  Serial.println("-------------- done --------------");

  delay(2000);

  timer4_initialization();

} // setup

void loop()
{
  Serial.print("ypr\t");
  Serial.print(ypr[0] * 180 / M_PI);
  Serial.print("\t");
  Serial.print(ypr[1] * 180 / M_PI);
  Serial.print("\t");
  Serial.print(ypr[2] * 180 / M_PI);
  Serial.println();
}

```

Here when I am using with the interrupt I am not getting anything printed, seems like the program is frozen somewhere in the interrupt -> function call.

What is the mistake I am making here.

How to take the measurement from MPU6050 using ISR routines.

  [1]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

title: MPU6050 Arduino Jeff Rowberg library interrupt Issue

Answers: 2

body:
The functions `mpu.dmpGetCurrentFIFOPacket(fifoBuffer)`, etc, are using I2C for getting the data. The I2C interface on the Uno and Mega (which you tagged your question with) is implemented in hardware and needs interrupts for handling the data bytes (taking the received byte out of the register or writing data to the register for sending).

By default interrupts are disabled inside of an ISR. Thus the mentioned functions cannot execute correctly. They are waiting for an interrupt, which is never going to happen, since the functions are executed while interrupts are disabled.

It is possible to reactivate interrupts in an ISR, but that is something, that you should only do in a few situations and only, when you know exactly, what you are doing.

Instead you should just set a volatile flag variable inside the ISR. In the main code (in `loop()`) you can then check for that flag, execute the I2C code when it is set and reset the flag afterwards. And you can then also just print, when there is new data instead of every loop iteration. So somewhat like this:

    volatile byte timer_flag = 0;

    ISR(TIMER4_CAPT_vect) {
      timer_flag = 1;
    }

    void loop(){
        if(timer_flag){
            if (!dmpReady) return;
            if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer)) {
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                // then print the values here, since we got new data from the MPU
            }
            timer_flag = 0; // Resetting the flag for the next timer interrupt
        }
    }

body:
I've tweaked chrisl's answer to show how to copy the ISR data and reset the ISR flag  in an atomic manner.

```cpp
volatile bool isr_timer_flag = false;
volatile uint32_t isr_counter = 0;  // Added to demonstrate how to copy a multibyte data type atomically.

ISR(TIMER4_CAPT_vect)
{
 isr_timer_flag = true;
 isr_counter++;
}

void loop()
{
 //
 // Get a copy of the data and reset the flag atomically by temporarily disabling interrupts.
 //

 // Disable interrupts by clearing the global interrupt flag.
 cli();

 // Copy the data.
 bool timer_flag = isr_timer_flag;
 uint32_t counter = isr_counter;

 // Reset the ISR flag for the next timer interrupt.
 // Resetting it here avoids clearing any re-flag during the following if statements.
 isr_timer_flag = false;

 // Enable interrupts by setting the global interrupt flag.
 sei();

    // Now use the local copy of the ISR flag.
    // The ISR flag could be re-flagged at any time during the remainder of the loop,
    // but a fresh copy will be obtained on the next iteration of the loop.

 if (timer_flag)
 {
  if (!dmpReady) return;
  if (mpu.dmpGetCurrentFIFOPacket(fifoBuffer))
  {
   mpu.dmpGetQuaternion(&q, fifoBuffer);
   mpu.dmpGetGravity(&gravity, &q);
   mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
   // then print the values here, since we got new data from the MPU
  }
 }
}
```


body:
I have a setup with serial comm from Raspberry Pi to Arduino. It's communicating at baud 9600 on both devices, and from Raspberry Pi 3b+ GPIO-14,UART0,TX0 to Arduino Nano RX0. There's a level shifter in between setup [as recommended by AdaFruit tutorials][1]. I'm sending data from Raspberry Pi as such:

```py
#loop here
m = []
m.append(255)
m.append(i) // index value between 0-150
m.append(p[0][i]) // value between 0-254
m.append(p[1][i]) // value between 0-254
m.append(p[2][i]) // value between 0-254
#print statement here
'''
Data: [255, 94, 0, 0, 0, 255, 95, 254, 0, 0, 255, 96, 0, 254, 0]
...
'''
```

And receiving data on Arduino as such:

```c
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    byte inChar = (byte)Serial.read();
    sprintf(printString, "Received: %d", inChar);
    Serial.println(printString);
  }
}
/*
Received: 255
Received: 94
Received: 0
Received: 255
Received: 95
Received: 254
Received: 0
Received: 255
Received: 96
Received: 0
Received: 254
Received: 255
Received: 94
Received: 0
Received: 0
Received: 0
Received: 255
Received: 254
Received: 255
...
*/
```

Any idea why there are so many missed bytes and how to fix this?

  [1]: https://learn.adafruit.com/neopixels-on-raspberry-pi/raspberry-pi-wiring

EDIT: @juraj There is a ground between both. I've measured with a portable oscilloscope. I can post the picture of the setup tomorrow.

@Edgar Bonet The loop function is empty, and looks as follows:

```c
void loop() {
}
```

I also don't have any data being sent back to the Raspberry Pi. I have the Serial TX wire out from Arduino completely disconnected

title: So many missed bytes with serial comm

Answers: 1

body:
Without the full codes, we can only guess. My guess would be the serial
receive buffer on the Arduino is overflowing.

One reason this could happen is if `serialEvent()` is not called
frequently enough. This function is called by the Arduino core on every
loop iteration, just after `loop()` returns. If your `loop()` takes too
long (e.g. you are using `delay()` or blocking waits), the receive
buffer can overflow before `serialEvent()` has a chance to empty it.

Another reason is if the Raspberry Pi is sending too much data, too
fast. For every byte the Arduino receives, it must send back
between 13 and 15 bytes. If too much data comes too fast, the transmit
buffer will eventually get full, and then `Serial.println()` becomes
_really slow_, because it has to wait for the bytes to actually get out
on the wire. This in turn slows down `serialEvent()` to the point where
it can make the receive buffer overflow.

**Edit**: If this (the Raspberry sending data too fast) is the cause of
the problem, the obvious solution is to have it send data more slowly,
as:

    repeat:
        send a message
        delay for some suitable time


body:
My sketch below is simply using a touch sensor to activate a servo motor to go from from initial position 0 to 180 then back to 0. then I want the Adruino NANO to go to sleep to conserve some battery life.

Being a novice to programing and after many attempts to use his code and intergrade it with mine. Was unsuccessful.

so if anyone can help intergrade the gammon's sketch below into mine it would be greatly appreciated. As I'm out of ideas.

**HERE IS MY SKETCH**
```cpp
#include <Servo.h>

// constants won't change
const int SENSOR = 2; // Arduino pin connected to motion sensor's pin 7
const int SERVO = 9; // Arduino pin connected to servo motor's pin 9

Servo servo; // create servo object to control a servo

int pos = 0; // variable to store the servo position

// variables will change:
int lastMotionState; // the previous state of motion sensor
int currentMotionState; // the current state of motion sensor

void setup() {

Serial.begin(9600); // initialize serial
pinMode(SENSOR, INPUT); // set arduino pin 9 to input mode
servo.attach(SERVO); // attaches the servo on pin 12 to the servo object

servo.write(0);
currentMotionState = digitalRead(SENSOR);
}

void loop() {
lastMotionState = currentMotionState; // save the last state
currentMotionState = digitalRead(SENSOR); // read new state

if (currentMotionState == LOW && lastMotionState == HIGH) { // pin state change: LOW -> HIGH
Serial.println("OFF");
servo.write(0);
delay(100); // waits (X)ms for the servo to reach the position
}
else
if (currentMotionState == HIGH && lastMotionState == LOW) { // pin state change: HIGH -> LOW
Serial.println("ACTIVE");
servo.write(180);
delay(2000); // waits (x)ms for the servo to reach the position
}
delay(10); // repeats program - larger delay - trigger is
}
```
**______________________________________**

****Author:Ab Kurk**  SLEEP SKETCH**

This sketch is part of the beginners guide to putting your Arduino to sleep
tutorial. It is to demonstrate how to put your arduino into deep sleep and
how to wake it up.

*/
```cpp
#include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
#define interruptPin 2 //Pin we are going to use to wake up the Arduino

void setup() {
Serial.begin(115200);//Start Serial Comunication
pinMode(LED_BUILTIN,OUTPUT);//We use the led on pin 13 to indecate when Arduino is A sleep
pinMode(interruptPin,INPUT_PULLUP);//Set pin d2 to input using the buildin pullup resistor
digitalWrite(LED_BUILTIN,HIGH);//turning LED on
}

void loop() {
delay(5000);//wait 5 seconds before going to sleep
Going_To_Sleep();
}

void Going_To_Sleep(){
sleep_enable();//Enabling sleep mode
attachInterrupt(0, wakeUp, LOW);//attaching a interrupt to pin d2
set_sleep_mode(SLEEP_MODE_PWR_DOWN);//Setting the sleep mode, in our case full sleep
digitalWrite(LED_BUILTIN,LOW);//turning LED off
delay(1000); //wait a second to allow the led to be turned off before going to sleep
sleep_cpu();//activating sleep mode
Serial.println("just woke up!");//next line of code executed after the interrupt
digitalWrite(LED_BUILTIN,HIGH);//turning LED on
}

void wakeUp(){
Serial.println("Interrrupt Fired");//Print message to serial monitor
sleep_disable();//Disable sleep mode

detachInterrupt(0); //Removes the interrupt from pin 2;

}
```

title: Arduino Sleep to conserve battery - How to intergrade it to existing sketch - HELP pls

Answers: 1

body:
I'm going to guess that you are doing something like a door or safe lock, which may occasionally be used to activate a motor to unlock something but 99.99% of the time is sitting there doing nothing, and you want to save power in that time.

You need to rework somewhat.

* An interrupt to detect a switch press. Then the processor can sleep, using very little power.

* The interrupt, when it happens, wakes the processor

* You activate the motor to unlock the door or whatever-it-is.

* You put the processor into low power mode, and go back to sleep

Since my name was mentioned in the question, tips for doing low-power stuff are [at this link](http://www.gammon.com.au/power). And [here for stuff about interrupts](http://www.gammon.com.au/interrupts).

Plus a slightly abridged version (due to space limitations) [here on this site](https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969).

*(You aren't supposed to make answers where the answer is totally in the link, but in this case the link is just supplementary material)*