body:
I"m kinda new here and new to the arduino framework.

I want to build a "menu" using LCD 20*4, so I want to detect "button clicked" event.

I've connected button to pin 8 and to ground, like this(please ignore the other wiring):
[![enter image description here][1]][1]

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

    int leftButton = 8;

    void setup() {
      pinMode(leftButton, INPUT);
      digitalWrite(leftButton, HIGH);
      Serial.begin(9600);

    }
    bool leftButtonClicked(){
      return digitalRead(leftButton);
    }
    void loop(){
      delay(20);
      Serial.println(digitalRead(leftButton));
    }

I am receiveing on the serial `1` while the button is not clicked, and when its clicked I receive `0`.

What is the problem? Thank you guys.

title: read state from button to check if clicked

Answers: 1

body:
As you are a beginner, you seem to have some misconceptions:

- **Reading button state with `digitalRead()`:** You thought something is wrong, because you thought that `digitalRead()` returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. `digitalRead()` returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via `pinMode(pin, INPUT_PULLUP)`. That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.

    That also gives you the inverted logic. In the end it is determined by you, what the `digitalRead()` value means. Think electrically about it.

- **Events:** In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.

- **Reading a button click:** In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using `delay(20)` (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the [Bounce2][1] library, which is also easy to use for reading button clicks and presses.

  [1]: https://github.com/thomasfredericks/Bounce2


body:
Project: The Arduino Oscilloscope - published in The MagPi No. 71 July 2018

This is my first Arduino project!
I'm porting over the sketch "Gather_A0.ino" but I'm encountering compile errors:
Error message: 'ADCSRA' was not declared in this scope.
What am I missing?

Error message:
```

Arduino: 1.8.12 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
D:\Arduino & Raspberry Pi\Oscilloscope\Arduino_Scope\Software\Gather_A0\sketch_apr09a\sketch_apr09a.ino: In function 'void setup()':
sketch_apr09a:15:3: error: 'ADCSRA' was not declared in this scope
   ADCSRA = (ADCSRA & 0xf8) | 0x04; // set 16 times division
   ^
D:\Arduino & Raspberry Pi\Oscilloscope\Arduino_Scope\Software\Gather_A0\sketch_apr09a\sketch_apr09a.ino: In function 'void trigger()':
sketch_apr09a:58:4: error: expected 'while' before '{' token
   }{
    ^
sketch_apr09a:58:4: error: expected '(' before '{' token
sketch_apr09a:58:4: error: expected primary-expression before '{' token
sketch_apr09a:58:4: error: expected ')' before '{' token
sketch_apr09a:58:4: error: expected ';' before '{' token
sketch_apr09a:60:1: error: expected '}' at end of input
 }
 ^
exit status 1
'ADCSRA' was not declared in this scope

```

title: The Arduino Oscilloscope - Error message: 'ADCSRA' was not declared in this scope

Answers: 0


body:
Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.

    module1.cpp
    module1.h
    module2.cpp
    module2.h
    ...
    main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.

    module1.cpp
    module1.h
    module1.ino # test program
    module2.cpp
    module2.h
    module2.ino # test program
    ...
    main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.

How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

title: How do I set up a multi-file project in the Arduino IDE?

Answers: 1

body:
You have two options with ArduinoIDE.

**First** Each module in a module directory

So the structure looks like

      main_routine
         main_routine.ino
      --module1
          module1.ino  #test routine
          module1.cpp
          module1.h
     --module2
      .....
included in `main_routine.ino`

       #include "module1/module1.h"
       #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)

The **second** (more hacky way) is to have everything in one dir and for development testing working with include guards in the `main_routine.ino`

     // for production comment all MODULEX_TEST and uncomment PRODUCTION
     //#define PRODUCTION
     #define MODULE1_TEST
     //#define MODULE2_TEST
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       #include "module1/module1.h"
    #endif

    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       uint8_t myModule1Var = 0;
    #endif

    setup(){
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       myModule1setup someInit(1,2,3);
    #endif
    .....
     }

    loop(){
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       void mymodule1Func(){....};
    #endif
    #ifdef MODULE1_TEST
       void mymodule1Test(){....};
    #endif

Pros and cons

  - +This approach gives you the possibility to test two modules together.
  - -Its harder to read, but
  - +easier to document with tools like doxygen
  - ~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)


body:
I am working at this project and I found that if I have set the temperature by rotating the pot to 312 C, the iron started heating up, but when it was at about 60 C then on the display (7 segment, 3 digit) appeared 312 (the temperature that I have set) and then appeared about 70 C. I did not rotate the pot, the 312 appeared from "nowhere".
I powered on again the soldering station and it showed 35 C - then 312 C - and then 52 C and then the temperature rise normally.
I set the pot randomly at 244 C and the problem did not appeared.
The problem also appeared at 344 C set temperature.
I tried with different soldering irons and 2 different potentiometers and the problem still persist.
I have also tried with different Arduino boards, but the problem still persist.

Is there a solution for this problem ?

The project page: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/?utm_source=eetech&utm_medium=eetech-social&utm_campaign=reposts-projects/

Explanation of the schematic: J2 from "schematic.jpg" is connected to J1 of "7 segment.jpg", pin to pin. The last 4 pins of J2 from "schematic.jpg" are connected to J3 from "7 segment.jpg" and the last pin from J2 ("schematic.jpg") is connected to J6 from the "7 segment.jpg".

https://ibb.co/Zdrt1Hq
https://ibb.co/DC0LzV2

My code:
```//Soldering station Software using PID
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>

//This array contains what segments need to be turned on to display numbers 0-9
byte const digits[] = {
  B00111111, B00000110, B01011011, B01001111, B01100110, B01101101, B01111101, B00000111, B01111111, B01101111
};

int digit_common_pins[] = {8, 9, 10}; //Common pins for the triple 7-Segment LED display
int max_digits = 3;
int current_digit = max_digits - 1;

unsigned long updaterate = 1200; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;

int temperature = 0;

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  DDRD = B11111111;  // sets Arduino pins 0 to 7 as outputs
  for (int y = 0; y < max_digits; y++)
  {
    pinMode(digit_common_pins[y], OUTPUT);
  }
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  //Read temperature
  Input = 0;
  for(int i=0;i<50;i++)
  Input += analogRead(A0);
  Input /= 50;
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 550, 25, 400);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(A1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 400);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    temperature = newSetpoint;
    lastupdate = millis();
  }

  double gap = abs(Setpoint - Input); //distance away from setpoint

  if (gap < 10)
  { //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }

  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature);
}

void show(int value) {
  int digits_array[] = {};
  boolean empty_most_significant = true;
  for (int z = max_digits - 1; z >= 0; z--) //Cycle through each digit
  {
    digits_array[z] = value / pow(10, z); //We now take each digit from the number
    if (digits_array[z] != 0 ) empty_most_significant = false; //Do not display leading zeros
    value = value - digits_array[z] * pow(10, z);
    if (z == current_digit)
    {
      if (!empty_most_significant || z == 0) { //Check to see that we do not have leading zeros and display the current digit
        PORTD = ~digits[digits_array[z]]; //Remove ~ for common cathode
      }
      else
      {
        PORTD = B11111111;
      }
      digitalWrite(digit_common_pins[z], LOW);//Change to LOW for common cathode
    } else {
      digitalWrite(digit_common_pins[z], HIGH);//Change to HIGH for common cathode
    }

  }
  current_digit--;
  if (current_digit < 0)
  {
    current_digit = max_digits; //Start over
  }
}```

title: Arduino Uno and 7 segment display - wrong value displayed

Answers: 0


body:
Full disclosure - I'm very new to Arduino. I am probably missing something simple. However, I've scoured the internet and can't seem to figure it out. I am trying to use an Arduino Duo Wifi rev2 to install a bootloader onto my Ender 3 (3D printer) - see: https://howchoo.com/g/mge1mdfkzjv/ender-3-bootloader-firmware-update-marlin

When I try to upload the ArduinoISP sketch, I get the following error:

    Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno WiFi Rev2, ATMEGA328"

    /Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/brandonbarks/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/brandonbarks/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/brandonbarks/Documents/Arduino/libraries -fqbn=arduino:megaavr:uno2018:mode=on -vid-pid=0000_0000 -ide-version=10812 -build-path /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513 -warnings=none -build-cache /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_cache_822969 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avr-gcc.path=/Users/brandonbarks/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/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -verbose /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
    /Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/brandonbarks/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/brandonbarks/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/brandonbarks/Documents/Arduino/libraries -fqbn=arduino:megaavr:uno2018:mode=on -vid-pid=0000_0000 -ide-version=10812 -build-path /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513 -warnings=none -build-cache /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_cache_822969 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avr-gcc.path=/Users/brandonbarks/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/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -verbose /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
    Using board 'uno2018' from platform in folder: /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6
    Using core 'arduino' from platform in folder: /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6
    Detecting libraries used...
    /Users/brandonbarks/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=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /dev/null
    Generating function prototypes...
    /Users/brandonbarks/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=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/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/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/preproc/ctags_target_for_gcc_minus_e.cpp
    Compiling sketch...
    /Users/brandonbarks/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=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp.o

    ArduinoISP:191:27: error: reference to 'SPISettings' is ambiguous
         void beginTransaction(SPISettings settings) {
                               ^~~~~~~~~~~
    /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:167:7: note: candidates are: class SPISettings
     class SPISettings {
           ^~~~~~~~~~~
    In file included from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/ArduinoAPI.h:31:0,
                     from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/Arduino.h:23,
                     from /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:39:
    /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/HardwareSPI.h:37:7: note:                 class arduino::SPISettings
     class SPISettings {
           ^~~~~~~~~~~
    ArduinoISP:191:27: error: 'SPISettings' has not been declared
         void beginTransaction(SPISettings settings) {
                               ^~~~~~~~~~~
    /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino: In member function 'void BitBangedSPI::beginTransaction(int)':
    ArduinoISP:192:39: error: request for member 'clock' in 'settings', which is of non-class type 'int'
           pulseWidth = (500000 + settings.clock - 1) / settings.clock;
                                           ^~~~~
    ArduinoISP:192:61: error: request for member 'clock' in 'settings', which is of non-class type 'int'
           pulseWidth = (500000 + settings.clock - 1) / settings.clock;
                                                                 ^~~~~
    /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino: In function 'void start_pmode()':
    ArduinoISP:410:24: error: reference to 'SPISettings' is ambiguous
       SPI.beginTransaction(SPISettings(SPI_CLOCK, MSBFIRST, SPI_MODE0));
                            ^~~~~~~~~~~
    /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:167:7: note: candidates are: class SPISettings
     class SPISettings {
           ^~~~~~~~~~~
    In file included from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/ArduinoAPI.h:31:0,
                     from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/Arduino.h:23,
                     from /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:39:
    /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/HardwareSPI.h:37:7: note:                 class arduino::SPISettings
     class SPISettings {
           ^~~~~~~~~~~
    exit status 1
    reference to 'SPISettings' is ambiguous

If anyone has any advice, I'd really appreciate it. Thanks!

title: Trouble Uploading Sketch - Issues with SPISettings

Answers: 0


body:
I am using a Wemos D1 Mini and an mpu 6050 accelerametor. I managed to get the acceleratmetor to work and have 1 value come out of movements. So when a peak it hit (aka, the threshold of 1.00 is hit) n gets incremetented with 1. So it work a bit like a pedometer. This value is pushed to my firebase DB.

However mY problem is that after pushing it once, so the value of n is 1. The program blocks for a second and either slows down bad or the accelerametor value drops to 0. this only happens when i my piece of firebase code in. Im not sure if this causes any delays..

here is my part of my code:

    #include <Wire.h>

    #include "ESP8266WiFi.h"
    #include "FirebaseArduino.h"

    #define FIREBASE_HOST "xxxxxxxxxx.firebaseio.com" //Without http:// or https:// schemes
    #define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXX"
    #define WIFI_SSID "Bankai"
    #define WIFI_PASSWORD "xxxxxxxxxxxx"

    const float HI_THRESHOLD = 1.00;
    const float LO_THRESHOLD = 0.70;
    bool count_flag = false;

    int n= 0; //will be used to store the count
    int oldValue = n;
    String myString;

    const uint8_t MPU_addr = 0x68; // I2C address of the MPU-6050

    const float MPU_GYRO_250_SCALE = 131.0;
    const float MPU_GYRO_500_SCALE = 65.5;
    const float MPU_GYRO_1000_SCALE = 32.8;
    const float MPU_GYRO_2000_SCALE = 16.4;
    const float MPU_ACCL_2_SCALE = 16384.0;
    const float MPU_ACCL_4_SCALE = 8192.0;
    const float MPU_ACCL_8_SCALE = 4096.0;
    const float MPU_ACCL_16_SCALE = 2048.0;

    struct rawdata {
      int16_t AcX; //Acceleration
      int16_t AcY; //Acceleration
      int16_t AcZ; //Acceleration
      int16_t Tmp;
      int16_t GyX; //Gyroscope
      int16_t GyY; //Gyroscope
      int16_t GyZ; //Gyroscope
    };

    // Using int variables to convert later on to degrees and decimals
    struct scaleddata {
      float AcX; //Acceleration
      float AcY; //Acceleration
      float AcZ; //Acceleration
      float Tmp;
      float GyX; //Gyroscope
      float GyY; //Gyroscope
      float GyZ; //Gyroscope
    };

    bool checkI2c(byte addr);
    void mpu6050Begin(byte addr);
    rawdata mpu6050Read(byte addr, bool Debug);
    void setMPU6050scales(byte addr, uint8_t Gyro, uint8_t Accl);
    void getMPU6050scales(byte addr, uint8_t &Gyro, uint8_t &Accl);
    scaleddata convertRawToScaled(byte addr, rawdata data_in, bool Debug);

    //start connection, serial, and connection to db
    void setup() {
      Wire.begin();
      Serial.begin(115200);

      mpu6050Begin(MPU_addr);

        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.print("Connecting to Wi-Fi");
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print(".");
        delay(100);
      }
      Serial.println();
      Serial.print("Connected with IP: ");
      Serial.println(WiFi.localIP());
      Serial.println();
        Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

    }

    //if the value now is different from the current value it gets pushed to the DB, otherwise a flood of numbers apperars.
    void loop() {
      rawdata next_sample;
      setMPU6050scales(MPU_addr, 0b00000000, 0b00010000);
      next_sample = mpu6050Read(MPU_addr, false);
      convertRawToScaled(MPU_addr, next_sample, false);

I feel likeit is thei part which creates the bottleneck.

      //myString = String(n);
      if(oldValue != n){
       Firebase.setInt("Reps/Value", n);
      }
      delay(100); // Wait 5 seconds and scan again

    }

     float filterConstant = 0.05;
      values.AcX = (float) data_in.AcX / scale_value;
      values.AcY = (float) data_in.AcY / scale_value;
      values.AcZ = (float) data_in.AcZ / scale_value;
      filteredAx = filteredAx * (1.0 - filterConstant) + values.AcX * filterConstant;
      filteredAy = filteredAy * (1.0 - filterConstant) + values.AcY * filterConstant;
      filteredAz = filteredAz * (1.0 - filterConstant) + values.AcZ * filterConstant;
      float result = sqrt((filteredAx * filteredAx) + (filteredAy * filteredAy ) + (filteredAz * filteredAx ));

    //  Serial.print(values.AcX); Serial.print("\t");
    //  Serial.print(filteredAx); Serial.print("\t");

      Serial.println(result);

      //    Serial.print(values.AcY); Serial.print("\t");
      //    Serial.print(values.AcZ);
    //  Serial.println();

     if( result > HI_THRESHOLD && !count_flag) //if analog_in > Hi_THRESHOLD and count_flag == false
         {
               n++;
               count_flag = true;
         }

         if(result <= HI_THRESHOLD) //set count_flag to false only when below the threshold
               count_flag = false;

      Serial.println(n);

      return values;
    }

Can you help me find the problem? Thank you!

title: acelermetor count goes down after 1 peak

Answers: 1

body:
Logging the data is indeed what slows your program down.  You can't avoid that.  There are several ways to deal with it depending on what you need.

Instead of logging data all the time, you could try to accumulate a bunch of data and then write it.  This approach of buffering data will still fail to read while you log, but you will be able to get bursts of good data in between.


body:
I am doing a line follower robot using motor driver shield l239D stacked with an Arduino uno to run 2 DC motors and two infrared sensors. I am supplying 12V to the motor driver shield trough three 18650 batteries.
The point is the car was working fine and it followed the line but  two days ago it stopped working after one week of working fine...
When the two DC motors and two sensors are connected the motors don't move they just buzz(the sound it makes when it's not getting enough power), it works sometimes a little bit...

Basically the car only works with no sensor connected. So I made measurements with the multimeter and I got this:

The three batteries:12.62V

The shield receives: 12.39V only with the two sensors connected and the motors disconnected.

The shield with the motors and two sensors connected:12.28V.

And when I measured how much the motors where receiving I got 0V! In both of them...

With just one motor and the sensors connected the motor started buzzing and I got 0.07V till the sound stopped and I got zero again.

Sometimes the motors work a little bit sometimes they just buzz and some times they don't buzz at all...

I see that the batteries are fine and they can deliver enough current for everything to work but the motors don't receive almost anything!!!

Can you help me and tell me suggestions of what I need to do please? I searched and asked a lot but haven't found anything that helps...
Here is my car and my circuit.

![enter image description here](https://i.stack.imgur.com/Z9ye6.jpg)![enter image description here](https://i.stack.imgur.com/mrb4w.jpg)![enter image description here](https://i.stack.imgur.com/n8qLm.jpg)

title: Motor driver shield l239D should be giving enough power but it doesn't

Answers: 0


body:
I have 7 float variables.

`float temperature, differential, calibration,hta,lta,hha,lha;`

I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.

Thanks!

title: store multiple of float type on EEPROM

Answers: 2

body:
With the `sizeof` function:

    int nrOfBytesOfTemperature = sizeof(temperature);

You can also use directly a type:

    int nrOfBytesOfFloat = sizeof(float);

body:
create a struct and store the struct

    #include <EEPROM.h>

    const int DATA_ADDR = 0;

    struct MyData {
      float temperature, differential, calibration,hta,lta,hha,lha;
    };

    MyData data;

    void setup() {
      data.temperature = 1.2;

      EEPROM.put(DATA_ADDR, data);

      EEPROM.get(DATA_ADDR, data);
    }

    void loop() {

    }


body:
I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html

Thank you!

title: Making a Bluetooth Mouse with Arduino

Answers: 1

body:
With that specific board, yes you can.  According to [this review](http://www.lucadentella.it/en/2018/01/25/ble-con-bluno-beetle/):

> Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


body:
I want to send basic information from a server to a client. 4 numbers representing a random sequence
for example 0100. I have put this in byte array and use the "server.write" to send it to the client. At the client side I always get 4 times "255" when i print it on the monitor (when i print in on serial monitor on the server side it shows the right sequence numbers).

This is (only relevant part of ) my code on the server:

    int sequence;
    byte myseq[4]={0,0,0,0};
    int i;
    byte a;

    void loop() {
      // wait for a new client:
      WiFiClient client = server.available();

      sequence=random(0,3);

    for (i = 0; i < 4; i = i + 1) {
      if (i == sequence){
      a=1;
      }
      else{
      a=0;
      }
       myseq[i] = a;
         }

      // when the client sends the first byte, say hello:
      if (client) {
        if (!alreadyConnected) {
          // clead out the input buffer:
          client.flush();
          Serial.println("We have a new client");
          client.println("Hello, client!");
          alreadyConnected = true;
        }

        if (client.available() > 0) {
          // read the bytes incoming from the client:
          char request = client.read();
          Serial.print(request);
          for (i = 0; i < 4; i = i + 1) {
          Serial.print(myseq[i]);
          server.write(myseq[i]);

          }

        }
      }
    }

------------------------------------------------------
the code on the client side

    byte response[4]={0,0,0,0};

    void loop() {

    if (client.connect(ServerIP, 23)) {
      client.print("741G");
      //String response = client.readStringUntil('\n');
      for (i = 0; i < 4; i = i + 1) {
      response[i] = client.read();
      Serial.println(response[i]);

      }

      //client.stop();
    }

Can somebody help me in explaining what i'm doing wrong ? what happens with the numbers once they get sent ? Apparently they arrive in a different format ?

thanks in advance !

ps : i see now that my sequence numbers are always 4 booleans (half a byte) maybe there is an easier way?

title: sending numbers from server to client (arduino mkr1010)

Answers: 0


body:
i use the "client.availbale" to check incoming data on the (mkr1010) client coming from (mkr1010) server but it always contains "0". Serial printing (monitor) it on server works. It looks as if the data never arrives? Thanks for helping out !

client code :

    if (client.connect(ServerIP, 23)) {
    client.print("741G");
    byte i = 0;
    Serial.println(client.available());

        while (client.available() > 0 && i < bufferSize) {

          incomingMessage[i] = client.read();
          Serial.println(incomingMessage[i]);
          Serial.println(i);
          // check if end of incoming message
          if (incomingMessage[i] == '\r') {
            // replace carriage return with null terminator
            incomingMessage[i] = '\0';
            // set array index counter to end
            i = bufferSize;
            // flush out any remaining control characters which would
            // stay in client buffer until next loop
            client.flush();
          }
          // increase array index counter
          i++;

my server code :

    // when the client sends the first byte, say hello:
      if (client) {
        if (!alreadyConnected) {
          // clead out the input buffer:
          client.flush();
          Serial.println("We have a new client");
          client.println("Hello, client!");
          alreadyConnected = true;
        }

        if (client.available() > 0) {
          // read the bytes incoming from the client:
          char request = client.read();
          Serial.print(request);

          for (i = 0; i < 4; i = i + 1) {
          Serial.print(myseq[i]);
          server.write(myseq[i]);

          }

title: Client.available remains empty (0)

Answers: 0


body:
So, I have been following this tutorial on how to run a stepper motor with Arduino using an A4988 Stepper Driver. This is the tutorial: [How To Control a Stepper Motor with A4988 Driver and Arduino][1]. I have connected the wires according to this schematic:

[![Schematic][2]][2]

I have connected the wires exactly like this and triple-checked it! The problem is the stepper motor is not turning. This is the code(it's simple):

    // defines pins numbers
    const int stepPin = 3;
    const int dirPin = 4;

    void setup() {
      // Sets the two pins as Outputs
      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
    }

    void loop() {
      digitalWrithe(dirPin,HIGH); // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin,HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin,LOW);
        delayMicroseconds(500);
      }
      delay(500); // One second delay
    }

One weird thing:
> **When I connect the sleep and reset pin on the A4988 board the stepper motor starts turning. Like why?**

**NOTE:** I replaced the MEGA with a UNO because at the moment I'm just testing.

  [1]: https://www.youtube.com/watch?v=5CmjB4WF5XA
  [2]: https://i.stack.imgur.com/VyPmX.png

title: Stepper Motor is not working with A4988 board

Answers: 1

body:
You have to connect the sleep and reset pin together. I assume that you took this schema on how to mechatronics. In his video you see that the sleep and reset pins are connected. I don't know why but it has to be like that.

Then, if the motor vibrates or click, it may be one of these problems:
- You didn't connect the motor properly
- The current is set too low on the board (screw on the motor driver)
- The battery (Vmot) isn't powerful enough

If it's not one of those problems, the A4988 chip might have an issue. I have a similar problem where it turn in one direction and only when the pwm signal goes throught the direction pin  instead of the step pin.


body:
i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some `serial.println` lines) and i see i get soft wdt reset right there in `http.post`.

i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.

do you have any idea what cause this problem?

title: random soft wdt reset while request

Answers: 1

body:
Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused

So the only thing as of now I can recommend

There is an issue with bearssl:

It's a WDT error caused by an extended SSL negotiation.

  - Change the core frequency to 160MHz (if not already done) and try again.
  - Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
  - Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess


body:
I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore.
My questions are:

1. Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
2. My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.

https://ibb.co/QnLHsM0

https://ibb.co/KxLFKsQ

title: Arduino "Phantom Powering"

Answers: 2

body:
When you disconnect the arduino from 5V you must also remove either

 - disconnect any other device that is connected to the arduino and has its own power supply
 - or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).

body:
> Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?

Yes.

> My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Not really.

Your problem only occurs when you "break" the system by separating the 5V from the Arduino - at which point current flows from the output of the op-amp and through the LED displays, through the IO pins, up through the clamping diodes inside the IO pins, and to the Arduino's 5V.

Since it only happens if you disconnect the 5V and you don't intend to disconnect the 5V then it's not a problem. However if you wanted to improve it then you could take the output of the 5V reguator and feed that direct into the Arduino's USB port. You could then power all the other devices that run at 5V from the Arduino's 5V pin.  That way if you remove the 5V from the Arduino then you also remove it from all the other 5V devices that potentially feed power back in.


body:
I have the following sketch...

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
    }

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
    }

This works great with my client code...

    import SerialPort from 'serialport';
    const port = new SerialPort('/dev/ttyACM0', {
      baudRate: 115200,
      autoOpen: false
    })

    port.open(function (err) {
      if (err) {
        return console.log('Error opening port: ', err.message)
      }

      // Because there's no callback to write, write errors will be emitted on the port:
      console.log("port opened");
      port.on('readable', function () {
        console.log('Data:', port.read())
      })
    })

Now I want to slow it down so I change the sketch to...

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
      delay(10000);
    }

I would expect this to delay each message by 10 seconds, however, it seems to never rerun so I do not get any messages. What am I missing? Why would delay break the loop?

title: Why is delay(1000) breaking my serial communication?

Answers: 2

body:
NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.

 So instead of

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
      delay(10000);
     }

you would do

    unsigned long timerStart = 0;
    unsigned long myTimer = 10000;

    setup(){....}

     void loop() {
      if(Serial.available() > 0 ){
         if(millis() - timerStart > myTimer){      // non blocking
           Serial.println("Hello world from Ardunio!");
           timerStart = millis(); // reset timer
         }
       }
     }

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing => not a good thing todo in communication scenarios,

body:
Get rid of `if(Serial.available() > 0)`. You only need that if statement if you're expecting information from `Serial`, but it doesn't seem to be the case for your project.

Also, only use `delay()` if you have a really good reason to.


body:
Hello i have one of [these](http://gg.gg/hwrmi)

My goal for this project is to have a higher quality mic and be able to play music through it

My question is how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line. I have prior knowlege on liking a aux as i have setup my Christmas lights as a vu meter using relays and a aux but the confusing part is the rj9 line

Are the speaker pins only to trigger a relay and allow power to flow from the car battery or am i completely wrong if im right i assume i could just solder the audio jacks positive negative to the rj9 mic positive negative and then find a method to triger the speaker relay

title: Car PA system enhancement

Answers: 1

body:
"how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line" - the arduino uno doesn't have a digital to analog converter, so without external hardware it's not possible to make him generate the audio signal. Also its ADCs are not fast enough to sample an audio signal coming from a microphone at a sufficient sample rate (I think the maximum are 1-2kHz). As you explicitly want to improve sound quality this is an issue.

When using an arduino uno you might be better off using an external audio circuit which only gets switched on and off by the arduino.
Controlling the siren's buttons will not be a big difficulty. You have to do some reverse engineering to find out the siren's logic level and how the buttons are used in the device. You can probably simply replace them with mosfets, but that is an electronic issue.


body:
I am really happy with my new Arduino stuff and playing around with all those pixels :).

I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.

My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.

I know that `delay();` will stop the code completely and wait till the time passes, but I wrote some code without the use of `delay();` and used `millis();` instead.

So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the `while();` part in my code works kinda like a `delay();` and that would prevent it from restarting until a full cycle. I used some `millis();` code from a different sample so it's not like the ones from Blink Without Delay.

I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.

```
#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}
```

Thanks in advance for you help.

title: Restart sequence of NeoPixel stick with a push button at any time

Answers: 2

body:
Firstly, good for you trying to avoid `delay()`.

However your `while` loop pretty much does exactly what `delay()` does anyway.

Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".

Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light *just one more LED*.  Once you have lit all 16 you can then restart your sequence.

And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.

For example `loop()` might look something like this (untested):

```
void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}
```

The key there is that the variable `lednum` contains the number of LEDs that you want to display. Once per second, controlled by `millis()`, the LEDs are updated to display that number of LEDs.

body:
This is not an answer, but an expansion on Majenko's code.

It adds another layer between the button press and the led display functions to make the program more flexible

    void loop() {

        static bool     tick          = false;                 // periodic trigger signal
        static bool     zap           = false;                 // enable signal to run sequence
        static bool     buttonClicked = false;                 // button moved from "released" to "pressed"

        static uint8_t  mode          = 0;                     // chooses the light sequence to run
        static uint8_t  lednum        = 0;

        static uint32_t animTicker    = millis();

        if (millis() - animTicker >= 1000) {                   // Once per second
            animTicker = millis();
            tick = true;                                       // set the tick flag
        }

        if (buttonClicked) {                                   // you could check for a double-click here
            buttonClicked = false;
            zap = !zap;                                        // start/stop with button  ... zap is used for the separation of the button click function and the display function
            if (zap) {
                lednum = 0;                                    // start animation sequence at beginning
                mode += 1; if (mode > 2) mode = 0;             // select the next mode .... this could be done with a double-click
            }
        }

        if (tick && zap) {
            tick = false;                                                   // clear the tick flag .... zap stays set for the duration of the animation sequence
            lednum++;

            if (lednum > NUM_LEDS_PER_STRIP) {
                zap = false;                                                // This stops the sequence (runs only once) ... use a counter if multiples are needed
            }

            else {
                switch (mode) {                                             // pick one of the sequences ....  only colors change in this example

                    case 0:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {  // Turn on up to lednum LEDs and turn off the others
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Blue;
                            } else {
                                ledStrip[i] = CRGB::Black;
                            }
                        }
                        break;

                    case 1:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Red;
                            } else {
                                ledStrip[i] = CRGB::Black;
                            }
                        }
                        break;

                    case 2:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Green;
                            } else {
                                ledStrip[i] = CRGB::Yellow;
                            }
                        }
                        break;
                }

                FastLED.show();
            }
        }

        buttonState = digitalRead(signalButtonPin);

        if (buttonState != lastButtonState) {        // button state transition
            lastButtonState = buttonState;           // new "last state"
            if (buttonState == LOW) {                // transition from "released" to "pressed"
                buttonClicked = true;
            }
        }
    }


body:
I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:

```
2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
```

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.

Does anybody know how to get rid of these messages?

Thank you very much.

title: Error messages while verifying code with Visual Studio Code

Answers: 1

body:
It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

  - You have to downgrade to January release 1.42 **AND**
  - Then turn off automatic updates for the moment.

How to get the release: [Click here](https://code.visualstudio.com/updates/v1_42)

Before installing /downgrade<br>
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.


body:
[![enter image description here][1]][1][![enter image description here][2]][2][![enter image description here][3]][3][![enter image description here][4]][4][![enter image description here][5]][5]I verified my code and uploaded it to the board and that was successful.

Info:
  - Using Mega 2560 Arduino Board with Adafruit V1
  - 3 DC 12 volt motors
  - on HP computer

Here is my code:

    #include <AFMotor.h>

    AF_DCMotor motor(1, MOTOR12_8KHZ);
    AF_DCMotor motor2(2, MOTOR12_8KHZ);
    AF_DCMotor motor3(2, MOTOR12_1KHZ);

    void setup()  {
      Serial.begin(9600);
      Serial.println("Motor Test!");
      motor.setSpeed(20); //set speed of motor
      motor2.setSpeed(20); //set speed of motor
      motor3.setSpeed(25); //set speed of motor
    }

    void loop() {
      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //first song starts
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(14000);

      Serial.print("tack");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song ends
      motor.run(RELEASE);
      delay(13000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock"); //second song starts
      motor.run(RELEASE);
      delay(24000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock"); //second song ends
      motor.run(RELEASE);
      delay(17000);

       Serial.print("tick");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //third song starts
      motor.run(RELEASE);
      delay(23000);

      Serial.print("tick");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //third song ends
      motor.run(RELEASE);
      delay(21000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tick");
      motor.run(FORWARD);
      delay(3000);

      Serial.print("tack"); //fourth song starts
      motor.run(RELEASE);
      delay(5000);

      Serial.print("tack");
      motor.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //fourth song ends
      motor.run(RELEASE);
      delay(21000);
       //waving motor
      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      //Waving motor
      Serial.print("tick"); //first song starts
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //first song ends
      motor2.run(RELEASE);
      delay(14000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //SEcond song starts
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //second song ends
      motor2.run(RELEASE);
      delay(15000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(5000);

      Serial.print("tack"); //Third song starts
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tock"); //third song ends
      motor2.run(RELEASE);
      delay(14000);

      Serial.print("tick"); //fourth song starts
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(BACKWARD);
      delay(2000);

       Serial.print("tock");
      motor2.run(FORWARD);
      delay(1000);

      Serial.print("tick");
      motor2.run(RELEASE);
      delay(1000);

      Serial.print("tick");
      motor2.run(FORWARD);
      delay(2000);

      Serial.print("tack");
      motor2.run(BACKWARD);
      delay(2000);

      Serial.print("tock"); //fourth song ends
      motor2.run(RELEASE);
      delay(7000);

      //dancing motor
      Serial.print("tock"); //first song starts
      motor3.run(RELEASE);
      delay(11000);

      Serial.print("tick");
      motor3.run(FORWARD);
      delay(22000);

      Serial.print("tock"); //first song stops //second song starts
      motor3.run(RELEASE);
      delay(16000);

        Serial.print("tick"); //Second song stops
      motor3.run(FORWARD);
      delay(28000);

      Serial.print("tock"); //Third song starts
      motor3.run(RELEASE);
      delay(15000);

      Serial.print("tick"); //Third song stops
      motor3.run(FORWARD);
      delay(33000);

      Serial.print("tock"); //fourth song starts
      motor3.run(RELEASE);
      delay(16000);

      Serial.print("tick");
      motor3.run(FORWARD);
      delay(5000);

      Serial.print("tock");
      motor3.run(RELEASE);
      delay(1000);

      Serial.print("tick"); //fourth song ends
      motor3.run(FORWARD);
      delay(16000);

      Serial.print("tock");
      motor3.run(RELEASE);
      delay(5000);
    }

  [1]: https://i.stack.imgur.com/M3e0o.jpg
  [2]: https://i.stack.imgur.com/aAU02.jpg
  [3]: https://i.stack.imgur.com/sk6xd.jpg
  [4]: https://i.stack.imgur.com/Y8ZEO.jpg
  [5]: https://i.stack.imgur.com/k7WQg.jpg

title: Why are my motors attached to an Arduino MEGA not running?

Answers: 1

body:
As you did not give details I assume the following:

  - You supply the MEGA via USB or external 5-12V power supply
  - the motors are supplied via an extra external 12V power supply with sufficiant amperage
  - All cabeling is checked and correct

Looks like this schematic (without 12V power supply attached to the motor shield)
[![AF_motor_shield_v1][1]][1]
[![AF_Motor_shield_v2][2]][2]

To your code:

  -  Get rid of the delay()s - they block processing so what happens:

         motor.run(FORWARD);  // => You give a command via lib
         delay(2000); // You stop your processing so the motor is not running

so you have two options both need the definition of a timeStamp var

  - working with a (blocking) while loops
  - or creating a finite state machine (search here on SO for details)

So I will for simplicity use the first approach

     // Copy this var before your setup
     unsigned long timeStamp = 0;
    // use your complete setup
     void setup(){...}
     // Change your loop functions like thes first three converted lines
     void loop(){
      timeStamp = millis();
      Serial.print("tick");
      while(millis()-timeStamp < 2000){
         motor.run(FORWARD);
      }
      timeStamp = millis();   // resets the time to current
      Serial.print("tock");
      while(millis()-timeStamp < 5000){
         motor.run(RELEASE);
      }
      timeStamp = millis();   // resets the time to current
      Serial.print("tack"); //first song starts
      while(millis()-timeStamp < 2000){
         motor.run(BACKWARD);
      }
    // .... AND SO ON .....
    }

Be aware that the whiles are blocking but for your sequential processing its ok.

  [1]: https://i.stack.imgur.com/4jF1P.jpg
  [2]: https://i.stack.imgur.com/toMGU.jpg


body:
I'm trying to write a little sensor reading application with a light sensor attached to an Arduino, which writes the information from the sensor over serial. I have written a python program to read the data from the serial port. The good news, is that my program is working completely fine... only if I make sure that the Arduino USB is connected to my laptop before I launch my Python program.

I have myself forgotten to connect the Arduino before running the program before, which can leave it hanging... until you realise and plug the Arduino back in. It would be nice to have a window helping users if they ever make the same mistake.

Here is the Arduino sketch I have running on my Arduino.

    int photoTran = A1;
      int reading = 0;

    void setup() {
      pinMode(photoTran, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // We just read the value on the analogPin
      reading = analogRead(photoTran);
      Serial.println(reading);
      delay(100);

    }

Here is the little catcher part of the Python script which checks whether the Arduino is connected before I get into the main part of my application. When I plug in the Arduino before running the Python script, it can still sometimes take a few attempts before connecting. (Just FYI: the window(), button, values, variables are from the PySimpleGUI framework that I'm using.)

    connected = False
    while connected == False:
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break
        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.1)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)
    window.close()

    # User exited from the GUI connection window
    if not connected:
        sys.exit(0)

Later on in my Python code, I want to read the sensor data coming to us from the Arduino. ReadArduino, and CleanThe are the functions that I use to read data from the Arduino.

    def ReadArduino( serialCon ):
    """ Try to read in a value from the Arduino. Sometimes we might read a value from the serial
        port before the arduino has sent anything. In such cases we will wait a small time, and read again.
        Until we pick up our first non empty integer value."""
    while True:
        val = serialCon.readline()
        print(val)
        val = cleanThe(str(val))
        if val != '':
            return val

    def cleanThe( lineVal ):
    """ The Arduino returns non-clean data back to us.
        We need to remove all the non-integer values to get
        a nice plottable integer value. Will accept '.' unconditionally for now,
        we may have to add conditions later. """
    S = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}
    clean = ''
    for char in lineVal:
        if char in S:
            clean += char
    return clean

Now the confusing part. When I run the application without the Arduino connected to my computer. It gets stuck in the while connected == False: while loop above. This is exactly what I want. Then when I plug it in, the serial port sets up and we break out of the loop. I even have a serial port object that I read from.

However, when I read from the serial port, I get back garbage hex values, without any sign of any useful integer values that I would expect.

Here are some sample raw val values that get read back when the python script is run with the Arduino connected before running: `
b'336\r\n'
b'349\r\n'
b'343\r\n'
b'322\r\n'`

Then here is the output I receive when the Arduino was not connected to my computer before running the Python script.

    b'\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\x00\xe0\x00\xe0\xe0\x00\x00\xe0\x00\xe0\x00\x00\x00\x00\x00\xe0\x00\x00\xe0\xe0\x00\x00\xe0\x00'

    b'\x00\x00\x00\xe0\x00\x00\xe0\x00\x00\xe0'

I have noticed, that when I am running my script with the Arduino plugged in from the start (i.e. the working case). The first value I read back from the Arduino is the same type of garbage hex:

    b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

It seems like in the working case, the hex is all sent on one line. Where as in the non-working case, these hex values, seem to be sent intermittently in smaller chuncks. Perhaps I could add a check to the Arduino code, to only write values back to serial if they are good? I do realise this may be more of a python serial issue than an Arduino issue, let me know if this is the case and I will move the post.

Has anyone experience some kind of problem like this before?

title: Arduino sends bad data ONLY when not connected at the launch my application

Answers: 2

body:
On the Arduino side make your code non blocking:

     unsigned long timeStamp = 0;
     unsigned long timerDelay = 1000; // 1 second

     setup(){....}

    void loop() {
    // We just read the value on the analogPin
     if (millis() - timestamp > timerDelay ) {
         reading = analogRead(photoTran);
         Serial.print(reading); // instead of println which sends additional \r\n
         timeStamp =millis();  // reset timer instead of delay(100);
     }
    }

On the Phyton side try to implement a routine waiting for the first char and then start reading from the next message on. The 1 second between sends on Arduino should suffice to ensure its working. The garbagge chars could be an init sequence from the port driver - this can not come from your code,

body:
Just to explicitly show what I changed to my python code I thought I would answer my own question. The solution I found ended up being in the Python, but the other suggestions were useful for cleaning up the output of my Arduino.
Here is the old auto connecting solution.

    connected = False
    window = sg.Window('Arduino Connection').Layout(layout)
    attempts = 0
    while connected == False:
        print("In connection while loop")
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break

        try:
            print("Attempting to connect")
            SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
            print(SER)
            connected = True
            ser.append(SER)
        except:
            time.sleep(0.1)
            attempts += 1
            window.FindElement('attempts').Update(attempts)

Here is the working solution where I ask the user to press a connect button.

        connected = False
    window = sg.Window('Arduino Connection').Layout(layout)
    attempts = 0
    while connected == False:
        print("In connection while loop")
        button, values = window.Read(timeout=300)
        if button in (None, 'Exit'):
            break
        if button == 'Ok':
            try:
                print("Attempting to connect")
                SER = serial.Serial(serial_port, baud_rate, timeout=0.02)
                print(SER)
                connected = True
                ser.append(SER)
            except:
                time.sleep(0.1)
                attempts += 1
                window.FindElement('attempts').Update(attempts)


body:
I'm trying to use the StackString-library which offers not to eat up RAM over time by re-assigning values to strings. I started from scratch and wrote a very basic democode which works.
Then I added an assignment to a STackString-variable from a normal string or a function with return-value string
See code below
If I try to compile
I get a compiler-error saying
no matching function for call to 'Stack::StackString<50>::append(String&)'

here is the code

    #include <StackString.hpp>
    using namespace Stack;  // it is very important to have this line of code. Otherwise the code won't compile

    StackString<50> myString = StackString<50>("Hello, World!");

    String NormalString = "1234Test";

    void setup()
    {
      Serial.begin(115200);
      Serial.println();
      Serial.println();
      Serial.println(myString.c_str());

      myString.prepend("Everybody say: ");
      Serial.println(myString.c_str());

      myString.append(" How are you doing?");
      Serial.println(myString.c_str());
      Serial.println();

      //myString = NormalString;
      myString.append(NormalString);

    }

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

    }

Do I have to do some typecasting? and if yes how does it look like?
WHat I want to do is assigning a StackString a new value. This means the STackString is on the left side of the "="  assigning operator. I have tried different variants to no avail.

Could this be a problem of the special construction as a "namespace" ?
No idea no clue

you find the STackString-library here:
https://gitlab.com/arduino-libraries/stackstring

best regards

Stefan

title: How to assign a string-variable to a StackString based on the StackString-library?

Answers: 1

body:
`StackString` doesn't know what a `String` is.  The `append` function only accepts a `const char *`, a `const char` or an `int`:

```
void append(const char* string);
void append(const char character);
void append(int number);
```

You can get a `const char *` from a `String` easily enough with `.c_str()`, so use that in the append:

```
myString.append(NormalString.c_str());
```

There is also no simple assignment (or complete content replacement) with `StackString` - you have to "clear" the string first.  So to replace the content with what is in `NormalString` you would:

```
myString.clear();
myString.append(NormalString.c_str());
```


body:
I have been learning lower level data reading on internet communication
As a part of bigger project I am testing web interface.

So far I could get main website displayed and by seeing the web-address read the data from GET request.
As I intend to send codes I wish to use POST method.

I am Trying to make this as standalone class for mine future projects, so I am only sending the class method itself. (Latter it would take websites content as a string, but for now input variables are yet to be implemented)

I am using esp8266, but would prefer to avoid esp8266 specific libraries as I wish it to eventually run on its realtek equivalent.

The code:

```
uint8_t Stranky::Stav(String obsahStranky, uint8_t obnovovat){
 WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    char vstupRiadok[150]={'\0'};
    uint8_t i=0;
    bool currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
  char c = client.read();
        vstupRiadok[i]=c;
        if(c=='\n' || i>=149) {
   Serial.println(vstupRiadok);
   //------------Extract variables here--------
   for(uint8_t j=0; j<149; j++) {
    //Serial.print(vstupRiadok[j]);
    vstupRiadok[j]='\0';
   }
   i=0;
  } else i++;
        if (c == '\n' && currentLineIsBlank) {
   Serial.println("Sending page");
   client.println(ohlasSa(1,1));
   client.println("<!DOCTYPE HTML>");
          // send a standard http response header
   client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
   client.println("<h1> Nic nove</h1>");
   client.println("<form method='POST'>");
   client.println("Name:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nSurname:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input type='reset'/> </form> </body>");
   client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("Prehliadač dpojený");
  }
}
```
This results in Browser code:
```
<!DOCTYPE HTML>
<html><head> <meta charset="utf-8"></head><body>
<h1> Nic nove</h1>
<form method='POST'>
   Name:<input type="text" id="Name" name="Name"/><br>
   Surname<input type="text" id="Surname" name="Surname"><br>
<input type="submit" value="Submit"/><input type='reset'/> </form> </body>
</html>
```
When I send any data over the form it does not get received  and only receive these:
```
WS:ac
:ref 1
WS:av
:ref 2
:ur 2
:rn 469
POST / HTTP/1.1

Host: 192.168.43.209

User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: sk,cs;q=0.8,ru;q=0.6,en;q=0.4,en-US;q=0.2

Accept-Encoding: gzip, deflate

Referer: http://192.168.43.209/

Content-Type: application/x-www-form-urlencoded

Content-Length: 25

Connection: keep-alive

Upgrade-Insecure-Requests: 1

Sending page

```

No post, or Cookie variables that I could extract

I am far from home and too short of data to be installing more software like wire-shark over phones network sharing

title: Arduino webserver POST receive varriables

Answers: 2

body:
Check your definition of

    String vstupRiadok

it should not be

    String vstupRiadok="                                      "; //80 blanks

I would replace it with a decent sized fixed char anyway

    char vstupRiadok[81] = {'\0'};

if you create an empty line or other text do not forget to write the end terminator `'\0'` and make sure the char array is +1 the size for the longest string totake

As String class is a problem on its own as an Arduino class.

The HTML code generated has a missing

     <meta charset    ="utf-8">

error in the dev-tools. Aside from that whats the server code running on the Arduino,its not given. The class creates a html page, but at least in FF75 it tries to call server.ip\odpoved - so there has to be some js or Arduino code to decode this route there are no params attached from the form.

**EDIT**An extraction routine would look like:

 bool currentLineIsBlank = true;
 bool currentLineIsGet = true;
 uint8_t tCount = 0;
 char tBuf[64];
 uint8_t n=0;
    uint8_t s=0;
 char *pch;

 Serial.print("Client request: ");

  while (client.connected()) {
   while (client.available()) {
  char c = client.read();

  if (currentLineIsGet && tCount < 63) {
    tBuf[tCount] = c;
    tCount++;
    tBuf[tCount] = 0;
  }

  if (c == '\n' && currentLineIsBlank) {
    Serial.println(tBuf);
    // retrieve the POST data
    Serial.print("POST data: ");
    while (client.available()) Serial.write(client.read());
    Serial.println();

    pch = strtok(tBuf, "?");

    while (pch != NULL) {
   if (strncmp(pch, "Name=", 5) == 0) {
              pch = pch+6;
     char Name [24] = {'\0'};
              while(pch != '&'){
                 char Name [n] = pch;
                 n++;
               }
              char Name [n+1] = {'\0'};
     Serial.print("Name="); Serial.println(Name);
   }

   if (strncmp(pch, "Surname=", 8) == 0) {
              pch=pch+9;
     char Surname[24] = {'\0'};
              while(pch != '\r') {   // check if your response has that after the content or if its '\0'
                 char Surname [s] = pch;
                 s++;
               }
              char Surname [s+1] = {'\0'};
     Serial.print("Surname="); Serial.println(Surname);
   }
   pch = strtok(NULL, "& ");
    }
   // here the Sending response part starts

 You do not need a JSON parser for this just get the post request

body:
Based on codebreakers code I have been able to combine it into working one

The problem was on a fact that communication starts with header variables, then empty line, then body containing the variables

First get the connection: and create base variables
```
uint8_t Stranky::Stav(){
 WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
 bool currentLineIsBlank = 0;
 bool body=0;             // Helps seeing if this is still header
 bool finished=0;         // To know if to terminate connection
 uint8_t i = 0;           // To prevent iterator from resetting to 0
 char fullLine[81]={'\0'};  // buffer for input character to line
 // char *pch;

 Serial.print("User connected\n");
 while (client.connected()) {
  while (client.available()) {
   bool linEnd=0;          // When to deal with line (print it)
```
Get one incoming character:
```
   char c = client.read();
```
Now deal with new line character first

If the last line was empty That would mean: Header is finished and moving to the body of the incoming data
 If not change currentLineIsBlank (until new line gets its first character)
```
   if(c=='\n') {
    if(currentLineIsBlank) {
     if(!body) body=1;
     currentLineIsBlank=0;
    } else {
     Serial. print("/");
     currentLineIsBlank=1;
     linEnd=1;
    }
```
Now lets deal with any other character then new line:

```
   } else {
    currentLineIsBlank=0;   //If it has a character then its not empty
    fullLine[i]=c;
    i++;                //Move to the next letter
   }
```
Make sure that our array doesn't overflow
```
   if(i>=81) linEnd=1;
```
Now we know what is happening we can take some action after the buffer line is finished

if we are at the body stage, but we havent "finised" sending code
```
   if(linEnd){
    if(body && !finished) {
     finished=1;          // Finishing sending page
     Serial.printf(F("Variables:\n\t"));
```
Start extracting characters from body of the incoming data.

In a simple form like ours POST variables are on a last line, so we will just keep rewriting the line
```
     uint8_t k=0;
     while (client.available()) {
      fullLine[k]=client.read();
      Serial.printf(F("%c"),fullLine[k]);
      if(k<80) k++;
      if(fullLine[k]=='\n') {
       k=0;
       Serial.println();
      }
     }
     // Here you can extract variables as shown in codebreakers' answer

```
Finaly send then websites html code:
```
     Serial.print("Sending page\n");
     client.println(heatheRoutine()); //I have extra routine to inject heather so I do not have to write it every time I write a page
     client.println("<!DOCTYPE HTML>");
     // send a standard http response header
     client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
     client.println("<h1>Fill the form now !!!</h1>");
     client.println("<form method='POST'>");
     client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input type='reset'/> </form> </body>");
     /*Serial.printf(F("Page source send\n"));*/
     client.println("</html>\n");
     break;
    }
```
If we are not dealing with the body yet:
```
    currentLineIsBlank=1;
    for(uint8_t j=0; j<i; j++) { //Print the last line
     Serial.print(fullLine[j]);
     fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
    }
    Serial.println();
    i=0;    //Since we are on an end of a line we are starting from first position in a buffer
   }
  }
```
If we have finished what we have wanted we need to get out of communication loop
```
  if(finished) {
   Serial.printf(F("Ending\n"));
   break;
  }
    }
```
And close the connection:
```
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
 client.stop();
    Serial.println("browser disconnected");
  }
}
```
Complete code:
```
uint8_t Stranky::Stav(){
    WiFiClient client = server.available();
  if (client) {
    // an http request ends with a blank line
    bool currentLineIsBlank = 0;
    bool body=0;             // Helps seeing if this is still header
    bool finished=0;         // To know if to terminate connection
    uint8_t i = 0;           // To prevent iterator from resetting to 0
    char fullLine[81]={'\0'};  // buffer for input character to line
    // char *pch;

    Serial.print("User connected\n");
    while (client.connected()) {
        while (client.available()) {
            bool linEnd=0;          // When to deal with line (print it)
            char c = client.read();
            if(c=='\n') {
                if(currentLineIsBlank) {
                    if(!body) body=1;
                    currentLineIsBlank=0;
                } else {
                    Serial. print("/");
                    currentLineIsBlank=1;
                    linEnd=1;
                }
            } else {
                currentLineIsBlank=0;   //If it has a character then its not empty
                fullLine[i]=c;
                i++;                //Move to the next letter
            }
            if(i>=81) linEnd=1;
            if(linEnd){
                if(body && !finished) {
                    finished=1;          // Finishing sending page
                    Serial.printf(F("Variables:\n\t"));
                    uint8_t k=0;
     while (client.available()) {
      riadok[k]=client.read();
      Serial.printf(F("%c"),riadok[k]);
      if(k<80) k++;
      if(riadok[k]=='\n') {
       k=0;
       Serial.println();
      }
     }
                    // Here you can extract variables as shown in codebreakers' answer

                    Serial.print("Sending page\n");
                    client.println("HTTP/1.1 200 OK\r\n");
                    client.println("Content-Type: text/html\r\n");
                    client.println("Connection: close\r\n");
                    client.println();
                    client.println("<!DOCTYPE HTML>");
                    client.println("<html><head> <meta charset=\"utf-8\"></head><body>");
                    client.println("<h1>Fill the form now !!!</h1>");
                    client.println("<form method='POST'>");
                    client.println("Meno:<input type=\"text\" id=\"Name\" name=\"Name\"/><br>\nPriezvisko:<input type=\"text\" id=\"Surname\" name=\"Surname\"><br>\n<input type=\"submit\" value=\"Submit\"/><input    type='reset'/>  </form> </body>");
                    /*Serial.printf(F("Page source send\n"));*/
                    client.println("</html>\n");
                    break;
                }
                currentLineIsBlank=1;
                for(uint8_t j=0; j<i; j++) { //Print the last line
                    Serial.print(fullLine[j]);
                    fullLine[j]='/0';     //restore default values To prevent characters leaking into next line
                }
                Serial.println();
                i=0;    //Since we are on an end of a line we are starting from first position in a buffer
            }
        }
        if(finished) {
            Serial.printf(F("Ending\n"));
            break;
        }
    }
    // give the web browser time to receive the data
    delay(1);

    // close the connection:
    client.stop();
    Serial.println("browser disconnected");
  }
}
```


body:
I am rather new to using an Arduino.
As a part of my Graduate-Level Chemistry research, I am trying to further the development of a cheap DIY, open-source, Flow Chemistry Syringe pump system.

The device utilizes Stepper Motors, Step Motor control boards, an Arduino Uno, and a 3D printed Pump frame. Simple code was previously developed using the Arduino IDE. I have expanded on this a bit to allow for more customization (syringe size, mostly). The limitation here, is that the Serial Monitor inputs will be taxing to the users. I need to develop a simple GUI that allows for all of the inputs I need (syringe size, flow (step) rate, start and stop functions, etc.). I need this gui to be a standalone application that can be easily shared (no need to download anything extra, no installations, deploy-able on at LEAST Win and Mac).

Our labs goal is to develop a system that is easy to use and distribute, reducing the costs associated with using Flow Chemistry. I have a decent understanding of Arduino IDE, and I am willing to learn whatever I need to make this work.

I have seen a few things about Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE which would make deployment too complicated.

How should I approach this? What language do I need to learn? What advice do you have?

title: Developing Standalone Arduino GUI Controller

Answers: 2

body:
The Uno is connected to the PC with a Serial interface (emulated over USB). The program on the PC only sees the Serial interface. It is not important, if there is really an Arduino at the other end. Nearly every programmung language can be used for interfacing a Serial interface, each gives advantages and disadvantages. But you will not have a single portable program file, that you can start on different OS without installing anything. Either you need to compile the program for each OS individually, or you can use a portable programming language, where you first need to install it's framework on the OS (for example python).

I would propose a different solution (that I'm currently also working on): Depending on your lab situation you could extend your project with a network interface, either Wifi or LAN. Then you can present a webinterface to the user. When writing HTML/javascript websites, it is easy to have them display correctly on most mayor browsers.

That way the GUI is really independent from the OS. For adding the network connection, you could use a LAN shield, Wifi shield, or directly change the microcontroller from an Arduino Uno to an ESP board, which has Wifi build in and is also has more computation power and memory.

The webinterface can be interactive by the use of javascript (since you cannot run php or similar on the Arduino or ESP).

Wether you want to use a companion application, that you write for the PC, or a webinterface is up to you and depends on your exact lab situation.

body:
I have a similar project ahead of me. While it is quite but obvious to be able to read the output voltages using arduino, I was wondering if we could create a python file which will be saved as an executable, but have in it, code that will run the original arduino cc file to read the averaged voltages from the pins. I tried using pyqt5 and/or tkinter but I am having thread issues in that the gui hangs after a few seconds of activity.(I used pyserial library here)
It will be really helpful if someone can help me out here.


body:
i´m trying to build a little monitor of an ESP8266 and an OLED display that displayes the Status of a Robotarm.

The robotarm is controled by a RAMPSboard that has a webserver, so i can check the status from a browser.
For that i´m trying to use the BasicHttpClient Sketch from Arduino to read the status and progress.

The problem is i.... don´t know how?
I guess i know where the data is in my HTML document, but i dont know how to call it via GET request.

With the modified BasicHttpClient Sketch i can read the whole html site and print it out on serial, but after weeks of reading and watching tutorials i´m still stucked.

Long story short.

i want to read "just" the status and progress off of that webserver, with a GET request

this is the part of HTML code where my data is...i guess:
here are 3 different times of the informations i´d like to "extract" and displayed on my little ESP8266 monitor
```
<span id="stat" title="Not Available">Idle</span>
<span id="stat" title="Not Available">Working</span>
<span id="stat" title="Not Available">Done</span>

<div class="progress-bar active" id="pgs" role="progressbar" style="width: 0%;">0% Complete</div>   //äusseresHTML
<div class="progress-bar active" id="pgs" role="progressbar" style="width: 1%;">1% Complete</div>
<div class="progress-bar active" id="pgs" role="progressbar" style="width: 22%;">22% Complete</div>
```

and i just need to change that part of the sketch as it now prints out everything of the page:

```
void loop() {...

     ... Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
----->          String payload = http.getString();   <---as i understand here i ask for everything
          Serial.println(payload);
        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
    } else {
      Serial.printf("[HTTP} Unable to connect\n");
    }
  }
```

Hopefully someone has the time to take a look at that and point me to String i need to call.

BTW, i think the main problem why i couldn´t find the answer myself is my english isnt that professional for that kind of stuff, so im doin hard to understand similar tutorials

title: Parsing Data from local websever

Answers: 0