body:
I have a program to load from a Aduino Nano as ISP to a ATMega328p chip that will have an internal clock at 16M, but I don't have a crystal handy.

Is there a way I can not have to buy a crystal? What should be the circuit's look like?

Here's how I have it hooked:

 1. Ground to Ground (Pin 8)
 2. 5V to VCC (Pin 7)
 3. D10 to Reset (Pin 1)
 4. D11 to MOSI (Pin 17)
 5. D12 to MISO (Pin 18)
 6. D13 to AVCC (Pin 20) (There are no resistors or capacitors, that all was part of a tutorial I cannot find anymore)

So I'm testing now with the basic Blink sketch and here is the resulting terminal comments.

    /Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/b77/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/b77/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/b77/Documents/Arduino/libraries -fqbn=megax8:avr:atmegax8:cpu=328_16 -vid-pid=0403_6001 -ide-version=10816 -build-path /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -warnings=none -build-cache /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avrdude.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /Applications/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
    /Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/b77/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/b77/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/b77/Documents/Arduino/libraries -fqbn=megax8:avr:atmegax8:cpu=328_16 -vid-pid=0403_6001 -ide-version=10816 -build-path /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -warnings=none -build-cache /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avrdude.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -verbose /Applications/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
    Using board 'atmegax8' from platform in folder: /Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3
    Using core 'megax8' from platform in folder: /Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3
    Detecting libraries used...
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /dev/null
    Generating function prototypes...
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/preproc/ctags_target_for_gcc_minus_e.cpp
    /Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/preproc/ctags_target_for_gcc_minus_e.cpp
    Compiling sketch...
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10816 -DARDUINO_ATmegaxX8 -DARDUINO_ARCH_AVR -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/cores/megax8 -I/Users/b77/Library/Arduino15/packages/megax8/hardware/avr/1.0.3/variants/megax8 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp.o
    Compiling libraries...
    Compiling core...
    Using precompiled core: /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_cache_67558/core/core_megax8_avr_atmegax8_cpu_328_16_27f180324ce8b44e5ad3e6dc83e4e5ee.a
    Linking everything together...
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-gcc -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/sketch/Blink.ino.cpp.o /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/../arduino_cache_67558/core/core_megax8_avr_atmegax8_cpu_328_16_27f180324ce8b44e5ad3e6dc83e4e5ee.a -L/var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627 -lm
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.eep
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-objcopy -O ihex -R .eeprom /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.hex
    /Users/b77/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-size -A /var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.elf
    Sketch uses 924 bytes (2%) of program storage space. Maximum is 32768 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    /Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -cstk500v1 -P/dev/cu.usbserial-AC012GAB -b19200 -Uflash:w:/var/folders/hv/kcqzq2sd5sl5kwxjrbq96vs80000gn/T/arduino_build_216627/Blink.ino.hex:i

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

             System wide configuration file is "/Users/b77/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
             User configuration file is "/Users/b77/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/cu.usbserial-AC012GAB
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.04s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.04s

    avrdude: Device signature = 0x000000 (retrying)

    An error occurred while uploading the sketch
    Reading | ################################################## | 100% 0.05s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

From what I've seen online, the device signature being 0x000000 could potentially mean that the lack of crystal may make it impossible for me to do the bootloading. The chip is also brand new and I've tested with more than one as I have 3.

My thought is that I probably read the tutorial wrong especially with the AVCC pin?

In any case, **how should I connect a Nano to an ATMega328p without a crystal?**

Thanks for your help!

title: Bootload from a Nano to an ATMega328 without a crystal

Answers: 1

body:
Alright. After reading some and some more, I was able to notice that SCK, just one pin down from AVCC, was the missing link.

Yet another reminder to properly **read the fabulous manual**.

It looks so easy now.


body:
Good evening,

I am writing Arduino code to flash multiple LEDS at different sequences from different pins. Everything is working well, however I cant determine how to add in a Morse Code A flash sequence.

Ideally the sequence would go 1s, on 1s off, 3s on, 3s off. then repeat continuously, this would be for a MO (A) bouy

Below is the format I have used for all other lights and works well with 8 different sequences.

```cpp
// A is 1s, B is 2.5s, C is 4s, D is 5s, F is 6s, G is 8s, H is 10s ,

#define aLed 2
#define bLed 3
#define cLed 4
#define dLed 5
#define fLed 6
#define gLed 7
#define hLed 8

void setup() {
  pinMode(aLed, OUTPUT); //pin2 Output
  pinMode(bLed, OUTPUT); //pin3 Output
  pinMode(cLed, OUTPUT); //pin4 Output
  pinMode(dLed, OUTPUT); //pin5 Output
  pinMode(fLed, OUTPUT); //pin6 Output
  pinMode(gLed, OUTPUT); //pin7 Output
  pinMode(hLed, OUTPUT); //pin8 Output

}

void loop() {
  BlinkA(1000);
  BlinkB(2500);
  BlinkC(4000);
  BlinkD(5000);
  BlinkF(6000);
  BlinkG(8000);
  BlinkH(10000);

}
 void BlinkA (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(aLed, !digitalRead(aLed));
 }
}
void BlinkB (int interval){
   static long prevMill = 0;
   if (((long)millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(bLed, !digitalRead(bLed));
  }
 }
  void BlinkC (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(cLed, !digitalRead(cLed));
 }
}
 void BlinkD (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(dLed, !digitalRead(dLed));
 }
}
 void BlinkF (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(fLed, !digitalRead(fLed));
 }
}
 void BlinkG (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(gLed, !digitalRead(gLed));
 }
}
 void BlinkH (int interval){
   static long prevMill = 0;
   if ((millis() - prevMill) >= interval){
    prevMill = millis();
    digitalWrite(hLed, !digitalRead(hLed));
 }
}

title: multiple blinking LEDs at different intervals, morse code A included

Answers: 1

body:
> multiple blinking LEDs at different intervals, (*not all periodic*)...

I changed your question hopefully with out changing its meaning.

Based on this question, I would suggest using a [finite state machine][1].  Assuming you are using differently named "BlankI()" functions for each LED, consider adding state machine features to 1 of these functions to control the "*not periodic*" LED.  Consider a state machine with 4 state one for each action:

 0. LED On for 1 second.
 1. LED Off for 1 second.
 2. LED On for 3 seconds.
 3. LED Off for 3 seconds.

Use a counter (either global or static to preserve its value between calls to that function) to track the states.  Use a [switch/case][2] coding pattern to set the "prevMill" to the appropriate time delay for the current state.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/


body: I have included Adafruit_SSD1306.h file however, it still shows me error  such as 'Adafruit_SSD1306_128x64_i2c_init(); was not declared in the scope' Can anyone enlighten me for this?

title: I have this issue on Arduino by stating that Adafruit_SSD1306_128x64_i2c_init(); was not declared in the scope, may I ask why?

Answers: 1

body:
Judging by <https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.h> there is no such function in that file, therefore it doesn't exist. That's why you get that error message.

What makes you think such a function would exist? Do you have a link to what led you to believe that?


body:
I googled and couldn't find a solution to my nice problem:
I have Ubuntu and I want to program a ESP32 ...............
I tried a lot of pip commands ... but it didnt work.
You have any idea how to install the correct packages?
Maybe you can tell me what to do. I am really lost.
I tried it last year and also failed.. Now I want to try it another time :)

       /.arduino15/packages/esp32/tools/esptool_py/3.0.0/esptool.py", line 38, in <module>
            import serial
        ImportError: No module named serial

title: Arduino ESP32 Import Error No module named serial

Answers: 4

body:
Open terminal and enter this command `python -m pip install pyserial` it will download `pyserial` for you and you will not receive the above error. The above error is because you don't have `pyserial` installed on the system.

The related documentation for pyserial could be found [here][1]

  [1]: https://pyserial.readthedocs.io/en/latest/pyserial.html

body: Problem resolved, Thank you.  I had installed pyserial.  The error surprisingly was related to the incorrect processor speed (!) in the Arduino IDE.  I have no idea why that would influence the serial/pyserial function.

body:
I had the same issue compiling the CameraWebServer example. I'm using Ubuntu 20.04. The problem occurs during the linking stage when the script invokes python. On my system this runs the system python which is python 2.7.18. I don't think the serial module (supplied by pyserial) is available on Ubuntu 20.04 for python 2.x.

My solution was first to abandon the Arduino IDE and use the arduino-cli to compile the example. I created a virtual python 3 environment, activated it, installed pyserial under the virtual environment and run arduino-cli to make the runtime. The python scripts appear to be compatible with python 3.

body:
Reference: https://www.how2shout.com/linux/how-to-install-python-2-7-on-ubuntu-20-04-lts/

I think Arduino IDE expects Python2 to be installed. My Version is Arduino-1.8.13
You also need Python2 modules so you need to install pip2

:~/curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py
:~/sudo python2 get-pip.py
:~/pip2 install pytools
:~/pip2 install pyserial


body:
Given below is my loop and it counts 1 to 250 using the push button i just added this part as this one is the main part. I want to make it in steps like one press (push button) SETS IT TO 10 OR 20 ETC. Many thanks in advance for your kindness.

    if ((digitalRead(2)==HIGH) && (digitalRead(7)==LOW))
     {
       if (j<255)
       {j++;
       lcd.setCursor(5,1);
       lcd.print("                ");
       lcd.setCursor(5,1);
       lcd.print(j);
       while((digitalRead(2)==HIGH) && (digitalRead(7)==LOW));}
     }
    else if ((digitalRead(2)==LOW) && (digitalRead(7)==HIGH))
     {
       if (j>0)
       {j--;
       lcd.setCursor(5,1);
       lcd.print("                ");
       lcd.setCursor(5,1);
       lcd.print(j);
       while((digitalRead(2)==LOW) && (digitalRead(7)==HIGH));}
    }

    analogWrite(9,j);
    //lcd.noDisplay();
    lcd.display();
    delay(100);

    }

title: i have problem in generating pwm in steps

Answers: 0


body:
Hello and thanks for any help in advanced.

What changes do I need to make to my code to get rid of the issue of the valve opening up again at end of cycle in "Auto" function.

Hardware:

 - Arduino Mega
 - Bi-polar Stepper Motor connected to Valve.
 - Weighing scale with TTL output.

Here is my code:
```
//Buttons
#include <mechButton.h> //Button Library
#define BTNa_PIN  10    //Button Pins
#define BTNb_PIN  6
mechButton aButton(BTNa_PIN);  // Set button to pin BTN_PIN.
mechButton bButton(BTNb_PIN);

//Stepper
#include <AccelStepper.h> //Stepper Library
#define dirPin 4          //Stepper Pins
#define stepPin 2
#define motorInterfaceType 1 //Interface set to driver
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);// Create a new instance

//Analog inputs for setting Max and Min Distance
const int analogPin = A0;
const int analogPin2 =A1;

//Data types for Scale Reading for Optima OP900a
char inString[32];
float Input;
float Setpoint;
float fSetpoint;

//Setup
void setup() {

  Serial.begin(9600);           // Fire up our serial monitor for arduino and computer
  Serial3.begin(9600);          //Fire up Serial for Scale for input

  aButton.setCallback(Manual);    // Set up our callback. (Also calls hookup() for idling.)
  bButton.setCallback(Auto);
  stepper.setMaxSpeed(3500);      // Set the maximum speed and acceleration for stepper motor:
  stepper.setAcceleration(5000);

  Setpoint = 4.44;               // Auto parameters
  fSetpoint = (Setpoint*0.9);

}
// Main Loop
void loop() {
   bool abuttonState;
   bool bButtonState;

   idle();                      // Let all the idlers have time to do their thing.
   abuttonState = aButton.trueFalse();    // Have a look at what the current button state is.
   bButtonState = bButton.trueFalse();
}
//Sub Functions
void Manual(void) {
    int maxOpen = analogRead(analogPin);
    maxOpen = map(maxOpen, 0, 1023, 0,100);

   Serial.print("Manual ");
   if (aButton.trueFalse()) {
      stepper.moveTo(0);
      stepper.runToPosition();
   } else {
      stepper.moveTo(maxOpen*40);
      stepper.runToPosition();

   }
}

void Auto(void) {
    int maxOpen = analogRead(analogPin);
    int minOpen = analogRead(analogPin2);
    maxOpen = map(maxOpen, 0, 1023, 0,100);
    minOpen = map(minOpen, 0, 1023, 0,100);

   while (Input < Setpoint){
     readScale();
     if (Input >= fSetpoint && Input < Setpoint){
     stepper.runToNewPosition((minOpen*10)+400);  //Blocking function research work around...
     Serial.print("Min");Serial.print(",");       //debugging
     Serial.println(Input);                       //debugging
     }
     else if (Input < fSetpoint) {
     stepper.runToNewPosition(maxOpen*40);         //Blocking function research work around...
     Serial.print("Max");Serial.print(",");       //debugging
     Serial.println(Input);                       //debugging
     }
     else{
     stepper.runToNewPosition(0);                 //Blocking function research work around...
     Serial.print("Close");Serial.print(",");     //debugging
     Serial.println(Input);                       //debugging
     }
     }
}

void readScale(void){
    byte inChar = Serial3.readBytesUntil('\n', inString, 18); //Scale reading for input
    float scaleInput = atof(&inString[7]);
    Input = scaleInput;
  }
```
I keep getting this strange behavior at the end of the "Auto" function where I am getting false 0.00 from the scale that causes the valve to open and close fully at the end.
```
Max,0.01
Max,0.01
Max,0.01
Max,0.00
Max,0.00
Max,0.00
Max,0.00
Max,0.35
Max,0.42
Max,0.51
Max,0.60
Max,0.66
Max,0.69
Max,0.75
Max,0.83
Max,0.88
Max,0.93
Max,1.00
Max,1.05
Max,1.11
Max,1.16
Max,1.21
Max,1.26
Max,1.32
Max,1.38
Max,1.43
Max,1.48
Max,1.53
Max,1.59
Max,1.64
Max,1.68
Max,1.74
Max,1.80
Max,1.84
Max,1.89
Max,1.94
Max,1.99
Max,2.04
Max,2.09
Max,2.14
Max,2.18
Max,2.23
Max,2.27
Max,2.32
Max,2.37
Max,2.41
Max,2.45
Max,2.50
Max,2.55
Max,2.59
Max,2.62
Max,2.68
Max,2.72
Max,2.76
Max,2.81
Max,2.85
Max,2.88
Max,2.93
Max,2.97
Max,3.00
Max,3.04
Max,3.08
Max,3.13
Max,3.17
Max,3.20
Max,3.23
Max,3.27
Max,3.31
Max,3.35
Max,3.39
Max,3.42
Max,3.46
Max,3.50
Max,3.52
Max,3.55
Max,3.60
Max,3.63
Max,3.66
Max,3.69
Max,3.73
Max,3.77
Max,3.80
Max,3.83
Max,3.87
Max,3.91
Max,3.94
Max,3.95
Max,3.98
Min,4.03
Min,4.06
Min,4.09
Min,4.13
Max,0.00
Max,0.00
Min,4.35
MZ��r��j
Min,4.36
Close,4.46
```

Any suggestions are welcome.

Thanks

title: Issue with input from weighing scale controlling a stepper motor based valve

Answers: 1

body:
There are a few issues here:

* `Serial3.readBytesUntil()` does not add a null character at the end of
  the string. You have to do it yourself if you want a properly
  terminated string.

* You are attempting to read a float starting at the eight byte of the
  string, even if you got less than eight bytes.

* `atof()` does not report errors. If it fails to parse a float, it just
  returns zero.

Just to see what may be going wrong, I suggest this version of
`readScale()` with verbose debug output:

```c++
void readScale(void) {
    byte inChar = Serial3.readBytesUntil('\n', inString, 18);
    inString[inChar] = '\0';  // terminate the string
    const char *start = &inString[7];  // where the number is expected
    char *end;  // where strtod() found it ends
    float scaleInput = strtod(start, &end);
    Serial.print("Scale -> \"");
    Serial.print(inString);
    Serial.print("\", parsed \"");
    *end = '\0';  // terminate the string after the number
    Serial.print(start);
    Serial.print("\" as ");
    Serial.println(scaleInput);
    Input = scaleInput;
}
```


body:
I need to transfer information between pyton script and arduino.

Data is always built like this "wheelbase:1000"
wheelbase can be another word and 1000 can be another value, : is always the separator

Here is my python code:
```
import serial.tools.list_ports
import serial
import time

ports = list(serial.tools.list_ports.comports())

for p in ports:
    print(p)

mcustring = str(ports[0]).split(" ")[0]
print(mcustring)

mcu = serial.Serial(mcustring, 9600)
mcu.timeout = 0.1

def write_read(x):
    mcu.write(x.encode())
    time.sleep(0.05)
    data = mcu.readline()
    return data

num = "wheelbase:1000\n"

for i in range(10):
     print(i)
     num = "wheelbase:1000"
     value = write_read(num)
     print(value) # printing the value
     time.sleep(1)        # wait 0.5 seconds
     num = "wheelbase:500"
     value = write_read(num)
     print(value) # printing the value
     time.sleep(1)

value = write_read(num)
print(num) # printing the value
time.sleep(1)

mcu.close()

```

and here is my arduino code:

```
String SerialRead1;
String SerialRead2;
double Wheelbase = 0;
double Level0 = 0;
double Gradient = 0;

void setup() {
  // put your setup code here, to run once:
Serial . begin ( 9600 ) ;        // turn on Serial Port
pinMode(LED_BUILTIN, OUTPUT);

}

void loop() {

  while (Serial.available() > 0) {
  SerialRead1 = Serial.readStringUntil(':') ;
  SerialRead1.trim();
  SerialRead2 = Serial.readStringUntil('\n') ;
  SerialRead2.trim();

  Serial.print ( "string1: " ) ;
  Serial.println(SerialRead1);
  Serial.print ( "string2: " ) ;
  Serial.println(SerialRead2);

  }

  if (SerialRead1 == "wheelbase"){
   Wheelbase = SerialRead2.toDouble();
  }

  if (SerialRead1 == "level"){
   Level0 = SerialRead2.toDouble();
  }

  if (SerialRead1 == "gradient"){
   Gradient = SerialRead2.toDouble();
  }

if (Wheelbase == 1000) {
    digitalWrite(LED_BUILTIN, HIGH);
}
else
{
    digitalWrite(LED_BUILTIN, LOW);
}

}
```

Here is my serial outpout:

```
COM6 - USB-SERIAL CH340 (COM6)
COM6
0
b''
b''
1
b''
b'string1: wheelbase\r\n'
2
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
3
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
4
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
5
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
6
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
7
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
8
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
9
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
```

I don't understand why , for i=0 qnd i = 1 the dqtq is not correctly transfered/received.

The LED blink correctly for i = 2 to 9

title: Serial communication between Python & Arduino:

Answers: 0


body:
I'm using the following class to create a stream from a WiFi (server) connection. The client (a PC application) connects to the ESP32 and then issues commands over this connection. This works fine. When the client disconnects gracefully, the connection is reset and the ESP32 is ready for another connection. Only one client can connect at a time, but that's ok for now.

The problem arises when the client disconnects unexpectedly (e.g. if I just kill the process on the PC). The connection remains open for a very long time (10 minutes or so) until the ESP32 detects that the connection died. Within that time, no new connection can be established. In that state, I can still see it printing "Still connected" messages to the serial console, with reducing pace (the number of messages per second drops significantly until it finally gives up).

Is there a way to reduce the timeout on a dead connection? The (working) connection itself might be idle for long times as well, so just because no messages are received doesn't mean we can drop the connection from the ESP32 end.

The `Connect()` function below is called from `loop()` and in normal mode, it just prints "New client connected" and "client disconnected" messages.
```cpp

class WifiCachingStream : public Stream
{
private:
 WiFiServer _server;
 WiFiClient _activeClient;
 bool _hasActiveClient;
public:
 WifiCachingStream(int port) :
 _server(port), _activeClient()
 {
  _hasActiveClient = false;
 }

 void Init()
 {
  _server.begin();
 }

 bool Connect();

 int read() override;

 size_t write(byte b) override;

 void maintain();

 int available() override
 {
  return _activeClient.available();
 }

 int peek() override
 {
  return _activeClient.peek();
 }

 void flush() override
 {
  // Do nothing. The implementation of WifiClient clears the _INPUT_ queue instead of the output queue!
  // _activeClient.flush();
 }

 bool isConnected() const
 {
  return _hasActiveClient;
 }
};

int idx = 0; // for testing only
bool WifiCachingStream::Connect()
{
 if (_activeClient.available() || _activeClient.connected())
 {
  if ((idx ++) % 10000 == 0)
  {
            // For testing: This is printed to the console, even after the communication has been killed on the PC
   Serial.println("Still connected");
            // This (attempts to) send a message over the link, which I would expect to cause the implementation to detect that the connection was dropped.
   Firmata.sendString(F("Still connected"));
  }
  return true;
 }

 _activeClient.stop();
 _activeClient = _server.accept();

 if (_activeClient)
 {
  Serial.println("New client connected");
  WiFi.setSleep(false);
  _hasActiveClient = true;
  return true;
 }

 if (_hasActiveClient)
 {
  _hasActiveClient = false;
  Serial.println("Client disconnected - entering WiFi low-power mode");
  // Low-power mode significantly increases round-trip time, but when nobody
  // is connected, that's ok.
  WiFi.setSleep(true);
 }

 return false;
}

// Other functions irrelevant
```

title: ESP32 TCP disconnect takes very long to be recognized

Answers: 1

body:
It's more or less a fact of life that having TCP detect a lost connection (ungraceful disconnect) takes a long time when nothing is being sent over it.

There may be some quaint and curious keepalive and time-out settings in the protocol itself, but implementing a heartbeat (call it an application-level keep-alive) that is sent by the client, and closing the connection from the ESP32-end when no heartbeat/keep-alive message has been received for a certain period, is probably your best bet and it will also give you precise control over the time-out time.


body:
I am a mechanical engineer starting my journey with Arduino, so please excuse me if I put some very generalized message.

* I need to sequentially operate 20 output relays, and then verify if the correct relay has been triggered. If the correct relay was triggered, the next relay will be triggered after a delay of 1-2 seconds.
* I plan to do this with an Arduino Uno so that I can generate error messages if any output has not been triggered.

However, the Uno doesn't have sufficient inputs and outputs to do this. So what are my options?

I want to ask you the below:-
1) If there are I/O expansion boards available for the Uno? If yes, sharing the details will be helpful;
2) A friend recommended to use a multiplexer. Can I use a multiplexer to convert a 4 pin output from the Arduino to 16 pin output, and probably use the saved pins to monitor the inputs? If yes, how?
3) Is there something available like a reverse multiplexer wherein the chip can convert the 16 output signals to 4 pin inputs to the Arduino?

Please let me know the best solution wrt the below parameters - reliability of operation, cost, compactness.

Thanks for your time and support.

title: How do I connect 20 outputs and 20 inputs to an Arduino board?

Answers: 2

body: Look for port expansion boards for the arduino, there are a lot of them many under a dollar. Typically they are in 8 or 16 channel designs. They probably will have PCF8574 or PCF8575 chips. These are low voltage (typically 5V) for the Arduino. You will have to use an interface if it is connected to another voltage. Each of these modules the channels can be individually programmed as an input or output. You can turn on or any of the outputs in any order and pattern you want. These devices operate with the I2C interface so you need only two lines from the Arduino to drive up to 8 of these modules. The pins should be labeled A4 (SDA), A5 (SCL) depending on the model of Arduino you have. Good luck!

body: Instead of using expansion boards, you could use an Arduino Mega or an Arduino Due instead. These have more than enough GPIO pins for 20 inputs and 20 outputs. The price isn't much higher compared to the extra expansion board and the extra wiring required.


body:
Well I am making a automatic car parking system where a any one parking their car will get a card as a token and have to return it before leaving with their cars one card for a slot
And if they don't do so the buzzer will go high
There is also a ultrasonic for each slot to check if the car is present or not.

So far I have managed to do all the part except to check or store a value when the card is removed for that I have been searching for a way to make my rfid reader to check for a tag continuously but all I get so far is my reader only respond when there is a card is present.
I am doing my project any way excluding this part but I would love to add it as it will help to increase the security level.

title: Rfid checking continuously for cards

Answers: 0


body:
I have bought some blank ESP-12F modules like this: https://www.aliexpress.com/item/1005001520382593.html

For these modules I have made my own adapter PCB to connect them, but now I don't get any connection with the esptool.py to these modules.

The connection is:
```
TX --------------- RX with an PL2303 USB adapter
RX --------------- TX with an PL2303 USB adapter
EN --------------- 3.3V
GPIO-0 ----------- GND over button
GPIO-15 ---------- GND over 4K7 resistor
RESET ------------ GND over button
GND -------------- GND
VCC -------------- 3.3V from AMS1117-3.3 blocked with Elko 220µF
```

With a serial terminal I can cleary see with 74880 baud the response for standard boot on TXD (GPIO1):
```
 ets Jan  8 2013,rst cause:2, boot mode:(7,7)

waiting for host
```
and on TXD1 (GPIO2)

```
 ets Jan  8 2013,rst cause:2, boot mode:(7,6)

waiting for host
```
----

For flash mode with RESET and GPIO-0 on TXD (GPIO1):
```
 ets Jan  8 2013,rst cause:2, boot mode:(5,7)

waiting for host
```
and on TXD1 (GPIO2)

```
 ets Jan  8 2013,rst cause:2, boot mode:(5,6)

waiting for host
```
----
I tried to connect with:

python3 esptool.py --port /dev/ttyUSB0 flash_id

or

python3 esptool.py --chip esp8266 --port /dev/ttyUSB0 flash_id

or

python3 esptool.py --no-stub --port /dev/ttyUSB0 flash_id

but no connection can be established.

"A fatal error occurred: Failed to connect to Espressif device: No serial data received."

With the trace option I get:

```
TRACE +0.000 Write 46 bytes:
    c000082400000000 0007071220555555 | ...$........ UUU
    5555555555555555 5555555555555555 | UUUUUUUUUUUUUUUU
    5555555555555555 5555555555c0     | UUUUUUUUUUUUU.
TRACE +0.082 Read 1 bytes: 72
TRACE +0.000 Read invalid data: 72
TRACE +0.000 Remaining data in serial buffer: 6c00
```

I tried the connection with this two versions:

esptool.py v3.3-dev

esptool.py v2.0-beta2

I assume this is simply bad hardware.

Is there anybody who has mastered this problem?

title: ESP8266 module ESP-12F does not connect to esptool.py

Answers: 1

body:
You have io 15 HIGH. Check the pull-down.

The first number in () on first line of the boot log is the state of the boot config pins. First bit is the state of io 2, second the state of io 0 and third is the state of io 15.

You have 5 or 7 which is 101 or 111 in binary. So you have io 15 HIGH.

io 15 HIGH is a mode where the esp8266 doesn't have its own flash memory but boots from the host MCU so you get "waiting for host".

io 15 must be LOW for the esp8266 to use the flash memory.

So you should see for normal mode
```
ets Jan  8 2013,rst cause:2, boot mode:(3,6)
```
and for flashing mode
```
ets Jan  8 2013,rst cause:2, boot mode:(1,6)
```
Note: it can be (3,7) and (1,7) too


body:
I am totally desperate and hope you can help me.
I've been building a project for a while where I have to control several **servos**. For this I bought some **MG996R** [servos][1] and a [ **PCA9685** 16-Channel Servo
Driver][2] board. Furthermore, I bought a suitable **power supply** (DV 5V - max 3A).

First, I connected my controller and the board as follows and attached the power supply at the intended place:
[![enter image description here][3]][3]

Everything **worked** as desired and I could control e.g. one servo with this example script.

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    Adafruit_PWMServoDriver myServos = Adafruit_PWMServoDriver();

    #define SERVOMIN  150
    #define SERVOMAX  600

    uint8_t servonum = 0;
    uint8_t numberOfServos =  1;

    void setup() {
      myServos.begin();
      myServos.setPWMFreq(60);
      delay(10);
    }

    void loop() {
      myServos.setPWM(0, 0, 500);
      delay(1000);
      myServos.setPWM(0, 0, 300);
      delay(1000);
    }

Then I tried something and reconnected a few cables while the power supply was still on (my bad) - after that **no servo moved** with the **original setup** (see picture above). After that I tried to find the broken part but couldn't find any - so I bought a **new Arduino, PCA board and power supply** to try and find the error - unfortunately **without** success.

Then I found out by chance that the servos move again when I connect the ground of the external power supply to the Arduino and plug the positive pole of the power supply to the **V+** with the PCA9685. That is,
[![enter image description here][4]][4]

I ordered a  pack of three **new** PCA9685s and again same problem - the servos no longer move when using the designated place for the power supply on the PCA9685 board - what is going on? Can anyone explain this and help me where the problem is?

  [1]: https://www.electronicoscaldas.com/datasheet/MG996R_Tower-Pro.pdf
  [2]: https://cdn-learn.adafruit.com/downloads/pdf/16-channel-pwm-servo-driver.pdf
  [3]: https://i.stack.imgur.com/hXZYWm.png
  [4]: https://i.stack.imgur.com/WNs8Cm.png

title: Arduino UNO and PCA9685 - Problem with external power supply

Answers: 0


body:
So, I have a working code of the stabilizer project using 2 servo motors, mpu6050, Arduino Uno. However, I want to add PID part for tuning the servo motors movement. I followed the example PID library and just changed the input as data received from the mpu6050 sensor, and output as the data that we send to servo motor. The problem is after adding the PID part project stopped working properly. Servo motors did not react to the accelerometer movement anymore. I tried printing out the values computed by the PID and all of them turned out to be 0 and they don't change even if I rotate the sensor. Can anyone spot the mistake in the code with PID part? I am pretty sure that the rest works perfectly.

```cpp
/*
                        DIY Gimbal - MPU6050 Arduino Tutorial
                        by Dejan, www.HowToMechatronics.com
                        Code based on the MPU6050_DMP6 example from the i2cdevlib library by Jeff Rowberg:
                        https://github.com/jrowberg/i2cdevlib
*/
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
#include "PID_v1.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
#include <Servo.h>
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

double Setpointx, Setpointy, Inputx, Inputy, Outputx, Outputy, pidX, pidY;
double Kp = 2, Ki = 5, Kd = 1;
PID myPID0 (&Inputx, &Outputx, &Setpointx, Kp, Ki, Kd, DIRECT) ;
PID myPID1 (&Inputy, &Outputy, &Setpointy, Kp, Ki, Kd, DIRECT) ;
// Define the 3 servo motors
Servo servo0;
Servo servo1;
Servo servo2;
float correct;
int j = 0;

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Setpointx = 10;
  Setpointy = 10;

  myPID0. SetMode (AUTOMATIC);
  myPID1. SetMode (AUTOMATIC);

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  // (115200 chosen because it is required for Teapot Demo output, but it's
  // really up to you depending on your project)
  Serial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  //Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(17);
  mpu.setYGyroOffset(-69);
  mpu.setZGyroOffset(27);
  mpu.setZAccelOffset(1551); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    // Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    //Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    // Serial.print(F("DMP Initialization failed (code "));
    //Serial.print(devStatus);
    //Serial.println(F(")"));
  }

  // Define the pins to which the 3 servo motors are connected
  servo0.attach(10); //Z Axis
  servo1.attach(9); //Y Axis
  servo2.attach(8); //X Axis
  servo1.write(90);
  servo2.write(90);
}
// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
    if (mpuInterrupt && fifoCount < packetSize) {
      // try to get out of the infinite loop
      fifoCount = mpu.getFIFOCount();
    }
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    fifoCount = mpu.getFIFOCount();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    // Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    // Yaw, Pitch, Roll values - Radians to degrees
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    Serial.print("\nX: ");
    Serial.print(pidX);
    Serial.print("\nY: ");
    Serial.print(pidY);
    ypr[0] = ypr[0] * 180 / M_PI;
    pidX = pidX * 180 / M_PI;
    pidY = pidY * 180 / M_PI;
    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(pidY, -90, 90, 0, 180);
      int servo2Value = map(pidX, -90, 90, 180, 0);
      // Control the servos according to the MPU6050 orientation
      servo0.write(90);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif
  }
}
```

title: PID control doesn't work. After computing the values, the values just become equal to 0

Answers: 2

body:
You seem to have some misconceptions about PID. For explaining I will use a different use case of a PID control, which is easier to understand (and also mentioned in the [documentation of the PID library][1]):

A PID control can be used in any feedback loop system with consistent feedback. When you drive your car you want it to reach a specific speed. For that you press the gas pedal, changing its angle until you reach the target speed. In this scenario you are doing the PID control. The setpoint is the target speed, the input is the actual current speed and the output is the angle of the gas pedal.

You see: Output and input/setpoint don't have the same unit. They are completely different measurements of different things. They are only connected via the feedback loop in the system, meaning that increasing the gas pedal angle will increase the speed of the car. The PID control is then just a formula which involves the actual speed, the desired speed and some scaling variables (Kp, Ki, Kd)(to tune the behavior of the control). And the output of the formula is then the needed gas pedal angle at that time.

**So what does this mean for you?**

- You don't need to convert the output value into an angle. The unit of the output is not important, since the PID will control itself to get to the setpoint. It is more important to tune the PID through Kp, Ki and Kd to get the PID to behave correctly in your system.

- The workflow looks like this:
  1. Set the setpoint variable `Setpointx` to the wanted input value.
  2. Read the input from the MPU and save it to `Inputx`
  3. Call `myPID0.Compute();` to compute the output from setpoint and input.
  4. Read the value from `Outputx` and write it to your servo. The servo movement will then cause a change in the read input in the next loop.
  5. repeat from step 2

- As I currently don't really understand your feedback loop system: Make sure, that the feedback loop is working correctly. An increase in the output should lead to an increase in the input. Make sure it is consistent. Your input value should not have too much noise (or the PID will react to that noise). For testing you might want to tune Kp, Ki and Kd down so that the PID works slower. Then you can see the behavior better. Make sure, that both PID controls aren't influencing each other. They need to be independent.

- Use `myPID0.Compute();` every time you write a new value to your servo and only then. Calling it in between will be just a waste. So it makes sense to use that line somewhere directly before writing to the servo.

---

If it still not works, then you should have a detailed look at the read values and how they relate to the servo angle. Are the requirements above met? Are they stable enough. Is the feedback loop as expected? What does changing Kp, Kd and Ki change in the outcome?

  [1]: https://playground.arduino.cc/Code/PIDLibrary/

body:
This chunk of code is feeding radians into the PID algorithm, and then discarding/overwriting the output with the initialized-to-zero pidX and pidY values.

    ...
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    ...

I'd set the output limits to match the device under control:

    void setup() {
       // join I2C bus (I2Cdev library doesn't do this automatically)
       Setpointx = 10;  // MPU degrees
       Setpointy = 10;  // MPU degrees

       myPID0. SetMode (AUTOMATIC);
       myPID1. SetMode (AUTOMATIC);
       myPID0.SetOutputLimits(0,180); // servo degrees
       myPID1.SetOutputLimits(0,180); // servo degrees
       ...

...and then convert the inputs to match the setpoints, and feed the constrained PID outputs directly to the controls:

    Inputx = ypr[2]*180.0/M_PI;
    myPID0.Compute();
    pid_X = Outputx;
    Inputy = ypr[1]*180/M_PI;
    myPID1.Compute();
    pidY = Outputy;
    ...
    servo1.write(Outputx);
    servo2.write(Outputy);
    ...

It is important to use the `PID.SetOutputLimits(min,max)` so that the PID routine can internally ensure that the outputs don't wander deep into infeasible control regimes.  If you don't call SetOutputLimits(), the default output constraints are 0-255, which would not make sense for a 0-180 servo.

One way to think of your PID constants `Kp = 2, Ki = 5, Kd = 1;` is how big an output unit change (degrees of servo setting) you want to make for a unit of input (MPU radians or degrees?) error, integrated error (error*seconds/5 per https://playground.arduino.cc/Code/PIDLibrarySetSampleTime/), or delta error.  They might need adjusting if the system isn't responding as you like.


body:
The CapacitiveSense library is the key to my project. A custom art touch lamp.
[Arduino CapacitiveSensor Library][1]

It works great with the Arduino UNO but the Nano Every has vastly different performance and issues with exactly the same code and HW. The Arduino is just too large for my project so I had high hopes that the Nano E would be a compatible fit.

My HW setup is per the example. Using a high value Resistor between pins 7 and 8 for Send and Receive(sensor). Works for the Uno but the Nano E just outputs a -2. Even though I tried resistor values 56K to 2M!. Realize the error -2 can mean a missing resistor. So I then tried the Threshold 3 way switch example code which suggests that just using pin 8 as an antenna is possible. I have a small steel plate (3"x4") connected directly to pin 8. Again Arduino Works great. By that I mean that I can adjust the parameters labeled in the code as a, b and c to get a repeatable trigger output to the serial monitor. The Nano Every with the same code though gets vastly different readings for cs and they don't stabilize. By vast , I mean Arduino returns cs numbers in range 100 to 200;s while the Nano E returns in the 33000's. Now I can make the code recognize those numbers for a trigger but subsequent touches range all over the place (1000's to 50000's) making touching the plate highly random with triggers.
I have made large tables (many hours) trying to dial the parameters in on the Nano with no success while it took me about 10 mins to dial in on the Arduino for reliable operation.
Why would the Nano Every be so different from the Uno?

The Threshold example code (bottom of page) in the library reference is perfect my setup as it is described as a used for a 3 way switch. The example code is below.

~~~
#include <CapacitiveSensor.h>
CapacitiveSensor cs_7_8 = CapacitiveSensor(7,8); //10M Resistor between pins 7 and 8, you may also connect an antenna on pin 8
unsigned long csSum;

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

void loop() {
    CSread();
}

void CSread() {
    long cs = cs_7_8.capacitiveSensor(80); //a: Sensor resolution is set to 80
 if (cs > 100) { //b: Arbitrary number
  csSum += cs;
  Serial.println(cs);
  if (csSum >= 3800) //c: This value is the threshold, a High value means it takes longer to trigger
  {
   Serial.print("Trigger: ");
   Serial.println(csSum);
   if (csSum > 0) { csSum = 0; } //Reset
   cs_7_8.reset_CS_AutoCal(); //Stops readings
  }
 } else {
  csSum = 0; //Timeout caused by bad readings
 }
}
~~~

Serial Output with Uno board with nice triggers.
parameters cs>700, csSum>=1500, samples are 10,

799
812
Trigger: 1161

I realize this is a lot of detail in this question. But I've searched this and other boards for anything on getting Capacitive Sensor to work reliably on any other board beside Uno and haven't found anything.
I'm also aware of the grounding issues talked about in relation to touch sensing. I had a previous post here about that using the Trinket M0 but abandoned that due to grounding issues with it.
I still have issues whether the Nano is connected via USB or an independent AC-DC power supply with 12vdc going to Nano.  I don't see any grounding issues with both the Arduino Uno and nano every with either USB power or independant AC-DC 12v power
Any insights appreciated.

  [1]: https://playground.arduino.cc/Main/CapacitiveSensor/

title: CapacitiveSensor Library example works with great with UNO but not with Nano Every?

Answers: 0


body:
``` c++
const int Trigger = 6;
const int Echo = 7;
const int LEDpin1 = 4;
const int LEDpin2 = 5;
const int Parameter = 400;
float Time;

void setup()
{
Serial.begin(9600);
pinMode(Trigger, OUTPUT);
pinMode(Echo, INPUT);
pinMode(LEDpin1,OUTPUT);
pinMode(LEDpin2,OUTPUT);
}
void loop()
{

digitalWrite(Trigger, HIGH);
delayMicroseconds(10);
digitalWrite(Trigger, LOW);
Time = pulseIn(Echo, HIGH);
Serial.print("Distance: ");
Serial.println(Time);
delay(10);
if (Time < Parameter)
digitalWrite(LEDpin1, HIGH);
else
digitalWrite(LEDpin1, LOW);

if (Time < Parameter)
digitalWrite(LEDpin2, HIGH);
else
digitalWrite(LEDpin2, LOW);

//**When I include -delay(5000)- right here, it also delays the Ultrasonic sensor to only detect every 5 seconds**
}
```

title: I want my LED's to turn on for 5 sec when the Ultrasonic Sensor Activated

Answers: 0


body:
Is there some code or library that would allow me to scan for nearby Bluetooth devices using a common ESP32 board ?
I only found similar code for actual Arduino boards.

title: Arduino library or code for ESP32 to scan for Bluetooth devices?

Answers: 2

body: The ESP32 Arduino boards support package includes libraries for ESP32 Bluetooth and BLE. Both libraries have examples which you can find in Arduino IDE Examples menu.

body:
https://github.com/esp32beans/ESP32-BT-exp is a Bluetooth Dual
Mode (classic and BLE) scanner. ESP32-BT-exp works on the original ESP32. No other ESP32 supports BT classic mode.


body: I have an arduino board (SAMD21 microcontroller) which supports either Arduino or CircuitPython programming. I'd like to program in pure C/C++ instead of Arduino, which seems to be possible without too much trouble. But I'm not sure whether to use C or C++. I thought Arduino was based in C++ but I went to look at some of the library files and they were written in C. Since I'm pretty sure they're not interchangeable, can someone help me learn which language I should use to program my board?

title: Should I use C or C++ for a pure code implementation of Arduino?

Answers: 1

body:
> I thought Arduino was based in C++

There is no language "Arduino" - the Arduino IDE runs a the GNU C++ compiler so "its language" is the language supported by the compiler. It is primarily C++ with a little bit of preprocessing done to your code to help learners get past some of the places they can trip over easily (adding #include statements when it thinks you need them, for instance).

Here is an [answer I wrote to a similar question][1] a few years ago. I think it's relevant to your question.

  [1]: https://arduino.stackexchange.com/a/824/313


body:
I am trying to make it so that my robot rolls straight when pin 8 is high and stop when pin 8 is low, the 2 servos is constant rotation servos. instead the servos spin when the wire touches it pin even without power to the wire, and they don't stop when the wire is pulled, but sometimes they don't start and sometimes they stop.
I'm new to coding and I really need this help.
```

#include <Servo.h>

Servo h1;
Servo h2;

#define servoPin 13
#define servoPin 3

int angle = 0;
const int buttonPin = 8;
int buttonState = 0;
void setup() {

  h2.attach(13); //left servo
  h1.attach(3); //right servo
  pinMode(8, INPUT);
}

void loop() {

  if (digitalRead(8) == LOW)  {
  h1.write(90); //no movement
  h2.write(90);//no movement

  } else  {
    h1.write(180); //go straight
    h2.write(0); //go straight
  }
}
  ```

title: servos act strangely instead of stopping/starting

Answers: 0


body:
I have a salvaged 40-pin TFT touch panel, and I am trying to see if I can control it with an Arduino. What are my chances of getting a driver for it ? I bought a RA8875 Driver Board from Adafruit, but the pin layout did not match.

Any suggestions are appreciated. Thank you

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

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

title: Possible way to interface a TFT touch panel with Arduino

Answers: 0


body:
I have this long, Serial.println() that is in quotes, on multiple lines.
Arduino IDE warns: "Missing terminating character".
I am certain there is a way to break the lines up, while having the entire text enclosed in quotes, but I don't remember how.

    Serial.println("
    <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
    <svg
       xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
        xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"
       id=\"svg8\" version=\"1.1\" viewBox=\"0 0 227.35277 156.29323\"
       height=\"6.1532764in\"
       width=\"8.9508963in\"
       sodipodi:docname=\"etchasketchborder.svg\">
        <defs
         id=\"defs2\" />
      <path
         style=\"fill:#ff0000;stroke:#ff0000;stroke-width:1.32300019;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
         d=\"m 12.000819,0.66145838 c -6.2819637,0 -11.33936062,5.05739692 -11.33936062,11.33936062 V 144.29249 c 0,6.28197 5.05739692,11.33936 11.33936062,11.33936 H 215.35224 c 6.28197,0 11.33885,-5.05739 11.33885,-11.33936 V 12.000819 c 0,-6.2819637 -5.05688,-11.33936062 -11.33885,-11.33936062 z M 18.932696,12.696383 H 205.5854 c 5.02557,0 9.07128,4.04571 9.07128,9.071282 v 77.03923 c 0,5.025575 -4.04571,9.071285 -9.07128,9.071285 H 18.932696 c -5.025572,0 -9.0712819,-4.04571 -9.0712819,-9.071285 v -77.03923 c 0,-5.025572 4.0457099,-9.071282 9.0712819,-9.071282 z\"
        />
      <ellipse
         style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
         cx=\"21.16666\"
         cy=\"130.59085\"
         rx=\"10.583334\"
         ry=\"9.0714283\" />
      <ellipse
         style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
         cx=\"200.62982\"
         cy=\"131.57361\"
         rx=\"10.583334\"
         ry=\"9.0714283\" />
          </svg>
    ");

title: how to put whitespace in long Serial println() input

Answers: 1

body:
Ah, I figured it out.
you cant do this:

    Serial.println("foo
                                    bar");

but you can do this:

    Serial.println("Foo"
                    "Bar");

So then in bash I write a little command, to take my svg files, and escape the quotes that exist in the file, then another line to add quotes at the start and end of every newline. then I can just copy paste my svg images into the println() function.

    $ sed -i 's/"/\\"/g' input.svg

and

    $ xargs -I{lin} echo \"{lin}\" <input.svg

respectively.


body:
I'm trying to control an adafruit soundboard with my elegoo uno R3. I'm a beginner programer and I'm trying to get the soundboard to play a sound file by name when I press a button. I have confirmed the soundboard works because it works when I run the menu program that I got from the tutorial I followed, but when I try to simplify that and transfer it to my own code something goes wrong. Here is my code:

    #include <Adafruit_Soundboard.h>
    #include <SoftwareSerial.h>

    #define SFX_TX 10
    #define SFX_RX 11
    #define SFX_RST 12

    int pin_a = 8;
    int pin_b = 7;
    int pin_c = 4;
    long randNumber;
    long randNumberCheck;
    const int buttonPin = 2;

    int buttonState = 0;
    int lightLoopCount = 0;

    #define NUM_SOUNDS 2
    char *soundName[NUM_SOUNDS] = {
      "T00     OGG",
      "T00     OGG",
    };

    SoftwareSerial ss = SoftwareSerial(SFX_TX, SFX_RX);
    Adafruit_Soundboard sfx = Adafruit_Soundboard(&ss, NULL, SFX_RST);

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

      if (!sfx.reset()) {
        Serial.println("Not found");
        while (1);
      }

      pinMode(pin_a, OUTPUT);
      pinMode(pin_b, OUTPUT);
      pinMode(pin_c, OUTPUT);

      pinMode(buttonPin, INPUT);

      randomSeed(analogRead(0));
    }

    void loop() {
      analogWrite(pin_a, 0);
      analogWrite(pin_b, 0);
      analogWrite(pin_c, 0);

      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      if (buttonState == HIGH) {

        sfx.playTrack(soundName[1]);

        if (!sfx.playTrack(soundName[1])) {
          Serial.print("Failed to play");
        }

        lightLoopCount = 0;
        while (lightLoopCount < 10) {
          analogWrite(pin_a, 0);
          analogWrite(pin_b, 0);
          analogWrite(pin_c, 0);

          // print a random number from 0 to 299
          randNumber = random(3);
          while (randNumber == randNumberCheck) {
            randNumber = random(3);
          }

          if (randNumber == 0) {
            analogWrite(pin_a, 255);
          }
          else if (randNumber == 1) {
            analogWrite(pin_b, 255);
          }
          else {
            analogWrite(pin_c, 255);
          }

          randNumberCheck = randNumber;

          delay(300);
          lightLoopCount++;
        }
      }
    }

Here is the datasheet for the soundboard: https://www.digikey.com/htmldatasheets/production/1800160/0/0/1/audio-fx-sound-board.html

I've tried several different ways to get the board to just play a sound by filename when I press the button. Everything else works when I press the button, I think I'm just having trouble converting the string into a char array that the board can understand. It's saying "Failed to play" when I press the button. Can someone help me convert the string properly?

title: How to use an Arduino to play audio from an Adafruit Soundboard using audio file name

Answers: 0


body:
so I was trying to control a bot wirelessly with the help of ps3 controller and USB host shield, i am using Arduino UNO as micro-controller. I was able to connect PS3 controller with Arduino and checked all button presses. It works very smoothly for button presses and shows on serial monitor which button was pressed without any lag. But the issue I am facing is that when I try to call any function on button press, the entire function is getting executed and execution comes back to void loop but Arduino stops accepting commands from ps3. But it shows that PS3 is still connected and the connection isn't lost. I went through different blogs and I found out that some say that issue is with new HOST SHIELD library 2.0 and some say that UNO computation takes time.
this is what I have tried.
  ```
#define motopinl1 8
#define motopinr1 9
# define motopine1 10

#define motopinl2 11
#define motopinr2 12
#define motopine2 13

#define val 200

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nPS3 Bluetooth Library Started"));
}

void moveforward()
{

 // digitalWrite(motopinl1,LOW);
  digitalWrite(motopinr1,LOW);
  digitalWrite(motopinl2,LOW);
 // digitalWrite(motopinr2,LOW);
  analogWrite(motopine1,200);
  analogWrite(motopine2,200);
 // digitalWrite(motopinl1,HIGH);
  //digitalWrite(motopinr2,HIGH);

  Serial.println("MoveForward called");
  Usb.Task();

}

void moveBackward()
{

  digitalWrite(motopinl1,LOW);
//  digitalWrite(motopinr1,LOW);
 // digitalWrite(motopinl2,LOW);
  digitalWrite(motopinr2,LOW);
  analogWrite(motopine1,200);
  analogWrite(motopine2,200);
 // digitalWrite(motopinr1,HIGH);
  //digitalWrite(motopinl2,HIGH);

  Serial.println("Movebackward called");
  Usb.Task();
}

void moveleft()
{

  digitalWrite(motopinl1,LOW);
 // digitalWrite(motopinr1,LOW);
  digitalWrite(motopinl2,LOW);
 // digitalWrite(motopinr2,LOW);
  analogWrite(motopine1,200);
  analogWrite(motopine2,200);
 // digitalWrite(motopinr2,HIGH);
  //digitalWrite(motopinr1,HIGH);

Usb.Task();
  Serial.println("Moveleft called");
}

void moveright()
{

 // digitalWrite(motopinl1,LOW);
  //digitalWrite(motopinr1,LOW);
  digitalWrite(motopinl2,LOW);
  digitalWrite(motopinr2,LOW);
  analogWrite(motopine1,200);
  analogWrite(motopine2,200);
 // digitalWrite(motopinl1,HIGH);
  //digitalWrite(motopinl2,HIGH);

  Serial.println("Moveright called");
  Usb.Task();
}

void stopit()
{
  digitalWrite(motopinl1,LOW);
  digitalWrite(motopinr1,LOW);
  digitalWrite(motopinl2,LOW);
  digitalWrite(motopinr2,LOW);
  analogWrite(motopine1,0);
  analogWrite(motopine2,0);
  Usb.Task();
}

void loop() {
  Usb.Task();

  if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
    if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
     // Serial.print(F("\r\nLeftHatX: "));
      //Serial.print(PS3.getAnalogHat(LeftHatX));
      //Serial.print(F("\tLeftHatY: "));
      //Serial.print(PS3.getAnalogHat(LeftHatY));
      if (PS3.PS3Connected) { // The Navigation controller only have one joystick
        //Serial.print(F("\tRightHatX: "));
        //Serial.print(PS3.getAnalogHat(RightHatX));
        //Serial.print(F("\tRightHatY: "));
        //Serial.print(PS3.getAnalogHat(RightHatY));
      }
    }

    // Analog button values can be read from almost all buttons
    if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
      Serial.print(F("\r\nL2: "));
      Serial.print(PS3.getAnalogButton(L2));
      if (PS3.PS3Connected) {
        Serial.print(F("\tR2: "));
        Serial.print(PS3.getAnalogButton(R2));
      }
    }

    if (PS3.getButtonClick(PS)) {
      Serial.print(F("\r\nPS"));
      PS3.disconnect();
    }
    else {
      if (PS3.getButtonClick(TRIANGLE)) {
        Serial.print(F("\r\nTriangle"));
        moveforward();
        PS3.setRumbleOn(RumbleLow);
      }
      if (PS3.getButtonClick(CIRCLE)) {
        Serial.print(F("\r\nCircle"));
        PS3.setRumbleOn(RumbleHigh);
        moveright();
      }
      if (PS3.getButtonClick(CROSS))
      {
          Serial.print(F("\r\nCross"));
          moveBackward();
      }
      if (PS3.getButtonClick(SQUARE))
      {
        Serial.print(F("\r\nSquare"));
        moveleft();
      }

      if (PS3.getButtonClick(UP)) {
        Serial.print(F("\r\nUp"));
        stopit();
        if (PS3.PS3Connected) {
          PS3.setLedOff();
          PS3.setLedOn(LED4);
        }
      }
      if (PS3.getButtonClick(RIGHT)) {
        Serial.print(F("\r\nRight"));
        if (PS3.PS3Connected) {
          PS3.setLedOff();
          PS3.setLedOn(LED1);
        }
      }
      if (PS3.getButtonClick(DOWN)) {
        Serial.print(F("\r\nDown"));
        if (PS3.PS3Connected) {
          PS3.setLedOff();
          PS3.setLedOn(LED2);
        }
      }
      if (PS3.getButtonClick(LEFT)) {
        Serial.print(F("\r\nLeft"));
        if (PS3.PS3Connected) {
          PS3.setLedOff();
          PS3.setLedOn(LED3);
        }
      }

      if (PS3.getButtonClick(L1))
        Serial.print(F("\r\nL1"));
      if (PS3.getButtonClick(L3))
        Serial.print(F("\r\nL3"));
      if (PS3.getButtonClick(R1))
        Serial.print(F("\r\nR1"));
      if (PS3.getButtonClick(R3))
        Serial.print(F("\r\nR3"));

      if (PS3.getButtonClick(SELECT)) {
        Serial.print(F("\r\nSelect - "));
        PS3.printStatusString();
      }
      if (PS3.getButtonClick(START)) {
        Serial.print(F("\r\nStart"));
        printAngle = !printAngle;
      }
    }
#if 0 // Set this to 1 in order to see the angle of the controller
    if (printAngle) {
      Serial.print(F("\r\nPitch: "));
      Serial.print(PS3.getAngle(Pitch));
      Serial.print(F("\tRoll: "));
      Serial.print(PS3.getAngle(Roll));
    }
#endif
  }
#if 0 // Set this to 1 in order to enable support for the Playstation Move controller
  else if (PS3.PS3MoveConnected) {
    if (PS3.getAnalogButton(T)) {
      Serial.print(F("\r\nT: "));
      Serial.print(PS3.getAnalogButton(T));
    }
    if (PS3.getButtonClick(PS)) {
      Serial.print(F("\r\nPS"));
      PS3.disconnect();
    }
    else {
      if (PS3.getButtonClick(SELECT)) {
        Serial.print(F("\r\nSelect"));
        printTemperature = !printTemperature;
      }
      if (PS3.getButtonClick(START)) {
        Serial.print(F("\r\nStart"));
        printAngle = !printAngle;
      }
      if (PS3.getButtonClick(TRIANGLE)) {
        Serial.print(F("\r\nTriangle"));
        PS3.moveSetBulb(Red);
      }
      if (PS3.getButtonClick(CIRCLE)) {
        Serial.print(F("\r\nCircle"));
        PS3.moveSetBulb(Green);
      }
      if (PS3.getButtonClick(SQUARE)) {
        Serial.print(F("\r\nSquare"));
        PS3.moveSetBulb(Blue);
      }
      if (PS3.getButtonClick(CROSS)) {
        Serial.print(F("\r\nCross"));
        PS3.moveSetBulb(Yellow);
      }
      if (PS3.getButtonClick(MOVE)) {
        PS3.moveSetBulb(Off);
        Serial.print(F("\r\nMove"));
        Serial.print(F(" - "));
        PS3.printStatusString();
      }
    }
    if (printAngle) {
      Serial.print(F("\r\nPitch: "));
      Serial.print(PS3.getAngle(Pitch));
      Serial.print(F("\tRoll: "));
      Serial.print(PS3.getAngle(Roll));
    }
    else if (printTemperature) {
      Serial.print(F("\r\nTemperature: "));
      Serial.print(PS3.getTemperature());
    }
  }
#endif
}```

I haven't connected to bot. I was checking whether function are being executed on button press or not or serial monitor. so there cannot be issue of power supply. problem is PS3 still remains connected, also line of execution returns to void loop, then why it stops further commands. please please do suggest any ideas and methods by which I can solve this problem. thank you.

title: Arduino Uno stops accepting command from PS3 Wireless controller?? although it remains connected!

Answers: 1

body: I found that when you use delay inbuilt function, it completely blocks Arduino from accepting any command, that causes some communication barrier. Although ps3 remains connected, it doesn't accept commands. so all you have to do is to remove all delays from your function and build logic based Millis.


body:
I have a project that consists of an Arduino, a NodeMCU and 2 servos. The NodeMCU is configured as master and the Arduino as slave. I have bidirectional flow of data between them.

In order to receive data from Arduino I use the `requestFrom()` function from the Wire.h library and I call this function in the NodeMCU loop every 100ms.

The problem is that the servos (which are connected to the Arduino to pins 10 and 11) twitch every approximatively 10s. If I change the interval at which the NodeMCU asks for data from Arduino to 200ms, the twitch interval for the servos changes to 20s.

Is there a buffer that gets full or what is happening? I think that the `Wire.onRequest()` handler from Arduino interferes with the PWM of the servos. Is there a workaround? Do you have any idea how to stop the servos from twitching? Perhaps make the libraries use different timers? Thanks in advance!

Code:

    #include "Arduino.h"
    #include <Wire.h>
    #include <Keypad.h>
    #include <Servo.h>

    Servo servo_1;//up-down servo
    Servo servo_2;//left-right servo

    byte deg_1=0;
    byte deg_2=0;

    byte manual_move_mode = 0;

    byte data_count = 0, master_count = 0;

    const byte ROWS = 4;
    const byte COLS = 4;

    char hexaKeys[ROWS][COLS] = {
      {'1', '2', '3', 'A'},
      {'4', '5', '6', 'B'},
      {'7', '8', '9', 'C'},
      {'*', '0', '#', 'D'}
    };

    byte rowPins[ROWS] = {9, 8, 7, 6};
    byte colPins[COLS] = {5, 4, 3, 2};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup() {
     Wire.begin(8);                /* join i2c bus with address 8 */
     Wire.onReceive(receiveEvent); /* register receive event */
     Wire.onRequest(requestEvent);
     Serial.begin(115200);           /* start serial for debug */
     Serial.println("Program Started");
     pinMode(13, OUTPUT);

     servo_1.attach(10);
     servo_1.write(0);
     servo_2.attach(11);
     servo_2.write(0);
    }

    void loop() {

     manual_move_servo();
     //send_keys();

    }

    // function that executes when data is received from master
    void receiveEvent(int howMany) {
      String data="";
     while (0 <Wire.available()) {
        char c = Wire.read();      /* receive byte as a character */
        data += c;

      }
        Serial.println(data);   /* print the request data */

        if (data=="PIN_13_HIGH"){
        digitalWrite(13,HIGH);
       } else if (data == "PIN_13_LOW"){
        digitalWrite(13,LOW);
       }

        if (data=="MANUAL_TRUE"){
        manual_move_mode = 1;
       } else if (data == "MANUAL_FALSE"){
        manual_move_mode = 0;
       }
    }

    void requestEvent()
    {
      char customKey = customKeypad.getKey();
      if (customKey){
        Serial.print("Transmission to NodeMCU begins...");
        Serial.println(customKey);
        Wire.write(customKey);  // sends hello string
      }
    }

    void manual_move_servo(){
      if (manual_move_mode == 1){
          char customKey = customKeypad.getKey();
      if (customKey=='2'){//move up
        //digitalWrite(13,HIGH);
        deg_1+=5;
        servo_1.write(deg_1);
      } else if(customKey=='8'){//move down
        //digitalWrite(13,LOW);
        deg_1-=5;
        servo_1.write(deg_1);
      } else if(customKey=='4'){//move left
        //digitalWrite(13,HIGH);
        deg_2+=5;
        servo_2.write(deg_2);
      } else if(customKey=='6'){//move right
        //digitalWrite(13,LOW);
        deg_2-=5;
        servo_2.write(deg_2);
      } else if(customKey=='*'){
        manual_move_mode = 0;//este nevoie sa trimitem inf asta spre nodemcu????? nu cred pentru ca nu comandam altceva in fctie de var asta cu nodemcu poate doar daca adaugam un led indicator pe interfata web
      }
      }
    //ne asiguram ca nu trecem de intervalele impuse
      if (deg_1<=5){
        deg_1=5;//daca pun 0 se duce automat la 180(probabil se intercaleaza intervale)
      }

      if (deg_1>=180){
        deg_1=180;
      }

        if (deg_2<=5){
        deg_2=5;//daca pun 0 se duce automat la 180(probabil se intercaleaza intervale)
      }

      if (deg_2>=180){
        deg_2=180;
      }
    }

    /*void send_keys(){

        char customKey = customKeypad.getKey();

      if (customKey){
        Serial.println(customKey);
        Serial.print("Transmission to NodeMCU begins...");
        Wire.beginTransmission(47); // begin with device address 8
        Wire.write(customKey);  // sends hello string
        Wire.endTransmission();// stop transmitting
      }
    }*/

title: Problem when using Servo.h and WIre.h libraries

Answers: 0


body:
Im working with node mcu ESP 8266 and trying to make it a webserver but keep encountering this problem.

````
   #include<ESP8266WiFi.h>
    WiFiClient client;
    WiFiServer server(80);
    void setup()
    {
    Serial.begin(9600);
    WiFi.begin("network","password");
    while(WiFi.status()!= WL_CONNECTED)
    {
      delay(200);
      Serial.print("...");
    }
    Serial.println("NodeMCu is connected");
    server.begin();
    }
    void loop()
    {
    client = server.available();
    if(client==1)
    {
       String request= client.readStringUntil("\n");
      Serial.println(request);
    }
    }
    ```

I'm getting this error :error: invalid conversion from 'const char*' to 'char' [-fpermissive]
   24 |    String request= client.readStringUntil("\n");
      |                                           ^~~~
      |                                           |
      |                                           const char*

title: How to fix this problem of invalid conversion from 'const char*' to 'char' [-fpermissive]

Answers: 0


body:
I am trying to simply read a voltage from a battery. I am able to work out how to do this using arduino code on an arduino board. (UNO)

When I try to do the same thing on a board using python the output seems erroneous.

Using arduino I will say for example get a voltage output to serial monitor or 1.39v which stays pretty much constant.

When doing so with the python board (Trinket M0) the output varies from 1.23342 -1.78484 and varies between these values.

My arduino code is as follows:

```c
int offset =0;// set the correction offset value
void setup() {
  // Robojax.com voltage sensor
  Serial.begin(9600);
}

void loop() {
  // Robojax.com voltage sensor
  int volt = analogRead(A0);// read the input
  double voltage = map(volt,0,1023, 0, 2500) + offset;// map 0-1023 to 0-2500 and add correction offset

  voltage /=100;// divide by 100 to get the decimal values
  Serial.print("Voltage: -");
  Serial.print(voltage);//print the voltge
  Serial.println("V");

delay(500);

}
```

My Python code is as follows

```python
import time
import board
from analogio import AnalogIn

analog_in = AnalogIn(board.A1)

def get_voltage(pin):
    return (pin.value * 3.3) / 65536

while True:
   print((get_voltage(analog_in),))
    time.sleep(0.1)

```
[![][1]][1]

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

title: I can get arduino code/board to show voltage using analog input but not python/board

Answers: 0


body:
I am trying to program my Arduino via bluetooth and have been following this tutorial very closely in order to do so: https://www.instructables.com/Program-an-Arduino-Wireless-Over-Bluetooth/

I have been able to put my HC-05 into AT command mode, entered the commands, and received the "OK" responses. When I go to try to upload the code, however, the sketch usually hangs and nothing happens. The TX on my HC-05 goes to the Arduino RX, RX to TX, VCC to 5V, GND to GND, and EN to RESET.

I am able to see the device no problem on my windows computer and seem to be using the correct port. Any ideas on how to fix the issue?

Any help is greatly appreciated!

title: Bluetooth Upload is Hanging

Answers: 0


body:
I'm currently working with a "WEMOS D1 R2 & mini" and am trying to call the time from an NTP server and display it onto an OLED display. I've been stuck on an error code that I can't seem to work around and was hoping for some pointers in the right direction. I've used an exception decoder to try an understand it but it's not really helping.

The error in the exception decoder:
```
Exception 29: StoreProhibited: A store referenced a page mapped with an attribute that does not permit stores
PC: 0x4020d032
EXCVADDR: 0x00000000

Decoding stack results
0x40202d64: ESP8266WiFiSTAClass::status() at C:\Users\XXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\libraries\ESP8266WiFi\src\ESP8266WiFiSTA.cpp line 563
0x4020292e: digitalClockDisplayOled() at C:\Users\XXX\Documents\Arduino\possible_fixed_clock/possible_fixed_clock.ino line 40
0x40202970: loop() at C:\Users\XXX\Documents\Arduino\possible_fixed_clock/possible_fixed_clock.ino line 35
0x4020512c: loop_wrapper() at C:\Users\XXX\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266\core_esp8266_main.cpp line 125
```

The code I'm using:
```
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET -1
#define OLED_SCREEN_I2C_ADDRESS 0x3C
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Defining constants
const char *ssid     = "XXX";
const char *password = "XXX";
const long offset = 3600;
// Background stuff
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", offset);
void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);

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

  timeClient.begin();
}

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

void digitalClockDisplayOled() {
  display.clearDisplay();
  display.setCursor(0,0);
  display.print(timeClient.getHours());
  printDigitsOled(timeClient.getMinutes());
  printDigitsOled(timeClient.getSeconds());
  display.display();
}

void printDigitsOled(int digits){
  display.print(":");
  if(digits < 10)
    display.print('0');
  display.print(digits);
}
```

What is this error code actually telling me, and what kind of implementation could I use to fix it?

title: Exception 29 when trying to display NTP time on an LED

Answers: 0


body:
Does anyone know if some Arduino based library is on the way to support new low power WiFi HaLow modules. If there is, I would like to know for which module?

For reference I'm sharing link [here][1]

  [1]: https://www.wi-fi.org/discover-wi-fi/wi-fi-certified-halow

title: WiFi HaLow library

Answers: 0


body: I am not that experienced with electronics, so this might be a silly question. But I dont know. Assume that I have connected some electronic circuit (transistors, leds, anything else) to the Arduino pins, is there any chance that I damage the hardware if I change the pinmode to input? What role do the integrated pullup/pulldown resistors play? Basically, is it possible to create some "unintended" flow of current, that damages the board or external hardware, if I change the pinmode or disable/enable the pullup/pulldown resistors (or something else that I dont know about)? Can I break the hardware by programming mistakes?

title: Can pin mode damage Arduino with connected electronics?

Answers: 1

body:
You are coming with some good questions about a complicated subject. You will be going through a learning process. If you do not violate the design parameters of the micro (voltage and current to name a few) you normally will not damage it. Knowing all of those parameters and what the circuirity surrounding the micro has a huge impact on your what can damage your micro and design. Without a schematic, this will change with each circuit and integration, it is impossible to give a definitive answer but I will take a SWAG.

Question: "is there any chance that I damage the hardware if I change the pinmode to input?"  and it depends on what mode the pin is in before you change it and what is connected to the pin. Generally you will not damage it assuming your voltages are equal to or less then the voltage supplying the microprocessor and the pin is not connected to an inductive component. You can get changes in your external hardware.

You ask "Can I break the hardware by programming mistakes?". Again I cannot give a definitive answer unless the circuit and what is connected is known. LEDs etc are generally no problem. If in doubt place a resistor in series with the load, something in the range of 330 to 500 ohms and see what happens. If you turn on some external device that damages stuff that is one possibility.

You ask: "if I change the pinmode or disable/enable the pullup/pulldown resistors..."Probably not but it depends on what is connected to the pins. Generally if the pull up resistors are needed such as for a button turning them off will cause some intermittent problems where it is on then off but that will not damage the micro, the effect on external devices is unknown as are the devices.

This stuff is not going to be assimilated in a few days but over a much longer period. There is always more then one way to do a project, the best is probably what you decide. You will make mistooks, and possibly destroy some of your Arduinos, this is to be expected, that is why I have spares. The most important part of the process is to enjoy and have fun.


body:
When unplugging the power source of a device that is writing some data "A" to an SD card, also other data "B" might get corrupted. (This is detailed [here][1].)

Regarding Arduino projects *without* an SD card, is it OK to remove the power source of Arduino microcontrollers anytime because the memory inside them uses a different technology than SD cards do (what are the names or differences of the respective technologies)?

Or are there several entirely independent memories - one for data and one for software/sketches?

Or do Arduino projects have to be programmed such that there are periods without data-writing and an LED indicates when it is safe to cut off the power?

  [1]: https://raspberrypi.stackexchange.com/questions/50345/is-it-okay-to-just-pull-the-plug/50347#50347

title: Can a power cut damage the software?

Answers: 1

body:
First we need to look at the different memory technologies in a microcontroller:
- First you have the flash memory. This is where the program is saved, but it can also be used to hold user data. On AVR based Arduinos it can only be written while programming or by the bootloader. But boards like the various ESPs can also have a little file system in it. Here you can get problems with a power loss while write operations happen.
- The RAM holds the current value of all variables. But it also always looses all data when unpowered. This is normal behavior because it is volatile memory. A power loss won't change anything here.
- That leaves us with EEPROM, a non-volatile memory type. You can corrupt your data with a power loss during write operations.

Then we need to look at the data structures. Most memory in Arduinos and similar boards a organized as a simple array of bytes. EEPROM is usually handled this way. If you write a data structure and have a power loss during that time, you must view this data structure as corrupt (for example writing a string with 20 characters, but while writing the 6th byte the power goes out). Other data is not harmed. On the other hand when you use a filesystem in flash like SPIFFS a write action in a file also involves handling a filesystem table. Outage during handling of the table might corrupt your filesystem integrity, thus can also harm other files.

SD cards are a special case, since their internal controllers move the data around to some unknown algorithm to implement wear leveling. This is not done with standard microcontrollers (you would need to implement it yourself if needed). The actual memory technology is also just flash, but you don't want to disturb the SD card while its handling its wear level algorithmus. That might corrupt the SD card completely. Also the linked answer talks about the SD card of a Raspberry Pi, which has a complete OS running on it. Running an OS involves way more changing non-volatile data than a microcontroller typically needs. So its way less likely to have the same situations with a microcontroller.

> Or do Arduino projects have to be programmed such that there are periods without data-writing and an LED indicates when it is safe to cut off the power?

Normally that is not needed, though it depends on your application and how the sketch handles the data. Are you saving data to non-volatile memory? How often do you do it? How often do you cut the power? If you are writing to byteswise memory like EEPROM, can you tolerate specific data corruptions? How much data are you writing each time?

Without assessing all these questions you cannot really say. Typically beginners just start without precaution in that direction. When you see problems after replugging, then you still can add an activity LED to the project.


body:
I have a bunch of `ATMEGA16U2` in my drawer and I need to make a small production of custom boards with Arduino-based firmware.

After a Google search I learn the `ATMEGA16U2` is often hosted on the Arduino boards as USB converter and there some hacks to reprogram it. But this is not my goal... I'm trying to understand how to compile and download the firmware using Arduino IDE and this MCU as target.

I guess (also from [this][1] old question) I need to update both the bootloader and the specification of the board.

Questions:

1. before reinvent the wheel are you aware of a ready-to-use porting for `ATMEGA16U2`? I did a search find nothing relevant

2. what is the official guide to update the files (bootloader + boards.txt) to support a new MCU? I find forum threads only

  [1]: https://arduino.stackexchange.com/questions/3122/arduino-core-for-atmega16u2

title: Porting Arduino for ATMEGA16U2

Answers: 0


body: I would like to know if it is possible to modify the VID and PID of the Native USB port of an Arduino Due.

title: How to modify an Arduino Due native USB port VID and PID?

Answers: 0


body: I am wondering where the extra 5v output power on the Arduino uno come from. Is it directly from the atmega328 microcontroller or from the external power source (usb or 9v battery). Thanks.

title: Where does the 5v Output power on the Arduino uno come from?

Answers: 1

body:
If you are connected to USB then it comes direct from the USB port's 5V.

If you have an external power supply connected (either to the barrel jack or to the VIN pin) then it comes from the onboard 5V regulator.

The only thing that ever comes from the ATMega chip is digital signals.