body:
I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b_I   but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.

Code:

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    #define servoPin 3 //~
    #define pushButtonPin 2

    int angle =90;    // initial angle  for servo
    int angleStep =5;
    const int minAngle = 50;
    const int maxAngle = 110;

    int buttonPushed =0;

    void setup() {
      // Servo button demo by Robojax.com
      Serial.begin(9600);          //  setup serial
      myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
      pinMode(pushButtonPin,INPUT_PULLUP);
       Serial.println("Robojax Servo Button ");
    }

    void loop() {
      if(digitalRead(pushButtonPin) == LOW){
        buttonPushed = 1;
      }
       if( buttonPushed ){
      // change the angle for next time through the loop:
      angle = angle + angleStep;

        // reverse the direction of the moving at the ends of the angle:
        if (angle <= minAngle || angle >= maxAngle) {
          angleStep = -angleStep;
           buttonPushed = 0;
        }
        myservo.write(angle); // move the servo to desired angle
          Serial.print("Moved to: ");
          Serial.print(angle);   // print the angle
          Serial.println(" degree");
      delay(100); // waits for the servo to get there
       }

    }

title: I'm trying to control a servo with a push of a button but its not working HELP

Answers: 1

body:
This condition below is never met because a boolean comparison is implied :

    if( buttonPushed ){

and buttonPushed is declared as :

    int buttonPushed =0;

A proper comparison should be OK :

    if( buttonPushed == 1)
    {
       // Do something
    }

Also the buttons need proper debouncing or the push event will have undetectable results :

https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html

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

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


body:
I am designing a new soldering station which will use a 24 V ac soldering iron.

I started to make some research and I designed a few steps of the soldering station. I will use a 24Vac/100VA toroidal transformer. I will use a 24V/50W soldering iron with K type thermocouple. For the thermocouple I will use a LM358 amplifier. Please have a look at the attached schematic and code. The code is not ready yet and I need some help in making the connection between the PID library and output in the code.
The voltage on the soldering iron looks like: https://ibb.co/CMF1gQ0
If I rotate the pot, nothing happens on the screen of the scope.

https://ibb.co/vdDRmnJ

I wrote a few lines of code but I don't know how to make the connection between the PID library functions and the interruption function and the other variables in my code.

Please have a look at the code and at the schematic and tell me what you think...
I am waiting for your help.

```
#include <PID_v1.h>

int AC_LOAD = 1;    // Output to Opto Triac pin
double set_value = 0;
double input = 0;
double output = 0;

PID aaa_PID(&input, &output, &set_value, 1, 0.05, 0.25, DIRECT);

void setup()
{
  aaa_PID.SetOutputLimits(0, 128);
  aaa_PID.SetMode(AUTOMATIC);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65
  int dimtime = (75*output);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  int set_point = analogRead(A1);
  set_point = map(set_point, 0, 1023, 150, 400);
  int in = analogRead(A0);
  input = map(in, 0, 550, 25, 400);
  set_value = set_point;
  aaa_PID.Compute();

}
```

title: Arduino PID controller for Triac

Answers: 2

body:
> I need some help in making the connection between the PID library and
> output in the code

PID calculates the value of `output` and it is used in `int dimtime = (75*output);`.

The `aaa_PID` object gets the reference to variable `output` with `&` so when the PID algorithm sets the output value it sets the value of this variable in your sketch.

`output` should be `volatile double output = 0;` because it is used in interrupt.

EDIT 2:

I hope you wired the zero crossing detector to pin 2, because that is the pin for external interrupt 0. And don't use pin 1 for Triac, it is wired to USB chip too.

EDIT:
Your code stays too long in interrupt. You exit the interrupt only in the time after firing the TRIAC and the next zero crossing.

In [this][1] Arduino SE answer I offer two sketches which demonstrate Triac control. This is one of them:

    #include <TimerOne.h>

    const byte INTERRUPT_PIN = 2;
    const byte TRIAC_PIN = 4;
    const byte TRIAC_PULSE_MICROS = 30;

    const int FADE_MAX = 9800;
    const int FADE_MIN = 2000;

    volatile bool triacOn;
    volatile int period = FADE_MIN; // microseconds cut out from AC pulse

    int fadeAmount = 10;

    void zeroCrossing() {
      triacOn = false; // triac tuns off self at zero crossing
      Timer1.setPeriod(period); // to call triacPulse() after off period
    }

    void triacPulse() {
      if (triacOn) { // stop pulse
        digitalWrite(TRIAC_PIN, LOW);
        Timer1.stop();
      } else { // start pulse
        digitalWrite(TRIAC_PIN, HIGH);
        triacOn = true;
        Timer1.setPeriod(TRIAC_PULSE_MICROS);
      }
    }

    void setup() {
      pinMode(TRIAC_PIN, OUTPUT);
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
      Timer1.initialize();
      Timer1.attachInterrupt(triacPulse);
    }

    void loop() {
      period = period + fadeAmount;
      if (period <= FADE_MIN || period >= FADE_MAX) {
        fadeAmount = -fadeAmount;
      }
      delay(25);
    }

the other uses direct registers access o AVR.

EDIT 3: mike's oscilloscope output of the sketch above: https://www.youtube.com/watch?v=dnfy_EsPlVI

EDIT 4: the PID outputs high values for high power and small values for lower power. but the Triac period is the off time. so the period should be something like `period = 11000 - (75 * output)`

here are the input and output values of mike's code based on this answer (blue is temperature, red is output for the Triac period):

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

The PID control gets smoother over time as it finetunes its parameters,
but I think a simple PID has some problems with the sine relation between the output (time) and the resulting heating power.

  [1]: https://arduino.stackexchange.com/questions/63631/fan-regulator-control-from-arduino/63674?r=SearchResults&s=2|26.8685#63674
  [2]: https://i.stack.imgur.com/jLlMh.png

body:
I see several issues here.

The most serious is in the wiring of the Arduino. The first argument of
`attachInterrupt()` is an interrupt number. On the Uno, “interrupt 0” is
wired to the pin “digital 2”. This is where you should connect the
output of the zero-crossing detector (ZERO\_OUT).

Then, as noticed by Juraj, there is the issue of the interrupt handler
taking too long to execute. This is generally considered bad practice,
and it has some negative consequences on the working of the Arduino core
like, e.g., the `millis()` function will be completely off. I do not
think, however, that this is a serious issue for you. There is one
single time-critical bit in your program, which is the generation of the
triac trigger pulses. You really do not care about `millis()` or any
other time-related things. Thus, at least for the initial version of the
program, I would not care too much, and just let the interrupt handler
delay as needed.

The third issue has been noted by chrisl in a comment: there is a race
condition with both the main program and the interrupt handler accessing
the same `output` variable. Race conditions are a nasty kind of bug
because usually things work fine “most of the time” and then fail at
unexpected times. I would not recommend, however, to run
`myPID.Compute()` with interrupts disabled: that may throw off the
timing of your triac pulses. Instead, compute the delay required by the
interrupt, save it to a temporary variable, then copy it to a variable
shared with the handler. Only the copy needs to be done with interrupts
disabled, and that takes only a handful of CPU cycles:

```c++
// Variable used by zero_crosss_int().
// Do not forget the `volatile' qualifier.
volatile int dimtime;

void loop() {
    // PID and associated computations.
    set_value = map(analogRead(A1), 0, 1023, 150, 400);
    input = map(analogRead(A0), 0, 550, 25, 400);
    aaa_PID.Compute();
    int tmp_dim_time = 75*output;

    // Critical section executed with interrupts disabled.
    noInterrupts();
    dimtime = tmp_dim_time;
    interrupts();
}
```

------------------------------------------------------------------------

**Edit**: If things do not work, you should try to debug piece by piece.
Sending debug messages to the serial port should help, although serial
communication is likely to be significantly slowed down by the
long-running interrupt handler. As an alternative, you can use the triac
control pulses as a debug aid, maybe with the heating element unplugged.
For example:

* In `loop()`, set `dimtime` to a value proportional to `set_value`.
  Turn the pot and look at the FIRING\_PULSE signal. Does the pulse
  width vary proportionally to the pot position? Is it in sync with the
  Vin zero-crossings?

* Set `dimtime` proportional to `input`. Heat the thermocouple by some
  external means. Does FIRING\_PULSE vary as expected?

* Set `dimtime` proportional to `output`, but keep the heating element
  unplugged. How does the pulse change as you move the pot or heat the
  thermocouple?


body:
**Hello everyone. Does MFRC522 module read all 13.56 MHz RFID tags?
Or there are different types of the 13.56 MHz tags that the MFRC522 module reads only one type of them?**

Answers: 0


body:
I am working in ESP8266 AsyncWebserver library and have been using this `[](parameter)` as an argument to some functions as shown below but does not really know what it means. Being a neophyte I am curious to know what does this convention means, its functionalities and how to use it. Hopefully experts here would help me with this.
<!-- language-all: lang-cpp -->

    server.on("/page",HTTP_GET,[](AsyncWebServerRequest * request){
        some code....;
        request->getParam("Param1")->value();
    });

title: What does []() argument in function mean?

Answers: 1

body:
That is called a [*lambda expression*](https://en.cppreference.com/w/cpp/language/lambda) and it's a way of including the content of a function as a parameter anonymously instead of writing an actual function and using the name of it.

It's shorthand for:

```
void myCallback(AsyncWebServerRequest * request) {
    // some code....;
    request->getParam("Param1")->value();
}

// ...

server.on("/page", HTTP_GET, myCallback);
```

It does have a few benefits over traditional functions at the expense of readability, such as the ability to "capture" local variables from the surrounding scope.


body:
I have working code on an Ai-Thinker ESP32-CAM board, programming over serial.

I would like to reprogram using OTA, but adding in the functionality from the BasicOTA sketch (which I have done on various other boards successfully) fails when OTA programming is attempted, the board reboots following an abort() and a stack trace is generated.

The invaluable ESP32 exception decoder shows the fault occurs from checking if memory location is safe to write.

Normally, I would choose a partition option which includes OTA, but the Ai-Thinker board doesn't have this option in the IDE

title: Why doesn't OTA work with the Ai-Thinker ESP32-CAM board?

Answers: 5

body:
The `boards.txt` file configures what can be configured in the Arduino IDE for each board.

On my installation, this is found at
`C:\Users\MyUser\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\boards.txt`

I found the section `esp32cam.name=AI Thinker ESP32-CAM` and changed the lines:

```
esp32cam.upload.maximum_size=3145728
esp32cam.build.partitions=huge_app
```
to
```
esp32cam.upload.maximum_size=1966080
esp32cam.build.partitions=min_spiffs
```

The various options are detailed in the same file with keys named `esp32.menu.PartitionScheme.`, and for some boards these options are configurable be the user. To add this, remove (or comment out with a `#` character) the two lines found above so they look like:

```
# esp32cam.upload.maximum_size=3145728
# esp32cam.build.partitions=huge_app
```
and add the required menu selections for your application- e.g.
```
esp32cam.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32cam.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32cam.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32cam.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA)
esp32cam.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32cam.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
```

After making any changes to `boards.txt`, restart the Arduino IDE for the change to take effect. Note that these changes (and any changes to the installation) may be overwritten by any future upgrades or library updates, so note your changes so they can be easily reapplied.

Alternatively, add the menu lines to `boards.local.txt`, introduced in [Arduino 1.6.6][1] so they should persist during updates. In this case, no change needs to be made to `boards.txt`, as the `boards.local.txt` entries override those in `boards.txt`. I haven't tested this, hopefully it works across library updates and IDE upgrades.

  [1]: https://arduino.github.io/arduino-cli/platform-specification/#boardslocaltxt

body:
You do not have to go through the hassle with editing the boards.txt if you want to have OTA only if you do not need it or you want a custom partition scheme.

That said the **OTA partition** is always what is left so e.g. `Med Spiffs App 1.9MB, Spiffs 190KB` means 1.9 MB OTA partiton.
The caveat is if you want to OTA a 1.8 MB App with 1 MB Spiffs that will NOT work. The OTA file has to be around 100kb (from experience) smaller than the availabe OTA partition. If you want to update APP and SPIFFS thats a topic on its own. So before editing your boards.txt check the following:

 - App (uncompressed) is OTA space + ~100KB
 - your OTA routine runs stable with/in small apps
 - no connection problems during upload and
 - proper OTA error handling in your code
 - for initial testing attach no hardware to the board.
 - If using the unmodified camera example or a custom on with face recognition you will fail with OTA because this is to big (~3MB APP!)
 - OTA routines (incl wifi libs) take ~800 kB for basic OTA

As I use AIThinker32cam modules in various scenarios I know what you are through ;-)

Enclosed two custom board definitions (with no OTA) as there is no predefined (ESP32 core 1.04) in `C:\Users\YOUR_USERNAME\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\boards.txt` just copy and paste into the section (search for `esp32AiThinkerCam.menu.PartitionScheme` :

    esp32AiThinkerCam.menu.PartitionScheme.noota_3g=1MB APP/3MB SPIFFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
    esp32AiThinkerCam.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
    esp32AiThinkerCam.menu.PartitionScheme.no_ota=2MB APP/2MB SPIFFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.no_ota.build.partitions=no_ota
    esp32AiThinkerCam.menu.PartitionScheme.no_ota.upload.maximum_size=2097152

and the "magic unlocker" is the `noota_3g.csv` found in `C:\Users\YOUR_USERNAME\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\tools\partitions`,there the partition scheme isdefined. If you want to change that for custom partitions please ask a new question.
**EDIT**

Enclosed acomplete boards.txt part for AI-Thinker just replace the complete existing part with this amd you have a bunch of new options - all tested in production with ESP32 core 1.04. (without custom partition schemes):

    ##############################################################

    esp32AiThinkerCam.name=ESP32 AI Thinker Cam

    esp32AiThinkerCam.upload.tool=esptool_py
    esp32AiThinkerCam.upload.maximum_size=1310720
    esp32AiThinkerCam.upload.maximum_data_size=327680
    esp32AiThinkerCam.upload.wait_for_upload_port=true

    esp32AiThinkerCam.serial.disableDTR=true
    esp32AiThinkerCam.serial.disableRTS=true

    esp32AiThinkerCam.build.mcu=esp32
    esp32AiThinkerCam.build.core=esp32
    esp32AiThinkerCam.build.variant=esp32
    esp32AiThinkerCam.build.board=ESP32_DEV

    esp32AiThinkerCam.build.f_cpu=240000000L
    esp32AiThinkerCam.build.flash_size=4MB
    esp32AiThinkerCam.build.flash_freq=40m
    esp32AiThinkerCam.build.flash_mode=dio
    esp32AiThinkerCam.build.boot=dio

    esp32AiThinkerCam.menu.CPUFreq.240=240MHz (WiFi/BT)
    esp32AiThinkerCam.menu.CPUFreq.240.build.f_cpu=240000000L
    esp32AiThinkerCam.menu.CPUFreq.160=160MHz (WiFi/BT)
    esp32AiThinkerCam.menu.CPUFreq.160.build.f_cpu=160000000L
    esp32AiThinkerCam.menu.CPUFreq.80=80MHz (WiFi/BT)
    esp32AiThinkerCam.menu.CPUFreq.80.build.f_cpu=80000000L

    esp32AiThinkerCam.build.partitions=default
    esp32AiThinkerCam.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue
    esp32AiThinkerCam.menu.PartitionScheme.default=Default 1.2MB APP/1.5MB SPIFFS (OTA)
    esp32AiThinkerCam.menu.PartitionScheme.default.build.partitions=default
    esp32AiThinkerCam.menu.PartitionScheme.defaultffat=Default FATFS 1.2MB APP/1.5MB FATFS (OTA)
    esp32AiThinkerCam.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
    esp32AiThinkerCam.menu.PartitionScheme.noota_3g=1MB APP/3MB SPIFFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
    esp32AiThinkerCam.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
    esp32AiThinkerCam.menu.PartitionScheme.no_ota=2MB APP/2MB SPIFFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.no_ota.build.partitions=no_ota
    esp32AiThinkerCam.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
    esp32AiThinkerCam.menu.PartitionScheme.huge_app=3MB APP/1MB SPIFFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.huge_app.build.partitions=huge_app
    esp32AiThinkerCam.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
    esp32AiThinkerCam.menu.PartitionScheme.noota_ffat=2MB APP/2MB FATFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
    esp32AiThinkerCam.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
    esp32AiThinkerCam.menu.PartitionScheme.noota_3gffat=1MB APP/3MB FATFS (No OTA)
    esp32AiThinkerCam.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
    esp32AiThinkerCam.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
    esp32AiThinkerCam.menu.PartitionScheme.minimal=Min SPIFFS 1.3MB APP/700KB SPIFFS (OTA)
    esp32AiThinkerCam.menu.PartitionScheme.minimal.build.partitions=minimal
    esp32AiThinkerCam.menu.PartitionScheme.min_spiffs=Med SPIFFS 1.9MB APP/190KB SPIFFS (OTA)
    esp32AiThinkerCam.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
    esp32AiThinkerCam.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080

    esp32AiThinkerCam.menu.FlashMode.qio=QIO
    esp32AiThinkerCam.menu.FlashMode.qio.build.flash_mode=dio
    esp32AiThinkerCam.menu.FlashMode.qio.build.boot=qio
    esp32AiThinkerCam.menu.FlashMode.dio=DIO
    esp32AiThinkerCam.menu.FlashMode.dio.build.flash_mode=dio
    esp32AiThinkerCam.menu.FlashMode.dio.build.boot=dio
    esp32AiThinkerCam.menu.FlashMode.qout=QOUT
    esp32AiThinkerCam.menu.FlashMode.qout.build.flash_mode=dout
    esp32AiThinkerCam.menu.FlashMode.qout.build.boot=qout
    esp32AiThinkerCam.menu.FlashMode.dout=DOUT
    esp32AiThinkerCam.menu.FlashMode.dout.build.flash_mode=dout
    esp32AiThinkerCam.menu.FlashMode.dout.build.boot=dout

    esp32AiThinkerCam.menu.FlashFreq.80=80MHz
    esp32AiThinkerCam.menu.FlashFreq.80.build.flash_freq=80m
    esp32AiThinkerCam.menu.FlashFreq.40=40MHz
    esp32AiThinkerCam.menu.FlashFreq.40.build.flash_freq=40m

    esp32AiThinkerCam.menu.UploadSpeed.921600=921600
    esp32AiThinkerCam.menu.UploadSpeed.921600.upload.speed=921600
    esp32AiThinkerCam.menu.UploadSpeed.115200=115200
    esp32AiThinkerCam.menu.UploadSpeed.115200.upload.speed=115200
    esp32AiThinkerCam.menu.UploadSpeed.256000.windows=256000
    esp32AiThinkerCam.menu.UploadSpeed.256000.upload.speed=256000
    esp32AiThinkerCam.menu.UploadSpeed.230400.windows.upload.speed=256000
    esp32AiThinkerCam.menu.UploadSpeed.230400=230400
    esp32AiThinkerCam.menu.UploadSpeed.230400.upload.speed=230400
    esp32AiThinkerCam.menu.UploadSpeed.460800.linux=460800
    esp32AiThinkerCam.menu.UploadSpeed.460800.macosx=460800
    esp32AiThinkerCam.menu.UploadSpeed.460800.upload.speed=460800
    esp32AiThinkerCam.menu.UploadSpeed.512000.windows=512000
    esp32AiThinkerCam.menu.UploadSpeed.512000.upload.speed=512000

    esp32AiThinkerCam.menu.DebugLevel.none=None
    esp32AiThinkerCam.menu.DebugLevel.none.build.code_debug=0
    esp32AiThinkerCam.menu.DebugLevel.error=Error
    esp32AiThinkerCam.menu.DebugLevel.error.build.code_debug=1
    esp32AiThinkerCam.menu.DebugLevel.warn=Warn
    esp32AiThinkerCam.menu.DebugLevel.warn.build.code_debug=2
    esp32AiThinkerCam.menu.DebugLevel.info=Info
    esp32AiThinkerCam.menu.DebugLevel.info.build.code_debug=3
    esp32AiThinkerCam.menu.DebugLevel.debug=Debug
    esp32AiThinkerCam.menu.DebugLevel.debug.build.code_debug=4
    esp32AiThinkerCam.menu.DebugLevel.verbose=Verbose
    esp32AiThinkerCam.menu.DebugLevel.verbose.build.code_debug=5

body:
As stated in the comments by @Codebreaker007 using the ESP32 Wrover Module works and if you put the pin definitions inline in the app there isn't a problem

    #define CAMERA_MODEL_AI_THINKER

    #if defined(CAMERA_MODEL_AI_THINKER)
      #define PWDN_GPIO_NUM     32
      #define RESET_GPIO_NUM    -1
      #define XCLK_GPIO_NUM      0
      #define SIOD_GPIO_NUM     26
      #define SIOC_GPIO_NUM     27

      #define Y9_GPIO_NUM       35
      #define Y8_GPIO_NUM       34
      #define Y7_GPIO_NUM       39
      #define Y6_GPIO_NUM       36
      #define Y5_GPIO_NUM       21
      #define Y4_GPIO_NUM       19
      #define Y3_GPIO_NUM       18
      #define Y2_GPIO_NUM        5
      #define VSYNC_GPIO_NUM    25
      #define HREF_GPIO_NUM     23
      #define PCLK_GPIO_NUM     22
    #else
      #error "Camera model not selected"
    #endif

body:
Here.

Download this working ESP32-CAM sketch zip file with working OTA uploading:
"Working_ESP32_CameraWebServer_V2_with_OTA"

at

https://github.com/wjsanek/wjsanek.git

Make sure you read the simple "READ ME FIRST" file in the zip after unzipping.

This sketch overcomes any "file to big" or other OTA sketch uploading problems with this crumby, tempremental ESP32-CAM board (the $5 ESP8266 NodeMCU is better but the Arducam camera for it costs $23).

The ESP32-CAM board does not like to transmit very far.

body:
OTA Requires you to partition your ESP32 with two sets of space for your program (ota_0 and ota_1 partitions) - during the OTA process, the unused one gets updated, and will be the next one that boots up.

This means that there's no room left for the camera (most camera driver libraries store the image in SPIFFS) to store the image data (OV2640 is 1622x1200 pixels, which is 1946400 bytes) because the only available partition schemes with OTA in Arduino IDE is 1.9mb program with 0.19mb (190kb) SPIFFs, which is 10-times-not-enough space to store camera images in.

the wjsanek project in here looks interesting - they're using one of the OTA partitions as the SPIFF for the camera. Very clever.


body:
I am developing a project for my college.

PROJECT OUTLINE:
There are 3 sensors (Temp., Accelerometer & Humidity) will read the respective parameters continuously. in between if I press 'PushButton1' for 2 seconds  the Arduino must enter into programming mode.

The programming mode has 6 Switch cases. Each case gets selected one after one on the even of 'PushButton1' gets pressed for short time.

Also if I press 'PushButton1' again for 2 seconds in Programming mode the Arduino should come out of the programming mode.

PROBLEM:
In my current sketch I have to press 'PushButton1' for 2 seconds in Programming Mode for 2 seconds to change the case. Also I don't understand how to get out of the Switch Case loop.

The sketch is attached with this topic.

    const int btn = 2;
    const int ledPin =  13;
    int selector = 0;
    boolean  volatile wait = false;
    const unsigned long event=2000;
    unsigned long a=0;
    unsigned long b=0;
    unsigned long c=0;
    void setup()
    {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    pinMode(btn, INPUT);
    attachInterrupt(digitalPinToInterrupt(btn),decoder,CHANGE);
    }

    void loop()
    {
      while(wait) {  }
      if (digitalRead(btn) == LOW) {
        a = millis();
      }
      else
      {
        b = millis();
        c=b-a;
        Serial.println(c);
            if (c>=event)
                {
                  doSwitchStatement();
                  selector++;
                  if (selector >6)
                      {
                      selector = 0;
                      delay(500);
                      }
                }
      }
      wait = true;
      interrupts();

    }

    void decoder()
    {
      noInterrupts();
      wait = false;
    }

    void doSwitchStatement()
    {
      switch(selector)
      {
      case 0:
        Serial.println("Case 0");
        break;

      case 1:
        Serial.println("Case 1");
        break;

      case 2:
       Serial.println("Case 2");
        break;

      case 3:
       Serial.println("Case 3");
         break;

      case 4:
       Serial.println("Case 4");
        break;

      case 5:
      Serial.println("Case 5");
        break;

      case 6:
      Serial.println("Case 6");
        break;

      }
    }

title: Pushbutton and switch case

Answers: 1

body:
I would do it as a simple state without the blocking while
define two bools

    bool buttonPress = false;
    bool inMenu = false;

and add it to the loop.
To differentiate between different press lengths you need to define them. There is nothing like an "automatic" short press recognition. Also use variables which are "speaking" making it easier to read code for others.

    const unsigned long buttonPressLong = 2000;  // 2 seconds
    const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
    const unsigned long buttonPressDebounce = 50;
    // debouncing for too short presse Thanks Edgar Bonet
    unsigned long buttonPressStart = 0;

The program below does what you want (tested on my uno test lab).
As Edgar Bonet commented before you should also debounce the button (look it up in WiKi) to exclude unwanted effects The times I use are practical on my hardware, so you could play around by looking at the serial monitor.

    const int btn = 2;
    const int ledPin =  13;
    int selector = 0;
    const unsigned long buttonPressLong = 2000;  // 2 seconds
    const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
    const unsigned long buttonPressDebounce = 50;  // debouncing for too short presse Thanks Edgar Bonet
    unsigned long buttonPressStart = 0;

    bool buttonPress = false;
    bool inMenu = false;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(btn, INPUT);
      }

    void loop() {
      if (digitalRead(btn) == LOW && !buttonPress ) {
        buttonPressStart = millis();
        buttonPress = true;
      }
      // The routine is only triggered if a previous pressing took place, otherwise it's ignored
      else if (digitalRead(btn) == HIGH && buttonPress) {
        if (millis() - buttonPressStart > buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
          Serial.print("Long press: ");
          Serial.println(millis() - buttonPressStart);
          buttonPress = false;
          inMenu = false;
        }
        if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && !inMenu) {
          Serial.print("First short press ");
          inMenu = true;
        }
        if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
          Serial.print("Short press: ");
          Serial.println(millis() - buttonPressStart);
          doSwitchStatement();
          selector++;
          if (selector > 6) {
            selector = 0;
            delay(500);
          }
          buttonPress = false;
        }
      }
      // Here you could do other stuff as it is non blocking
    }
    doSwitchStatement(){...}// Stays the same as yours

Look at the code used as it is non blocking (of course there is room for improvement) but as a starter for your further experiments ...


body:
I have found many projects involving esp32cam, but in all projects video is being seen on local server only.For its of no use.As for a home security project user can view the video at remote location like MI robotic camera.

Also i do not want any port forwarding or tunneling service from a third party like www.nabto.com, www.ngrok.com etc.

title: how to get live view of esp32cam at remote sever using ssh tunneling?

Answers: 0


body:
I understand that some arduinos are capable of presenting themselves as a [USB HID][1] device to a PC.

I would like to use one to build a custom input controller that lets me read maybe 8 or so turn knobs that can infinitely turn left and right.

I am new to Arduino, but have cross-compiled avr binaries before.

Which arduino would be a good choice for this? And any additional parts that would help?

The end product would look like a MIDI mix panel, but it shouldn’t talk MIDI, just USB HID (to a linux PC.)

Note: there is an expensive, and out of stock, device that is similar to what I have in mind called MIDI Fighter Twister, pictured below, to get an idea.

[![Twister][2]][2]

  [1]: https://en.wikipedia.org/wiki/USB_human_interface_device_class
  [2]: https://i.stack.imgur.com/3O1Wl.jpg

title: USB control panel with endless turn knobs

Answers: 1

body:
Options for the Arduino you have:

 - Get an Arduino supporting HID drivers (e.g. 32u4 based boards, Due /Zero/ Arduino Leonardo/ Micro or Pro Micro/ M0)
 - You use [this library](https://github.com/NicoHood/HID) it supports UNO/MEGA/Leonardo/(Pro)Micro/ any 8u2/16u2/at90usb8/162/32u2/32u4 compatible boards and some more

Then you have to "just" code the communication between your programm and the HID driver -> pretty standard serial/usb stuff.<br>
The parts (knobs) you seek could be rotary encoders, which have no fixed zero point, endless rotation and need 2 input pins per encoder (except GND or optional push function). The signals a rotary encoder produces (and what can be handled by libraries) are based on a [2-bit gray code](https://en.wikipedia.org/wiki/Gray_code) available on 2 digital data signal lines.
So when choosing whatever Arduino make sure you have enough (usable) I/O ports for the number of encoders and possible additional parts (status led/s or similar, I2C LCD display)


body:
I have written a simple calculator program for an LCD keypad shield. It works fine except for the multiplication case. It gives me zero. However, I have noticed that when I enclose the expression num1 * num2 in parenthesis it does work. Why is that so?

    #include <LiquidCrystal.h>

    LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.clear();
    }

    void loop() {

      float ans = 0;

      lcd.print("Starting Calc");
      delay(500);

      lcd.clear();
      lcd.print("Enter 1st Num");
      while (Serial.available() == 0) {}
      float num1 = Serial.parseFloat();

      lcd.clear();
      lcd.print("Enter 2nd Num");
      while (Serial.available () == 0) {}
      float num2 = Serial.parseFloat();

      lcd.clear();
      lcd.print("Enter Operator");
      lcd.setCursor(0, 1);
      lcd.print(" R+, U*, D/, L- ");
      int val = analogRead(A0);

      while (val > 1000) {
        val = analogRead(A0);
      }

      if (val == 0) { // addition
        ans = num1 + num2;
      }

      if (val >= 97 && val <= 98) { // multiplication
        ans = num1 * num2;
      }

      if (val >= 253 && val <= 254) { // division
        ans = num1 / num2;
      }

      if (val >= 407 && val <= 408) { // subtraction
        ans = num1 - num2;
      }

        lcd.clear();
        lcd.print("Answer is = ");
        lcd.print(ans);
        delay(2000);
    }

-----------------------------------------------------------------------
Modified Code
------------------------------------------------------------------------

    #include <LiquidCrystal.h>

    LiquidCrystal lcd (8, 9, 4, 5, 6, 7);

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.clear();
    }

    void loop() {

      float ans = 0.0;

      lcd.print("Starting Calc");
      delay(500);

      lcd.clear();
      lcd.print("Enter 1st Num");
      while (Serial.available() == 0) {}
      float num1 = Serial.parseFloat();

      lcd.clear();
      lcd.print("Enter 2nd Num");
      while (Serial.available () == 0) {}
      float num2 = Serial.parseFloat();

      lcd.clear();
      lcd.print("Enter Operator");
      lcd.setCursor(0, 1);
      lcd.print(" R+, U*, D/, L- ");

      // here we split our logic.. first repeatedly read input value until valid operator read
      // secondly we perform the arithmetic operation accordingly

      char input = ' '; // space = no operator read so far
      int val;

      do {
        val = analogRead(A0);
        // see how if statements are written concisely for readability
        // if only one statement after condition you can skip curly brackets
        if (val == 0) input = '+';
        if (val >= 97 && val <= 98) input = '*';
        if (val >= 253 && val <= 254) input = '/';
        if (val >= 407 && val <= 408) input = '-';
      } while (input == ' ');

      Serial.println(input);
      Serial.println(num1);
      Serial.println(num2);
      delay(1000);

      // perform arithmetic operation
        switch (val) { // not written in a standard way but very readable
          case '+': ans = num1 + num2; break;
          case '-': ans = num1 - num2; break;
          case '*': ans = num1 * num2; break;
          case '/': ans = num1 / num2; break;
        }

      lcd.clear();
      lcd.print("Answer = ");
      lcd.print(ans);
      delay(2000);
    }

title: Multiplication operator with or without braces

Answers: 1

body:
The parentheses should definitely make no difference. My guess is that
what you saw was just a coincidence. The analog ranges you have defined
are extremely narrow. Any instability in the circuit can throw your
readings out of the expected ranges. If you get a reading that does not
fit in any of those ranges, none of the `if` conditions will evaluate to
`true`, and you end up with the result being zero, as this is how you
initialized the variable `ans`.

I suggest two changes to your program:

 1. Make the ranges wider
 2. Repeatedly read the analog input _until_ you get a valid reading.

To illustrate the second item, here is a code snippet that splits the
logic of you `if` chain in two parts: first read the operator
(repeatedly until we get a valid reading), then perform the operation:

```c++
// Read the operator.
char op = ' ';  // space = no operator read so far
do {
    int val = analogRead(A0);
    if (val == 0) op = '+';
    if (val >= 97 && val <= 98) op = '*';
    if (val >= 253 && val <= 254) op = '/';
    if (val >= 407 && val <= 408) op = '-';
} while (op == ' ');

// Perform the operation.
switch (op) {
    case '+': ans = num1 + num2; break;
    case '*': ans = num1 * num2; break;
    case '/': ans = num1 / num2; break;
    case '-': ans = num1 - num2; break;
}
```


body:
I am trying to control an led with a bluetooth module, but it is not working with an if else condition.

When I use this code I found on the internet the led blinks when I send the string from an android app:

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

        void loop() {
          // put your main code here, to run repeatedly:
         if(Serial.available()>0)
           {
              char data= Serial.read(); // reading the data received from the bluetooth module
              switch(data)
              {
                case 'a': digitalWrite(13, HIGH);break; // when a is pressed on the app on your smart phone
                case 'd': digitalWrite(13, LOW);break; // when d is pressed on the app on your smart phone
                default : break;
              }
              Serial.println(data);
           }
           delay(50);
        }

Where as when I use this code that I made myself the code compiles and uploads but the serial does not recieve values and the led does not change state when the strings are sent from the app, can someone help me identify why?:

        void setup() {
        Serial.begin(9600);
         pinMode(13, OUTPUT);
         }

        void loop() {
         if(Serial.available()>0)
           {
              char data= Serial.read();
              if (data == 'a')
              {
                digitalWrite(13, HIGH);
              }
              else if (data == 'b')
              {
                digitalWrite(13, LOW);
              }
              Serial.println(data);
           }
           delay(50);
        }

Thank You

title: How to use HC-05 to recieve data?

Answers: 0


body:
For Arduino Nano 33 IoT, I want to turn off everything except Bluetooth and Wireless since I don't use them.

My question please: Can I switch off / deactivate the IMU sensors completely? If yes, How please?

title: Saving Power :: Reducing Power Consumption

Answers: 0


body:
I want to feed thousands of analog vibration sensor readings into an array as fast as possible, and then analyze them. Here is my sketch:

<!-- language: lang-cpp -->

```
const int pSensor1 = A0;
const int aSize=10000;

int a[aSize];

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

void loop()
{
  for (int i = 0; i < aSize; i++) a[i] = analogRead(pSensor1);

  int RMS = 0;
  for (int i = 0; i < aSize; i++) RMS += pow(a[i], 2);
  RMS = sqrt(RMS/aSize);

  Serial.println("Hello");
}
```

This compiles and runs fine. My problem arises when I try to change the last line to:

`Serial.println(RMS);`

I get the error:

> Arduino: 1.8.12 (Windows 10), Board: "Arduino Nano, ATmega328P"
>
> Sketch uses 3270 bytes (10%) of program storage space. Maximum is
> 30720 bytes. Global variables use 20188 bytes (985%) of dynamic
> memory, leaving -18140 bytes for local variables. Maximum is 2048
> bytes. data section exceeds available space in board Not enough
> memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for
> tips on reducing your footprint. Error compiling for board Arduino
> Nano.

Why does attempting to Serial print a single floating point variable use 985% of dynamic memory?

title: Serial.println using too much memory (not Strings)

Answers: 1

body:
Probably if you don't print them then the compiler sees that array is never used for anything so it gets optimized away.  It sees that it is useless code that doesn't affect anything and simply removes it.  Once you print it then it actually has to be included in the compiled code.

Think about this.  The Arduino you are using has 2000 bytes of memory.  One int takes 2 bytes.  You want 10,000 of them.  That's 20,000 bytes of memory.  20,000 bytes will never ever fit into 2,000 bytes.  You need to choose a more reasonable number of samples.


body:
Currently working with [ADS1292rShield](https://github.com/Protocentral/ADS1292rShield_Breakout) library.
Is there any way to read the value of the respiration and heart rate without using the Protocentral GUI. Printing DataPacketHeader to the console just results in corrupted ASCII.

```c
DataPacketHeader[9] = s32DaqVals[0];            // 4 bytes Respiration data
DataPacketHeader[10] = s32DaqVals[0]>>8;
DataPacketHeader[11] = s32DaqVals[0]>>16;
DataPacketHeader[12] = s32DaqVals[0]>>24;

    for(i=0; i<15; i++)
    {
      Serial.write(i);
      Serial.write(DataPacketHeader[i]);     // transmit the data over USB
    }
```
Here is the output below of the Arduino serial monitor, is there any way to make sense of the data or how it is converted to a readable integer on the GUI?

```
⸮ < 0 p s | ` r I @ @ 9    ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ < 2 $ & O ` q ` 8 0 ! > ⸮ ⸮ ⸮ ⸮ ⸮  ! 8 ! | H a @  9 $  ! ⸮ 8 B x  ⸮ ⸮ ⸮ ⸮  y a ` p  f ⸮ ⸮ ⸮ ⸮ ⸮ 1 b N p ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ " D ` ` ` p
 ! ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ 0 ⸮ ' # 3 @ O ` D B @ @ ! ⸮ ⸮ ⸮ ⸮ ⸮ 0  a F ⸮ ⸮ ⸮ ⸮ ⸮ ⸮ " x p $ 0 ⸮
```

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

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

title: Read the respiration data to Arduino serial console

Answers: 0


body:
As per title, I have 3 LEDs connected to an Uno. Also connected is an HC-05.

edit: forgot to add a question, my bad.  Is there any glaring major issues in this code that I've overlooked?  Not looking for anyone to write my code for me, just want to understand what I messed up and an idea of how to fix.

```
const int RED=2;
const int BLUE=4;
const int GREEN=6;

String inputString;
String buttonId;

char junk;

void setup() {
  Serial.begin(9600);
  pinMode(RED, OUTPUT);
  pinMode(BLUE, OUTPUT);
  pinMode(GREEN, OUTPUT);
  digitalWrite(RED,LOW);
  digitalWrite(BLUE,LOW);
  digitalWrite(GREEN,LOW);
}

void loop()
{
  if(Serial.available()){
  while(Serial.available())
    {
      char inChar = (char)Serial.read(); //read the input
      inputString += inChar;        //make a string of the characters coming on serial
    }
    Serial.println(inputString);
    while (Serial.available() > 0)
    { junk = Serial.read() ; }
    if(inputString == "r_on"){      // control red led
      digitalWrite(RED, HIGH);
    }else if(inputString == "r_off"){
      digitalWrite(RED, LOW);
    }
    inputString = "";
    if(inputString == "b_on"){      // control blue led
      digitalWrite(BLUE, HIGH);
    }else if(inputString == "b_off"){
      digitalWrite(BLUE, LOW);
    }
    inputString = "";
    if(inputString == "g_on"){      // control green led
      digitalWrite(GREEN, HIGH);
    }else if(inputString == "g_off"){
      digitalWrite(GREEN, LOW);
    }
    inputString = "";
  }
}
```

Picture of my App inventor block program in imgur link below

https://i.stack.imgur.com/F6jBq.jpg

title: Control of 3 LEDs over Bluetooth using MIT App Inventor

Answers: 0


body:
I'm using my Arduino to make a speaker-like device. Instead of sound, it receives the beat of the song, thus the data comes in an array of floats. Each item in the array is a timestamp, an LED is turned on based on that value.

For example, [0.01,0.53] means sleep 0.01s, turn on LED, pop off 0.01, sleep 0.53 seconds, turn on LED.

I have two questions:

1)How can I receive data and pop off data at the same time? I'm thinking I can send maybe 10 items for the Arduino to buffer at one time, and repeat that until the whole action is done. The popping off action is time sensitive, so I can't do it sequentially. How can I run both functions at once? Are arduinos capable of multithreading?

2)I'm using an arduino with BLE and sending over the data using `serial.read()` from an iPhone. and the device only allows 18 bytes to be sent over at one time and it is very slow. What other methods can I use? I need to send 18 bytes from my iPhone, wait 2 seconds, then send it again otherwise the arduino treats it as one single send and the other values are not sent over.

3)Is there a better way of doing all of this that I'm missing?

Thank you very much.

title: Bluetooth multithreading

Answers: 0


body:
I am working on VTOL aircraft and currently I am looking for some good board as flight controller (FC). I could made it by myself, but it requests lot of time. I was thinking about one of fpv drone FC (I have avaiable this one:

https://www.banggood.com/cs/Original-Airbot-Omnibus-F4-Pro-V3-Flight-controller-SD-5V-3A-BEC-OSD-Current-Sensor-LC-Filter-p-1319177.html?gmcCountry=CZ&currency=CZK&createTmp=1&utm_source=googleshopping&utm_medium=cpc_bgs&utm_content=lijing&utm_campaign=ssc-cz-cs-all-newcustom-ncv80-1118&gclid=CjwKCAjwqJ_1BRBZEiwAv73uwEgBJQ1B3dcKvZJZy2lR5-wN-XC150Ybn0kZObpUQbgkbvKiN_fY5BoCCVEQAvD_BwE&cur_warehouse=CN

This board has very small dimensions and it has already everything I need. The problem is that it is made for softwares like betaflight etc. It uses STM32 F405 so I tried to add STM 32 support for arduino (https://github.com/stm32duino/Arduino_Core_STM32) and upload arduino code in it.

I had to install stm32 cube programmer and because this board is not one of arduino boards I have to build the code for different board with same processor (FEATHER_F405). Because of it I have to change board pinout in this file (C:\Users\<user>\AppData\Local\Arduino15\packages\STM32\hardware\stm32\1.8.0\variants\FEATHER_F405). I checked if are those pins correct (in code I command to those pins to be High and then Low while I was measuring them with multimeter). So all the pins are correct. I was able to blik the onboard LED and beep the buzzer. **The only problem I have is serial communication.** I tried to send some Strings to computer via serial port, but I didnt received any data. Here is sample code that I used:

    #include <SoftwareSerial.h>

    #define LED 4 //PB_5   //Inverted (High => LED ON)
    #define BUZZ 3 //PB_4

    #define _RX1 D0 //PA_10
    #define _TX1 D1 //PA_9

    //#define D_P 35 //PA_11
    //#define D_M 36 //PA_12

    //SoftwareSerial mySerial(_RX1, _TX1); // RX, TX
    HardwareSerial  hwSerial_1(_RX1, _TX1);   // RX, TX

    void setup() {

      hwSerial_1.begin(9600);
     //mySerial.begin(9600);

      pinMode(LED,OUTPUT);
      pinMode(BUZZ,OUTPUT);

      //pinMode(_RX1,OUTPUT);
      //pinMode(_TX1,OUTPUT);

      //pinMode(D_P,OUTPUT);
      //pinMode(D_M,OUTPUT);
    }

    void loop() {

      digitalWrite(LED, HIGH);
      /*
      digitalWrite(_RX1, HIGH);
      digitalWrite(_TX1, HIGH);
      digitalWrite(D_P, HIGH);
      digitalWrite(D_M, HIGH);*/

      delay(1000);

      digitalWrite(LED, LOW);
      /*
      digitalWrite(_RX1, LOW);
      digitalWrite(_TX1, LOW);
      digitalWrite(D_P, LOW);
      digitalWrite(D_M, LOW);*/

      delay(1000);

      digitalWrite(BUZZ, HIGH);
      delay(100);
      digitalWrite(BUZZ, LOW);
      delay(1000);

      hwSerial_1.println("HelloWorld");
      //mySerial.println("HelloWorld");

    }

I tried to run serial communication via USB and via UART1 (I used USB/ TTL conventer -> FT232), but non of these works. I also tried to use software serial and hardware serial library, but it didnt helped.

Do you have any advices how to make serial communication work?

title: Uploading arduino code to race drone flight controller

Answers: 1

body:
Sorry for answering this late to this problem but I stumbled on the very same issue. After many hours of debugging, here is what I've found:

 - The default serial (e.g. the serial that you will use through the object `Serial`) is actually what is labelled RX3 and TX3 on the board and is mapped like so:
    - RX3 -> PB_11
    - TX3 -> PB_10
 - Serial6 is connected through an inverter (5v becomes 0v and vice versa) and can be used as an SBUS line. Serial 6 is mapped like so:
    - RX6 -> PC_7
    - TX6 -> PC_6
 - Serial1 is mapped like so:
    - RX1 -> PA_10
    - TX1 -> PA_9
    - however, PA_10 and PA_11 are not used as UARTs on the FEATHER board. In order to enable them, you can edit the file `hardware/stm32/2.3.0/variants/STM32F4xx/F405RGT_F415RGT/PeripheralPins_FEATHER_F405.c`.
      - In the array `PinMap_UART_TX` (line 178), uncomment the line regarding the pin `PA_9` and comment the line regarding the pin `PB_6`.
      - In the array `PinMap_UART_RX` (line 193), uncomment the line regarding the pin `PA_10` and comment the line regarding the pin `PB_7`.
 - However, if you try to read from this uart you will probably receive garbage data because the Feather F405 board uses a 12MHz external oscillator, when the omnibus F4 uses a 8MHz clock. To fix this, you can go to the files that define the Feather F405 : `hardware/stm32/2.3.0/variants/STM32F4xx/F405RGT_F415RGT/variant_FEATHER_F405.h` line 178 you will read : `#define HSE_VALUE 12000000U`. This has to be changed into : `#define HSE_VALUE 8000000U`.


body:
I'm writing an Arduino application in C/C++ and I'm storing my source code in Github.

However, to make my code runnable, I have had to install multiple libraries through the Arduino desktop tool like this:

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

And I have had to update the firmware and certificates through the Arduino desktop tool like this:

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

How can I store these firmware updates, library changes and certificates in source control? Is there a binary image I can download and check in? Better yet, is there some plain-text source file that I can check-in to derive such a binary?

  [1]: https://i.stack.imgur.com/MKAkN.png
  [2]: https://i.stack.imgur.com/fSDt7.png

title: How to store firmware configuration or image in source-control?

Answers: 1

body:
For libraries only add comment next to #include with version number and author's name if the library is in Library Manager or the download location if it is not in Manager.

Example:

    #include <MemoryFree.h> // https://github.com/mpflaga/Arduino-MemoryFree
    #include <Ethernet.h> // Ethernet 2.00

Put NINA firmware version in some comment at the top of the main sketch file. The firmware is part of the Arduino boards package so no need to store it in your repo. If you modified the firmware, publish source code in your fork of the official repository and there you can then release the binary too.

Put public certificate keys and similar files in sketch folder in subfolder called `extras` or `data`.

And write a README file for your repository.


body: Can I connect 220V AC supply to node MCU pin D1 and D3 while node MCDU is power off?

title: Can I connect 220V AC supply to Node MCU (or any arduino)pin D1 and D3 while node MCDU is power off?

Answers: 1

body:
No, never! 220V is way way way too much for a microcontroller. The Uno runs on 5V, the ESP8266 on 3.3V. You should never connect any more voltage than that to the microcontroller. Also you must not connect a negative voltage to the microcontroller pins.

Besides the voltage difference: You should also not connect a voltage to the pins of a microcontroller, while the microcontroller itself is turned off (meaning that it does not have the necessary supply voltage). In that case a parasite current would run through the clamping diodes, which powers the microncontroller, until the diodes get blown.

---

As an **important** side note: **Don't do anything with mains power (like 220V AC), until you really know, what you are doing!!! One error and it can kill you !!!**


body:
i've totally done everything i could,but when i run my arduino uno with my 16*2 lcd (with i2c) . it has a higher brightness on the top and a lower one in the bottom. ive even tried putting example codes but my arduino totally freaks out, starting to change it's backlight . i cant even use lcd.print . i had tried just to adjust my lcd with a ldr , this is the code:

        // Include Wire Library for I2C
    #include <Wire.h>
    // Include NewLiquidCrystal Library for I2C
    #include <LiquidCrystal_I2C.h>
    int ldr;
    int sensor=0;
    int lcdb=5;

    // Define LCD pinout
    const int  en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3;

    // Define I2C Address - change if reqiuired
    const int i2c_addr = 0x3F;

    LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE);

    void setup()
    {

      // Set display type as 16 char, 2 rows
      lcd.begin(16,2);
      Serial.begin(9600);
      lcd.setCursor(0,1);
      lcd.print("hello world");
      lcd.setCursor(0,0);
      delay(1000);
      lcd.print("hello world");

    }
    void loop()
    {
      int ldr=analogRead(sensor);
      ldr=map(ldr, 0, 1023, 0,255);
      delay(1000);
      analogWrite(lcdb,ldr);

    }

title: hello,i have an problem with my arduino with an lcd

Answers: 0


body:
The instructions to put the Arduino into DFU say I should shortcut briefly the 2 leftmost ICSP headers next to the USB port.
[![enter image description here][1]][1]
But [my board][2] does not have them. Does anybody know what are the right headers or if it is at all possible to set my board into DFU mode?

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/tt3Pc.jpg
  [2]: https://www.aliexpress.com/item/32881951235.html
  [3]: https://i.stack.imgur.com/siX2L.jpg

title: Put Arduino in DFU mode (no RST pin)

Answers: 2

body: This board doesn't use as USB adapter an ATMega16u2 with Arduino firmware. It uses a simple USB chip CH340. So you can't put it in DFU mode to upload a firmware.

body:
It has a CH340G usb serial adapter, which cannot be reprogrammed and has no DFU mode.

If you are looking for DFU mode because it's not detecting correctly and you think it's because the 16u2 isn't programmed correctly, the problem is probably that you need to install the CH340G drivers, not the normal Arduino drivers.

If you are looking for DFU mode for some project that requires custom firmware on the CH340G, that board is not usable for that project, you will need to get a faithful clone of the Uno, which has the 16u2, not the CH340G based ones

**EDIT**

If you want to use your Arduino as a HID device you need the DFU mode

If you [use this library](https://github.com/NicoHood/HID/wiki/Installation) which supports UNO/MEGA/Leonardo/(Pro)Micro/ any 8u2/16u2/at90usb8/162/32u2/32u4 compatible board and some more **BUT you need an 16u2 chip**


body:
When I examine the datasheet for the Arduino Micro (couldn't find the Pro Micro on their site, btw) then I see some data pins annotated with a ~ character, and some are not.

For instance, D9 has a ~ annotation, D8 does not.

What does this annotation mean?

[![pinout][1]][1]

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

title: What does a tilde (~) mean as annotation for a data pin?

Answers: 1

body: It means the pin can be a PWM output for use with `analogWrite()`.


body:
<!-- language: lang-cpp -->

    lcd_key = read_LCD_buttons();
    float temp = dht.readTemperature();
    delay(1000);
    // lcd.setCursor(0,0);

    if(temp < 0) {
     lcd.print(temp);
    }

    if(temp >= 0.00 || temp <= 5.00) {
     lcd.setCursor(0,6);
     lcd.print(temp);
     delay(100);
    }

Here I got simple code about reading temperature from DHT sensor and lcd but when I raise or lower the DHT's temperature the lcd's cursor always printing my data from 0,0.

I want that when the temperature between 0-5 celcius it shall write data on 0,6 in lcd screen but this code not working.

Thank you for answers.

title: DHT11 and Liquidcrystal setting cursor issue

Answers: 2

body:
I guess it because you use

    if(temp >= 0.00 || temp <= 5.00){ // writes over 0 OR under 5 which will always be true for all values measured

and not

    if(temp >= 0.00 && temp <= 5.00){   // writes over 0 AND under 5 which you want

body:
I have a feeling you may be using invalid coordinates.

`0, 6` means *Column 0, Row 6*, but most LCDs don't have 6 rows.  Instead I think you want `6, 0` for *Column 6, row 0*.


body:
I'm trying to write the payload of a MQTT message into a file in the SPIFFS file system of my esp32 board. I've tried this:

    if(file.print((long)payload)) {
       Serial.println("File was written");
    }else {
       Serial.println("File write failed");
    }

payload is a byte* and file was opened in the setup() function like:

    File file;
    if(!SPIFFS.exists("/testfile")){
      file = SPIFFS.open("/testfile", "r+");
    }

I always get an error when writing to it telling me that the file write failed. Is this the correct approach for what I'm trying to accomplish?

title: writing mqtt payload to spiffs file

Answers: 2

body:
Open the file in the loop or the subroutine, but not in setup as file is then a local var to setup

In your code it should be

    file = SPIFFS.open("/testfile", "a"); // a ... append

> a      Open for appending (writing at end of file).  The file is
>        created if it does not exist.  The stream is positioned at the
>        end of the file.

r+   positions stream at the beginning of the file

and to get lines you can afterwards analyze you should use

    if(file){
       file.println("Your MQTT payload");
       Serial.println("File was written");
       file.close();
    } else {
        Serial.println("File write failed");
    }

and do not forget to close after the operation.

**EDIT**

As reaction to the comments here a "clean solution" as a function:

    bool writeLog(const char fileName[],  char payloadMqtt[]) {
      File logFile = SPIFFS.open(fileName, "a");
      if (!logFile)  {
            Serial.println("logFile open failed");
        return false;
      }
      else {
        //Write data to file
        Serial.println("writing Data to logFile");
        logFile.print(payloadMqtt);
        logFile.close();
        return true;
      }
    }

You call it with:

    writeLog("/myfilepath", payload);

and can also be used like

    if (writeLog("/myfilepath", payload)) Serial.println("Log save success");
    else Serial.println("Log save failure");

Hope this helps to understand the nature of SPIFFS/LittleFS/SD operations

body:
Use `file.write(payload, length);` for byte array. `length` should be the count of payload bytes, not the size of the payload array.

`print` and `write` return the count of bytes written. It is not meaningful to use the return value as boolean.


body:
I am working on a project using pro mini 8MHz/3.3v and SIM7100, I want to know how can I used AT+CFTRANTX command. I am try to read file from EFS and write to SD card via Serial port. I have get some data in SD but is junk.

My board is Arduino Pro Mini (ATMega 328) 8MHz/3.3 V datasheet (DEV-11114) and Modem is home-made board with SIM7100 module, already test board and module work with all functions without any problem. I’ve added a schematic of the board to the question.

Here is SIM7100 Schematic
[![enter image description here][1]][1]

Here is SD Module, Pro Mini and SIM7100 pin layout
[![enter image description here][2]][2]

c:\data2.txt is: A1 to F0

A1A2A3A4A5A6A7A8A9A0B1B2B3B4B5B6B7B8B9B0C1C2C3C4C5C6C7C8C9C0D1D2D3D4D5D6D7D8D9D0E1E2E3E4E5E6E7E8E9E0F1F2F3F4F5F6F7F8F9F0

Any help would be appropriated.

The code that I am using, I tried it with every possible baud rate:

```
#include <SPI.h>
#include <SD.h>
#include <SoftwareSerial.h>
SoftwareSerial simSerial(7, 6);
File myFile;

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

  simSerial.begin(9600);
  Serial.print("\nInitializing SD card...");

  if (!SD.begin(10)) {
    Serial.println("\nInitialization failed!");
    while (1);
  }
  Serial.println("\nInitialization done.");
  delay(8000); //For booting SIM7100
  if (SD.exists("1.TXT")) SD.remove("1.TXT");

  myFile = SD.open("1.txt", FILE_WRITE);
  if (myFile) {
    simSerial.println("AT+CFTRANTX=\"c:/data.txt\"");
    while (simSerial.available() > 0) {
      byte voc = simSerial.read();
      myFile.write(voc);
    }
    myFile.close();
    // Serial.println("\nClose done.");
  } else {
    // Serial.println("Error opening 1.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("1.txt");
  if (myFile) {
    Serial.println("1.txt:");
    while (myFile.available()) {
      Serial.print(myFile.read());
    }
    myFile.close();
    Serial.println("\nReading SD Card done.");
  } else {
    Serial.println("Error opening 1.txt");
  }

}

void loop() {

}
```
Here is test sketch for software & hardware serial.
```
SoftwareSerial mySerial(7,6); // RX, TX

void setup()
{
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Hardware Serial port!");
  mySerial.begin(9600);
  mySerial.println("AT+CFTRANTX=\"c:/data.txt\"");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}
```

  [1]: https://i.stack.imgur.com/igkE8.png
  [2]: https://i.stack.imgur.com/zhgbn.png

title: How to use AT+CFTRANTX command in SIM7100

Answers: 2

body:
The Manual v1.02 of Sim7100 with all the commands [can be downloaded here](https://cdn-global-hk.hobbyking.com/media/file/1/1/110495-manual.pdf)<br>
Here is code to test it compiled for UNO without warnings and errors: Please test it and give feedback (read the comments to get the flow of code) Test with  the RX/TX of the Sim7100 to pins 4/5 (Software Serial and the Sim7100 to baud rate 9600):

    #include <SPI.h>
    #include <SD.h>

    #include <SoftwareSerial.h>

    #define SD_ChipSelectPin 10

    SoftwareSerial simSerial(5, 6); // RX, TX to TX RX of the SIM7100 module
    //#define simSerial Serial
    char receiveArray[256] = {'\0'};
    void readSerialPort(uint8_t);
    uint8_t counter = 0;

    void setup() {
       Serial.begin(57600);
        while (!Serial) {
         ;
        }
      simSerial.begin(9600); // using HW Serial on a Pro Mini
      while (!simSerial) {
        ;
      }

      simSerial.println("AT+IPR=9600"); // set sim7100 to same serial speed
      delay(1000);
      simSerial.flush();   // Flush buffer

      SD.begin(SD_ChipSelectPin);
      if (!SD.begin(SD_ChipSelectPin)) {
        //Serial.println("Error opening SD-card");
        return;
      }
      delay(1000);
      if (SD.exists("1.TXT")) SD.remove("1.TXT");
      delay(1000);
    }

    void loop() {

      if (counter < 3) {
        File saveFile = SD.open("1.TXT", FILE_WRITE);
        if (saveFile) {
          // This has to be the Serial the SIM7100 is attached to
          simSerial.println("AT+CFTRANTX=\"c:/data.txt\"\r");
          while (!simSerial.available()) {} // wait for data to arrive

            readSerialPort(0);

          saveFile.close();

          // Serial.println("Success creating file");
        } else {
          // Serial.println("Error creating file");
        }
        counter++;
      }
    }

    /* For a first test we print everything to 1.txt -
      there will be "garbagge" as the AT response in it -
      we can "clean" in a later  by using the intermediate array or the counter */
    void readSerialPort(uint8_t startIndex = 0) {
      uint16_t i = 0;   // counter and we want later to filter the first X chars
      while (simSerial.available() > 0) {
        char inChar = simSerial.read();
        if (i >= startIndex) { // if we want to filter the first 16 chars it would be i>=16 (as it starts with 0)
          if (inChar == '\n') {
            receiveArray[i] = '\0'; // terminate the array
            return;
          }
          if (inChar != '\r') {
            receiveArray[i] = inChar;
            i++;
          }
        }
      }
    }

body:
When having trouble in getting started with a modem, it's usually best to connect to the modem in "interactive mode", to verify that you're sending the right commands and getting the right responses.

Have you made sure that your modem/module's UART is at the right logic level to interface directly with your Pro Mini? How about the supply voltage? (Post a link to the product). If you're done with all that, then connect **only** the modem to the Pro Mini:

    5V/3.3V -> Vcc (depending on the module's supply voltage)
    D6 -> Modem TX
    D7 -> Modem RX
    Gnd -> Gnd

Then, upload the following to your Pro Mini:

    #include <SoftwareSerial.h>

    SoftwareSerial fserial(6, 7);

    void setup(void)
    {
        Serial.begin(57600);
        // I assume this is the default for your modem
        fserial.begin(115200);
        Serial.println("Starting.");
    }

    void loop(void)
    {
        while (fserial.available())
            Serial.write(fserial.read());
        while (Serial.available())
            fserial.write(Serial.read());
    }

This should basically transfer everything you send from your Serial Monitor to the modem, and in the reverse, transfer everything the modem sends to your Serial Monitor.

After uploading the sketch, in the Serial Monitor, set the `Line Ending` at the bottom to `Carriage Return`. Then you can first send the simple `AT` and should receive `OK` from the modem, to confirm that your setup works. Then to test your file reading code, send your command `AT+CFTRANTX="c:/data.txt"` and see what you get.

If you can confirm this works, writing code to do this automatically should then be much clearer. Or at the very least, you'll have ruled out a whole bunch of possible problems.

(**Note**: the Arduino may not work reliably with 115200 baud on Software Serial. So you may want to change the modem's baud rate quickly with `AT+IPREX=9600`. And then modify your sketch accordingly and re-upload.)


body:
PROBLEM STATEMENT:

 1. A circuit is measuring various parameters (Temperature, Humidity,
    etc.) through sensors connected to it continuously.
 2.  When a Push Button is Pressed and Hold for 2 seconds in between the Arduino should enter into Setup mode.(I have used IF loop and
    millis() function to achieve this )
 3. In Setup mode there are 6 screens which will appear one after one.
 4. Once Arduino enters into Setup mode Switch case 0 (screen1) should appear (I have used serial monitor for the same).
 5. Now if I press the same push button and released within a moment the next Switch case 1 (screen2) should appear.
 6. Step 5 will be repeated till Switch case 5 (screen6).
 7. After Switch case 5 the loop rolls over to Switch case 0 (SCREEN1) then Switch case 1, Switch case 2, so on.
 8. If in between above Switch Case loop Push Button is Presses and Hold for 2 seconds the Switch case loop must get terminated and the
    Arduino should go back to MAIN LOOP() where it is measuring the
    sensor parameter.
 9. Again if the push button is Pressed and Hold for 2 seconds in between sensing process the Arduino should enter into Setup mode.

CONSIDERATIONS:<br>

 1. Push Button is connected to Pin2 of Arduino (ACTIVE LOW)
 2. The input at Pin2 is considered as interrupt so that Arduino provides service to any moment of the time.
 3. Arduino serial monitor is used to demo the Screen1-Screen6 as output.
 4. 0.1uf Capacitor is used across the Push Button for debounce considerations. And 10K, 0.25W resistor is connected from VCC to Pin
    no.2
 5. The code for sensing parameters (Temperature, Humidity, etc.) is yet to be written.

ACHIEVEMENT:
Upto Point No. 7 of PROBLEM STATEMENT the code is working fine.

BUG:
If I press Push Button for 2 seconds in SWITCH CASE loop, Arduino is going out of the SWITCH CASE and going into MAIN LOOP() but again coming back to SWITCH CASE() loop.
It should ask again to press Push Button for 2 Seconds to enter into Setup Mode.

    const int btn = 2;
    const int ledPin =  13;
    int selector = 0;
    boolean  volatile wait = false;
    const unsigned long event=2000;
    unsigned long previous1=0;
    unsigned long current1=0;
    unsigned long sum1=0;
    unsigned long previous2=0;
    unsigned long current2=0;
    unsigned long sum2=0;
    bool buttonPress = false;
    void setup()
    {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    pinMode(btn, INPUT);
    attachInterrupt(digitalPinToInterrupt(btn),decoder,CHANGE);
    }

    void loop()
    {
      if (digitalRead(btn) ==LOW && !buttonPress)
      {
        previous1 = millis();
        buttonPress = true;
      }
      else if (digitalRead(btn) == HIGH && buttonPress)
      {
        current1 = millis();
        sum1=current1-previous1;
        Serial.println(sum1);
        Serial.println("SUM1");
        if (sum1>=event)

           {  BREAK1:
              doSwitchCase();
              selector++;
              goto BREAK1;
              if (selector >6)
                  {
                      selector = 0;
                      delay(500);
                  }
            }
            buttonPress = false;
      }
      wait = true;
      interrupts();

    }

    void decoder()
    {
     noInterrupts();
     wait = false;
    }

    void doSwitchCase()
    {
      switch(selector)
      {
      case 0:
        Serial.println("SCREEN1");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
        break;

      case 1:
        Serial.println("SCREEN2");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
        break;

      case 2:
       Serial.println("SCREEN3");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
       break;

      case 3:
       Serial.println("SCREEN4");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
       break;

      case 4:
       Serial.println("SCREEN5");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
       break;

      case 5:
      Serial.println("SCREEN6");
        while (digitalRead(btn)!=LOW) ;
        previous2 =millis();
        while (digitalRead(btn)!=HIGH) ;
        current2=millis();
        sum2=current2-previous2;
            if(sum2>=event)
            {
             Serial.println(sum2);
             loop();
            }
      break;
      }
    }

title: Pushbutton and switch case follow up question

Answers: 1

body:
One note before **NEVER** use goto in C++ its bad style and makes in an object oriented language to 99.9% no sense. To enter the switch case after a2 second press you have just to enter one statement t omy original proposal.I did not read your code as it gets unreadable the more functionality you want to add. Think about refactoring it or you will run out of luck to get help (as nobody tortues himself with caotic code of others:<br>

    const int btn = 2;
    const int ledPin =  13;
    int selector = 0;
    const unsigned long buttonPressLong = 2000;  // 2 seconds
    const unsigned long buttonPressShort = 250;  // 0.25 secondis feasable
    const unsigned long buttonPressDebounce = 50;  // debouncing for too short presse Thanks Edgar Bonet
    unsigned long buttonPressStart = 0;

    bool buttonPress = false;
    bool inMenu = false;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(btn, INPUT);
      }

    void loop() {
      if (digitalRead(btn) == LOW && !buttonPress ) {
        buttonPressStart = millis();
        buttonPress = true;
      }
      // The routine is only triggered if a previous pressing took place, otherwise it's ignored
      else if (digitalRead(btn) == HIGH && buttonPress) {
        if (millis() - buttonPressStart > buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
          Serial.print("Long press: ");
          Serial.println(millis() - buttonPressStart);
          buttonPress = false;
          inMenu = false;
        }
        if (millis() - buttonPressStart < buttonPressLong && millis() - buttonPressStart > buttonPressDebounce && !inMenu) {    // HERE IS A CHANGE
          Serial.print("First long press ");    // HERE IS A CHANGE
          inMenu = true;
        }
        if (millis() - buttonPressStart < buttonPressShort && millis() - buttonPressStart > buttonPressDebounce && inMenu) {
          Serial.print("Short press: ");
          Serial.println(millis() - buttonPressStart);
          doSwitchStatement();
          selector++;
          if (selector > 6) {
            selector = 0;
            delay(500);
          }
          buttonPress = false;
        }
      }
      // Here you could do other stuff as it is non blocking
    }
    doSwitchStatement(){...}// Stays the same as yours

I just changed 1 statement (and 1 debug msg) to achieve what you want see // HERE IS A CHANGE


body:
I'm writing a code where `analogRead()` reads ADC value from load. After reading ADC value, if it is not in range, I need to manipulate Timer1 value. Which is also getting changed.
But, after changing the Timer value,  if the load value again gets restored, ADC doesn't show the same value again, but shows some other value.

Please refer below code:

    #include <TimerOne.h>

    int LED = 13;
    int IN0 = 12;
    int IN1 = 11;
    int OUT1 = 10;
    int OUT2 = 9;
    int OUT3 = 8;
    int OUT4 = 7;
    //float A0;
    //int OUT5 = 6;
    const float refvolt = 5.0;
    int volts = 0;
    byte tempL_flag = 0;
    float samples, loadval, avgacs, acsvaluef =0;
    float refval = 2.0;
    bool lflag=0;
    unsigned long count = 0;

    void setup()
    {
     pinMode(IN0, INPUT);
     pinMode(IN1, INPUT);
     pinMode(OUT1, OUTPUT);
     pinMode(OUT2, OUTPUT);
     pinMode(OUT3, OUTPUT);
     pinMode(OUT4, OUTPUT);
     pinMode(LED, OUTPUT);
     pinMode(A0, INPUT);
     //digitalWrite(OUT3, LOW);
     Timer1.initialize(370000);
     Serial.begin(9600);
    }

    word ADC_READ(byte sample, byte tim, byte CH)
    {
     word adcdata;
     word avrdata;
     word abcdata;
     byte i;

     for(i=0; i<sample; i++)
     {
      adcdata = 0;
      adcdata = analogRead(CH);
      avrdata = avrdata + adcdata;
      delay(tim);
     }
     return(avrdata/sample);
    }

    void flash_L()
    {
     digitalWrite(LED, !digitalRead(LED));
     digitalWrite(OUT4, !digitalRead(OUT4));

     if (digitalRead(OUT4)==1)
     {
      loadval = ADC_READ(10, 10, A5);
      Serial.println(loadval);

      if(loadval < refval)
      {
       Timer1.initialize(185000);
      }
      else
      {
       tempL_flag = 1;
      }
      return;
     }
    }

    void loop() {

     delay(2000);

     if(digitalRead(IN0)==1)
     {
      Timer1.attachInterrupt(flash_L);
     }
     else if(digitalRead(IN0)==0)
     {
      digitalWrite(LED, LOW);
      digitalWrite(OUT4, LOW);
     }
    }

title: ADC value changing after changing Timer1 value in program

Answers: 1

body:
> ADC doesn't show the same value again

You are not reading the ADC correctly, so `ADC_READ()` can return
anything. See the comments in the code:

```c++
word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;  // not needed
    word avrdata;  // not initialized
    word abcdata;  // not used
    byte i;
    for (i = 0; i < sample; i++)
    {
        adcdata = 0;  // useless
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return (avrdata/sample);
}
```

The big issue is `avrdata` not being initialized. Its initial value is
whatever was left there (in the stack or some CPU registers) by the code
that ran before. The value returned by the function is then hard to
predict and depends on what the rest of the program is doing.

The other remarks I left in the comments are not that problematic,
although they are revealing of some lack of attention to detail. Same
for some badly named variables. Here is how I would implement this
function:

```c++
word ADC_READ(byte samples, byte time, byte channel)
{
    word sum = 0;
    for (int i = 0; i < samples; i++)
    {
        sum += analogRead(channel);
        delay(time);
    }
    return sum/samples;
}
```


body:
I am plotting the graph of some sensor values on my Arduino serial plotter which looks something like this -[![enter image description here][1]][1]

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

But what I want to do is hover over any point on the graph and display the time at that point. Is there any way to do that, if not with Arduino serial plotter, with Processing? Or any other tool is fine too. Thanks.

title: How to find the time of any point on the graph on an Arduino serial plotter or Processing software?

Answers: 1

body: The Arduino Serial Plotter is not meant for this. It just directly draws, what you send. You can solve this in processing, by calculating the time from the number of the current sample (which is what you see on the x axis in your plot) via the used sampling rate.


body:
I have 2560 mega, and I Want to generate 3-phase PWM signal at 62.5khz, synced and shifted 120 degrees apart.

I need that for 3-phase split-coil boost converter (or even isolated flyback converter), with <s>3 phase transformer</s> coupled inductor. So I dont need sine wave table [like here](https://forum.arduino.cc/index.php?topic=236778.0), but actually, a direct square wave PWM output, from 3 synced digital pins, with chosen duty cycle. How can I do that?

title: How to generate 3 PWM signals

Answers: 1

body:
If you have any timers left, I would (regardless of the number of PWM signals and if you need different PWM frequencies) just dedicate a timer to do IRQs to manage them.

The frequency of the IRQs would then depend on how accurately you want to control the duty cycle, ref. also to the comment from Edgar Bonet .


body:
I want to do LED toggeling so I wrote this:

<!-- language: lang-cpp -->

    int led=13, button=12;

    void setup()
    {
     // put your setup code here, to run once:
     pinMode(led,OUTPUT);
     pinMode(button,INPUT);
    }

    void loop()
    {
     // put your main code here, to run repeatedly:
     if(digitalRead(button)==HIGH && digitalRead(led)==LOW)
     {
      digitalWrite(led,HIGH);
     }

     if(digitalRead(button)==HIGH && digitalRead(led)==HIGH)
     {
      digitalWrite(led,LOW);
     }
    }

But It doesn't work well, sometimes I need to press the button many times in order to turn on or of...and some times with just one press.

I saw this video but I didn't understand it well:
https://www.youtube.com/watch?v=aMato4olzi8&t=415s

Anyway I don't know why my way doesn't work well.

title: My LED toggeling doesn't work the way I want

Answers: 1

body:
There are a few problems with your approach.

1.  You seem to have the button backwards.  You should wire a button so that it is between the pin and ground.  This way it should read LOW when pressed, not HIGH.  It should also have pinMode(pin, INPUT_PULLUP) instead of INPUT.  With the button wired the way you have it to read HIGH then you will need an extra resistor for each button.  With it wired the right way where it reads LOW then it needs nothing extra.

2.  If the first if statement is true and the button is pressed and it turns on the led, what do you think are the chances that you are fast enough to get your finger off the button in the 62.5 nanoseconds it takes to get to that next if statement?   It's not going to happen, so the button is still pressed there and now the led is on so this line turns it right back off.  Only in the rare case where you happen to get your finger off the button at just the right instant will the led stay lit.  To solve this, look at the "State Change Example" that comes with the IDE.  It shows how to keep track of the last state of the button in a variable so you can act only once when the button actually changes state.

3.  Once you get that worked out you will notice that it seems like for every time you press your button it registers tens of presses.  This is switch bounce.  That's a term you should google.  The contacts are making and breaking contact really fast in the in-between pushed and not-pushed state.  But you need to get the first two issues solved before you worry about bounce.


body:
I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

 1. The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
 2. If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.

title: Arduino Uno SD card storage

Answers: 2

body:
Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.

Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.

Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.

body:
To start with power consumption rules an Arduino UNO out so you will need some device capable of (deep) sleep mode. Devices like ESP8266 or ESP32. The table below shows the differences between each mode (information from the ESP8266 datasheet).

    Item           Modem-sleep     Light-sleep       Deep-sleep
    Wi-Fi                 OFF          OFF         OFF
    System clock          ON         OFF          OFF
    RTC               ON         ON          ON
    CPU                  ON      Pending         OFF
    Substrate current   15 mA        0.4 mA        ~20 uA
    Avg. current (DTIM = 1) 16.2 mA     1.8 mA        –
    Avg. current (DTIM = 3) 15.4 mA     0.9 mA        –
    Avg.current (DTIM = 10) 15.2 mA     0.55 mA

These modules have around 4MB flash which yoi could use for storage of data (SPIFFS/LittleFS) so 1MB for programs and 3MB for on board storage, after that you save to SD and fill up the onboard FS again or you send the data via WLAN to an online storage or database or to a server in your network (depending on your scenario) These devices cost as much as an Arduino UNO clone (5-7$) and can be programmed with the same IDEs as Arduinos and in the same (extern C/)C++ derivate. So if power consumption is an issue look at those IoT devices


body:
I am new to arduino.  I have a project in which I need an arduino to generate a +5VDC  signal in response to a *change* *of* *status*, (high/5VDC To low/ground) from an external source.

The external source is a stand alone receiver/transmitter set which outputs +5VDC when the transmitter is out of range and ground when the transmitter is within range.

The goal is to have the arduino output +5VDC (triggering a series of events) only when the TX is within range of the RX (signal voltage is GRND vs. +5vDC).  The series of events are controlled via a stand alone event controller which is initiated by a +5VDC signal courtesy of the arduino.

I already have a RX/TX set which outputs +5VDC when the the TX is absent and GROUND when the TX is within range.  I also have the event controller.  I only need the arduino solution.

I have an arduino UNO but I am open to other option if needed.

Solution: give me +5VDC when signal voltage (from receiver) is low (ground).

If anyone could point me in the right direction it would be greatly appreciated.  This is my first arduino project so I have much to learn.

Best regards

title: Generate 5VDC signal when external sensor input changes from high to low

Answers: 2

body:
This is literally the simplest Arduino program possible.  I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.

    void setup(){
      pinMode(yourInputPin, INPUT_PULLUP);
      pinMode(yourOutputPin, OUTPUT);
    }

    void loop(){
      if(digitalRead(yourInputPin) == LOW){
         digitalWrite(youOutputPin, HIGH);
      }
      else {
         digitalWrite(yourOutputPin, LOW);
      }
    }

All you need to do is supply the appropriate pin numbers.

body:
Why waste an Arduino on such a paltry job?  Here's a circuit that has just 3  components in it that does what you want:

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

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

<!-- End schematic -->

It's basically a NOT gate (you can use an actual NOT gate, like a 74HC04 if you like) where the output is the opposite of the input.  You could even remove R2 if you like - that just prevents the input floating when there's no valid signal detected.

This form of gate is called *RTL* - Resistor-Transistor Logic, and is one of the simplest logic gate arrangements there is.


body:
The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters.  The if statement does not work with characters.  I have tried both == and === in the if statement

    var SerialPort = require('serialport')
    var Readline = SerialPort.parsers.Readline
    var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
      baudRate: 9600
    })

    var parser = new Readline()
    serialPort.pipe(parser)
    parser.on('data', function (data) {
    if(data === 'c'){/// c is not recognized
      console.log('data received: ' + data)
    }

    })
    serialPort.on('open', function () {
      console.log('Communication is on!')
    })

The Arduino code is as follows:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(12, 13); // RX, TX
    int x = 0;
    int y = -30000;
    int z = 0;
    String data;
    char command = 'q';
    int left = 0;
    int right = 0;
    int left_pwm = 0;
    int right_pwm = 0;

    void setup() {
      mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
      Serial.begin(9600);
      }
    void loop() {//map and compass data
    if (y==30000) {
     mySerial.println('c');
     delay(5);
     mySerial.println(299);
     delay(5);
     z = -25000;
     }

     if(z==30000){
     mySerial.println('lon');
     delay(5);
      mySerial.println(529);
      delay(5);
      mySerial.println('lat');
     delay(5);
       mySerial.println(522);
              y = -30000;
        }
      y++; z++;

      if (!mySerial.available()) {
        return;
      }

      data = mySerial.readString();
       sscanf(data.c_str(), "%cddd,d", &command, &left, &right, &left_pwm, &right_pwm);

      if (command == 'n') { // we got a navigation command
        // update the GPIO accordingly, this only happens once after a new 'n' command has been received
        Serial.print(command);
        Serial.print(left);
        Serial.print(right);
        Serial.print(left_pwm);
        Serial.print(",");
        Serial.println(right_pwm);
        }

        }////end loop

title: Node.js cannot recognize characters from the serial port

Answers: 1

body:
If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the `'ņ'` character is removed from the string. But `Serial.println()` sends `"\r\n"` as line ending. That means, that your string is "c\r", which is not equal to "c".

By using the `trim()` method of the String type, you can remove all white space from start and end of the string, including line ending characters like `'\r'`.


body:
I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using *SD.open("test.txt", FILE_WRITE);* but my code fails to create *SD.open("DATA/data_test.txt", FILE_WRITE);* in a directory.
Here's the piece of code that successfully creates a file in the root:

    String final_book_name = upload_book_name + ".txt";
    if (SD.exists(final_book_name.c_str())) {
      SD.remove(final_book_name.c_str());
    }
    tft.println(final_book_name); // This successfully prints "test.txt"
    book_file = SD.open(final_book_name, FILE_WRITE);
    if (SD.exists(final_book_name.c_str())) {
      tft.print("Created file");
    } else {
      tft.print("Failed to create/replace\nfile!");
    }

and here's the piece of the code that fails to create a file in a directory:

    if (!SD.exists(DATA_DIR)) {
      SD.mkdir(DATA_DIR);
    }
    String final_book_name = upload_book_name + ".txt";
    String book_data_path = DATA_DIR;
    book_data_path += "/data_" + final_book_name;
    if (SD.exists(book_data_path.c_str())) {
      SD.remove(book_data_path.c_str());
    }
    tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
    File book_data_file = SD.open(book_data_path, FILE_WRITE);
    if (SD.exists(book_data_path.c_str())) {
      book_data_file.print(upload_book_font);
      book_data_file.print("|");
      book_data_file.print("0");
      book_data_file.close();
    } else{
      tft.print("Failed to create/replace\ndata file!");
      if (SD.exists(final_book_name.c_str())) {
        SD.remove(final_book_name.c_str());
      }
    }

title: STM32 and SDFat - Can't create file in directory in SD

Answers: 2

body:
As you have given no variable for `DATA_DIR`

    String book_data_path = DATA_DIR;
    book_data_path += "/data_" + final_book_name;

so your resulting path looks like

    DATA_DIR + "/data_" + final_book_name

IF `DATA_DIR = "/"` then it would be `"/" + "/data_" + final_book_name`

As tip do not use the string class but char arrays

definition

     const char[] DATA_DIR = "/books";
     char book_data_path [128] = {'\0'};
     char final_book_name [13] =  {'\0'}; // IF no LFN support is used its 8.3 !!!
     const char upload_book_name[] = "my_book";
     strcpy (final_book_name, upload_book_name);
     strcat (final_book_name, ".txt");
     Serial.println(final_book_name);

If you want long filr namesupport us SDFat library or enable LFB withSD lib (whichneeds about 35% ,ore memory as SDfat (when using long file names).

**EDIT**
As you are using SDFat and I do not know which version/fork there is abug with writing to subdirectories. Please check the following:

To check run the `SdFat\examples\DirectoryFunctions` and watch your serial monitor for the results

SdFile.cpp. At line 782 and 1452, you have (in my version):

    if (block <= m_vol->cacheBlockNumber()
      && block < (m_vol->cacheBlockNumber() + nb)) {

The working code has:

    if (m_vol->cacheBlockNumber() <= block
      && block < (m_vol->cacheBlockNumber() + nBlock)) {

If you have the upper version change it and it should work

**EDIT 2** Work around for buggy SDFat lib

Here is a workaround code

    const char DATA_DIR [] = "data";
    char final_book_name[128] ={'\0'};
    char book_data_path [256] ={'\0'};

    if (!SD.exists(DATA_DIR)) {
      SD.mkdir(DATA_DIR);
      SD.chdir(DATA_DIR);
    }

    strcpy (final_book_name, upload_book_name);
     strcat (final_book_name, ".txt";
    String book_data_path = DATA_DIR;

    strcpy(book_data_path, "data_");
    strcat(book_data_path, final_book_name);

    if (SD.exists(book_data_path)) {
      SD.remove(book_data_path);
    }
    SD.mkdir(book_data_path);
    SD.chdir(book_data_path);

    tft.println(DATA_DIR);
    tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
    File book_data_file = SD.open(final_book_name, FILE_WRITE);
    if (SD.exists(final_book_name)) {
      book_data_file.print(upload_book_font);
      book_data_file.print("|");
      book_data_file.print("0");
      book_data_file.close();
    } else{
      tft.print("Failed to create/replace\ndata file!");
      if (SD.exists(final_book_name)) {
        SD.remove(final_book_name);
      }
    }

body:
I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.

UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.